Repository navigation
Description
Describe the bug
Megatron-LM runs its MoE experts through TE's operation fuser when --use-transformer-engine-op-fuser --moe-grouped-gemm --swiglu are set. It builds te.pytorch.ops.Sequential(GroupedLinear, ScaledSwiGLU, GroupedLinear) from the weights of its GroupedLinear modules, with accumulate_into_main_grad=True when Megatron's gradient-accumulation fusion is on, which is the default (megatron/core/transformer/moe/experts.py:709-716 and 810-817). In BF16 we see two failures that the unfused paths do not have.
-
Misaligned address in the grouped wgrad GEMM. With one weight per expert,
GroupedLinear._fuser_backward_grouped_tensorpasses each expert'smain_gradas an output of the grouped wgrad GEMM (transformer_engine/pytorch/ops/basic/grouped_linear.py:1895-1899, GEMM call at line 1923). Megatron gives each parameter amain_gradview into one FP32 buffer. Without the distributed optimizer, the parameters are packed without padding (megatron/core/distributed/param_and_grad_buffer.py:1015-1056). A parameter whose size is not a multiple of 4 elements therefore moves every latermain_gradoff 16-byte alignment. In our runs that parameter is the MoE router bias, which has one element per expert. With 3 experts, the weight gradients of the layer-0 experts start 12 bytes past a 16-byte boundary, and the wgrad GEMM fails. WithCUDA_LAUNCH_BLOCKING=1the error is raised at that call:RuntimeError: /TransformerEngine/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu:1115 in function execute_grouped_gemm: cuBLAS Error: the function failed to launch on the GPUWithout it, the run fails with
torch.AcceleratorError: CUDA error: misaligned address. In both cases a destructor then raisesCUDA error: misaligned addressat teardown ("terminate called after throwing an instance of 'c10::AcceleratorError'"), so the process aborts with SIGABRT. The same run trains with--no-gradient-accumulation-fusion(the wgrad goes into freshly allocated tensors), with--use-distributed-optimizer(Megatron then pads every parameter start to 64 elements), and with 4 experts (a 4-element router bias). In earlier runs, 2, 5 and 6 experts with biases also failed, and so did input widths 1 and 9 with the norm described in (2), whose weight and bias have one element per input feature each. These cases fit the same pattern: the parameters packed before the expert weights add up to a size that is not a multiple of 4.TE's non-grouped GEMM passes the actual alignment of A, B, C and D to the cuBLASLt heuristic (
transformer_engine/common/gemm/cublaslt_gemm.cu:750-761).select_grouped_gemm_algo(cublaslt_grouped_gemm.cu:994-1027) sets no alignment preference, and the output pointers are not checked. -
NaN gradients with a first-GEMM input width (
in_features) of 2. Megatron's latent MoE (--moe-latent-size) sets this width. With width 2 and a norm before the up projection (--moe-use-norm-before-up-proj), the gradient norm is NaN in the first step and the loss is NaN in the second. Width 8 trains. This is a separate problem from (1): every expertmain_gradstarts on a 16-byte boundary in this run, and with--no-gradient-accumulation-fusion(nomain_gradinvolved) the NaN is the same. It depends on the width: with width 2, the rows of the input and of the weight gradient are shorter than 16 bytes. In earlier runs, widths 4, 6 and 12 also gave NaN, every multiple of 8 trained, and Megatron's experts without the op fuser (te.pytorch.GroupedLinearmodules, and oneLinearper expert) trained with widths 1 and 2. A NaN is the worst outcome here: a run without a NaN check would train on garbage.
The CuTe-DSL fused grouped MLP is not involved. In TE 2.19.0 it is registered only with NVTE_CUTEDSL_FUSED_GROUPED_MLP=1 (transformer_engine/pytorch/ops/fused/grouped_mlp.py:916) and used only with an MXFP8 or NVFP4 recipe (grouped_mlp.py:815-816). These runs are BF16 and do not set the variable.
Steps/Code to reproduce bug
We reproduce this through Megatron-LM (main at 23a3025, one GPU, mock data). The Megatron-LM code involved is unchanged on main at 928ce7c (2026-11-08); Megatron-LM line numbers refer to that commit, TE line numbers to v2.19.0. We can try to reduce it to a standalone te.pytorch.ops script if that helps.
git clone https://github.com/NVIDIA/Megatron-LM && cd Megatron-LM && git checkout 23a3025cb85c4ce676a80a08c1e44fdd42e49d92
BASE="--num-layers 2 --hidden-size 256 --num-attention-heads 4 --seq-length 512 \
--max-position-embeddings 512 --micro-batch-size 2 --global-batch-size 8 \
--mock-data --tokenizer-type NullTokenizer --vocab-size 1024 --bf16 \
--train-iters 3 --lr 1e-4 --log-interval 1 --eval-iters 0 --eval-interval 1000 \
--use-transformer-engine-op-fuser --moe-grouped-gemm --swiglu"
# (1) 3 experts with biases (4 experts, --no-gradient-accumulation-fusion or --use-distributed-optimizer train)
CUDA_LAUNCH_BLOCKING=1 torchrun --nproc_per_node 1 pretrain_gpt.py $BASE --no-bias-dropout-fusion --num-experts 3
# (2) input width 2 (width 8 trains; --no-gradient-accumulation-fusion does not help)
torchrun --nproc_per_node 1 pretrain_gpt.py $BASE --disable-bias-linear --num-experts 2 \
--moe-latent-size 2 --moe-use-norm-before-up-proj
Result of (1), in the first backward pass, then SIGABRT:
File ".../transformer_engine/pytorch/ops/basic/grouped_linear.py", line 1923, in _fuser_backward_grouped_tensor
wgrad_gemm(grouped_x, grouped_dy, wgrad_output)
File ".../transformer_engine/pytorch/cpp_extensions/gemm.py", line 670, in general_grouped_gemm_for_grouped_tensor
return grouped_gemm_impl(
RuntimeError: /TransformerEngine/transformer_engine/common/gemm/cublaslt_grouped_gemm.cu:1115 in function execute_grouped_gemm: cuBLAS Error: the function failed to launch on the GPU
terminate called after throwing an instance of 'c10::AcceleratorError'
what(): CUDA error: misaligned address
Result of (2), first two steps:
iteration 1/ 3 | ... | lm loss: 7.004893E+00 | ... | grad norm: nan | ...
ERROR:megatron.core.rerun_state_machine:Unexpected result nan on rank 0 at iteration #3 invocation #1 (message='found NaN in local forward loss calculation')
Megatron's NaN check then stops the run. Reproduced on 2026-11-07 and 2026-11-08 with TE 2.19.0.
Expected behavior
The grouped GEMM accepts the buffers that the non-grouped GEMM accepts: it selects an algorithm for the actual alignment of its inputs and outputs, falls back to a path that supports them, or raises a clear error that names the constraint. Small input widths give correct gradients, as in the unfused paths. A silent NaN should not be possible.
Environment overview (please complete the following information)
- Environment location: Docker.
- Method of Transformer Engine install:
pip install --no-cache-dir --no-build-isolation "transformer_engine[pytorch]==2.19.0"on top ofnvcr.io/nvidia/pytorch:26.08-py3. - If method of install is [Docker], provide
docker pull&docker runcommands used:docker pull nvcr.io/nvidia/pytorch:26.08-py3, then thepip installabove in a derived image; run with--gpus alland the Megatron-LM tree mounted.
Environment details
NVIDIA docker image nvcr.io/nvidia/pytorch:26.08-py3: PyTorch 2.14.0a0, CUDA 13.4. Transformer Engine 2.19.0 (installed as above).
Device details
- GPU model: NVIDIA B300 SXM6 (compute capability 10.3); the runs above use one GPU.
Additional context
We found no matching issue in TransformerEngine or Megatron-LM. We first saw both failures with Megatron-LM bab851bf and TE 2.18 and 2.19. The distributed optimizer's padding is in megatron/core/optimizer/distrib_optimizer.py:720. We report the unpadded buffer layout to Megatron-LM separately (NVIDIA/Megatron-LM#9193).
On main (c1c2d4d, 2026-11-07), #3785 (merged on 2026-10-31, not yet in a release) added checks that the uniform last dimension of A, B and D, and the leading dimension of each tensor in a discrete A list, span a multiple of 16 bytes (cublaslt_grouped_gemm.cu:1597-1614 and 635-638). With these checks, (2) probably fails with a clear error instead of a NaN; we have not run it, and small widths would still not be supported as in the unfused paths. The pointers of a discrete D list are still not checked (build_grouped_gemm_multi_out_args, cublaslt_grouped_gemm.cu:578-608), and select_grouped_gemm_algo (lines 1024-1053) still sets no alignment preference, so (1) is unchanged in the source. We have not run TE 2.20 or main.
How we found it. We are researchers at the University of Seville (Diverso Lab). We are building a feature model of Megatron-LM's configuration space in UVL, the Universal Variability Language (Benavides et al., UVL: Feature modelling with the Universal Variability Language, Journal of Systems and Software 225, 2025, https://doi.org/10.1016/j.jss.2024.112326). UVL is a knowledge representation from software product-line engineering. The model is available at https://github.com/jagalindo/megatron-lm-uvl. The model has every command-line argument (877) and environment variable (59) as a typed feature, plus 525 cross-tree constraints that encode the checks in validate_args and the config dataclasses. We extracted it by static analysis of the source. We then use a solver (flamapy with Z3) to generate test configurations: samples that satisfy every constraint, which Megatron should accept and train, and mutants that each violate one constraint, which Megatron should reject at the check the constraint was derived from. Each configuration is run on real GPUs, so Megatron serves as the test oracle. A configuration that the model accepts but Megatron crashes on, hangs on, or rejects at an unrelated point is how bugs like this one surface. These came from valid samples of Megatron-LM with the op fuser (2 or 3 experts with biases, and small --moe-latent-size values); further runs on one GPU mapped the limits.
We thank Verda (@verda-cloud) for the GPU resources (8× NVIDIA B300) used to run this campaign.
Activity
siddhant-rajhans commentedon Nov 10, 2026
Thanks for the detailed report. I reproduced (1) on Hopper as well: H100 with NGC PyTorch 26.10 (cuBLASLt 13.8.1), on TE 2.20.2 and main, both standalone with
te.ops.GroupedLinearand with your Megatron-LM command. #3845 computes misaligned outputs through aligned buffers and adds a host-side pointer check; with it, your 3-expert command trains. I could only test Hopper, so if you can run your B300 configurations against the branch, that would cover Blackwell.jagalindo commentedon Nov 10, 2026
Thanks a lot @siddhant-rajhans, that was quick!
I tried #3845 on a B300 (sm_103) this morning, building TE from your branch and from main (8b34364) for comparison, with the same Megatron-LM setup as in the report.
misaligned addresson main, trains fine with your branch (grad norms 0.769 / 0.732 / 0.710, same as what we got before with--no-gradient-accumulation-fusion).unalignedtests: all 18 pass on your branch; on main they fail with the misaligned address error.So it looks good on Blackwell too. One thing: our container (NGC PyTorch 26.08) ships cuBLASLt 13.7.0, and TE warns on both builds that this version has a grouped GEMM bug and recommends 13.8.1+. I didn't have a newer cuBLAS at hand, so these results are with 13.7.0.
siddhant-rajhans commentedon Nov 10, 2026
Thank you for running it on B300; I've added your results to the PR description. Since then, fb1c833 makes the staging run the same GEMM on an aligned copy of the output, which fixes an edge case with bias that the FP32
main_gradpath does not hit, so your results still apply.vthumbe1503 commentedon Nov 18, 2026
Thanks @siddhant-rajhans for the PR and also @jagalindo to test out the solution on Megatron side.
I think the right solution to this exists on Megatron side. Can we simply pad the main_grad buffer on the Megatron side to have 16byte alignment requirement instead. Concern I have with a TE solution is that We are inducing a performance penalty silently for unaligned inputs by doing an additional D2D copy.
Handling additional padding with Megatron's main_grad buffers, we wont need that addtional copy.
jagalindo commentedon Nov 18, 2026
Thanks @vthumbe1503, that makes sense to me. For reference, the Megatron-LM side was reported as NVIDIA/Megatron-LM#9193, and NVIDIA/Megatron-LM#9564 from @siddhant-rajhans adds the padding.
I tried both PRs together on a B300: with #9564 the 3-expert case trains, and without it the new check in #3845 gives a clear "must be 16-byte aligned" error instead of the crash. Details are in the Megatron-LM PR.
pggPL commentedon Nov 25, 2026
Both parts are now addressed on TE
main:main_gradpadding tracked on the Megatron-LM side in Without the distributed optimizer, main_grad views are not 16-byte aligned, and the TE op-fuser MoE experts crash with "misaligned address" Megatron-LM#9193 / Align parameter starts in the gradient buffer without the distributed optimizer Megatron-LM#9564).Closing as completed on the TE side.