Skip to content

feat: add SiTU support to FP8/FP4 Mega MoE - #396

Merged
RayWang96 merged 2 commits into
deepseek-ai:nv_devfrom
Barry-Delaney:feat/mega-moe-situ
Aug 11, 2026
Merged

RayWang96 merged 2 commits into
deepseek-ai:nv_devfrom
Barry-Delaney:feat/mega-moe-situ

Conversation

@Barry-Delaney

@Barry-Delaney Barry-Delaney commented Jul 30, 2026 •

Copy link
Copy Markdown

Summary

  • Add SiTU gated activation support to SM100 FP8/FP4 Mega MoE while preserving the default SwiGLU path.
  • Thread activation, situ_beta, and situ_linear_beta through symmetric-buffer validation, Python/C++ APIs, JIT specialization, and the routed/shared L1 epilogue.
  • Restrict SiTU to FP8xFP4, reject activation clamp and non-positive or non-finite beta values, and keep BF16 Mega MoE SwiGLU-only.

This is a semantic port of longlee0622/DeepGEMM@cc832217 onto the latest nv_dev. It uses the author refactor-ready follow-up 39d7cac and preserves the original authorship and sign-off.

Validation

  • Built the exact PR commit with ./develop.sh.
  • Passed the focused deterministic routed SiTU regression for both fast_math modes.
  • Verified high-beta SiTU converges to SwiGLU, each beta control changes the result independently, the two controls remain distinct, and every output is finite with a non-degenerate baseline.
  • Verified situ_beta=+inf is rejected by the API validation.
  • PTXAS comparison reported the same 56-byte stack frame and zero spill stores/loads for SiTU and SwiGLU.
  • git diff --check and Python py_compile passed.

