[Megatron-LM] feat: add grouped gemm fp4 support, skip cache trans weight and santize code#891
[Megatron-LM] feat: add grouped gemm fp4 support, skip cache trans weight and santize code#891RuibinCheung wants to merge 7 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR simplifies the Megatron Primus Turbo wrapper by removing the experimental OPT-1 “fused grouped wgrad” single-GPU path and its associated debug/env-var scaffolding, returning PrimusTurboGroupedLinear to the standard grouped_gemm_fp8 backward flow.
Changes:
- Removed the OPT-1 fused grouped-wgrad branch (and
_MainGradShim) fromPrimusTurboGroupedLinear, always using the plaingrouped_gemm_fp8call. - Simplified
_bridge_weight_gradto always accumulategrad_quantized_weightintoweight.main_grad, dropping the old “fused path returns None” branch and the gfx1250 Triton add workaround. - Stopped forwarding
PRIMUS_TURBO_FUSE_GROUPED_WGRAD/PRIMUS_TURBO_FUSE_WGRAD_DEBUGinto the DeepSeek V4 1GPU example run script.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| primus/backends/megatron/core/extensions/primus_turbo.py | Removes the OPT-1 fused wgrad/debug path and simplifies FP8 weight-grad bridging back to the default grouped GEMM behavior. |
| examples/deepseek-v4/run_deepseek_v4_pro_muon_1gpu.sh | Drops forwarding of the removed OPT-1 env vars to the container runtime. |
| weight.main_grad.add_(grad_quantized_weight) | ||
| weight.grad_added_to_main_grad = True |
59a49d7 to
27f8c9c
Compare
| elif PrimusTurboLowPrecisionGlobalStateManager.is_turbo_fp4_enabled(): | ||
| quant_config = PrimusTurboLowPrecisionGlobalStateManager.get_turbo_quant_config() | ||
| assert quant_config.mxfp4_scaling(), "Turbo FP4 is enabled but quant config is not mxfp4." | ||
|
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
primus/backends/megatron/core/extensions/primus_turbo.py:190
- _WeightGradBridge.backward unconditionally calls
weight.main_grad.add_(grad_quantized_weight). If autograd suppliesNoneforgrad_quantized_weight(e.g., if an upstream op returns no wgrad), this will raise a TypeError with a hard-to-debug message. Add an explicit assertion (or guard) so failures are clearer and intentional.
weight.main_grad.add_(grad_quantized_weight)
weight.grad_added_to_main_grad = True
| try: | ||
| import triton | ||
| import triton.language as tl | ||
| pass |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (1)
primus/backends/megatron/core/extensions/primus_turbo.py:175
_WeightGradBridge.backwardassumesgrad_quantized_weightis always a Tensor. Previously this code handledgrad_quantized_weight is None(e.g., when a fused/accumulate-in-main-grad path returns no explicit weight grad). Without a guard, this will raise whengrad_quantized_weightisNone. Also, if Triton is unavailable, the gfx1250 branch should fall back toadd_()even if_is_gfx1250()returns true.
if _is_gfx1250():
inplace_add_triton_(weight.main_grad, grad_quantized_weight)
else:
weight.main_grad.add_(grad_quantized_weight)
weight.grad_added_to_main_grad = True
| try: | ||
| import triton | ||
| import triton.language as tl | ||
| pass | ||
|
|
||
| _HAVE_TRITON = True | ||
| except (ImportError, ModuleNotFoundError): | ||
| _HAVE_TRITON = False |
There was a problem hiding this comment.
Stale comment
安全审查结论:未发现此 PR 当前版本引入或暴露的中危及以上高置信漏洞,因此未提交新的行内 finding。已重点复核最新提交新增的 gfx1250 Triton 梯度累加内核、单次 microbatch 的 FP8/FP4 未缓存量化路径及 grouped MXFP4 GEMM:内核访问由实际目标张量
numel和掩码限制,输入均来自同一训练进程内的模型参数、autograd 梯度或由 MoE 路由结果生成且受 token 数量约束的计数;量化配置由受限 recipe 构造并经过格式及硬件能力检查。未发现攻击者可控输入通向注入、越权、秘密泄漏、SSRF、路径遍历、不安全反序列化或可利用越界读写 sink。此前无本自动化留下的未解决 finding 线程;旧评估已清理。Sent by Cursor Automation: Find vulnerabilities
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
primus/backends/megatron/core/extensions/primus_turbo.py:94
- The Triton availability guard is broken: the
tryblock contains onlypass, so_HAVE_TRITONis always set to True, and the subsequent unconditional import ofinplace_add_triton_will still raise ImportError when Triton isn’t installed. This both misreports capability and removes the previous graceful fallback behavior.
try:
pass
_HAVE_TRITON = True
except (ImportError, ModuleNotFoundError):
primus/backends/megatron/core/extensions/primus_turbo.py:175
_bridge_weight_gradassumesinplace_add_triton_is always importable. If Triton (or the helper module) isn’t available, this will crash on gfx1250 even though there is a safe Torch fallback.
if _is_gfx1250():
inplace_add_triton_(weight.main_grad, grad_quantized_weight)
else:
weight.main_grad.add_(grad_quantized_weight)
weight.grad_added_to_main_grad = True
| if not torch.cuda.is_available(): | ||
| return False | ||
| try: | ||
| return "gfx1250" in torch.cuda.get_device_properties(0).gcnArchName | ||
| except Exception: | ||
| return False |
There was a problem hiding this comment.
Stale comment
安全审查结论:未发现此 PR 当前版本引入或暴露的中危及以上高置信漏洞,因此未提交新的行内 finding。已复核此前评估及最新同步;当前合并提交相对前一 PR 头未改变代码。新增 Triton
inplace_add的访问范围由目标张量numel与逐元素掩码限制,调用输入来自同一训练进程内的模型参数和 autograd 梯度;新增 grouped MXFP4 路径接收框架生成的 MoE token 计数及受 MXFP4 recipe/硬件能力检查约束的量化配置。未发现攻击者可控输入通向注入、越权、秘密泄漏、SSRF、路径遍历、不安全反序列化或可利用越界读写 sink。此前本自动化没有未解决的安全 finding 线程;旧评估已清理。Sent by Cursor Automation: Find vulnerabilities
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
primus/backends/megatron/core/extensions/primus_turbo.py:94
- The Triton availability guard is currently a no-op (
try: pass) so_HAVE_TRITONis always set to True, andinplace_add_triton_is imported unconditionally. This makes the module fail to import in environments where Triton isn’t installed, and the_HAVE_TRITONflag is misleading.
Consider restoring a real optional import that both (1) detects Triton correctly and (2) avoids importing the Triton helper when Triton is unavailable.
try:
pass
_HAVE_TRITON = True
except (ImportError, ModuleNotFoundError):
primus/backends/megatron/core/extensions/primus_turbo.py:175
inplace_add_triton_can be unavailable if Triton isn’t installed (or if the import is intentionally made optional). The current code calls it unconditionally on gfx1250, which would raise at runtime in that case. Guard the call and fall back toTensor.add_when the Triton helper isn’t available.
if _is_gfx1250():
inplace_add_triton_(weight.main_grad, grad_quantized_weight)
else:
weight.main_grad.add_(grad_quantized_weight)
weight.grad_added_to_main_grad = True
| if not dst.is_cuda or not dst.is_contiguous() or dst.numel() != src.numel(): | ||
| return dst.add_(src) |
There was a problem hiding this comment.
Stale comment
安全审查结论:未发现此 PR 当前版本引入或暴露的中危及以上高置信漏洞,因此不提交新的行内 finding。
已复核历史审查线程:此前本自动化没有未解决的安全 finding。当前同步仅将
main合入分支,PR 修改的 6 个文件与上一轮已审查头提交逐字节一致。新增 Triton 梯度累加内核的访问上界由目标张量numel和逐元素掩码约束,调用参数来自同一训练进程内的模型参数与 autograd 梯度;grouped MXFP4 路径仅消费框架生成的张量、MoE token 计数及通过 MXFP4 类型和硬件能力检查的量化配置。未发现攻击者可控输入可到达注入、越权、秘密泄漏、SSRF、路径遍历、不安全反序列化或可利用的越界内存访问 sink。旧评估已清理。Sent by Cursor Automation: Find vulnerabilities
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (3)
primus/backends/megatron/core/extensions/primus_turbo.py:94
- The
try/exceptblock here is effectively a no-op (pass) and will always set_HAVE_TRITON = True, even when Triton is not installed. It also makes the subsequent Triton import unconditional, so the module can fail to import in environments without Triton. Replace this with a real optional import that definesinplace_add_triton_when available and sets it toNoneotherwise (and drop_HAVE_TRITONsince it’s unused).
try:
pass
_HAVE_TRITON = True
except (ImportError, ModuleNotFoundError):
primus/backends/megatron/core/extensions/primus_turbo.py:116
_is_gfx1250()queries device properties for device index 0, which can be the wrong GPU in multi-GPU jobs (each rank typically sets a non-zero current device). Usetorch.cuda.current_device()(andgetattrforgcnArchName) to avoid mis-detecting the architecture.
if not torch.cuda.is_available():
return False
try:
return "gfx1250" in torch.cuda.get_device_properties(0).gcnArchName
except Exception:
primus/backends/megatron/core/extensions/primus_turbo.py:175
grad_quantized_weightcan legally beNonein PyTorch autograd (e.g., if the corresponding input doesn’t require grad or an upstream op returnsNone). The current code unconditionally doesweight.main_grad.add_(grad_quantized_weight), which will throw aTypeErrorifgrad_quantized_weightisNone. Guard againstNoneand also only callinplace_add_triton_when it’s available (it should beNonewhen Triton isn’t installed).
if _is_gfx1250():
inplace_add_triton_(weight.main_grad, grad_quantized_weight)
else:
weight.main_grad.add_(grad_quantized_weight)
weight.grad_added_to_main_grad = True
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (2)
primus/backends/megatron/core/extensions/primus_turbo.py:99
- The Triton availability probe is currently a no-op (
try: pass) and sets_HAVE_TRITON = Trueunconditionally._HAVE_TRITONis also unused, whileinplace_add_triton_is imported unconditionally and will raise at import time if Triton isn't installed. This makes the module behavior inconsistent and can break environments that previously relied on the Torch fallback.
try:
pass
_HAVE_TRITON = True
except (ImportError, ModuleNotFoundError):
_HAVE_TRITON = False
from primus.backends.megatron.core.extensions._triton.inplace_add import (
inplace_add_triton_,
)
primus/backends/megatron/core/extensions/primus_turbo.py:116
_is_gfx1250()queriestorch.cuda.get_device_properties(0), which can be the wrong device on multi-GPU nodes (or when the current device is not 0). This can incorrectly enable/disable the gfx1250 workaround on a given rank.
if not torch.cuda.is_available():
return False
try:
return "gfx1250" in torch.cuda.get_device_properties(0).gcnArchName
except Exception:
There was a problem hiding this comment.
安全审查结论:未发现此 PR 当前版本引入或暴露的中危及以上高置信漏洞,因此不提交新的行内 finding。
已复核历史审查线程;此前本自动化没有未解决的安全 finding。新增 Triton 梯度累加内核的访问范围受目标张量 numel 和逐元素掩码约束,输入来自同一训练进程内的模型参数与 autograd 梯度;新增 grouped MXFP4 路径仅消费路由生成且受 token 数约束的 m_splits、框架内部张量,以及通过 MXFP4 类型和硬件能力检查的结构化量化配置。其余改动删除实验性环境变量路径或仅调整缓存策略/文档,未扩大安全边界。旧评估已清理。
Sent by Cursor Automation: Find vulnerabilities


