Skip to content
Prev Previous commit
Next Next commit
Keep unfilled delayed grouped wgrads away from autograd
With delay_wgrad_compute=True and fuse_wgrad_accumulation=False,
GroupedLinear returned the still-empty wgrad buffer to autograd from the
main backward pass. Autograd stored it as (or added it into) .grad before
backward_dw() had written it, so accumulating the delayed result on top
read uninitialized memory. Return None instead, as Linear does, and let
backward_dw() own .grad.

The tied-gradient tests compared multi-term BF16 sums from the delayed
and regular paths with a fixed 1e-2 tolerance. The two paths add the same
terms in a different order, so allow a few BF16 roundings at the
gradient's magnitude. The graphed microbatch test compared against a
PyTorch FP32 reference bitwise, but TE runs FP32 GEMMs in TF32; compare
graph replay against the same TE modules run eagerly instead.

Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
  • Loading branch information
0z5a authored and denera committed Oct 30, 2026
commit 0b11be3daedfc1f4836ba12edc7c94a94fa1f57f
36 changes: 32 additions & 4 deletions tests/pytorch/test_cuda_graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,23 +829,37 @@ def test_make_graphed_callables_with_delayed_wgrad(with_order, set_to_none, bias
@pytest.mark.parametrize("set_to_none", (False, True))
@pytest.mark.parametrize("tied", (False, True))
def test_graphed_delayed_wgrad_accumulates_microbatches(with_order, set_to_none, tied):
"""Separate delayed graphs contribute to shared weights across microbatches."""
"""Separate delayed graphs contribute to shared weights across microbatches.

Graph replay must match the same TE modules run eagerly bitwise. The independent PyTorch
FP32 reference gets a TF32 tolerance: TE computes FP32 GEMMs in TF32, so once SGD moves
the weights off TF32-representable values the two no longer agree bitwise.
"""
reset_rng_states()
modules = tuple(
Linear(16, 16, bias=False, params_dtype=torch.float32, delay_wgrad_compute=True)
for _ in range(2)
)
reference = torch.nn.Sequential(
*(
Linear(16, 16, bias=False, params_dtype=torch.float32, delay_wgrad_compute=True)
for _ in range(2)
)
)
torch_reference = torch.nn.Sequential(
torch.nn.Linear(16, 16, bias=False, device="cuda"),
torch.nn.Linear(16, 16, bias=False, device="cuda"),
)
if tied:
modules[1].weight = modules[0].weight
reference[1].weight = reference[0].weight
torch_reference[1].weight = torch_reference[0].weight
with torch.no_grad():
for module, reference_module in zip(modules, reference):
for module, reference_module, torch_module in zip(modules, reference, torch_reference):
module.weight.fill_(0.25)
reference_module.weight.copy_(module.weight)
torch_module.weight.copy_(module.weight)
tf32_tols = {"rtol": 1e-2, "atol": 1e-2}
graph_options = {}
if with_order:
graph_options = {"_order": [1, 2, -2, -2.5, -1, -1.5], "_num_layers_per_chunk": [1, 1]}
Expand All @@ -855,33 +869,47 @@ def test_graphed_delayed_wgrad_accumulates_microbatches(with_order, set_to_none,
**graph_options,
)
optimizer = torch.optim.SGD(reference.parameters(), lr=1 / 64)
torch_optimizer = torch.optim.SGD(torch_reference.parameters(), lr=1 / 64)
parameters = tuple(dict.fromkeys(param for module in modules for param in module.parameters()))
graph_optimizer = torch.optim.SGD(parameters, lr=1 / 64)
try:
for _ in range(3):
optimizer.zero_grad(set_to_none=set_to_none)
graph_optimizer.zero_grad(set_to_none=set_to_none)
torch_optimizer.zero_grad(set_to_none=set_to_none)
for _ in range(2):
input_ = torch.randint(-2, 3, (8, 16), device="cuda").float() / 4
graph_input = input_.detach().requires_grad_(True)
reference_input = input_.detach().clone().requires_grad_(True)
torch_input = input_.detach().clone().requires_grad_(True)
output = graphed[1](graphed[0](graph_input))
expected = reference(reference_input)
torch_expected = torch_reference(torch_input)
torch.testing.assert_close(output, expected, rtol=0, atol=0)
torch.testing.assert_close(output, torch_expected, **tf32_tols)
output.sum().backward()
expected.sum().backward()
torch_expected.sum().backward()
for callable_ in reversed(graphed):
callable_.backward_dw()
for reference_module in reversed(reference):
reference_module.backward_dw()
torch.testing.assert_close(graph_input.grad, reference_input.grad, rtol=0, atol=0)
for module, reference_module in zip(modules, reference):
torch.testing.assert_close(graph_input.grad, torch_input.grad, **tf32_tols)
for module, reference_module, torch_module in zip(modules, reference, torch_reference):
assert module.weight.grad is not None
torch.testing.assert_close(
module.weight.grad, reference_module.weight.grad, rtol=0, atol=0
)
torch.testing.assert_close(
module.weight.grad, torch_module.weight.grad, **tf32_tols
)
graph_optimizer.step()
optimizer.step()
for module, reference_module in zip(modules, reference):
torch_optimizer.step()
for module, reference_module, torch_module in zip(modules, reference, torch_reference):
torch.testing.assert_close(module.weight, reference_module.weight, rtol=0, atol=0)
torch.testing.assert_close(module.weight, torch_module.weight, **tf32_tols)
finally:
reset_graphs(graphed)

Expand Down
32 changes: 17 additions & 15 deletions tests/pytorch/test_tied_delayed_wgrad.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@
from transformer_engine.pytorch.quantization import is_fp8_block_scaling_available


def _assert_accumulated_close(actual, expected):
"""Compare delayed and regular BF16 gradients that sum several contributions.

Both paths add the same per-use and per-microbatch terms, but in a different order, and
each BF16 addition rounds by up to half an ulp of its result. Allow a few such roundings
at the gradient's magnitude; a dropped or duplicated contribution is far larger.
"""
atol = max(1e-2, 4 * torch.finfo(torch.bfloat16).eps * expected.abs().max().item())
torch.testing.assert_close(actual, expected, rtol=1e-2, atol=atol)


def _build_two_linears(delay, *, bias=False, device="cuda"):
"""Build two BF16 Linear layers with independent parameters."""
hidden_size = 16
Expand Down Expand Up @@ -178,11 +189,8 @@ def test_tied_layernorm_mlp_gradients(
for index in backward_dw_order:
delayed[index].backward_dw()
for name in names:
torch.testing.assert_close(
getattr(delayed[0], name).grad,
getattr(regular[0], name).grad,
rtol=1e-2,
atol=1e-2,
_assert_accumulated_close(
getattr(delayed[0], name).grad, getattr(regular[0], name).grad
)
assert torch.count_nonzero(delayed[0].fc1_weight.grad) > 0
assert torch.count_nonzero(delayed[0].fc2_weight.grad) > 0
Expand Down Expand Up @@ -255,11 +263,8 @@ def test_tied_grouped_linear_gradients(set_to_none, backward_dw_order, packed, m
for index in backward_dw_order:
delayed[index].backward_dw()
for name in names:
torch.testing.assert_close(
getattr(delayed[0], name).grad,
getattr(regular[0], name).grad,
rtol=1e-2,
atol=1e-2,
_assert_accumulated_close(
getattr(delayed[0], name).grad, getattr(regular[0], name).grad
)
assert torch.count_nonzero(getattr(delayed[0], names[0]).grad) > 0

Expand Down Expand Up @@ -325,10 +330,7 @@ def test_tied_grouped_linear_ops_gradients(set_to_none, backward_dw_order, packe
for index in backward_dw_order:
delayed[index].backward_dw()
for name in names:
torch.testing.assert_close(
getattr(delayed[0], name).grad,
getattr(regular[0], name).grad,
rtol=1e-2,
atol=1e-2,
_assert_accumulated_close(
getattr(delayed[0], name).grad, getattr(regular[0], name).grad
)
assert torch.count_nonzero(getattr(delayed[0], names[0]).grad) > 0
12 changes: 8 additions & 4 deletions transformer_engine/pytorch/module/grouped_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,10 +539,12 @@ def _grouped_linear_setup_ctx(
bwd_args.grad_output_quantizers = [None] * num_gemms


def _finish_wgrad(weight, main_grad, wgrad, fuse_wgrad_accumulation):
def _finish_wgrad(weight, main_grad, wgrad, fuse_wgrad_accumulation, delayed=False):
"""Return the gradient expected by autograd or MCore's main-grad hooks."""
if not fuse_wgrad_accumulation:
return wgrad
# A delayed wgrad is written later by backward_dw(), which accumulates into
# ``.grad`` itself. Its buffer is still unfilled here, so autograd must not see it.
return None if delayed else wgrad
if not hasattr(weight, "grad_added_to_main_grad"):
return None
weight.grad_added_to_main_grad = True
Expand Down Expand Up @@ -771,8 +773,9 @@ def _grouped_linear_backward_impl(
if is_dist_weight:
wgrad_list = finalize_weight_grads(origin_weights, wgrad_list)
else:
delayed = args.wgrad_store is not None and args.wgrad_store.delay_wgrad_compute()
wgrad_list = [
_finish_wgrad(weight, main_grad, wgrad, args.fuse_wgrad_accumulation)
_finish_wgrad(weight, main_grad, wgrad, args.fuse_wgrad_accumulation, delayed)
for weight, main_grad, wgrad in zip(origin_weights, main_grads, wgrad_list)
]
else:
Expand Down Expand Up @@ -1290,8 +1293,9 @@ def grouped_gemm_wgrad(inputmats, grad_output_mats, grad_weights):
if is_dist_weight:
wgrad_list = finalize_weight_grads(origin_weights, wgrad_list)
else:
delayed = args.wgrad_store is not None and args.wgrad_store.delay_wgrad_compute()
wgrad_list = [
_finish_wgrad(weight, main_grad, wgrad, args.fuse_wgrad_accumulation)
_finish_wgrad(weight, main_grad, wgrad, args.fuse_wgrad_accumulation, delayed)
for weight, main_grad, wgrad in zip(origin_weights, main_grads, wgrad_list)
]
else:
Expand Down