Signed-off-by: Jonas Li <[email protected]>
(cherry picked from commit 39d7cac)
sigmoid = {1.0f / denom.x, 1.0f / denom.y};
}
gate = __fmul2_rn(sigmoid, {
kSiTUBeta * tanhf(raw_gate.x / kSiTUBeta),

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: raw_gate.x / kSiTUBeta 与 up.x / kSiTULinearBeta 是对编译期常量的除法,编译器不一定会替换为乘倒数(非 fast-math 语义下不会)。建议预先定义 constexpr float kInvSiTUBeta = 1.0f / kSiTUBeta;(linear beta 同理)并改为乘法:ULP 级差异相对 BF16 输出量化可忽略,却能省去每元素两次 div 指令。

🤖 v5

Comment thread deep_gemm/mega/__init__.py Outdated
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]:
assert activation == 'swiglu', f'Only `swiglu` activation is supported, got `{activation}`'
assert activation == 'swiglu' or (activation == 'situ' and isinstance(l1_weights, tuple)), \
f'Only FP8xFP4 MegaMoE weights support `situ`, got activation={activation!r}'

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: transform_weights_for_mega_moe 用 isinstance(l1_weights, tuple) 作为 FP8xFP4 的代理条件来限制 SiTU,语义正确但略隐晦,且断言消息未说明 tuple 要求。建议在消息中补充类似 'situ requires FP8 (weight, sf) tuples' 的提示,便于用户在传入 BF16 单张量权重 + activation=situ 时快速定位原因。

🤖 v5

@ds-review-bot

Copy link
Copy Markdown
Collaborator

🤖 ds-review-bot Code Review

v6

未发现会破坏现有功能或导致 SiTU 路径错误的实质性问题。

v4

⚠️ 未完成评审(no_result_file:模型未产出结果文件)

v5

本 MR(commit 7f17040,cherry-pick 自 39d7cac,保留原作者署名与 sign-off)为 SM100 FP8xFP4 Mega MoE 增加 SiTU 门控激活支持,同时保留默认 SwiGLU 路径。审查结论:实现完整、正确,建议合并。已逐项核实:(1) activation/situ_beta/situ_linear_beta 完整贯穿对称缓冲区校验(csrc/apis/mega.hpp:45 放宽为 swiglu 或 fp8xfp4+situ)、Python API、C++ API、JIT 特化与 kernel 的统一 L1 epilogue——routed 与 shared 共用同一 epilogue(cuh:999 'Unified L1 epilogue'),单处修改即覆盖两条路径;(2) SiTU 正确限制在 FP8xFP4:SymmBuffer/transform_weights 的 Python 断言与 host 端 DG_HOST_ASSERT 双层防护,BF16 API(mega.hpp:318)保持 SwiGLU-only,bf16_mega_moe 未新增 SiTU 参数;(3) host 端校验完备:SiTU 与 activation_clamp 互斥,std::isfinite(beta) &amp;&amp; beta &gt; 0 同时拒绝 +inf/NaN/0/负值(与 PR 中 situ_beta=+inf 被拒绝的验证一致),非 SiTU 时禁止传入 beta,kernel 内 DG_STATIC_ASSERT(cuh:90)提供编译期兜底且 SwiGLU 默认 beta=0 可经短路通过;(4) JIT fmt 模板 26 个 {} 占位符与 kernel 26 个非默认模板参数逐一对应、顺序正确,Python 位置参数与 pybind 签名一致,不同 beta 生成不同代码文本因而 JIT 缓存行为正确;(5) 默认 SwiGLU 路径与改动前逐语句等价(仅 raw_gate/gate 重命名与 up 提前声明),无行为回归;(6) 测试脚本正确处理 BF16 断言、SiTU 下 clamp 置 None、beta 仅在非 BF16 分支传入、legacy TileLang baseline 在 SiTU 下跳过;(7) git diff --check 干净,工作区无未提交改动。下述评论均为非阻塞性小建议(suggestion),不影响合并。

Files reviewed: 5
Issues found: 🔵 4 suggestion
Inline comments posted: 4

⚠️ Parse warning: [v4] no_result_file:模型未产出结果文件

Comment on lines +1065 to +1066
constexpr float kInvSiTUBeta = 1.0f / kSiTUBeta;
constexpr float kInvSiTULinearBeta = 1.0f / kSiTULinearBeta;

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.

🟡 warning: 避免对极小 beta 的倒数溢出: 当任一 beta 是小于约 2.94e-39 的有限正数时,当前 API 校验会接受它,但这里的预计算倒数会溢出为 inf;零 gate/up 随后的 0 * inf 会产生 NaN,并污染激活值及 amax 归约。请保留除法,或额外要求两个倒数均为有限值。

🤖 v6

up, {kInvSiTULinearBeta, kInvSiTULinearBeta});
gate = __fmul2_rn(sigmoid, {
kSiTUBeta * tanhf(scaled_gate.x),
kSiTUBeta * tanhf(scaled_gate.y)});

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: In the SiTU branch, tanhf() is used unconditionally even when kFastMath=true, whereas the same branch switches sigmoid to math::fast_rcp and exp to __expf. SM75+ offers tanh.approx.f32 (via __tanhf or inline PTX); if profiling later shows the L1 epilogue is a bottleneck, using the approximate tanh under kFastMath would keep the precision/performance trade-off consistent with the SwiGLU fast path. PTXAS comparison already shows no stack-frame/spill regression, so this is purely optional and does not block merge.

🤖 v4f