Description
This PR adds FP4 (MXFP4) grouped GEMM support to
PrimusTurboGroupedLinear.It also fixes memory footprint by skipping the parameter transpose cache under current scaling.
Finally, it removes the experimental OPT-1 fused grouped-wgrad path together with its debug scaffolding to clean up the code.
Fixes # (issue)
Type of change
Changes
Please list the changes introduced in this PR:
PrimusTurboGroupedLinear.When Turbo FP4 is enabled, build MXFP4 (
float4_e2m1fn_x2) quantized weight buffers and dispatch togrouped_gemm_fp4, replacing the previousassert False, "FP4 is not supported in PrimusTurboGroupedLinear".disable_parameter_transpose_cacheis now OR'ed withquant_config.current_scaling()acrossPrimusTurboLinear,PrimusTurboRowParallelLinear,PrimusTurboColumnParallelLinear,PrimusTurboLayerNormColumnParallelLinear, andPrimusTurboGroupedLinear, so a stale transposed weight is not reused under current scaling.Drop the
_MainGradShimhelper, thefused_grouped_wgrad/_expert_main_grad_viewintegration, thePRIMUS_TURBO_FUSE_GROUPED_WGRAD/PRIMUS_TURBO_FUSE_WGRAD_DEBUGenv-var gating and debug prints, and the associatedis_gfx1250Triton in-place add workaround in_bridge_weight_grad._bridge_weight_gradto always accumulategrad_quantized_weightintoweight.main_gradand flaggrad_added_to_main_grad.PRIMUS_TURBO_FUSE_GROUPED_WGRADandPRIMUS_TURBO_FUSE_WGRAD_DEBUGenv vars fromexamples/deepseek-v4/run_deepseek_v4_pro_muon_1gpu.sh, and drop the unusedcontextlib/osimports.Checklist: