Skip to content

Add SM100 NVFP4 MegaMoE with fused BF16 shared experts - #409

Merged
RayWang96 merged 11 commits into
deepseek-ai:nv_devfrom
zhou9402:codex/nvfp4-fused-shared-oss-pr
Aug 27, 2026
Merged

RayWang96 merged 11 commits into
deepseek-ai:nv_devfrom
zhou9402:codex/nvfp4-fused-shared-oss-pr

Conversation

@zhou9402

@zhou9402 zhou9402 commented Aug 17, 2026 •

Copy link
Copy Markdown

Summary

  • Add a dedicated SM100 NVFP4 x NVFP4 MegaMoE kernel.
  • Fuse the optional BF16 shared expert into the same persistent MegaMoE kernel.
  • Apply routed scaling after the routed top-k reduction and before adding the shared-expert output.
  • Preserve ModelOpt NVFP4 scales without affecting the existing BF16 or FP8 x FP4 MegaMoE paths.

Design highlights

  • Native NVFP4 routed path. Both routed activations and weights use packed E2M1 data with per-16-element E4M3 scale factors. This requires a bit-aware symmetric-buffer layout, NVFP4-specific TMA/UTCCP handling, and an in-kernel L1 requantization epilogue.

  • Post-L2 top-k weighting. Top-k routing weights are stored in a new NVFP4-specific buffer and applied to the BF16 routed output after L2, immediately before the combine write. Applying top-k weights directly in the L1 epilogue can reduce the intermediate magnitude before NVFP4 quantization and introduce additional precision loss.

  • ModelOpt scale handling. Per-expert gate/up scales are applied before SwiGLU. The down-projection input scale normalizes the in-kernel NVFP4 intermediate quantization and is folded back into the L2 output scale: l2_scale = l2_alpha * a2_scale.

  • Correct routed/shared ordering. The kernel accumulates the routed top-k outputs, rounds the routed sum to BF16, applies routed_scaling_factor, and then adds the BF16 shared-expert output.

  • BF16 shared expert inside MegaMoE. Optional BF16 shared L1 and L2 work is inserted into the existing scheduler as SharedLinear1 and SharedLinear2 phases. These tasks reuse the existing TMA-load, MMA, and epilogue warp roles; shared computation uses ordinary BF16 UMMA without scale factors or UTCCP.

  • Separate shared K tiling. Routed NVFP4 and shared BF16 tasks reuse the same shared-memory byte tiles but contain different numbers of elements, so SHARED_BLOCK_K describes the BF16 K extent independently from the routed NVFP4 K extent.

  • Fused shared epilogues. Shared L1 applies SwiGLU and stores a BF16 intermediate. Shared L2 writes to an additional local combine slot, allowing the final combine phase to perform routed scaling and the shared add without separate shared-expert launches.

  • Compatibility. The new NVFP4 path does not affect the existing BF16 or FP8 x FP4 MegaMoE paths.

Validation

Test Result
Boundary/adversarial accuracy, 42 cases PASS; max rel-L2 0.005421
Random fuzz, 22 cases PASS; max rel-L2 0.002655
Shared-only accuracy, 10 cases PASS; max rel-L2 0.001134
GLM-5.2 layer replay, 75 layers PASS; fused closer to FP32 in 69/75
GLM-5.2 deterministic E2E, 0/8K context PASS; serial 32/32, fused 32/32
Clean GB300 build and 4-rank correctness PASS; max rel-L2 0.001315

Performance

Pure CUDA-kernel time on 8x GB300 with EP8. All three arms have the same BF16-input to BF16-output model boundary and include routed computation, dispatch/combine, routed scaling, the BF16 shared expert, and the final add.

  • FlashInfer modular baseline: FlashInfer one-sided All-to-All dispatch -> TRT-LLM NVFP4 routed experts -> FlashInfer one-sided All-to-All combine -> routed scaling -> serial DeepGEMM BF16 shared expert -> add. This arm does not call MegaMoE. Optimized FlashInfer configurations are used, and the NVFP4 expert tactic is autotuned independently for each workload size. For each M, the table reports the lowest audited latency among runs with the correct tactic and identical timing boundary.
  • DG unfused: routed-only sm100_fp4_fp4_mega_moe -> routed scaling -> serial DeepGEMM BF16 shared expert -> add.
  • DG fused: one sm100_fp4_fp4_mega_moe kernel containing the routed path, routed scaling, BF16 shared expert, and final add.
M/rank FlashInfer modular, no MegaMoE (us) DG routed-only + serial shared (us) DG fused shared (us) Fused vs FI Fusion gain
1 132.064 131.584 105.504 20.11% 19.82%
2 154.096 146.608 124.784 19.02% 14.89%
4 168.720 164.816 140.464 16.75% 14.78%
8 189.232 183.104 160.512 15.18% 12.34%
16 199.360 190.528 166.672 16.40% 12.52%
32 203.792 192.400 168.464 17.34% 12.44%
64 209.184 195.232 171.200 18.16% 12.31%
128 257.328 203.536 179.216 30.36% 11.95%
256 268.633 221.920 190.960 28.91% 13.95%
512 346.718 275.192 234.177 32.46% 14.90%
1024 539.041 417.849 365.346 32.22% 12.57%
2048 918.737 690.976 604.784 34.17% 12.47%
4096 1721.712 1400.384 1248.720 27.47% 10.83%
8192 3345.690 2539.136 2218.608 33.69% 12.62%
16384 6559.996 5400.112 4871.792 25.73% 9.78%

Fusion gain compares the two DeepGEMM arms. Fused vs FI compares against the modular, non-MegaMoE FlashInfer baseline.

Complete test recipe

Revisions and environment

  • Hardware: 8x GB300, two hosts x four GPUs, EP8
  • CUDA 13, PyTorch 2.13.0+cu130, vLLM 0.17.2rc1.dev4473+g3ada0d7f1, FlashInfer 0.6.16rc5

Build and correctness

CUDA_VISIBLE_DEVICES=0,1,2,3 \
python tests/test_nvfp4_mega_moe.py \
  --num-processes 4 \
  --num-max-tokens-per-rank 128 \
  --num-tokens 128 \
  --hidden 6144 \
  --intermediate-hidden 2048 \
  --num-experts 256 \
  --num-topk 8 \
  --num-shared-experts 1 \
  --per-expert-alphas 1 \
  --per-expert-a2 1 \
  --routed-scaling-factor 0.75 \
  --num-correctness-tests 2

The boundary, zero-token, masked-routing, and shared-only cases use the same command with the corresponding --num-tokens, --zero-token-rank, --masked-ratio, --routing-hot-rank, and --num-shared-experts settings.

Performance shape and inputs

  • Hidden size: 6144
  • Routed/shared intermediate size: 2048
  • Routed experts: 256; top-k: 8; BF16 shared experts: 1
  • Routed scaling factor: 0.75
  • M/rank: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384
  • Symmetric-buffer token capacity per rank: 16512
  • Deterministic seed: 20260811
  • All arms use identical BF16 inputs, top-k metadata, ModelOpt NVFP4 weights/scales, and BF16 shared weights.
  • Data generation, weight conversion, JIT compilation, and backend autotuning are completed before measurement.

Timed call graphs

FI modular:
  BF16->NVFP4 quantization
  -> FlashInfer one-sided dispatch prepare/sanitize/dispatch
  -> TRT-LLM routing + NVFP4 BMM1 + NVFP4 BMM2 + finalize
  -> FlashInfer combine prepare/combine
  -> routed BF16 scale
  -> DeepGEMM BF16 shared L1 + SwiGLU + BF16 shared L2
  -> BF16 add

DG unfused:
  routed-only sm100_fp4_fp4_mega_moe
  -> routed BF16 scale
  -> DeepGEMM BF16 shared L1 + SwiGLU + BF16 shared L2
  -> BF16 add

DG fused:
  sm100_fp4_fp4_mega_moe with routed scaling and BF16 shared expert enabled

Timing

  • Timing follows deep_gemm.testing.bench_kineto and reports selected CUDA-kernel time only.
  • Perform five untimed warmup calls before profiling.
  • Use Kineto schedule wait=0, warmup=1, active=1 with 30 calls in the measured phase.
  • Before each measured call, evict L2 with the repository benchmark's 8 GB eviction buffer. Eviction, CUDA sleep, distributed barriers, CPU launch gaps, router/top-k selection, data generation, weight conversion, JIT compilation, and autotuning are excluded.
  • FI backend-internal quantization, routing, dispatch, expert, finalize, and combine CUDA kernels are included.
  • Sum the selected CUDA rows per rank and report the maximum across all eight ranks.

@zhou9402
zhou9402 force-pushed the codex/nvfp4-fused-shared-oss-pr branch from d69d22b to cb1f99d Compare August 21, 2026 03:17
@zhou9402
zhou9402 force-pushed the codex/nvfp4-fused-shared-oss-pr branch 3 times, most recently from 26478dc to e425dec Compare August 21, 2026 06:09
@zhou9402
zhou9402 force-pushed the codex/nvfp4-fused-shared-oss-pr branch from e425dec to 2deb26a Compare August 21, 2026 08:55
@zhou9402
zhou9402 marked this pull request as ready for review August 21, 2026 12:43
Comment thread deep_gemm/mega/__init__.py Resolved
Comment thread csrc/apis/mega.hpp Resolved
Comment thread csrc/apis/mega.hpp Resolved
Comment thread csrc/apis/mega.hpp Resolved
# Returns `((packed_weights, mn_major_packed_sf), dequantized_weights)`
num_groups, n, k = bf16_weights.shape
w = torch.empty((num_groups, n, k // 2), device='cuda', dtype=torch.int8)
w_sf = torch.empty((num_groups, n, k // 64), device='cuda', dtype=torch.int32)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 suggestion: _quantize_weights_to_nvfp4 loops per expert group in Python and calls cast_back_from_fp4 per group. Fine for correctness tests, but consider vectorizing across the group dimension if suite runtime becomes an issue for large expert counts.

🤖 v5

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this unchanged for now: it is correctness-test-only setup outside the measured region, and the current suite runtime is acceptable. We can vectorize it later if it becomes a material test-runtime bottleneck.

@ds-review-bot

Copy link
Copy Markdown
Collaborator

🤖 ds-review-bot Code Review

v6

新增 FP4 API 未验证对称缓冲区布局,使用默认缓冲区配置时可能通过大小检查却读取错误偏移,导致静默错误输出。

v5

This MR adds an SM100 NVFP4 x NVFP4 MegaMoE kernel on nv_dev, with an optional fused BF16 shared expert whose output is added after routed scaling, while preserving ModelOpt NVFP4 scale semantics (per-16-element E4M3 block SF, per-expert weight_scale_2 alphas, and the down-proj input_scale folded into the L2 alpha) and reusing the existing MegaMoE scheduler and public API. The change is well layered: a new device kernel (deep_gemm/include/deep_gemm/impls/sm100_fp4_fp4_mega_moe.cuh, ~1.8K lines), a JIT wrapper (csrc/jit_kernels/impls/sm100_fp4_fp4_mega_moe.hpp), a validated host API with pybind registration (csrc/apis/mega.hpp), Python bindings and exports (deep_gemm/mega/init.py, deep_gemm/init.py), NVFP4-aware heuristics/scheduler/layout extensions, and a thorough reference test (tests/test_nvfp4_mega_moe.py) whose _quantize_to_fp4_e2m1_rne reproduces cvt.rn.satfinite.e2m1x2.f32 round-to-nearest-even exactly. Verified during review: the pybind signature (21 args) matches the Python call site and fp4_fp4_mega_moe is exported; host-side validation is strict (SF layout, shared-triple co-presence enforced on both the Python and C++ sides, alpha/a2-scale shapes, finiteness of routed_scaling_factor); the combine epilogue preserves the serial pipeline's BF16 -> scale -> BF16 ordering before the shared add in both kHasShared branches; SHARED_BLOCK_K in the scheduler is a clean backward-compatible relaxation for the BF16 shared expert's K tiling; and get_byte_addressable_element_size() correctly guards all byte-based SM90/SM100/SM120 heuristic call sites from sub-byte NVFP4 (no remaining unguarded get_element_size() uses outside the bit-aware MegaMoE helper). Reported validation (boundary/fuzz/shared-only accuracy, GLM layer replay, deterministic E2E, 4-rank correctness) and the ~10-20% fusion gains are consistent with the implementation. Overall the MR is in good shape and approvable; the comments below are non-blocking suggestions.

v4p

本 MR 为 SM100 新增 NVFP4 x NVFP4 MegaMoE 实现,并在核内融合 BF16 shared expert:路由输出在 combine 阶段先做 routed scaling,再与 shared 输出相加;同时保持 ModelOpt NVFP4 scale 与既有 MegaMoE scheduler/API。整体实现与现有 FP8/BF16 MegaMoE 模式一致,主机侧 buffer/启发式布局、设备侧 TMA/MMA/epilogue/combine 路径以及 Python 封装均同步完整,未发现明确的正确性问题。

Files reviewed: 15
Issues found: 🔴 1 critical | 🔵 7 suggestion
Inline comments posted: 7
General comments (无法定位到 diff): 1


📍 未定位到 diff 的评论

🔵 suggestion deep_gemm/include/deep_gemm/impls/sm100_fp4_fp4_mega_moe.cuh:L1687: The kHasShared epilogue applies routed_scaling_factor on the last reduce iteration, relying on the shared slot being the highest bit and therefore consumed last by __ffs. This coupling between the dispatch-side slot encoding and the combine-side ordering is subtle; consider adding a static assertion or a targeted test that ties the slot-ordering assumption to the encoding, so a future change to slot layout cannot silently scale the shared contribution as well. 🤖 v5

@zhou9402
zhou9402 marked this pull request as draft August 21, 2026 22:17
@zhou9402
zhou9402 marked this pull request as ready for review August 22, 2026 09:01
Comment thread deep_gemm/mega/__init__.py Resolved
Comment thread csrc/apis/mega.hpp Resolved
Comment thread csrc/apis/mega.hpp Resolved
Comment thread csrc/apis/mega.hpp Resolved
# Returns `((packed_weights, mn_major_packed_sf), dequantized_weights)`
num_groups, n, k = bf16_weights.shape
w = torch.empty((num_groups, n, k // 2), device='cuda', dtype=torch.int8)
w_sf = torch.empty((num_groups, n, k // 64), device='cuda', dtype=torch.int32)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 suggestion: Looping per expert group and calling cast_back_from_fp4 per group is fine for correctness tests, but could be vectorized across the group dimension if suite runtime becomes an issue for large expert counts.

🤖 v5

@ds-review-bot

Copy link
Copy Markdown
Collaborator

🤖 ds-review-bot Code Review

v6

未发现新的非重复问题,但先前指出的 FP4 API 未校验对称缓冲区布局问题仍然存在,传入默认 FP8 布局缓冲区时可能静默产生错误结果。

v5

The NVFP4 x NVFP4 MegaMoE implementation is well layered and the fused BF16 shared-expert design (post-L2 top-k weighting, routed scaling before the shared add, ModelOpt scale folding l2_scale = l2_alpha * a2_scale) matches the description and is consistent across the device kernel, JIT wrapper, host API, Python bindings, and test. However, the current HEAD is the same revision that the v6 review targeted, and none of the v6 comments have been addressed yet. One issue is blocking: fp4_fp4_mega_moe does not validate the symmetric-buffer layout, so a default fp8xfp4-layout buffer passes the byte-size check but the kernel reads wrong offsets (routing-weight sidecar shifts the input region), silently producing incorrect results.

v4p

本 MR 为 SM100 新增 NVFP4 x NVFP4 MegaMoE 内核,并在同一持久化内核中融合 BF16 shared expert:routed 输出在 combine 阶段先按 routed_scaling_factor 缩放,再与 shared-expert 输出相加,同时保持既有 BF16 / FP8xFP4 MegaMoE 路径不受影响。整体实现分层清晰,主机侧校验、布局/启发式/调度器扩展以及测试覆盖均较完整,本次复审未发现新的明确正确性缺陷。需要注意的是,讨论中已提出的关键问题在当前 diff 中仍未修复:fp4_fp4_mega_moe 未保存/校验 SymmBuffer 的 mma_type 或布局,使用默认 fp8xfp4 缓冲区时可通过 C++ 字节数检查,但 FP4 布局在 input 前额外放置了 routing-weight sidecar,内核会按错误偏移读取缓冲区,导致静默错误结果;建议合入前在 Python 层保存 mma_type 并校验,或至少检查 sym_buffer.x 的 dtype 与形状。

Files reviewed: 15
Issues found: 🔴 1 critical | 🔵 7 suggestion
Inline comments posted: 7
General comments (无法定位到 diff): 1


📍 未定位到 diff 的评论

🔵 suggestion deep_gemm/include/deep_gemm/impls/sm100_fp4_fp4_mega_moe.cuh:L1677: The kHasShared combine epilogue applies routed_scaling_factor on the last reduce iteration, relying on the shared slot being lane kNumTopk in the ballot mask (highest set bit, consumed last by __ffs). This couples the dispatch-side slot encoding to the combine-side ordering only via a comment. Suggested fix: add a DG_STATIC_ASSERT (e.g. that kNumTopk + 1 slots fit in the 32-bit ballot and that the shared slot index is kNumTopk, above all routed slots) and/or a targeted test tying the slot ordering to the encoding. 🤖 v5

@zhou9402

Copy link
Copy Markdown
Author

Follow-up on the shared-slot ordering suggestion: addressed structurally in 814d9bc and clarified in 0c067ed. The shared producer and combine consumer both use kSharedCombineSlot, defined as the slot immediately after routed top-k. The combine path separately asserts that routed plus shared slots fit in the 32-bit ballot, and the reference test verifies BF16 routed rounding, routed scaling, then shared addition. The previous equality static assert was tautological and has been removed.

@zhou9402

Copy link
Copy Markdown
Author

Addressed the symmetric-buffer layout concern in 4d789d4. The layout metadata guard was originally added in 814d9bc; this follow-up makes the MMA type, activation, shared-tensor set, and shared-expert-count checks explicit ValueError validations instead of Python assert, so they remain active under optimized Python execution. The wrong-layout regression test now verifies the explicit rejection path.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants