feat(moe): support Qwen3.5 NVFP4 MegaMoE (#2825)

## Summary

Enable Qwen3.5 MoE models to use the NVFP4 MegaMoE backend with BF16
activations and externally computed routing results.

- Quantize activations and stage routing data into the MegaMoE
workspace, extending the NVFP4 MegaMoE kernel with gated SiLU alongside
SiTU; existing callers keep the prequantized input path. Keep shared
experts on their existing independent execution path.
- Skip the redundant all-reduce after MegaMoE output while preserving
attention communication fusion.
- Allocate workspace for the configured capacity and retain the existing
default tactic selection.
- Size draft decode autotune warmup batches to attention TP so empty TP
ranks do not skip tuning collectives entered by their peers, and reject
speculative serving configurations with less than one request per
attention TP rank during argument validation; prefill-only roles are
exempt.
- Build the MTP draft head and logits processor from the shared target
head layout so the draft matches the target under attention DP.
- Reject incompatible Qwen3.5 MegaMoE configurations during
construction: EP must exceed 1 with MoE TP 1, the all-to-all backend
must be none, expert placement must be trivial without EPLB or redundant
experts, and attention rows must already be scattered with attention TP
different from MoE TP times EP, so configurations with TP8 and EP8 are
unsupported.

## Performance

End-to-end serving throughput comparing NVFP4 MegaMoE with the
FlashInfer TRTLLM NVFP4 MoE baseline. Qwen3.8-Flash-Next uses an agentic
multi-turn benchmark on four B300 GPUs. Qwen3.8-Max uses AIME26 on eight
B300 GPUs, with temperature 0, fixed 4096-token outputs, and prefix
caching disabled. Max results report median throughput across three
rounds of finite request batches.

| Model | Parallelism | MTP steps | KV cache | Mean input tokens |
| --- | --- | ---: | --- | ---: |
| Qwen3.8-Flash-Next-NVFP4 | DP4, TP1, EP4 | 3 | FP8 | ~57,000 |
| Qwen3.8-Max-NVFP4 | DP4, TP2, EP8 | 7 | FP8 | 135.4 |

### Qwen3.8-Flash-Next-NVFP4

| Concurrency | TRTLLM MoE (tokens per second) | MegaMoE (tokens per
second) | Change |
| ---: | ---: | ---: | ---: |
| 1 | 205.78 | 208.56 | +1.3% |
| 8 | 712.78 | 751.98 | +5.5% |
| 16 | 849.37 | 860.05 | +1.3% |
| 32 | 931.31 | 1,014.84 | +9.0% |
| 64 | 1,072.86 | 1,148.71 | +7.1% |
| 128 | 1,189.70 | 1,278.68 | +7.5% |
| 256 | 1,260.79 | 1,365.89 | +8.3% |

### Qwen3.8-Max-NVFP4

| Concurrency | TRTLLM MoE (tokens per second) | MegaMoE (tokens per
second) | Change |
| ---: | ---: | ---: | ---: |
| 1 | 182.76 | 182.42 | -0.2% |
| 8 | 1,154.46 | 1,133.89 | -1.8% |
| 16 | 1,846.30 | 1,923.38 | +4.2% |
| 32 | 3,061.75 | 3,397.71 | +11.0% |
| 64 | 5,456.23 | 5,690.81 | +4.3% |

## Validation

- 344 targeted tests passed, including draft warmup coverage for
attention TP sizes 1, 2, and 8.
- Verified the complete SM103 native build: all 24 kernel groups,
scheduler, and engine.
- Qwen3.8-Max NVFP4 with DP4, TP2, EP8, and MTP7 completed startup with
autotuning enabled and an empty tactic cache. All eight ranks completed
CUDA graph capture; four concurrent requests each generated 128 tokens
successfully.
- Evaluated the full GSM8K test set using the existing CI evaluation
parameters: batch size 16, temperature 0, max output 1,024 tokens, and
thinking disabled.

| Model | Configuration | Dataset | Accuracy |
|---|---|---|---:|
| Qwen3.8-Flash-Next NVFP4 | MegaMoE, DP4 and EP4, MTP3 | GSM8K |
**97.04%** |

---------

Signed-off-by: minedec <jiandong@lightseek.org>
This commit is contained in:
minedec
2026-11-02 15:06:51 +08:00
committed by GitHub
parent 373158a73b
commit fe58cfcd4b
16 changed files with 1252 additions and 110 deletions
+20
View File
@@ -1537,6 +1537,11 @@ than failing at its first forward (`BaseCausalLM.set_embed_and_head` refuses
both sides are shared and the draft's copies are dropped before the KV-cache
budget is profiled, as before.
A drafter sharing a target head constructs its head and logits processor from
`mapping.lm_head`, just like the target. Attention TP is a separate layout:
under attention DP the head is normally replicated even when attention uses
multiple ranks. The factory checks the two logits layouts before binding.
Checkpoint tap labels remain zero-based completed-layer IDs. Prefix tap L is
produced after L. AttnRes tap L is produced at L+1's entry by that layer's
mixer, before input-layer normalization or snapshot mutation; the final tap
@@ -2267,3 +2272,18 @@ cache groups. Its eager and captured decode share metadata refresh and DCP
partial-output reduction; SWA and compressor tails remain replicated. See
[the V4.1 context-parallel contract](deepseek-v41-context-parallelism.md) for
ownership, graph lifetime and supported configurations.
### Distributed draft tuning
The startup draft decode uses one request per attention TP rank so that
sequence-parallel router projections have nonempty, equal local row counts.
A single-request TP warmup can skip a GEMM on an empty peer while another
peer waits in distributed tactic selection. The draft remains in the same
autotune context as the target. Serving batches and graph capture sizes are
unchanged. A speculative decode service must reserve at least one request
per attention TP peer: `max_num_seqs // data_parallel_size >= attn_tp_size`.
Server-argument validation rejects smaller capacities before allocating
buffers or running a forward, including with `--disable-autotune` (which
disables profiling, not startup warmup). Increase `--max-num-seqs` to at
least `data_parallel_size * attn_tp_size`. Prefill-only roles do not run
this draft decode warmup and are exempt.
@@ -421,6 +421,7 @@ class ModelExecutorConfig:
# ====== DP =========
data_parallel_size: int = 1
attention_tp_size: int = 1
world_size: int = 1
world_group: list[int] | None = None
@@ -531,6 +532,7 @@ class ModelExecutorConfig:
query_shard_rank=server_args.mapping.attn.qcp_rank,
enable_memory_saver=server_args.enable_memory_saver,
data_parallel_size=server_args.mapping.attn.dp_size,
attention_tp_size=server_args.mapping.attn.tp_size,
world_size=server_args.mapping.world_size,
world_group=server_args.mapping.world_group,
pp_size=server_args.mapping.pp_size,
@@ -1150,10 +1152,11 @@ class ModelExecutor:
# Prefill-only roles do not allocate decode/verify scratch.
# The draft model is reached through the shared speculative
# forward, not model_runner.forward above. One request
# exposes its operators; FI still owns their bucket
# enumeration.
# per attention TP rank keeps sequence-parallel router
# GEMMs nonempty on every peer during distributed tuning.
self.forward_step.warmup_decode_path(
batch_sizes=(1,), graph_phase=False
batch_sizes=(self.config.attention_tp_size,),
graph_phase=False,
)
finally:
set_autotune_process_group(None)
+3 -1
View File
@@ -2591,7 +2591,9 @@ class KimiLinearMoE(nn.Module):
if self.execution_plan.use_mega_moe:
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe import runner
moe_runner = runner.get_runner(self.experts.plan, self.experts)
moe_runner = runner.get_runner(
self.experts.plan, self.experts, prequantized=True
)
activation, scales, ids, weights = moe_runner.input_buffers(
num_tokens, max_tokens
)
@@ -66,7 +66,7 @@ from tokenspeed.runtime.layers.quantization.nvfp4 import Nvfp4Config
from tokenspeed.runtime.layers.quantization.utils import should_exclude_quant_module
from tokenspeed.runtime.utils import add_prefix
from tokenspeed.runtime.utils.cuda_stream import StreamFork
from tokenspeed.runtime.utils.env import envs
from tokenspeed.runtime.utils.env import envs, global_server_args_dict
_is_blackwell = current_platform().is_blackwell
@@ -300,6 +300,31 @@ class Qwen3_5MoeSparseMoeBlock(nn.Module):
self.use_deepep = get_all2all_backend().is_deepep() and (
moe_backend.is_flashinfer_cutedsl() or moe_backend.is_deep_gemm()
)
self.use_mega_moe = moe_backend.is_mega_moe()
if self.use_mega_moe:
if mapping.moe.ep_size <= 1:
raise ValueError("Qwen3.5 MegaMoE requires EP>1")
if not get_all2all_backend().is_none():
raise ValueError(
"Qwen3.5 MegaMoE owns dispatch/combine and requires "
"--all2all-backend none"
)
if (
global_server_args_dict.get("enable_eplb", False)
or global_server_args_dict.get("ep_num_redundant_experts", 0)
or global_server_args_dict.get("init_expert_location", "trivial")
not in (None, "trivial")
):
raise ValueError(
"Qwen3.5 MegaMoE requires trivial expert placement without "
"EPLB or redundant experts"
)
if mapping.attn.tp_size == mapping.moe.tp_ep_size:
raise ValueError(
"Qwen3.5 MegaMoE requires scattered MoE rows: attention TP must "
"differ from MoE TP*EP; TP8/EP8 is unsupported. Use DP4/TP2/EP8 "
"or DP8/TP1/EP8."
)
self.comm_manager = CommManager(
mapping=mapping,
layer_id=layer_index,
@@ -338,6 +363,7 @@ class Qwen3_5MoeSparseMoeBlock(nn.Module):
"routing_method_type": RoutingMethodType.RenormalizeNaive,
"normalize_topk_weights": config.norm_topk_prob,
},
routing_mode="precomputed_topk" if self.use_mega_moe else None,
)
self.topk = TopK(
top_k=config.num_experts_per_tok,
@@ -354,14 +380,14 @@ class Qwen3_5MoeSparseMoeBlock(nn.Module):
quant_config=quant_config,
reduce_results=False,
prefix=add_prefix("shared_expert", prefix),
# The DeepEP path runs the whole block on this rank's token
# DeepEP and MegaMoE run the whole block on this rank's token
# shard, so the shared expert is data parallel over those rows:
# replicated weights, no cross-rank reduction. Sharding it
# instead would reduce partial products belonging to different
# tokens. It also lifts the dense-TP ceiling that a small
# shared_expert_intermediate_size imposes under block-quantized
# FP8 (a shard must stay >= the quantization block).
replicate_weights=self.use_deepep,
replicate_weights=self.use_deepep or self.use_mega_moe,
parallelism="moe_shared",
)
self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
@@ -388,6 +414,10 @@ class Qwen3_5MoeSparseMoeBlock(nn.Module):
max_num_tokens_per_gpu: int,
ctx: ForwardContext,
) -> torch.Tensor:
if self.use_mega_moe:
return self._forward_mega_moe(
hidden_states, num_global_tokens, max_num_tokens_per_gpu, ctx
)
if self.use_deepep:
return self._forward_deepep(
hidden_states, num_global_tokens, max_num_tokens_per_gpu, ctx
@@ -396,6 +426,59 @@ class Qwen3_5MoeSparseMoeBlock(nn.Module):
hidden_states, num_global_tokens, max_num_tokens_per_gpu, ctx
)
def _forward_mega_moe(
self,
hidden_states: torch.Tensor,
num_global_tokens: int,
max_num_tokens_per_gpu: int,
ctx: ForwardContext,
) -> torch.Tensor:
"""Route already-scattered rows, including empty collective owners."""
num_tokens = hidden_states.shape[0]
if num_tokens > 0:
router_logits, _ = self.gate(hidden_states)
topk_output = self.topk(hidden_states, router_logits)
else:
router_logits = hidden_states.new_empty((0, self.experts.num_experts))
topk_output = self.topk.empty_topk_output(
hidden_states.device,
hidden_states=hidden_states,
router_logits=router_logits,
)
shared_output = None
# Fork after the router GEMM: shared GEMMs may reuse its dense scratch,
# while routed MegaMoE owns a separate workspace.
with self.stream_fork.scope(
enable=(
self.shared_expert is not None
and num_tokens > 0
and get_is_cuda_graph_phase()
),
overlap=get_is_capture_mode(),
) as fork:
with fork.branch():
if self.shared_expert is not None and num_tokens > 0:
shared_output = self.shared_expert(hidden_states)
# Empty owners must still enter the collective. The result is
# complete for local rows and aliases the reusable workspace.
output = self.experts(
hidden_states=hidden_states,
topk_output=topk_output,
num_global_tokens=num_global_tokens,
max_num_tokens_per_gpu=max_num_tokens_per_gpu,
do_finalize=True,
)
if shared_output is not None:
fused_gate_sigmoid_mul_add(
hidden_states,
self.shared_expert_gate.weight.squeeze(0),
shared_output,
output,
)
return output
def _forward_tp(
self,
hidden_states: torch.Tensor,
@@ -166,7 +166,7 @@ class Qwen3_5ForConditionalGenerationNextN(nn.Module):
if config.tie_word_embeddings:
self.lm_head = self.model.embed_tokens
else:
if self.mapping.attn.has_dp:
if self.mapping.attn.has_dp and not self.mapping.lm_head.has_tp:
self.lm_head = ReplicatedLinear(
config.hidden_size,
config.vocab_size,
@@ -179,20 +179,22 @@ class Qwen3_5ForConditionalGenerationNextN(nn.Module):
config.vocab_size,
config.hidden_size,
quant_config=quant_config,
tp_rank=self.mapping.attn.tp_rank,
tp_size=self.mapping.attn.tp_size,
tp_group=self.mapping.attn.tp_group,
tp_rank=self.mapping.lm_head.tp_rank,
tp_size=self.mapping.lm_head.tp_size,
tp_group=self.mapping.lm_head.tp_group,
prefix=add_prefix("lm_head", prefix),
)
# The shared target head follows mapping.lm_head. Under attention DP
# its replicated vocabulary can differ from the attention TP layout.
self.logits_processor = LogitsProcessor(
config,
skip_all_gather=self.mapping.attn.has_dp,
tp_rank=self.mapping.attn.tp_rank,
tp_size=self.mapping.attn.tp_size,
tp_group=self.mapping.attn.tp_group,
tp_rank=self.mapping.lm_head.tp_rank,
tp_size=self.mapping.lm_head.tp_size,
tp_group=self.mapping.lm_head.tp_group,
do_argmax=True,
dp_lm_head_tp=False,
dp_lm_head_tp=self.mapping.attn.has_dp and self.mapping.lm_head.has_tp,
)
def get_hot_token_id(self):
@@ -2416,6 +2416,24 @@ class ServerArgs:
self.validate_model_update_options()
if (
self.speculative_algorithm is not None
and self.disaggregation_mode != "prefill"
and self.max_num_seqs is not None
):
dp_size = self.mapping.attn.dp_size
tp_size = self.mapping.attn.tp_size
# Draft startup uses one request per TP peer, even when tactic
# profiling is disabled. Clamping would leave empty tuning peers;
# exceeding this capacity would overrun per-request decode state.
if self.max_num_seqs // dp_size < tp_size:
raise ValueError(
"Speculative decode warmup requires max_num_seqs // "
"data_parallel_size >= attn_tp_size, got "
f"{self.max_num_seqs} // {dp_size} < {tp_size}. "
f"Set --max-num-seqs to at least {dp_size * tp_size}."
)
if self.mapping.has_attn_dp:
if self.chunked_prefill_size > self.max_prefill_tokens:
raise ValueError(
@@ -0,0 +1,209 @@
# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""CPU layout regression; replace only GPU experts, routing and collectives.
NVFP4 arithmetic is covered by the Blackwell MegaMoE kernel test. Here the
real Qwen block, router projections, shared MLP and CommManager exercise
scattered layouts, uneven token shards and empty collective owners.
"""
from unittest.mock import patch
import pytest
import torch
import torch.nn.functional as F
from tokenspeed_kernel.ops.tuning import autotune, is_autotuning
from torch import nn
from tokenspeed.runtime.configs.qwen3_5_text_base_config import Qwen3_5BaseTextConfig
from tokenspeed.runtime.distributed.mapping import Mapping
from tokenspeed.runtime.execution.context import ForwardContext
from tokenspeed.runtime.layers.moe import topk as topk_module
from tokenspeed.runtime.layers.moe import utils as moe_utils
from tokenspeed.runtime.layers.moe.topk import TopKOutputFormat
from tokenspeed.runtime.layers.moe.utils import All2AllBackend, MoeBackend
from tokenspeed.runtime.models import qwen3_5_moe
from tokenspeed.runtime.models.qwen3_5_moe import Qwen3_5MoeSparseMoeBlock
class CPUExperts(nn.Module):
"""Stand-in for GPU experts: expert e computes (e+1)*x."""
def __init__(self, *, num_experts, hidden_size, **kwargs):
super().__init__()
self.num_experts = num_experts
self.hidden_size = hidden_size
self.topk_output_format = TopKOutputFormat.STANDARD
self.w13_input_scale_quant = torch.ones(1)
self.rows = None
def forward(self, *, hidden_states, topk_output, **kwargs):
x = hidden_states
self.rows = x.shape[0]
if not self.rows:
return torch.empty((0, self.hidden_size))
factor = (topk_output.topk_weights * (topk_output.topk_ids + 1)).sum(-1)
return x * factor[:, None]
def _cpu_topk(logits, k, *, renormalize, **kwargs):
weights, ids = logits.float().softmax(-1).topk(k, dim=-1)
if renormalize:
weights = weights / weights.sum(-1, keepdim=True)
return weights, ids
def _cpu_shared_add(x, gate, shared, output):
output.add_(torch.sigmoid(x @ gate)[:, None] * shared)
@pytest.mark.parametrize("attn_tp", [1, 2, 4])
@pytest.mark.parametrize("tokens", [0, 1, 3, 8, 11])
@pytest.mark.parametrize("tune_mode", [False, True])
@pytest.mark.parametrize("shared", [False, True])
def test_mega_moe_restores_attention_rows(attn_tp, tokens, shared, tune_mode):
hidden = 32
config = Qwen3_5BaseTextConfig(
hidden_size=hidden,
num_experts=8,
num_experts_per_tok=2,
moe_intermediate_size=32,
shared_expert_intermediate_size=32 if shared else 0,
)
for rank in range(8):
torch.manual_seed(42)
mapping = Mapping(
rank=rank,
world_size=8,
attn_tp_size=attn_tp,
dense_tp_size=attn_tp,
moe_tp_size=1,
moe_ep_size=8,
)
with (
patch.object(moe_utils, "MOE_BACKEND", MoeBackend.MEGA_MOE),
patch.object(moe_utils, "ALL2ALL_BACKEND", All2AllBackend.NONE),
patch.object(qwen3_5_moe, "MoELayer", CPUExperts),
):
block = Qwen3_5MoeSparseMoeBlock(config, mapping)
with torch.no_grad():
for p in block.parameters():
p.uniform_(-0.1, 0.1)
x = torch.randn(tokens, hidden)
weights, ids = _cpu_topk(F.linear(x, block.gate.weight), 2, renormalize=True)
expected = x * (weights * (ids + 1)).sum(-1, keepdim=True)
if shared:
gate, up = F.linear(x, block.shared_expert.gate_up_proj.weight).chunk(2, -1)
shared_out = F.linear(
F.silu(gate) * up, block.shared_expert.down_proj.weight
)
expected += (
F.linear(x, block.shared_expert_gate.weight).sigmoid() * shared_out
)
ctx = ForwardContext(
attn_backend=None,
token_to_kv_pool=None,
bs=1,
num_extends=1,
input_num_tokens=tokens,
forward_mode=None,
output_layout=None,
global_num_tokens=[tokens] * 8,
)
parts = torch.tensor_split(x, attn_tp)
expected_parts = torch.tensor_split(expected, attn_tp)
local_rank = mapping.attn.tp_rank
inputs = parts[local_rank]
wanted = expected_parts[local_rank]
with (
autotune(tune_mode=tune_mode, tuning_buckets=None, round_up=None),
patch.object(topk_module, "moe_topk", _cpu_topk),
patch.object(qwen3_5_moe, "fused_gate_sigmoid_mul_add", _cpu_shared_add),
):
total, capacity = block.comm_manager.get_num_tokens(ctx)
actual = block(inputs, total, capacity, ctx)
assert is_autotuning() == tune_mode
torch.testing.assert_close(actual, wanted)
assert block.experts.rows == len(parts[local_rank])
@pytest.mark.parametrize(
"moe_tp,moe_ep,all2all,options,message",
[
(8, 1, All2AllBackend.NONE, {}, "EP>1"),
(1, 8, All2AllBackend.DEEPEP, {}, "all2all-backend none"),
(1, 8, All2AllBackend.NONE, {"enable_eplb": True}, "trivial expert placement"),
(
1,
8,
All2AllBackend.NONE,
{"ep_num_redundant_experts": 1},
"trivial expert placement",
),
(
1,
8,
All2AllBackend.NONE,
{"init_expert_location": "random"},
"trivial expert placement",
),
],
)
def test_mega_moe_rejects_incompatible_options(
moe_tp, moe_ep, all2all, options, message
):
config = Qwen3_5BaseTextConfig(hidden_size=32, num_experts=8)
mapping = Mapping(
rank=0,
world_size=8,
attn_tp_size=2,
dense_tp_size=2,
moe_tp_size=moe_tp,
moe_ep_size=moe_ep,
)
with (
patch.object(moe_utils, "MOE_BACKEND", MoeBackend.MEGA_MOE),
patch.object(moe_utils, "ALL2ALL_BACKEND", all2all),
patch.dict(qwen3_5_moe.global_server_args_dict, options, clear=True),
pytest.raises(ValueError, match=message),
):
Qwen3_5MoeSparseMoeBlock(config, mapping)
@pytest.mark.parametrize("attn_tp,ep", [(8, 8), (4, 4), (2, 2)])
def test_mega_moe_rejects_replicated_rows(attn_tp, ep):
config = Qwen3_5BaseTextConfig(hidden_size=32, num_experts=8)
mapping = Mapping(
rank=0,
world_size=8,
attn_tp_size=attn_tp,
dense_tp_size=attn_tp,
moe_tp_size=1,
moe_ep_size=ep,
)
with (
patch.object(moe_utils, "MOE_BACKEND", MoeBackend.MEGA_MOE),
patch.object(moe_utils, "ALL2ALL_BACKEND", All2AllBackend.NONE),
patch.dict(qwen3_5_moe.global_server_args_dict, {}, clear=True),
pytest.raises(ValueError, match="requires scattered MoE rows"),
):
Qwen3_5MoeSparseMoeBlock(config, mapping)
+68 -2
View File
@@ -96,6 +96,7 @@ class _AutotuneConfig:
max_num_seqs: int = 8
data_parallel_size: int = 1
attention_tp_size: int = 1
chunked_prefill_size: int = -1
context_len: int = 4
world_size: int = 1
@@ -194,13 +195,21 @@ class _ProcessGroupManagerDouble:
return self._group
@pytest.mark.parametrize("attention_tp_size", [1, 2, 8])
@pytest.mark.parametrize("chunk_size", [-1, 16, 17])
@pytest.mark.parametrize("speculative", [False, True])
@pytest.mark.parametrize("disabled", [False, True])
@pytest.mark.parametrize("failure", [False, True])
@pytest.mark.parametrize("prefill_only", [False, True])
def test_startup_uses_native_buckets_without_reading_capture_sizes(
monkeypatch, tmp_path, chunk_size, speculative, disabled, failure, prefill_only
monkeypatch,
tmp_path,
chunk_size,
speculative,
disabled,
failure,
prefill_only,
attention_tp_size,
):
events = []
metadata = []
@@ -230,7 +239,10 @@ def test_startup_uses_native_buckets_without_reading_capture_sizes(
raise RuntimeError("profiling failed")
def draft(*, batch_sizes, graph_phase):
assert batch_sizes == (1,)
assert batch_sizes == (attention_tp_size,)
assert tuning_module.is_autotuning() is (
not disabled and tuning_module._autotuner is not None
)
assert graph_phase is False
assert tuning_module.is_warming_up()
events.append("draft")
@@ -243,6 +255,7 @@ def test_startup_uses_native_buckets_without_reading_capture_sizes(
executor = _AutotuneExecutor(
config=_AutotuneConfig(
chunked_prefill_size=chunk_size,
attention_tp_size=attention_tp_size,
autotune_cache_key={},
disable_autotune=disabled,
prefill_only=prefill_only,
@@ -649,6 +662,59 @@ class _ModelConfigDouble:
quantization: str | None
@pytest.mark.parametrize("tp,dp,max_num_seqs", [(8, 1, 4), (2, 4, 4), (2, 4, 7)])
@pytest.mark.parametrize("disable_autotune", [False, True])
@pytest.mark.parametrize("role", ["null", "decode"])
def test_speculative_warmup_rejects_capacity_below_attention_tp(
tp, dp, max_num_seqs, disable_autotune, role
):
with pytest.raises(ValueError, match=f"Set --max-num-seqs to at least {tp * dp}"):
ServerArgs(
model="x",
dtype="bfloat16",
world_size=tp * dp,
attn_tp_size=tp,
data_parallel_size=dp,
ep_size=tp * dp,
max_num_seqs=max_num_seqs,
speculative_algorithm="MTP",
disable_autotune=disable_autotune,
disaggregation_mode=role,
)
@pytest.mark.parametrize(
"tp,dp,max_num_seqs", [(8, 1, 8), (2, 4, 8), (2, 4, 9), (1, 8, 8)]
)
def test_speculative_warmup_accepts_capacity_covering_attention_tp(
tp, dp, max_num_seqs
):
args = ServerArgs(
model="x",
dtype="bfloat16",
world_size=tp * dp,
attn_tp_size=tp,
data_parallel_size=dp,
ep_size=tp * dp,
max_num_seqs=max_num_seqs,
speculative_algorithm="MTP",
)
assert args.max_num_seqs == max_num_seqs
@pytest.mark.parametrize("algorithm,role", [(None, "null"), ("MTP", "prefill")])
def test_small_capacity_without_draft_decode_warmup_is_preserved(algorithm, role):
args = ServerArgs(
model="x",
dtype="bfloat16",
attn_tp_size=8,
max_num_seqs=4,
speculative_algorithm=algorithm,
disaggregation_mode=role,
)
assert args.max_num_seqs == 4
def test_pipeline_stages_share_shape_keyed_cache_identity():
# Real args: attn_tp_size=2 infers world_size=2 and resolves dense/moe/
# linear-attention widths to the same 2 with moe ep/dp and pp at 1.
+134 -8
View File
@@ -4,8 +4,12 @@ from unittest import mock
import pytest
import torch
from torch import nn
from transformers import PretrainedConfig
import tokenspeed.runtime.layers.logits_processor as logits_module
import tokenspeed.runtime.models.qwen3_5_nextn as nextn_module
from tokenspeed.runtime.distributed.mapping import Mapping
from tokenspeed.runtime.execution.factory import _check_shared_head_layout
from tokenspeed.runtime.execution.forward_batch_info import ForwardMode
from tokenspeed.runtime.layers.dense.nvfp4 import Nvfp4W4A16LinearMethod
from tokenspeed.runtime.layers.logits_processor import (
@@ -15,6 +19,7 @@ from tokenspeed.runtime.layers.logits_processor import (
)
from tokenspeed.runtime.layers.quantization.modelopt_mixed import ModelOptMixedConfig
from tokenspeed.runtime.layers.quantization.nvfp4 import Nvfp4Config
from tokenspeed.runtime.models.base.causal_lm import BaseCausalLM
from tokenspeed.runtime.models.qwen3_5_nextn import (
Qwen3_5ForConditionalGenerationNextN,
_resolve_mtp_quant_config,
@@ -49,14 +54,7 @@ def test_attention_dp_draft_lm_head_receives_quant_config(monkeypatch):
monkeypatch.setattr(
nextn_module, "LogitsProcessor", mock.Mock(return_value=nn.Module())
)
mapping = SimpleNamespace(
attn=SimpleNamespace(
has_dp=True,
tp_rank=0,
tp_size=1,
tp_group=None,
)
)
mapping = Mapping(rank=0, world_size=2, attn_tp_size=1, attn_dp_size=2)
config = SimpleNamespace(
hidden_size=4,
vocab_size=8,
@@ -81,6 +79,134 @@ def test_attention_dp_draft_lm_head_receives_quant_config(monkeypatch):
)
class _EmbeddingOnlyDraft(nn.Module):
"""CPU stand-in for the transformer; only its shared embedding is needed."""
def __init__(self, config, mapping, quant_config, prefix):
super().__init__()
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
class _HeadOnlyTarget(BaseCausalLM):
model_cls = _EmbeddingOnlyDraft
@pytest.mark.parametrize("rank", range(8))
@pytest.mark.parametrize("attn_tp", [1, 2, 4])
@pytest.mark.parametrize("tied", [False, True])
def test_attention_dp_mtp_shares_target_head_layout(monkeypatch, rank, attn_tp, tied):
mapping = Mapping(
rank=rank, world_size=8, attn_tp_size=attn_tp, attn_dp_size=8 // attn_tp
)
config = PretrainedConfig(
hidden_size=4,
vocab_size=8,
rms_norm_eps=1e-6,
num_hidden_layers=1,
tie_word_embeddings=tied,
)
# The GPU transformer and CUDA cache management are outside this test;
# the head, logits processors and factory layout check are real classes.
monkeypatch.setattr(nextn_module, "Qwen3_5DraftForCausalLM", _EmbeddingOnlyDraft)
monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None)
monkeypatch.setattr(torch.cuda, "synchronize", lambda: None)
target = _HeadOnlyTarget(config, mapping)
with torch.no_grad():
target.lm_head.weight.copy_(
torch.arange(target.lm_head.weight.numel()).reshape_as(
target.lm_head.weight
)
/ 100
- 0.16
)
draft = Qwen3_5ForConditionalGenerationNextN(config, mapping)
_check_shared_head_layout(target, draft)
draft.set_embed_and_head_module(target.model.embed_tokens.weight, target.lm_head)
hidden = (
torch.arange(3 * config.hidden_size, dtype=torch.float32).reshape(3, -1) / 7
)
metadata = LogitsMetadata(forward_mode=ForwardMode.DECODE, query_shard=None)
actual = draft.logits_processor._get_logits(
hidden, draft.lm_head, metadata, require_full_vocab=False
)
expected = torch.nn.functional.linear(hidden, target.lm_head.weight)
torch.testing.assert_close(actual, expected)
@pytest.mark.parametrize("rank", range(8))
def test_attention_dp_mtp_shares_vocab_sharded_head(monkeypatch, rank):
mapping = Mapping(
rank=rank, world_size=8, attn_tp_size=1, attn_dp_size=8, lm_head_tp_size=2
)
config = PretrainedConfig(
hidden_size=4,
vocab_size=128,
rms_norm_eps=1e-6,
num_hidden_layers=1,
tie_word_embeddings=False,
)
monkeypatch.setattr(nextn_module, "Qwen3_5DraftForCausalLM", _EmbeddingOnlyDraft)
monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None)
monkeypatch.setattr(torch.cuda, "synchronize", lambda: None)
target = _HeadOnlyTarget(config, mapping)
draft = Qwen3_5ForConditionalGenerationNextN(config, mapping)
_check_shared_head_layout(target, draft)
full_weight = torch.arange(128 * 4, dtype=torch.float32).reshape(128, 4) / 100
width = target.lm_head.weight.shape[0]
start = mapping.lm_head.tp_rank * width
with torch.no_grad():
target.lm_head.weight.copy_(full_weight[start : start + width])
draft.set_embed_and_head_module(target.model.embed_tokens.weight, target.lm_head)
rows = [1 + r % 3 for r in range(8)]
hidden = [
torch.arange(n * 4, dtype=torch.float32).reshape(n, 4) / 7 + r
for r, n in enumerate(rows)
]
# Only the distributed transport is simulated on CPU. The real target and
# draft heads, layout validation, and logits GEMM handle distinct DP rows
# and vocabulary shards; the peer contributes its independently computed shard.
def gather(local, group, counts):
return torch.cat(
[
(local if r == rank else hidden[r])[:count]
for r, count in zip(group, counts)
]
)
def transpose(local_logits, group, *, input_split_sizes):
offset = sum(input_split_sizes[: group.index(rank)])
return torch.cat(
[
(
local_logits[offset : offset + rows[rank]]
if r == rank
else torch.nn.functional.linear(
hidden[rank], full_weight[i * width : (i + 1) * width]
)
)
for i, r in enumerate(group)
],
dim=1,
)
monkeypatch.setattr(logits_module, "token_all_gather", gather)
monkeypatch.setattr(logits_module, "all_to_all_transpose", transpose)
metadata = LogitsMetadata(
forward_mode=ForwardMode.DECODE,
query_shard=None,
global_num_tokens=rows,
all_decode_or_idle=True,
)
actual = draft.logits_processor._get_logits(
hidden[rank], draft.lm_head, metadata, require_full_vocab=False
)
torch.testing.assert_close(
actual, torch.nn.functional.linear(hidden[rank], full_weight)
)
class _DraftModel(nn.Module):
def __init__(self, tied: bool):
super().__init__()
@@ -455,3 +455,84 @@ over 896 experts. It consumes contiguous FP32 logits and bias and writes
normalized FP32 weights (scale 1) and INT32 IDs into caller-owned buffers.
The routing-only kernel has no expert-plan workspace or 8,192-token limit.
Other contracts retain their existing routers.
## NVFP4 MegaMoE for Qwen3.5
The `mega_moe` NVFP4 adapter supports gated SiLU (`silu(gate) * up`) and
Kimi K3 SiTU. Gated SiLU selects the existing kernel epilogue with both SiTU
parameters set to `None`. BF16 inputs are quantized and staged with routing
directly into the symmetric workspace in one kernel, including masking unused
capacity rows. BF16 staging rejects routing tensors whose row counts differ
from the live activation count before launching the staging kernel.
Prequantized packed E2M1 inputs with linear E4M3 block scales
remain supported for existing callers. `get_runner` requires an explicit
`prequantized=True` for packed NVFP4 inputs (including direct workspace writes),
or `prequantized=False` for fused BF16 quantization and staging.
Input format is part of the runner's
tuning key, and calibrated input scales stay runtime tensors across graph replay;
weights are converted once to interleaved gate/up rows and blocked scales.
Gate/up global weight scales must match. The adapter currently targets
SM100/SM103 and requires MoE TP=1.
Qwen3.5 uses precomputed Qwen top-k and a separate, fully replicated shared
expert with its original sigmoid gate. Select
`--moe-backend mega_moe --all2all-backend none` with NVFP4 routed weights,
MoE TP=1 and EP>1. Attention rows must already be scattered before the MoE,
for example DP4/TP2/EP8 or DP8/TP1/EP8. Layouts with attention TP equal to
MoE TP*EP (including TP8/EP8) are rejected before weights are constructed.
The common communication manager handles input and final normalization and
row gathering; the model needs no additional all-reduce bypass or row slicing.
`Qwen3_5MoeSparseMoeBlock` checks MegaMoE options during construction: EPLB, redundant experts, nontrivial placement
and external all-to-all backends are unsupported. The NVFP4 weight adapter
checks MoE TP=1. Weight dtype, activation and
hardware compatibility are checked by the common MoE kernel planner.
All ranks, including empty token owners, must enter the expert call with the
same capacity. Existing runner warmup and autotuning reserve the workspace
before graph capture; returned outputs alias that workspace. Shared experts
run independently on the existing auxiliary stream during CUDA graph capture
and replay, overlapping routed experts; the streams join before applying the
shared sigmoid gate and gathering rows. Warmup retains serialized execution
so kernel tuning and compilation finish before capture.
Run the kernel regression on Blackwell, for example:
```bash
PYTHONPATH="tokenspeed-kernel/test:$PYTHONPATH" torchrun --standalone --nproc-per-node=2 \
tokenspeed-kernel/test/nvidia/ops/moe/test_trtllm_mega_moe.py \
--activation silu --input-format bf16 --intermediate-size 192 --capacity 8 --tokens 5
```
Repeat with `--input-format nvfp4` to cover prequantized inputs, and with
`--autotune` for tactic coverage. The test compares a dequantized
reference, uneven/idle ranks, graph replay and alternating capacities.
`test_trtllm_mega_moe_input_stage.py` separately checks byte-exact packed data
and scales against FlashInfer quantization, INT32/INT64 route inputs and outputs,
zero-token owners, changing live counts and alternating captured graphs on the
same workspace, with a compile guard across changing live counts.
The stager converts route IDs and scores to their destination buffer dtypes
and keys compiled specializations by all input and output dtypes; current
MegaMoE workspaces store INT32 IDs.
Qwen3.5 follows K3's empty-owner path: gate, top-k, quantization and shared
expert work are skipped when there are no local tokens, but the rank still
participates in the collective MegaMoE call. Nonempty ranks use normal tuning;
the model does not disable GEMM tuning for uneven batches.
MegaMoE reserves scratch for all candidate tactics before CUDA graph capture,
whether tactic autotuning is enabled or disabled. With tuning disabled,
`forward()` selects the original capacity-based default; enabling
`MEGAMOE_TACTIC_AUTOTUNE=1` searches the candidates. The candidate set excludes
FC2 write-back tactics. Token capacity and persistent addresses do not change,
and launches with an unreserved tactic or capacity are rejected.
The temporary full-capacity workspace experiment reserves the configured maximum
per-rank token capacity before capture, including the prefill ceiling (8192 in
the capacity test) and the MTP verification batch (64 requests times 4 tokens).
This follows the serving-capacity allocation policy of vLLM's MegaMoE buffer;
the CuTe kernel retains its own layouts and alignment. Each forward executes
one collective with no 128-token chunk loop. All layers and captured capacities
continue to share stable workspace addresses. Kimi K3 writes packed activations
and routes directly into views of this full-capacity symmetric allocation.
@@ -38,7 +38,7 @@ def trtllm_mega_moe_process_weights(plan: dict, w: torch.nn.Module) -> None:
raise ValueError("NVFP4 MegaMoE requires MoE TP=1")
gate_scale, up_scale = w.w13_weight_scale_2.unbind(dim=1)
if not torch.equal(gate_scale, up_scale):
raise ValueError("NVFP4 SiTU MegaMoE requires equal gate/up weight_scale_2")
raise ValueError("NVFP4 MegaMoE requires equal gate/up weight_scale_2")
experts = w.num_local_experts
intermediate = w.intermediate_size
for name in ("w13_weight", "w13_weight_scale"):
@@ -92,7 +92,7 @@ def trtllm_mega_moe_process_weights(plan: dict, w: torch.nn.Module) -> None:
signatures=format_signatures("x", "dense", {torch.bfloat16, torch.uint8}),
traits={
"weight_dtype": frozenset({"nvfp4"}),
"activation": frozenset({"situ"}),
"activation": frozenset({"silu", "situ"}),
"routing_mode": frozenset({"precomputed_topk"}),
"supports_deferred_finalize": frozenset({False}),
"supports_ep": frozenset({True}),
@@ -105,7 +105,7 @@ def trtllm_mega_moe_process_weights(plan: dict, w: torch.nn.Module) -> None:
)
def trtllm_nvfp4_mega_moe_apply(
plan: dict,
x: tuple[torch.Tensor, torch.Tensor],
x: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
w: torch.nn.Module,
router_logits: torch.Tensor | None,
topk_weights: torch.Tensor,
@@ -115,7 +115,7 @@ def trtllm_nvfp4_mega_moe_apply(
do_finalize: bool,
enable_pdl: bool,
) -> torch.Tensor:
"""Dispatch NVFP4 tokens, run SiTU experts, and combine on the source ranks.
"""Dispatch NVFP4 tokens, run gated SiLU or SiTU experts, and combine on the source ranks.
Uses the upstream heuristic by default. Set MEGAMOE_TACTIC_AUTOTUNE=1
identically on every EP rank before startup to participate in FlashInfer's
@@ -128,7 +128,7 @@ def trtllm_nvfp4_mega_moe_apply(
Args:
plan: Selected NVFP4 MoE plan containing the EP process group.
x: Packed E2M1 activations and linear E4M3 block scales.
x: BF16 activations, or packed E2M1 activations and linear E4M3 scales.
w: Local expert module with MegaMoE-prepared weights.
router_logits: Unused; routes are supplied explicitly.
topk_weights: Final routing weights, including the model routing scale.
@@ -144,11 +144,12 @@ def trtllm_nvfp4_mega_moe_apply(
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe.runner import get_runner
del router_logits, num_tokens_global, enable_pdl
if not do_finalize or not isinstance(x, tuple):
raise ValueError(
"MegaMoE requires prequantized inputs and complete finalization"
)
runner = get_runner(plan, w)
if not do_finalize:
raise ValueError("MegaMoE requires complete finalization")
prequantized = isinstance(x, tuple)
if not prequantized and x.dtype != torch.bfloat16:
raise ValueError("MegaMoE requires BF16 or prequantized NVFP4 inputs")
runner = get_runner(plan, w, prequantized=prequantized)
weights = (
w.w13_weight,
w.w13_weight_scale,
@@ -158,4 +159,7 @@ def trtllm_nvfp4_mega_moe_apply(
w.mega_fc2_alpha,
w.mega_fc1_norm,
)
return runner.run(x, topk_ids, topk_weights, weights, max_num_tokens_per_gpu)
routed_input = x if prequantized else (x, w.w13_input_scale_quant)
return runner.run(
routed_input, topk_ids, topk_weights, weights, max_num_tokens_per_gpu
)
@@ -6,6 +6,10 @@ Revision: `d1166c722ad3b81d7809c9ea98c05e0f1f860248`.
Upstream files retain their Apache-2.0 notices; see LICENSE.
Local adaptation: package imports use the TokenSpeed kernel namespace; formatting follows the repository hooks.
`runner.py` is the TokenSpeed host adapter; it owns symmetric workspaces and launches.
`input_stage.py` is the TokenSpeed BF16-to-workspace adapter. Its input-quantization
scaling order follows FlashInfer's CUDA NVFP4 recipe, including the reciprocal
of the product of block and global decode scales; it stages routing in the same
launch. The expert epilogue keeps the TensorRT-LLM implementation above.
`dynamic_mainloop.py` separates NVVM operand-version detection from the CTA group enum rename for CuTeDSL 4.7.
@@ -0,0 +1,174 @@
# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Quantize BF16 rows and stage routes directly into the MegaMoE workspace."""
import cuda.bindings.driver as cuda
import cutlass
import cutlass.cute as cute
import cutlass.torch as cutlass_torch
import torch
@cute.jit
def _aligned(tensor: cute.Tensor, alignment: cutlass.Constexpr):
pointer = tensor.iterator
return cute.make_tensor(
cute.make_ptr(
pointer.dtype,
pointer.toint(),
pointer.memspace,
assumed_align=alignment,
),
tensor.layout,
)
class _Nvfp4InputStageKernel:
def __init__(self, hidden: int, top_k: int):
self.hidden = hidden
self.top_k = top_k
@cute.jit
def __call__(
self,
x: cute.Tensor,
input_scale: cute.Tensor,
ids: cute.Tensor,
scores: cute.Tensor,
q_out: cute.Tensor,
sf_out: cute.Tensor,
ids_out: cute.Tensor,
scores_out: cute.Tensor,
stream: cuda.CUstream,
):
self.stage(
x, input_scale, ids, scores, q_out, sf_out, ids_out, scores_out
).launch(grid=(q_out.shape[0], 1, 1), block=(128, 1, 1), stream=stream)
@cute.kernel
def stage(
self,
x: cute.Tensor,
input_scale: cute.Tensor,
ids: cute.Tensor,
scores: cute.Tensor,
q_out: cute.Tensor,
sf_out: cute.Tensor,
ids_out: cute.Tensor,
scores_out: cute.Tensor,
):
row = cute.arch.block_idx()[0]
tid = cute.arch.thread_idx()[0]
live = row < x.shape[0]
if live:
source = cute.zipped_divide(x[row, None], (16,))
target = cute.zipped_divide(q_out[row, None], (16,))
load = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), cutlass.BFloat16, num_bits_per_copy=128
)
store = cute.make_copy_atom(
cute.nvgpu.CopyUniversalOp(), cutlass.Float4E2M1FN, num_bits_per_copy=64
)
norm = cutlass.Float32(input_scale[0])
decode_global = cute.arch.rcp_approx(norm)
reciprocal_six = cute.arch.rcp_approx(cutlass.Float32(6.0))
for block in cutlass.range(tid, self.hidden // 16, 128, unroll=1):
values_bf16 = cute.make_rmem_tensor((16,), cutlass.BFloat16)
cute.copy(load, _aligned(source[(None,), (block,)], 16), values_bf16)
values = cute.make_rmem_tensor((16,), cutlass.Float32)
values.store(values_bf16.load().to(cutlass.Float32))
amax = cutlass.Float32(0.0)
for i in cutlass.range_constexpr(16):
amax = cute.arch.fmax(amax, cute.arch.fmax(values[i], -values[i]))
scale = (norm * (amax * reciprocal_six)).to(cutlass.Float8E4M3FN)
# Match FlashInfer CUDA's encode scale. norm * rcp(scale)
# differs at FP4 ties from rcp(scale * rcp(norm)).
encode = cutlass.Float32(0.0)
if amax != cutlass.Float32(0.0):
encode = cute.arch.rcp_approx(
cutlass.Float32(scale) * decode_global
)
packed = cute.make_rmem_tensor((16,), cutlass.Float4E2M1FN)
scaled = values.load() * cute.full_like(values, encode, cutlass.Float32)
packed.store(scaled.to(cutlass.Float4E2M1FN))
cute.copy(store, packed, _aligned(target[(None,), (block,)], 8))
sf_out[row, block] = scale
# Mask the entire capacity tail in the same launch. Counts are runtime
# tensor extents, so eager and graphs use the same padding contract.
if tid < self.top_k:
expert = cutlass.Int64(-1)
score = cutlass.Float32(0.0)
if live:
expert = cutlass.Int64(ids[row, tid])
score = cutlass.Float32(scores[row, tid])
ids_out[row, tid] = expert.to(ids_out.element_type)
scores_out[row, tid] = score.to(scores_out.element_type)
def _view(tensor: torch.Tensor, alignment: int):
result = cutlass_torch.from_dlpack(tensor, assumed_align=alignment)
return result.mark_layout_dynamic(leading_dim=cutlass_torch.get_leading_dim(tensor))
class Nvfp4InputStage:
def __init__(self, hidden: int, top_k: int):
if hidden % 64 != 0 or not 0 < top_k <= 128:
raise ValueError(
"NVFP4 input staging requires hidden % 64 == 0 and top_k <= 128"
)
self.kernel = _Nvfp4InputStageKernel(hidden, top_k)
self.compiled: dict[tuple, object] = {}
def run(self, x, input_scale, ids, scores, q_out, sf_out, ids_out, scores_out):
"""Write live quantized rows and masked tail routes into caller-owned buffers."""
if not x.shape[0] == ids.shape[0] == scores.shape[0]:
raise ValueError("MegaMoE route rows must match activation rows")
key = (
x.dtype,
input_scale.dtype,
ids.dtype,
scores.dtype,
q_out.dtype,
sf_out.dtype,
ids_out.dtype,
scores_out.dtype,
)
arguments = (
_view(x, 16),
_view(input_scale, 4),
_view(ids, 4),
_view(scores, 4),
_view(q_out.view(torch.float4_e2m1fn_x2), 16),
_view(sf_out, 4),
_view(ids_out, 4),
_view(scores_out, 4),
cuda.CUstream(torch.cuda.current_stream().cuda_stream),
)
compiled = self.compiled.get(key)
if compiled is None:
if torch.cuda.is_current_stream_capturing():
raise RuntimeError(
"MegaMoE input staging requires eager warmup before capture"
)
compiled = cute.compile(self.kernel, *arguments)
self.compiled[key] = compiled
compiled(*arguments)
@@ -21,6 +21,7 @@
from __future__ import annotations
import itertools
import logging
import os
import cuda.bindings.driver as cuda
@@ -43,6 +44,7 @@ from flashinfer.autotuner import (
is_in_profile_measurement,
)
from tokenspeed_kernel.ops.tuning import get_autotune_max_num_tokens
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe.input_stage import Nvfp4InputStage
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe.megamoe_kernel import (
Sm100MegaMoEKernel,
_layout_regions,
@@ -77,6 +79,10 @@ def _init_fp4(shapes, dtype, device):
return torch.randint(0, 256, shapes, dtype=dtype, device=device)
def _init_bf16(shapes, dtype, device):
return torch.randn(shapes, dtype=dtype, device=device)
def _init_scales(shapes, dtype, device):
return torch.ones(shapes, dtype=torch.float8_e4m3fn, device=device).view(dtype)
@@ -98,14 +104,18 @@ class MegaMoEWorkspace:
intermediate: int,
top_k: int,
capacity: int,
situ_beta: float,
situ_linear_beta: float,
situ_beta: float | None,
situ_linear_beta: float | None,
*,
prequantized: bool,
):
self.capacity = capacity
self.hidden = hidden
self.intermediate = intermediate
self.num_experts = num_experts
self.top_k = top_k
self.prequantized = prequantized
self.input_stage = None if prequantized else Nvfp4InputStage(hidden, top_k)
self.situ_beta = situ_beta
self.situ_linear_beta = situ_linear_beta
self.world = dist.get_world_size(group)
@@ -124,6 +134,7 @@ class MegaMoEWorkspace:
and situ_linear_beta == 25.0
)
self.key = (
id(group),
torch.cuda.current_device(),
self.world,
num_experts,
@@ -133,6 +144,7 @@ class MegaMoEWorkspace:
capacity,
situ_beta,
situ_linear_beta,
prequantized,
)
self.kernels = {
(capacity, tactic): self._make_kernel(capacity, tactic)
@@ -196,6 +208,12 @@ class MegaMoEWorkspace:
self.output = torch.empty(
(capacity, hidden), dtype=torch.bfloat16, device=device
)
logging.getLogger(__name__).info(
f"MegaMoE workspace: ep_rank={dist.get_rank(group)}, "
f"capacity={capacity}, tactics={len(_TACTICS)}, "
f"local_bytes={self.local.nbytes}, symmetric_bytes={self.storage.nbytes}, "
f"output_bytes={self.output.nbytes}, route_bytes={self.topk_ids.nbytes}"
)
self.mapper = SymBufferHost(
offsets=tuple(
int(p) - self.storage.data_ptr() for p in self.handle.buffer_ptrs
@@ -268,6 +286,10 @@ class MegaMoEWorkspace:
)
def _kernel(self, capacity: int, tactic: tuple):
if capacity > self.capacity or tactic not in _TACTICS:
raise ValueError(
"MegaMoE capacity or tactic was not reserved before capture"
)
key = (capacity, tactic)
kernel = self.kernels.get(key)
if kernel is None:
@@ -347,7 +369,19 @@ class MegaMoEWorkspace:
if not tokens <= capacity <= self.capacity:
raise ValueError("MegaMoE token count exceeds workspace capacity")
kernel = self._kernel(capacity, tactic)
self.stage_inputs(x, topk_ids, topk_weights, capacity)
if self.prequantized:
self.stage_inputs(x, topk_ids, topk_weights, capacity)
else:
self.input_stage.run(
x[0],
x[1],
topk_ids,
topk_weights,
self.x[:capacity],
self.scales[:capacity],
self.topk_ids[:capacity],
self.topk_weights[:capacity],
)
profiling = is_in_profile_measurement()
key = (capacity, tactic, *[t.data_ptr() for t in weights], output.data_ptr())
# Do not retain temporary profiling clones through cached DLPack views.
@@ -423,9 +457,12 @@ class MegaMoERunner(TunableRunner):
hidden: int,
intermediate: int,
top_k: int,
situ_beta: float,
situ_linear_beta: float,
situ_beta: float | None,
situ_linear_beta: float | None,
max_capacity: int,
*,
prequantized: bool,
tactic_autotune: bool,
):
self.group = group
self.world = dist.get_world_size(group)
@@ -438,9 +475,10 @@ class MegaMoERunner(TunableRunner):
self.situ_beta = situ_beta
self.situ_linear_beta = situ_linear_beta
self.max_capacity = max_capacity
self.tactic_autotune = os.environ.get("MEGAMOE_TACTIC_AUTOTUNE", "0") == "1"
self.prequantized = prequantized
self.tactic_autotune = tactic_autotune
self._extras = (
"nvfp4_situ_bf16_graph_fixed_workspace_epi_only_v10_blackwell_small_cap124",
"nvfp4_full_collective_workspace_v7_blackwell_small_cap124",
self.world,
num_experts,
hidden,
@@ -449,6 +487,8 @@ class MegaMoERunner(TunableRunner):
situ_beta,
situ_linear_beta,
max_capacity,
prequantized,
self.tactic_autotune,
)
self._key = (group, self.device, *self._extras)
self.workspace: MegaMoEWorkspace | None = None
@@ -467,11 +507,12 @@ class MegaMoERunner(TunableRunner):
DynamicTensorSpec((11,), (0,), _token_buckets, _token_capacity),
),
constraint_specs=tuple(
ConstraintSpec(i, 0, lambda shapes: shapes[11][0]) for i in range(4)
ConstraintSpec(i, 0, lambda shapes: shapes[11][0])
for i in ((0, 1, 2, 3) if prequantized else (0, 2, 3))
),
tensor_initializers=(
(0, _init_fp4),
(1, _init_scales),
(0, _init_fp4 if prequantized else _init_bf16),
(1, _init_scales if prequantized else autotuner_initializer_ones),
(2, init_routes),
(3, autotuner_initializer_ones),
(11, autotuner_initializer_empty),
@@ -541,6 +582,7 @@ class MegaMoERunner(TunableRunner):
self.max_capacity,
self.situ_beta,
self.situ_linear_beta,
prequantized=self.prequantized,
)
return self.workspace
@@ -548,16 +590,20 @@ class MegaMoERunner(TunableRunner):
self, tokens: int, max_tokens: int
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
capacity = _token_capacity(max_tokens)
if capacity > self.max_capacity:
if not self.prequantized:
raise ValueError("Direct input buffers require prequantized MegaMoE")
if not 0 <= tokens <= max_tokens or capacity > self.max_capacity:
raise ValueError("MegaMoE token count exceeds the configured maximum")
return self._ensure_workspace().input_buffers(tokens, capacity)
workspace = self._ensure_workspace()
return workspace.input_buffers(tokens, capacity)
def run(self, x, topk_ids, topk_weights, weights, max_tokens: int):
capacity = _token_capacity(max_tokens)
if capacity > self.max_capacity:
raise ValueError("MegaMoE token count exceeds the configured maximum")
workspace = self._ensure_workspace()
# All ranks use the same capacity, including ranks with no local tokens.
if x[0].shape[0] > max_tokens:
raise ValueError("MegaMoE local rows exceed the collective token bound")
inputs = [
*x,
topk_ids,
@@ -592,8 +638,11 @@ class MegaMoERunner(TunableRunner):
return chosen(inputs=inputs, tactic=tactic)
def get_runner(plan: dict, w: torch.nn.Module) -> MegaMoERunner:
"""Return the shared runner for the plan's EP group and module's geometry."""
def get_runner(plan: dict, w: torch.nn.Module, *, prequantized: bool) -> MegaMoERunner:
"""Return the shared runner with an explicit input contract.
Pass prequantized=True for NVFP4 inputs or False for fused BF16 staging.
"""
group = plan["process_group"]
num_experts = w.num_experts
hidden = w.hidden_size
@@ -602,6 +651,7 @@ def get_runner(plan: dict, w: torch.nn.Module) -> MegaMoERunner:
situ_beta = w.activation_situ_beta
situ_linear_beta = w.activation_situ_linear_beta
max_capacity = _token_capacity(get_autotune_max_num_tokens())
tactic_autotune = os.environ.get("MEGAMOE_TACTIC_AUTOTUNE", "0") == "1"
key = (
id(group),
torch.cuda.current_device(),
@@ -612,6 +662,8 @@ def get_runner(plan: dict, w: torch.nn.Module) -> MegaMoERunner:
situ_beta,
situ_linear_beta,
max_capacity,
prequantized,
tactic_autotune,
)
runner = _runners.get(key)
if runner is None:
@@ -624,6 +676,8 @@ def get_runner(plan: dict, w: torch.nn.Module) -> MegaMoERunner:
situ_beta,
situ_linear_beta,
max_capacity,
prequantized=prequantized,
tactic_autotune=tactic_autotune,
)
_runners[key] = runner
return runner
@@ -18,7 +18,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""NVFP4 MegaMoE SiTU correctness at K3 geometry, including EP and graph replay.
"""NVFP4 MegaMoE gated SiLU and SiTU correctness, including EP and graph replay.
Run directly with torchrun; WORLD_SIZE=16 uses all 896 K3 experts.
Pass --autotune to sweep all tactics before checking eager and graph results.
@@ -37,11 +37,8 @@ from unittest.mock import patch
import pytest
import torch
import torch.distributed as dist
from tokenspeed_kernel.numerics.torch.activation import torch_situ_and_mul
from tokenspeed_kernel.numerics.torch.moe import torch_moe_experts
from tokenspeed_kernel.numerics.torch.quantization import (
dequantize_nvfp4_blocks,
fake_quantize_nvfp4,
dequantize_nvfp4_blocks as _dequant,
)
from utils import is_nvidia
@@ -68,7 +65,27 @@ LOCAL_EXPERTS = 56
TOP_K = 16
def _weights(plan, intermediate: int):
def _requant(x, scale):
values = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6], device=x.device)
blocks = x.reshape(*x.shape[:-1], -1, 16)
sf = (blocks.abs().amax(-1) / (6 * scale)).to(torch.float8_e4m3fn).float()
normalized = blocks / (sf.unsqueeze(-1) * scale).clamp_min(1e-30)
# Ties select an even E2M1 code, matching round-to-nearest-even.
distances = (normalized.abs().unsqueeze(-1) - values).abs()
nearest = distances.argmin(-1)
tie = (nearest % 2 == 1) & (nearest < 7)
next_distance = distances.gather(
-1, (nearest + 1).clamp_max(7).unsqueeze(-1)
).squeeze(-1)
nearest = torch.where(
tie & (next_distance == distances.amin(-1)), nearest + 1, nearest
)
return (values[nearest] * normalized.sign() * sf.unsqueeze(-1) * scale).reshape_as(
x
)
def _weights(plan, activation: str, intermediate: int):
w = torch.nn.Module()
w.tp_size = 1
w.num_experts = LOCAL_EXPERTS * dist.get_world_size()
@@ -76,8 +93,8 @@ def _weights(plan, intermediate: int):
w.hidden_size = HIDDEN
w.intermediate_size = intermediate
w.top_k = TOP_K
w.activation_situ_beta = 4.0
w.activation_situ_linear_beta = 25.0
w.activation_situ_beta = 4.0 if activation == "situ" else None
w.activation_situ_linear_beta = 25.0 if activation == "situ" else None
one = torch.ones(1, device="cuda")
reference = []
for name, rows, cols, amplitude, global_scale in (
@@ -106,7 +123,7 @@ def _weights(plan, intermediate: int):
torch.full(s2_shape, global_scale, device="cuda"), requires_grad=False
),
)
reference.append(dequantize_nvfp4_blocks(data, scales) * global_scale)
reference.append((_dequant(data, scales), global_scale))
w.w13_input_scale = torch.nn.Parameter(
torch.tensor([0.75], device="cuda"), requires_grad=False
)
@@ -117,9 +134,10 @@ def _weights(plan, intermediate: int):
return w, reference
def _inputs(tokens, experts):
x = torch.randn(tokens, HIDDEN, dtype=torch.bfloat16, device="cuda")
if tokens:
def _quantized(x):
if isinstance(x, tuple):
return x
if x.shape[0]:
q, sf = fp4_quantize(
x,
torch.tensor([1 / 0.75], device="cuda"),
@@ -129,16 +147,26 @@ def _inputs(tokens, experts):
else:
q = torch.empty((0, HIDDEN // 2), dtype=torch.uint8, device="cuda")
sf = torch.empty((0, HIDDEN // 16), dtype=torch.uint8, device="cuda")
return q, sf
def _input_tensors(x):
return x if isinstance(x, tuple) else (x,)
def _inputs(tokens, experts, *, prequantized):
x = torch.randn(tokens, HIDDEN, dtype=torch.bfloat16, device="cuda")
ids = (
torch.arange(TOP_K, device="cuda") * 53
+ torch.arange(tokens, device="cuda")[:, None] * 17
+ dist.get_rank() * 13
) % experts
weights = torch.randn(tokens, TOP_K, device="cuda").softmax(-1).bfloat16()
return (q, sf), ids.int(), weights
return (_quantized(x) if prequantized else x), ids.int(), weights
def _reference(x, ids, weights, reference, capacity):
def _reference(x, ids, weights, reference, capacity, activation):
x = _quantized(x)
tensors = [
torch.nn.functional.pad(t, (0, 0, 0, capacity - t.shape[0]))
for t in (x[0], x[1].view(torch.uint8), ids, weights)
@@ -153,21 +181,36 @@ def _reference(x, ids, weights, reference, capacity):
dist.all_gather_single(global_tensor, local.contiguous())
gathered.append(global_tensor)
q, sf, routes, scores = gathered
hidden = dequantize_nvfp4_blocks(q, sf.view(torch.float8_e4m3fn)) * 0.75
output = torch_moe_experts(
hidden,
reference[0],
reference[1],
torch.where(scores != 0, routes, -1),
scores.float(),
activation=lambda gate_up: torch_situ_and_mul(gate_up, 4.0, 25.0),
w13_bias=None,
w2_bias=None,
quantize_input=None,
quantize_intermediate=lambda t: fake_quantize_nvfp4(t, 1.25),
round_expert_output=torch.Tensor.bfloat16,
first_expert=dist.get_rank() * LOCAL_EXPERTS,
)
hidden = _dequant(q, sf.view(torch.float8_e4m3fn))
output = torch.zeros(hidden.shape, dtype=torch.float32, device="cuda")
for local_expert in range(LOCAL_EXPERTS):
rows, choices = torch.where(
(routes == local_expert + dist.get_rank() * LOCAL_EXPERTS) & (scores != 0)
)
if rows.numel() == 0:
continue
# Global scales belong to the GEMM epilogues. Folding them into the
# operands changes FP32 rounding before the intermediate FP4 quantizer.
w1, scale1 = reference[0]
w2, scale2 = reference[1]
gate, up = ((hidden[rows] @ w1[local_expert].T) * (0.75 * scale1)).split(
w1.shape[1] // 2, dim=-1
)
if activation == "silu":
activated = torch.nn.functional.silu(gate) * up
else:
activated = (
(4 * torch.tanh(gate / 4))
* torch.sigmoid(gate)
* (25 * torch.tanh(up / 25))
)
partial = (
((_requant(activated, 1.25) / 1.25) @ w2[local_expert].T)
.mul(1.25 * scale2)
.bfloat16()
.float()
)
output.index_add_(0, rows, partial * scores[rows, choices].float()[:, None])
dist.all_reduce(output)
rank = dist.get_rank()
return output[rank * capacity : rank * capacity + x[0].shape[0]].bfloat16()
@@ -188,12 +231,20 @@ def _check(output, expected, label):
assert error < 0.005, (label, error.item())
def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: int):
def run_correctness(
capacity: int,
live_tokens: int,
tune: bool,
activation: str,
intermediate: int,
*,
prequantized: bool,
):
torch.manual_seed(713 + dist.get_rank())
plan = moe_plan(
"nvfp4",
input_dtype=torch.bfloat16,
activation="situ",
activation=activation,
requires_deferred_finalize=False,
routing_mode="precomputed_topk",
a2a_backend="none",
@@ -214,14 +265,14 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
combine_order="rank",
features=frozenset(),
)
w, ref = _weights(plan, intermediate)
w, ref = _weights(plan, activation, intermediate)
tokens = live_tokens if dist.get_rank() == 0 else max(1, live_tokens - 2)
x, ids, weights = _inputs(tokens, w.num_experts)
x, ids, weights = _inputs(tokens, w.num_experts, prequantized=prequantized)
def run():
def apply(inputs):
return moe_apply(
plan,
x,
inputs,
w,
None,
topk_weights=weights,
@@ -236,21 +287,37 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
shared_out=None,
)
def run():
return apply(x)
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe.runner import get_runner
external_inputs = x, ids, weights
runner = get_runner(plan, w)
values_out, scales_out, ids_out, weights_out = runner.input_buffers(
tokens, capacity
)
values_out.copy_(x[0])
scales_out[:tokens].copy_(x[1].view(torch.uint8))
ids_out.copy_(ids)
weights_out.copy_(weights)
x, ids, weights = (values_out, scales_out[:tokens]), ids_out, weights_out
runner = get_runner(plan, w, prequantized=prequantized)
if not prequantized:
# Reject each short routing tensor before any GPU staging reads it.
for ids, weights in (
(external_inputs[1][:-1], external_inputs[2]),
(external_inputs[1], external_inputs[2][:-1]),
):
with pytest.raises(
ValueError, match="route rows must match activation rows"
):
apply(x)
x, ids, weights = external_inputs
if prequantized:
values_out, scales_out, ids_out, weights_out = runner.input_buffers(
tokens, capacity
)
values_out.copy_(x[0])
scales_out[:tokens].copy_(x[1].view(torch.uint8))
ids_out.copy_(ids)
weights_out.copy_(weights)
x, ids, weights = (values_out, scales_out[:tokens]), ids_out, weights_out
# A cold tune must preserve real producer data while it profiles synthetic data.
AutoTuner.get().clear_cache()
expected = _reference(x, ids, weights, ref, capacity)
expected = _reference(x, ids, weights, ref, capacity, activation)
cached_profiles = set(AutoTuner.get().profiling_cache)
print(f"rank={dist.get_rank()} launching eager", flush=True)
guard = (
nullcontext()
@@ -261,7 +328,9 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
side_effect=AssertionError("MegaMoE tuning requires explicit opt-in"),
)
)
with guard, autotune(
# Tuning initializes random profiling tensors. Keep those draws from
# changing the later graph/idle test vectors between tuned and untuned runs.
with guard, torch.random.fork_rng(devices=[torch.cuda.current_device()]), autotune(
tune_mode=True, tuning_buckets=None, round_up=None
), torch.inference_mode():
output = run()
@@ -270,12 +339,14 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
# Later capacity changes overwrite producer views. Keep each graph's
# source inputs independent so every replay stages its own data again.
x, ids, weights = external_inputs
if not prequantized and not tune:
torch.testing.assert_close(output, apply(_quantized(x)), atol=0, rtol=0)
if tune:
tuner = AutoTuner.get()
tactics = {
key.nearest_profile: value[0]
for key, value in tuner.profiling_cache.items()
if key.custom_op == "trtllm_nvfp4_mega_moe"
if key.custom_op == "trtllm_nvfp4_mega_moe" and key not in cached_profiles
}
assert len(tactics) == (capacity - 1).bit_length() + 1
assert not tuner.stats.failed_tactics.get(
@@ -288,20 +359,25 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = run()
replacement, replacement_ids, replacement_weights = _inputs(tokens, w.num_experts)
replacement, replacement_ids, replacement_weights = _inputs(
tokens, w.num_experts, prequantized=prequantized
)
for dst, src in zip(
(*x, ids, weights), (*replacement, replacement_ids, replacement_weights)
(*_input_tensors(x), ids, weights),
(*_input_tensors(replacement), replacement_ids, replacement_weights),
):
dst.copy_(src)
expected = _reference(x, ids, weights, ref, capacity)
expected = _reference(x, ids, weights, ref, capacity, activation)
for _ in range(3):
graph.replay()
torch.cuda.synchronize()
_check(captured, expected, "graph replay")
if not prequantized and not tune:
torch.testing.assert_close(captured, apply(_quantized(x)), atol=0, rtol=0)
first_graph = (graph, captured, expected, x, ids, weights)
tokens = 0 if dist.get_rank() == 0 and dist.get_world_size() > 1 else 1
x, ids, weights = _inputs(tokens, w.num_experts)
expected = _reference(x, ids, weights, ref, capacity)
x, ids, weights = _inputs(tokens, w.num_experts, prequantized=prequantized)
expected = _reference(x, ids, weights, ref, capacity, activation)
if tune:
with patch.object(
tuner, "_profile_single_kernel", wraps=tuner._profile_single_kernel
@@ -314,8 +390,17 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
torch.cuda.synchronize()
_check(output, expected, "uneven/idle rank")
runner = get_runner(plan, w)
arena = runner.workspace
assert arena.capacity == 1 << (get_autotune_max_num_tokens() - 1).bit_length()
# Every candidate must be usable without growing the reserved arena,
# including when the normal execution path has tactic tuning disabled.
for tactic in runner.TACTICS:
arena._kernel(arena.capacity, tactic)
assert "fc2_output_workspace" not in arena.region_sizes["local"]
with pytest.raises(ValueError, match="not reserved"):
arena._kernel(4, (256, 512, "static", "reuse_dispatch_warps", 8))
with pytest.raises(ValueError, match="not reserved"):
arena._kernel(arena.capacity * 2, runner.TACTICS[0])
pointers = (
arena.storage.data_ptr(),
arena.local.data_ptr(),
@@ -327,8 +412,8 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
capacity = 1 if capacity > 1 else min(maximum, 2)
tokens = min(capacity, live_tokens + 1)
tokens = tokens if dist.get_rank() == 0 else max(1, tokens - 2)
x, ids, weights = _inputs(tokens, w.num_experts)
expected = _reference(x, ids, weights, ref, capacity)
x, ids, weights = _inputs(tokens, w.num_experts, prequantized=prequantized)
expected = _reference(x, ids, weights, ref, capacity, activation)
_check(run(), expected, "alternate capacity eager")
other_graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(other_graph):
@@ -358,14 +443,16 @@ def run_correctness(capacity: int, live_tokens: int, tune: bool, intermediate: i
dist.barrier()
if dist.get_rank() == 0:
print(
"PASS NVFP4 SiTU MegaMoE eager, graph replay, idle ranks, and shared-arena capacity switching",
f"PASS NVFP4 {activation} MegaMoE eager, graph replay, idle ranks, and shared-arena capacity switching",
flush=True,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("tune", [False, True])
def test_nvfp4_situ_megamoe(tune, monkeypatch):
@pytest.mark.parametrize("activation", ["situ", "silu"])
@pytest.mark.parametrize("prequantized", [False, True])
def test_nvfp4_megamoe(tune, activation, prequantized, monkeypatch):
if tune:
monkeypatch.setenv("MEGAMOE_TACTIC_AUTOTUNE", "1")
else:
@@ -397,7 +484,20 @@ def test_nvfp4_situ_megamoe(tune, monkeypatch):
),
):
set_autotune_process_group(dist.group.WORLD)
run_correctness(4, 4, tune, INTERMEDIATE)
run_correctness(
4, 4, tune, activation, INTERMEDIATE, prequantized=prequantized
)
if not tune and activation == "silu":
# Larger live batches, then idle ranks and alternating
# graphs that retain the full-capacity arena.
run_correctness(
512,
300,
False,
activation,
INTERMEDIATE,
prequantized=prequantized,
)
import cuda.bindings.driver as cuda
import cutlass.cute as cute
@@ -485,13 +585,20 @@ if __name__ == "__main__":
parser.add_argument("--capacity", type=int, default=4)
parser.add_argument("--tokens", type=int, default=4)
parser.add_argument("--autotune", action="store_true")
parser.add_argument("--activation", choices=("situ", "silu"), required=True)
parser.add_argument("--input-format", choices=("bf16", "nvfp4"), required=True)
parser.add_argument("--intermediate-size", type=int, required=True)
args = parser.parse_args()
os.environ["MEGAMOE_TACTIC_AUTOTUNE"] = "1" if args.autotune else "0"
set_autotune_max_num_tokens(args.capacity)
set_autotune_process_group(dist.new_group(backend="gloo"))
run_correctness(
args.capacity, args.tokens, args.autotune, args.intermediate_size
args.capacity,
args.tokens,
args.autotune,
args.activation,
args.intermediate_size,
prequantized=args.input_format == "nvfp4",
)
finally:
set_autotune_process_group(None)
@@ -0,0 +1,189 @@
# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Check the fused stager against FlashInfer quantization and captured reuse."""
from contextlib import nullcontext
import pytest
import torch
from utils import assert_no_cute_compile, is_nvidia
if not is_nvidia():
pytest.skip("NVIDIA GPU required", allow_module_level=True)
from tokenspeed_kernel.ops.quantization.flashinfer import fp4_quantize # noqa: E402
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe.input_stage import ( # noqa: E402
Nvfp4InputStage,
)
@pytest.mark.parametrize("id_rows,score_rows", [(2, 3), (3, 2), (4, 3), (3, 4)])
def test_input_stage_rejects_mismatched_route_rows(id_rows, score_rows):
stager = Nvfp4InputStage(128, 2)
# Shape validation must reject invalid input before accessing CUDA or compiling.
x = torch.empty(3, 128, dtype=torch.bfloat16)
scale = torch.ones(1)
ids = torch.empty(id_rows, 2, dtype=torch.int32)
scores = torch.empty(score_rows, 2)
q = torch.empty(16, 64, dtype=torch.uint8)
sf = torch.empty(16, 8, dtype=torch.float8_e4m3fn)
routes = torch.empty(16, 2, dtype=torch.int32)
weights = torch.empty(16, 2)
with pytest.raises(ValueError, match="route rows must match activation rows"):
stager.run(x, scale, ids, scores, q, sf, routes, weights)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("hidden", [128, 3584, 8192])
@pytest.mark.parametrize("ids_dtype", [torch.int32, torch.int64])
@pytest.mark.parametrize("routes_dtype", [torch.int32, torch.int64])
@pytest.mark.parametrize("scores_dtype", [torch.float32, torch.bfloat16])
def test_fused_nvfp4_input_stage(hidden, ids_dtype, routes_dtype, scores_dtype):
torch.manual_seed(710)
capacity, top_k = 16, 10
stager = Nvfp4InputStage(hidden, top_k)
scale = torch.tensor([1 / 0.75], device="cuda")
q = torch.empty(capacity, hidden // 2, device="cuda", dtype=torch.uint8)
sf = torch.empty(capacity, hidden // 16, device="cuda", dtype=torch.float8_e4m3fn)
routes = torch.empty(capacity, top_k, device="cuda", dtype=routes_dtype)
weights = torch.empty(capacity, top_k, device="cuda", dtype=torch.float32)
def inputs(n):
x = torch.randn(n, hidden, device="cuda", dtype=torch.bfloat16)
x[:, :16] = 0
ids = torch.randint(0, 512, (n, top_k), device="cuda", dtype=ids_dtype)
scores = torch.rand(n, top_k, device="cuda").to(scores_dtype)
return x, ids, scores
def run(x, ids, scores):
stager.run(x, scale, ids, scores, q, sf, routes, weights)
def check(x, ids, scores):
n = x.shape[0]
if n:
expected_q, expected_sf = fp4_quantize(
x, scale, is_sf_swizzled_layout=False, enable_pdl=False
)
torch.testing.assert_close(q[:n], expected_q, atol=0, rtol=0)
torch.testing.assert_close(
sf[:n].view(torch.uint8), expected_sf.view(torch.uint8), atol=0, rtol=0
)
torch.testing.assert_close(routes[:n], ids.to(routes_dtype), atol=0, rtol=0)
torch.testing.assert_close(weights[:n], scores.float(), atol=0, rtol=0)
assert (routes[n:] == -1).all()
assert (weights[n:] == 0).all()
# The same compiled stager must handle changing live counts, zero owners,
# and a shrinking batch without leaving previously live routes behind.
for iteration, n in enumerate((3, 13, 1, 0, 7)):
x, ids, scores = inputs(n)
with assert_no_cute_compile() if iteration else nullcontext():
run(x, ids, scores)
check(x, ids, scores)
captured = []
for n in (3, 13, 0):
x, ids, scores = inputs(n)
run(x, ids, scores)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
run(x, ids, scores)
captured.append((graph, x, ids, scores))
# Update both activations and the layer scale after capture. Replays must
# read the current values, including when a smaller graph follows a larger one.
scale.fill_(0.5)
for graph, x, ids, scores in captured:
new_x, new_ids, new_scores = inputs(len(x))
x.copy_(new_x)
ids.copy_(new_ids)
scores.copy_(new_scores)
for saved in (captured[1], captured[0], captured[2], captured[1]):
graph, x, ids, scores = saved
graph.replay()
check(x, ids, scores)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_input_stage_reuses_compiled_routes_by_output_dtype():
stager = Nvfp4InputStage(128, 2)
x = torch.randn(3, 128, device="cuda", dtype=torch.bfloat16)
scale = torch.ones(1, device="cuda")
ids = torch.tensor([[1, 5], [7, 2], [3, 0]], device="cuda")
scores = torch.rand(3, 2, device="cuda")
q = torch.empty(16, 64, device="cuda", dtype=torch.uint8)
sf = torch.empty(16, 8, device="cuda", dtype=torch.float8_e4m3fn)
weights = torch.empty(16, 2, device="cuda")
for dtype in (torch.int32, torch.int64, torch.int32):
routes = torch.empty(16, 2, device="cuda", dtype=dtype)
stager.run(x, scale, ids, scores, q, sf, routes, weights)
torch.testing.assert_close(routes[:3], ids.to(dtype), atol=0, rtol=0)
assert (routes[3:] == -1).all()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("output", ["q", "sf", "scores"])
def test_input_stage_switches_output_dtype(output):
stager = Nvfp4InputStage(128, 2)
x = torch.randn(3, 128, device="cuda", dtype=torch.bfloat16)
scale = torch.ones(1, device="cuda")
ids = torch.tensor([[1, 5], [7, 2], [3, 0]], device="cuda")
scores = torch.rand(3, 2, device="cuda")
expected_q, expected_sf = fp4_quantize(
x, scale, is_sf_swizzled_layout=False, enable_pdl=False
)
for iteration, alternate in enumerate((False, True, False)):
q = torch.empty(
16,
64,
device="cuda",
dtype=torch.int8 if alternate and output == "q" else torch.uint8,
)
sf = torch.empty(
16,
8,
device="cuda",
dtype=(
torch.float32 if alternate and output == "sf" else torch.float8_e4m3fn
),
)
weights = torch.empty(
16,
2,
device="cuda",
dtype=torch.bfloat16 if alternate and output == "scores" else torch.float32,
)
routes = torch.empty(16, 2, device="cuda", dtype=torch.int32)
with assert_no_cute_compile() if iteration == 2 else nullcontext():
stager.run(x, scale, ids, scores, q, sf, routes, weights)
torch.testing.assert_close(q[:3].view(torch.uint8), expected_q, atol=0, rtol=0)
torch.testing.assert_close(
sf[:3].float(),
expected_sf.view(torch.float8_e4m3fn).float(),
atol=0,
rtol=0,
)
torch.testing.assert_close(routes[:3], ids.int(), atol=0, rtol=0)
torch.testing.assert_close(
weights[:3], scores.to(weights.dtype), atol=0, rtol=0
)
assert (routes[3:] == -1).all()
assert (weights[3:] == 0).all()