raw_gate, {kInvSiTUBeta, kInvSiTUBeta});
const auto scaled_up = __fmul2_rn(
up, {kInvSiTULinearBeta, kInvSiTULinearBeta});
gate = __fmul2_rn(sigmoid, {

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: 延续此前的非阻塞评论:SiTU 分支在 kFastMath=true 时仍使用精确 tanhf,而同分支 sigmoid 已用 math::fast_rcp、exp 已用 __expf。PTXAS 对比显示无栈帧/spill 回归,推迟处理可接受;若后续 profiling 显示 L1 epilogue 成为瓶颈,建议在 deep_gemm/include/deep_gemm/common/math.cuh 中仿照 math::fast_rcp 添加 math::fast_tanh(内联 PTX tanh.approx.f32,SM75+ 可用),并仅在 kFastMath 下启用,使精度/性能折衷与 SwiGLU 快速路径一致。

🤖 v5

} else {
sigmoid = {1.0f / denom.x, 1.0f / denom.y};
}
auto gate = raw_gate;

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: SiTU 分支中 auto gate = raw_gate; 是死初始化:gate 在任何读取之前即被 gate = __fmul2_rn(sigmoid, ...) 无条件覆盖。编译器会消除该赋值,无正确性影响,但建议在赋值处直接声明(如 const auto gate = __fmul2_rn(...))以提高可读性。

🤖 v5

Comment thread csrc/apis/mega.hpp
const auto situ_beta = situ_beta_opt.value_or(0.0f);
const auto situ_linear_beta = situ_linear_beta_opt.value_or(0.0f);
DG_HOST_ASSERT(not use_situ or not activation_clamp_opt.has_value());
DG_HOST_ASSERT(not use_situ or

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: beta 校验逻辑正确,但 DG_HOST_ASSERT 失败时仅显示原始条件字符串。这些是面向用户的 API 约束(situ 与 activation_clamp 互斥;beta 必须有限且为正;提供 beta 必须搭配 activation='situ'),建议补充简短注释或拆分为更具描述性的断言,便于用户从报错中快速定位原因。可选、非阻塞。

🤖 v5

@ds-review-bot

Copy link
Copy Markdown
Collaborator

🤖 ds-review-bot Code Review

v6

SiTU 主路径基本完整,但合法的极小正 beta 会因倒数溢出而产生 NaN,违反当前 API 接受所有有限正 beta 的校验语义。

v4f

The MR adds SiTU (Sigmoid-Tanh-Unit) gated activation support to the SM100 FP8xFP4 Mega MoE while preserving SwiGLU as the default. Verified against HEAD be4faf9 (feat 7f17040 + perf refinement), the combined diff f8e8fb5..be4faf9 touches exactly 5 files, matching the PR description. The change is complete and internally consistent: activation/situ_beta/situ_linear_beta are threaded through symmetric-buffer validation (mega.hpp, init.py), the Python/C++ APIs (pybind positional arg order matches the C++ signature 1:1), JIT specialization (26 template placeholders align with 26 fmt args in the correct order activation_clamp -> fast_math -> use_situ -> situ_beta -> situ_linear_beta), and the single unified routed/shared L1 epilogue (if constexpr (kUseSiTU) branch computing sigmoid(gate) * betatanh(gate/beta) * beta_lintanh(up/beta_lin), which correctly degenerates to SwiGLU as beta -> inf). Restrictions are enforced as described: SiTU is limited to FP8xFP4 (Python asserts in SymmBuffer/get_symm_buffer_for_mega_moe; bf16_mega_moe remains SwiGLU-only), activation clamp is rejected for SiTU, and non-positive/non-finite betas are rejected via std::isfinite && > 0 (so situ_beta=+inf fails as claimed), with a kernel-level DG_STATIC_ASSERT backstop. All prior discussion-history items are resolved: (1) the constexpr reciprocal optimization (kInvSiTUBeta/kInvSiTULinearBeta with __fmul2_rn replacing per-element divides) landed in the perf-refinement commit be4faf9; (2) the transform_weights_for_mega_moe assertion message now reads 'situ requires FP8xFP4 (weight, sf) tuples for both L1 and L2 weights', making the tuple requirement self-documenting; (3) the float->JIT-string round trip is lossless because the shared to_string(float) in csrc/jit_kernels/impls/runtime_utils.hpp uses hexfloat fmt::format("{:a}f"), so close beta values cannot collide in the JIT cache, with no new risk beyond the pre-existing kActivationClamp pattern. git diff --check passes and the working tree is clean. Runtime claims (develop.sh build, deterministic GPU regression for both fast_math modes, PTXAS stack-frame parity) could not be re-executed in this sandbox (bash restricted to git, no CUDA device), but the committed tests/test_mega_moe_situ.py implements exactly the described metamorphic regression (seeded 20260730, finiteness, high-beta convergence to SwiGLU, and independence of the two beta controls). Approve; only one non-blocking suggestion remains.

v5

The MR cleanly adds SiTU gated activation to SM100 FP8xFP4 Mega MoE while preserving the default SwiGLU path; no correctness issues were found. Verified: (1) SiTU is restricted to FP8xFP4 — get_symm_buffer_size_for_mega_moe (csrc/apis/mega.hpp:45) requires mma_type == 'fp8xfp4' for 'situ', bf16_mega_moe (csrc/apis/mega.hpp:318) still asserts activation == 'swiglu', and sm100_bf16_mega_moe.cuh is untouched, so BF16 Mega MoE stays SwiGLU-only. (2) Beta validation (csrc/apis/mega.hpp:187-199) rejects activation_clamp together with situ, requires both betas to be provided, finite (std::isfinite rejects +inf and NaN) and strictly positive, and rejects betas without activation='situ'. (3) JIT specialization is consistent: 26 fmt placeholders match 26 arguments and the tail order (kNumSMs, kNumRanks, kActivationClamp, kFastMath, kUseSiTU, kSiTUBeta, kSiTULinearBeta) exactly matches the kernel template parameter list; float non-type template params follow the existing kActivationClamp precedent. (4) Kernel math (sm100_fp8_fp4_mega_moe.cuh:1062-1092) computes sigmoid(gate) * betatanh(gate/beta) * linear_betatanh(up/linear_beta), which converges to SwiGLU as beta -> inf; DG_STATIC_ASSERT guards non-positive betas and the SwiGLU branch is unchanged. (5) Python/pybind positional argument order is aligned end-to-end. (6) The new deterministic metamorphic test covers both fast_math modes and skips correctly on non-SM100 devices. Prior review comments: the constexpr-division comment is resolved in be4faf9 (kInvSiTUBeta/kInvSiTULinearBeta + __fmul2_rn); the to_string(float) round-trip concern is confirmed safe (runtime_utils.hpp:65 uses lossless hexfloat '{:a}f', so distinct betas always produce distinct JIT cache entries); the tuple-assertion-message comment is resolved (message now names the FP8xFP4 (weight, sf) tuple requirement). Risk: default-path regression none (SwiGLU/BF16 paths and existing signatures unchanged, new params default to None); PTXAS shows no perf regression (same 56B stack frame, zero spills vs SwiGLU).

Files reviewed: 5
Issues found: 🟡 1 warning | 🔵 4 suggestion
Inline comments posted: 5

@RayWang96
RayWang96 merged commit 8b1392b into deepseek-ai:nv_dev Aug 11, 2026
RayWang96 pushed a commit that referenced this pull request Nov 19, 2026
…26/09) as merged into nv_dev

#447 brought the content of upstream 66081d4 (#432) and 78b6900 (#441)
into nv_dev, but was squash-merged, so neither commit became an ancestor
of nv_dev and the merge base with main stayed at 559d79f (#377). This
merge records 78b6900 as the second parent without changing any file, so
the next upstream merge starts from 78b6900 instead of re-applying 26/09.

Checked before recording: of the 128 files upstream changed between
559d79f and 78b6900, 97 are byte-identical on nv_dev; a three-way merge
of 78b6900 changes no file outside its conflicts except
smxx_clean_logits.cuh, which upstream deleted and nv_dev keeps for the
SM120 and SM100 FP16-weight MQA logits; and every upstream-side line in
the 25 conflicted files is present on nv_dev or replaced by an nv_dev
change (SM120 arch/alignment generalizations, #459, #396).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

4 participants