[BUG] FP32 MoE router has TE/fallback numerical mismatch on H200 hidden by test tolerances; downstream GLM parity diverges
Describe the bug
Follow-up to #4914 and its merged tolerance adjustment #4915. @NVIDIA/mcore-oncall
With BF16 router inputs/weights and moe_router_dtype="fp32", RouterGatingLinearFunction.forward has backend-dependent computation semantics:
# TE path: BF16 operands, FP32 output
te_general_gemm(weight, inp, torch.float32, layout="TN", bias=None)[0]
# Non-TE path: explicitly FP32 operands and output
torch.mm(inp.float(), weight.float().t())
We measured a difference on H200, even though it is small enough to pass both the original and relaxed router unit-test tolerances. In a downstream real-weight GLM-5.3-Flash forward ablation, leaving this router difference as the only unaligned factor produces substantial final-logit divergence after 45 layers.
The concrete concern is the precision contract and regression coverage for an FP32 router. FP32 output dtype does not make these two operand/compute paths numerically interchangeable. This report does not establish a defect in TE's BF16 GEMM contract, or require arbitrary different GEMM implementations to be universally bitwise identical.
Measured operator evidence
40 cases: H=4096, 288 experts, S=17/65/2048/4096/8192, eight independent GPU ranks using real BF16 gate weights from layers [3,4,7,22,43,44,3,44] and seeded synthetic BF16 activations. TF32 disabled. FP64 reference multiplies the same already-representable BF16 operand values.
| Path | Bitwise matches FP32 F.linear reference |
Worst maxabs vs that reference | Worst relative L2 vs FP64 |
|---|---|---|---|
| Current Core TE, BF16 operands / FP32 output | 0/40 | 7.915496826171875e-5 | 4.417671635972549e-6 |
| Core fallback, explicit FP32 operands | 40/40 | 0 | 3.022438903911386e-7 |
| TE with operands explicitly cast to FP32 | 40/40 | 0 | 3.022438903911386e-7 |
Every discrepancy above fits even within the old atol=1e-3. The current test uses atol=1e-2, rtol=2e-2 for FP32 after #4915. Consequently, passing that test cannot establish strict FP32-reference compatibility. The smaller H200 differences are compatible with the earlier maintainer observation that the H20 unit-test failure was not reproduced on H100/H200.
Source inspected on upstream main on 2026-10-12: moe_utils.py blob aa60d2d3df038089878932959c85fa678bcb271b; test_routers.py blob 4cfbcb5d82e96ee383caccfc1a4936a55372a6ee. The differing operand casts remain present. The upstream TE bias-casting change does not affect this report (bias=None). GPU measurements were run on the pinned downstream Core revision below, not on a freshly executed upstream-main checkout.
Controlled downstream effect
We compared the two router paths while holding expert accumulation order, top-k ordering/normalization, dense/shared gate/up projection layout and post-FC2 expert weighting aligned to the native reference. Both arms share the same checkpoint, tokens and reference; all 45 layers propagate their own accumulated hidden states. Three repeats per arm and length gave identical results within each arm.
| S | Only router GEMM unaligned: final-logit relative L2 | Explicit FP32 router: final-logit relative L2 | Loss delta with router unaligned |
|---|---|---|---|
| 2048 | 20.471948% | 0 | -0.0010100156 |
| 4096 | 16.054147% | 0 | +0.0000180807 |
| 8192 | 13.049029% | 0 | +0.0001743352 |
First nonzero accumulated difference occurs at zero-based layer 3 (first MoE). Later MoE selections diverge; at 4K/8K DSA selections also diverge. Explicit FP32 F.linear router with the other factors aligned gives exact layer outputs, logits, loss and selections. This is a conditional ablation, not an additive attribution of the original baseline's total error. The whole-model explicit-FP32 arm uses F.linear; retaining TE with FP32 operands has so far only been verified in the operator experiment above.
The inputs are repeated diagnostic text, with shared token prefixes. These logits differences do not imply an equivalent quality/perplexity regression. This evidence is forward-only, single-GPU model execution per rank (TP/CP/PP/EP/ETP=1), using identically dequantized checkpoint projections and a pinned recurrent-KDA/eager-attention reference. Production training, distributed backward, other kernels and performance remain unvalidated.
Steps/Code to reproduce bug
Existing upstream test:
python -m pytest tests/unit_tests/transformer/moe/test_routers.py -k test_router_gating_linear -v
Passing this test is expected to miss our measured H200 discrepancy at its existing tolerances. Compare the individual paths and report exactness, maxabs and relative L2 in addition to allclose.
Below is a reduced standalone diagnostic extracted from the measured harness. Supply an existing GLM-5.3-Flash checkpoint directory containing its safetensors index. It preserves the three call paths and actual gate-weight shapes. This shortened snippet has been syntax-checked but has not been rerun verbatim; the numerical table comes from the completed 40-case harness linked below. Its RNG stream differs from that harness, which performed combine diagnostics before router measurements; exact numerical values are not promised.
NVIDIA_TF32_OVERRIDE=0 OMP_NUM_THREADS=1 python repro_router.py /path/to/GLM-5.3-Flash
import json
import sys
from pathlib import Path
import torch
import torch.nn.functional as F
from safetensors import safe_open
from megatron.core.transformer.moe import moe_utils as mu
root = Path(sys.argv[1])
weight_map = json.loads((root / "model.safetensors.index.json").read_text())["weight_map"]
torch.cuda.set_device(0)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
te = mu.te_general_gemm
assert te is not None
print({"torch": torch.__version__, "cuda": torch.version.cuda,
"gpu": torch.cuda.get_device_name()})
@torch.no_grad()
def compare(x, w):
ref = F.linear(x.float(), w.float())
ref64 = F.linear(x.double(), w.double())
current = mu.router_gating_linear(x, w, None, torch.float32)
try:
mu.te_general_gemm = None
fallback = mu.router_gating_linear(x, w, None, torch.float32)
finally:
mu.te_general_gemm = te
cast_te = te(w.float(), x.float(), torch.float32, layout="TN")[0]
for name, y in [("core_te", current), ("fallback", fallback),
("te_fp32_operands", cast_te)]:
assert y.dtype == torch.float32 and torch.isfinite(y).all()
delta = y.double() - ref.double()
print({"path": name, "exact": torch.equal(y, ref),
"maxabs": delta.abs().max().item(),
"rel_l2": (delta.norm() / ref.double().norm()).item(),
"rel_l2_fp64": ((y.double() - ref64).norm() / ref64.norm()).item(),
"old_test_pass": torch.allclose(y, ref, atol=1e-3, rtol=2e-2),
"current_test_pass": torch.allclose(y, ref, atol=1e-2, rtol=2e-2)})
for slot, layer in enumerate([3, 4, 7, 22, 43, 44, 3, 44]):
torch.manual_seed(21200 + slot)
key = f"model.language_model.layers.{layer}.mlp.gate.weight"
with safe_open(str(root / weight_map[key]), framework="pt", device="cpu") as f:
w = f.get_tensor(key).cuda()
assert w.dtype == torch.bfloat16 and tuple(w.shape) == (288, 4096)
for seq in [17, 65, 2048, 4096, 8192]:
x = torch.randn((seq, 4096), device="cuda", dtype=torch.bfloat16)
print({"slot": slot, "layer": layer, "seq": seq})
compare(x, w)
Expected behavior
Please clarify whether moe_router_dtype="fp32" is intended to specify output storage only, or a strict FP32-operand computation path consistent with the fallback and reference models.
For workloads requiring the latter, provide or preserve a supported path that casts input/weight to FP32 before GEMM. Keeping TE with explicitly cast operands is a candidate: it matched all 40 tested operator cases. Memory/performance and full backward behavior need validation before adopting a runtime change.
Please strengthen regression coverage for this precision contract: compare TE and fallback using identical BF16 source values against an FP64 reference, record actual errors, and include sensitive routing/accumulated-forward checks. A test-tolerance relaxation alone cannot address the measured end-to-end compatibility failure. Portable tests need justified numerical bounds; the observed bitwise matches are evidence for this tested stack, not a universal backend guarantee.
Additional context
- Measured environment: NVIDIA H200; PyTorch
2.10.0a0+b558c986e8.nv25.11; CUDA 13.0; Python 3.12.3;NVIDIA_TF32_OVERRIDE=0, PyTorch TF32 disabled. Exact TE package version was not captured in this operator run's environment record; we do not infer it from #4914's environment. - Pinned measured downstream Core revision:
china-qijizhifeng/Nex-Megatron@2f83fe50f1435429cd60b8fb104d7bfb6e583b53; the relevant no-bias TE/fallback operand handling matches the inspected upstream paths. - Operator evidence: completed eight-rank run, 40 router cases; harness SHA256
293141524683997d7226c6a157abe6eb7ebb301b7637c846806bb0b11e3fb6d9. For S=65, current TE and fallback input/weight gradients each matched the native reference on all eight ranks; this does not establish full-depth backward correctness. - Full 2K/4K/8K factorial results: compare ACD (router is the only unaligned factor) with ABCD (all factors aligned). All 144 cases completed; failing controls retained their original failed numerical gates.
- Full-depth deterministic-combine follow-up: 48/48 chains exact with other factors aligned, confirming that existing scoped deterministic combine can match the reference at H=4096.
- Native Transformers reference pinned at
eb4d9e2a64a013bec12289288b85d0b1210ba0aa; modeling-source SHA2562092bbb4efa2a8087b74f4a4da37635c503fe1df9ae73f1e6e8342af8b4b8e8b. Weight-provenance manifest SHA256cb7c51e342115ed05b2e38ae17803a5c2d1c5454a484428d974de1f70a691eeb; reference/weight hashes and shared token prefixes verified.
Please provide the exact TE build and an accessible upstream reproducer. We should clarify whether FP32 routing promises FP32 operands, then compare both backends against a higher-precision reference, including gradients and routing sensitivity. Explicit operand casts are a candidate, subject to memory/performance validation.
Picking this up — below are the three artifacts requested in
https://github.com/NVIDIA/Megatron-LM/issues/8126#issuecomment-6155415855
(the accessible reproducer, the exact TE build, and the higher-precision
comparison including gradients and routing sensitivity), measured on GB200
(sm_100) as an independent data point next to the reporter's H200 numbers,
plus one finding that goes beyond the original report: the backward's
FP32-operand intent does not actually hold on the TE path — its grad GEMM
computes in TF32 regardless of torch.backends.cuda.matmul.allow_tf32=False.
Environment
- GB200 (sm_100), CUDA 12.8, torch 2.7.1+cu128, TransformerEngine 2.16.0 (the exact TE build used for all numbers below)
- Megatron-LM main @ a77288b (source-level reference for the call forms)
- TF32 disabled on the torch side for every measurement
(
torch.backends.cuda.matmul.allow_tf32 = False)
Reproducer
Zero-dependency (torch + transformer_engine only, no megatron import),
mirroring the exact call forms of RouterGatingLinearFunction in
megatron/core/transformer/moe/moe_utils.py:
repro_router_gemm.py (forward + routing)
import torch
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
from transformer_engine.pytorch.cpp_extensions import general_gemm
def te_fwd(weight_bf16, inp_bf16): # mcore TE path: BF16 operands, FP32 out
return general_gemm(weight_bf16, inp_bf16, out_dtype=torch.float32,
quantization_params=None, gelu=None, gelu_in=None,
accumulate=False, out=None, bias=None,
use_split_accumulator=False, grad=False,
ub=None, ub_type=None, extra_output=None,
bulk_overlap=False, layout="TN")[0]
def fb_fwd(weight_bf16, inp_bf16): # mcore fallback path: FP32 operands
return torch.mm(inp_bf16.float(), weight_bf16.float().t())
def ref(weight_bf16, inp_bf16): # FP64 reference
return torch.mm(inp_bf16.double(), weight_bf16.double().t())
torch.manual_seed(42 + S)
inp = torch.randn(S, 4096, device='cuda').to(torch.bfloat16)
weight = (torch.randn(288, 4096, device='cuda') * 0.02).to(torch.bfloat16)
a, b, c = te_fwd(weight, inp), fb_fwd(weight, inp), ref(weight, inp)
# metrics: bitwise match vs C, rel err, and top-8 flip rate between a and b
1. Forward: the two paths are not interchangeable (confirms the report)
| S | A (TE, BF16 ops) vs FP64 | B (fallback, FP32 ops) vs FP64 |
|---|---|---|
| 17 | rel 4.39e-06, bitwise 0.000 | rel 1.83e-07, bitwise 0.000 |
| 2048 | rel 4.42e-06, bitwise 0.000 | rel 6.12e-07, bitwise 0.000 |
| 8192 | rel 4.41e-06, bitwise 0.000 | rel 6.11e-07, bitwise 0.000 |
The TE path's error is consistently ~7-24x the fallback's, and the two paths disagree bitwise almost everywhere (A-vs-B bitwise ≈ 0.4%, max abs diff 2-4e-05). This reproduces the report's semantics claim on a different architecture (GB200 vs H200).
2. Routing sensitivity (gap analysis)
On synthetic BF16 inputs (S=8192, H=4096, E=288): A-B divergence is max 4.24e-05 / p99.9 2.10e-05, while the empirical top8/top9 logit-gap distribution has 0.098% of tokens below 1e-04 and 1.34% below 1e-03. So a single layer flips few tokens (our synthetic runs measured 0 top-8 flips — synthetic gaps are large), but the flip probability is a systematic nonzero quantity driven by the tail of the gap distribution; over 45+ routed layers and real-weight logits (which sit closer together) this is exactly the divergence amplifier the original report observed downstream. We did not attempt to manufacture flips with adversarial inputs — the honest statement is "divergence scale overlaps the gap-distribution tail", with numbers above.
3. Backward: the FP32-operand intent does NOT hold on the TE path (new)
RouterGatingLinearFunction.backward deliberately casts operands to
router_dtype (FP32) before both TE calls. Measured with FP32 outputs
(before the cast-back to BF16, i.e. isolating the GEMM itself):
| grad tensor | TE grad path vs FP64 | fallback torch.mm vs FP64 |
|---|---|---|
| grad_input [S,H] | 2.081e-04 | 3.055e-07 |
| grad_weight [E,H] | 2.082e-04 | 8.121e-07 |
That ~680x gap is not accumulation order. Fingerprint test on the same
inputs (fallback torch.mm under different math modes):
| compute path | rel vs FP64 |
|---|---|
| FP32 operands, tf32 OFF | 3.055e-07 |
| FP32 operands, tf32 ON | 2.081e-04 |
| TE general_gemm(grad=True), FP32 operands | 2.081e-04 |
The TE grad GEMM's error is bit-for-bit at the TF32-on fingerprint
(2.081e-04 == 2.081e-04): despite FP32 operands and the torch-side
allow_tf32=False, TE's cuBLASLt path computes in TF32 (or an
equivalent-precision configuration). So on this stack the backward's
explicit .to(router_dtype) casts buy nothing on the TE branch — its
gradients land ~3 orders of magnitude further from the FP64 reference than
the plain torch.mm fallback.
Two API notes for reproduction (TE 2.16.0):
general_gemm(..., grad=True)expects the matrices transposed relative to the call form currently in main (passingweight[E,H] as A raises a cublasLt dimension assertion;weight.t()[H,E] works and returns [S,H]).- The grad-path fingerprint above used the working transposed form; the mcore call form as written does not execute on this TE version.
Implication for the fix direction
"Explicit operand casts" resolves the forward asymmetry (one side of the
contract), but per §3 the backward also needs either (a) routing both
backward GEMMs through torch.mm as the fallback does, or (b) pinning TE's
math mode to true FP32 for the router GEMMs — otherwise the router's
gradient contract stays silently TF32-grade on the TE path. Happy to open a
PR for whichever behavior maintainers prefer.
@tang-t21 — your H200 numbers are consistent with everything we measure here on GB200; the reproducer above should let you attach exact TE-build numbers to the original report if you're still on this.
Follow-up to my earlier comment (https://github.com/NVIDIA/Megatron-LM/issues/8126#issuecomment-6516445559), hardening the §3 fingerprint claim at tensor level — same seed/inputs as above, so the error norms reproduce the posted numbers exactly (2.081e-04 / 3.055e-07):
| comparison (grad_input, [2048, 4096]) | bitwise match | max abs diff |
|---|---|---|
TE general_gemm(grad=True) vs torch.mm tf32 ON |
1.000000 (every element) | 0 |
TE general_gemm(grad=True) vs torch.mm tf32 OFF |
0.000132 | 3.98e-04 |
So the backward's TE path doesn't merely show a TF32-grade error signature — its output is bitwise identical to a tf32 GEMM (same kernel selection, same bits), while differing from the true-FP32 torch.mm everywhere. On this stack, the explicit FP32-operand casts in RouterGatingLinearFunction.backward have no effect on the TE branch.
One more datapoint relevant to the fix direction: we tested the "explicit operand casts" candidate on the forward, and it does not deliver FP32 either.
With allow_tf32=False, general_gemm(weight.float(), inp.float(), out_dtype=fp32) (layout "TN") produces output that is bitwise identical to a torch.mm run with TF32 enabled (100% of elements, max abs diff 0, verified at S=2048 and S=8192) and matches a true-FP32 torch.mm on only ~0.26% of elements. So on this stack, TE's cuBLASLt path truncates to TF32 regardless of operand dtype — in both the forward and the grad GEMMs. Casting the operands only costs time (+38 µs at S=2048, +122 µs at S=8192) and memory, with no precision change.
Given that, the only path we measured that actually honors the FP32 router contract is the plain torch.mm branch that already exists as the fallback in both forward and backward. For the memory/perf validation: routing both backward GEMMs through torch.mm costs +17 µs (S=2048) / +430 µs (S=8192) per layer and saves 33 / 134 MB of peak memory (TE workspace), ~4% of a top-8 MoE block's expert GEMM time at S=8192. We're happy to open the PR (extend the existing fp64 exclusion to fp32) whenever useful.
Opened #8940 implementing option (a) — routing the FP32 router GEMMs through torch.mm by extending the existing fp64 exclusion, with a regression test. Happy to adjust if maintainers prefer a different contract.
The fix for this is up in #8940 (validated on the fingerprint case from this thread). If you get a chance to check it against your H200/GLM reproduction, a confirmation here would help the reviewers — no rush.
Thanks for the follow-up. I reran PR #8940 against the original H200/GLM reproduction.
Environment:
- NVIDIA H200, 8 GPUs
- CUDA 13.0
- PyTorch
2.10.0a0+b558c986e8.nv25.11 - Transformer Engine
2.20.2+6ea2a74 - TF32 disabled
- Megatron-LM source at
a8b812d29b4c8b29ccb85d654db4acb0c83975d6 - Real GLM-5.3-Flash gate weights
- Sequence lengths 17, 65, 2048, 4096, and 8192
The PR path matched the explicit FP32 reference exactly in all 40 forward cases. The input and weight gradients also matched exactly across all 8 ranks. Top-8 expert routing had zero set changes.
The direct TE path still showed the discrepancy described in this issue, with a maximum absolute error of approximately 8.20e-5 against the FP32 reference. The PR’s torch.mm fallback removes this difference in the tested cases.
Thanks @tang-t21 and @YYuJLiu for the careful measurements.
Sorry for the late reply. I spent some time on analysing where the forward and backward errors actually come from, because they have different root causes and calling both "TF32-grade" hides that.
Forward: an accumulation difference, not TF32 operand rounding
In the forward, both operands are BF16 (8 significant bits). TF32 has 11 significant bits and the same exponent range, so every BF16 value is exactly representable in TF32. Rounding BF16-derived FP32 operands to TF32 therefore loses nothing. This explains why, in our measurements, these two paths are bitwise identical:
- the BF16 GEMM with FP32 accumulation and FP32 output (current TE path)
- the FP32 GEMM with TF32 enabled on the same BF16-derived values (
.float()+ TE, ortorch.mmwithallow_tf32=True)
Both feed identical operand values to the Tensor Cores, the products are exact (BF16×BF16 needs at most 16 bits), and both use the same MMA accumulation.
Also, we expected it's identical to a true-FP32 path as well, because no information is added or lost among these paths. However it's not the case as @YYuJLiu shows.
The remaining difference from the true-FP32 path (CUBLAS_COMPUTE_32F, which runs on SIMT FFMA) is in accumulation. FFMA rounds each multiply-add to FP32 round-to-nearest. A Tensor Core MMA instead calculates a block of products and rounds once into the FP32 accumulator.
The numbers in this thread match that picture. The relative L2 error vs FP64 is ~4.4e-6 for the BF16 Tensor Core path and ~2e-7 to 6e-7 for FFMA, a ~10× gap. While TF32 operand rounding would give something on the order of its unit roundoff, 2^-11 ≈ 4.9e-4, which is two orders of magnitude larger than what is observed. So the forward error is not TF32-grade. It is an FP32-accumulation-class difference between Tensor Core and FFMA.
This also reconciles the two sets of observations:
- @tang-t21's runs used
NVIDIA_TF32_OVERRIDE=0, which overrides TE's TF32 choice, so "TE with operands cast to FP32" ran true FP32 and matched the reference 40/40. - @YYuJLiu's GB200 runs only set
torch.backends.cuda.matmul.allow_tf32=False, which TE does not consult, so the cast-to-FP32 TE path ran in TF32 and was bitwise equal to the BF16 path.
Backward: true TF32 operand rounding
In the backward, grad_output is a real FP32 tensor, not BF16-derived. TE currently hard-codes CUBLAS_COMPUTE_32F_FAST_TF32 whenever A, B, and D are all FP32 (cublaslt_gemm.cu). This setting ignores PyTorch's allow_tf32 (while NVIDIA_TF32_OVERRIDE is respected by cuBLAS). Each grad_output element is therefore rounded to 11 significant bits, a relative perturbation of up to ~4.9e-4. That is consistent with the ~2.1e-4 normwise error @YYuJLiu measured. The BF16 weight and BF16 input lose nothing, and the Tensor Core accumulation term (~1e-6) is negligible next to the operand error.
So the backward error is genuinely TF32-grade, and it comes from the operand that is truly FP32.
On impact: grad_input is cast back to BF16 (u ≈ 3.9e-3) right after, which largely masks this error. grad_weight is where it is more likely to persist. We are not aware of end-to-end convergence data for either yet. The 13–20% final-logit divergence in @tang-t21's report is forward-only and comes from discrete top-k flips amplified across 45 layers. Any implementation that is not bitwise identical to the reference, including a different FP32 FFMA kernel order, could trigger that divergence.
The solutions we expected
The general rule we expected:
- Avoid materializing FP32 intermediates.
- Keep the precision as much as possible.
- Achieve high performance.
For the forward, when route_dtype=fp32 is set, both accumulation and output are in FP32 now. While the error is much smaller than BF16/TF32 GEMMs, it's worse than the FP32 FFMA path. We need to understand how big the impact is.
For the backward, we admit that even when route_dtype=fp32 is set, certain precision is lost with grad_output being casted to TF32, which could be avoided by setting NVIDIA_TF32_OVERRIDE=0. This is a temporary solution and should be superseded by some further fix.
Thanks for separating the forward accumulation difference from the backward operand rounding. I followed up on both and tested a per-call TE precision control as a possible follow-up to #8940.
- GB200, temporary override. With PyTorch TF32 disabled in both processes,
NVIDIA_TF32_OVERRIDE=0made TE match stricttorch.mmbitwise on all 32 raw backward comparisons (dXanddW, four token counts, two weight dtypes, and twograd_outputsources). In forward, TE with operands cast to FP32 matched bitwise at 2,048 and 8,192 tokens. At 17 and 65 tokens it still differed, with relative L2 error of about1.3e-7against FP64. The BF16 TE forward remained at about4.4e-6against FP64. This run used PyTorch 2.7.1, CUDA 12.8, and TE 2.16.0. - Weight gradients. At 2,048 tokens with BF16 inputs and native FP32
grad_output, rawdWrelative L2 error against FP64 was2.08e-4for default TE and8.12e-7for stricttorch.mm. For BF16 weights, 89.62% of the returned BF16dWentries matched the strict path bitwise. FP32 weights keep the rawdW. In the BF16-derivedgrad_outputcontrol, default TE's rawdWerror fell to3.30e-6, and 99.84% of the returned BF16 entries matched. Thegrad_outputdistributions and convergence of a training run remain unmeasured. - Forward routing sensitivity. With public GLM-5.3-Flash gate weights and correction biases from six layers, synthetic BF16 activations, four seeds, and five token counts, BF16 TE versus strict FP32 changed the top-8 expert set in 68 of 346,032 token evaluations (0.0197%). In 59 of those 68, the strict reference's eighth and ninth scores were exactly tied after sigmoid and bias. Nine had a positive reference margin. The maximum absolute logit difference was
1.01e-4. These are standalone router evaluations using synthetic activations. Checkpoint revision
I also prototyped general_gemm(..., allow_tf32=False) in TE to request CUBLAS_COMPUTE_32F for an individual call. On H100 with CUDA 13.0, PyTorch 2.9.1 and TE 3.0.0.dev0 based on 37be77c, this matched strict torch.mm bitwise in all 32 raw gradient comparisons. The worst raw gradient relative L2 error against FP64 was 5.74e-7 for both strict paths, versus 2.94e-4 for default TE.
| Tokens | Default TE | Strict TE | Strict torch.mm |
Warm incremental PyTorch peak per path |
|---|---|---|---|---|
| 2,048 | 134.4 µs | 315.5 µs | 315.8 µs | 68.5 MiB |
| 8,192 | 428.5 µs | 1,115.2 µs | 1,115.2 µs | 260.5 MiB |
The H100 timings are medians across seven alternating CUDA Graph trials of 100 replays each. The standalone harness includes both backward GEMMs, FP32 operand conversions and BF16 gradient cast-back. Peak measures incremental PyTorch allocations after warmup, with cached workspace outside that measurement.
The per-call control addresses backward precision and still materializes FP32 operands. Its latency was 2.35–2.60× default TE and essentially the same as the PyTorch fallback. For #8940, I'd keep the BF16-operand forward on the existing TE path and consider the strict backward fallback separately. An efficient TE backward path that preserves the FP32 operand and avoids full FP32 copies of BF16 operands still needs a design and benchmark.
@yaox12 I prototyped a mixed-input router backward on H100. It splits FP32 grad_output within each tile, accumulates in FP32, and writes BF16 gradients directly.
With BF16 activations and weights, 288 experts, and hidden size 4096, the two backward GEMMs plus dtype conversions took 15–43% less time than the current TE path across five token counts. At 8192 tokens, warm incremental PyTorch allocations dropped from 260.5 to 66.25 MiB. Across 90 raw gradient comparisons, the maximum relative L2 error against FP64 was 2.64e-7.
The same approach was slower than default TE on GB200. Would you be open to reviewing an H100-scoped Triton backward PR for BF16 activations and weights?
@yaox12, would it make sense to prototype the mixed-input router backward in Transformer Engine so Megatron can keep calling TE? The H100 Triton prototype takes FP32 grad_output and BF16 activations or weights, accumulates in FP32, and writes BF16 gradients directly without materializing full FP32 operand copies. The latency improvement has been validated on H100 for the tested shapes. Prototype results
I also tested the per-call CUBLAS_COMPUTE_32F prototype on GB200 with the process-wide override unset. All 32 raw gradient comparisons matched strict torch.mm bitwise, and its latency and incremental allocations were essentially the same as strict torch.mm. The H100 mixed-input prototype can differ bitwise from that reference.
If a mixed-input GEMM fits TE's scope, would you prefer a Triton backend or another implementation approach?