Skip to content
Next Next commit
Accumulate delayed wgrads into shared (tied) parameters
backward_dw() assigned the popped delayed wgrad to Parameter.grad. When two
modules share one Parameter, each pops its own contribution and the later one
silently replaced the earlier, so the shared gradient came out too small -- on
the issue's own 16x16 / batch=2 BF16 repro it was 0.6015x the regular path, with
256/256 elements differing.

The bias takes the same pop path and hits the same bug, with an extra twist: the
second module's bgrad is numerically ~0, so it wiped out a contribution the first
module had already written correctly (1.0984 delivered vs 33.0859 expected).

Initialise on the first contribution of the step and add on every later one, for
both the weight and the bias. dtype/shape/buffer-alias contracts are unchanged,
and the fused wgrad-accumulation branch is untouched.

tests/pytorch/test_tied_delayed_wgrad.py covers the matrix: tied and non-tied,
both backward_dw() orders, multiple microbatches, two optimizer steps with
set_to_none True/False, the bias case, and parity with a plain nn.Linear oracle.
It uses only the public te.Linear API so it cannot be satisfied by a shared
implementation detail of the fix. Without the fix it fails 5 and passes 3; with
it, 8 pass.

Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de>
  • Loading branch information
0z5a authored and denera committed Oct 30, 2026
commit 0ece9cc33f9ce1b94a652caf928dcb9ebc825cad
177 changes: 177 additions & 0 deletions tests/pytorch/test_tied_delayed_wgrad.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# See LICENSE for license information.
"""Tied parameters must accumulate delayed wgrads, not overwrite them (#3437).

``backward_dw()`` used to *assign* the popped delayed wgrad to
``Parameter.grad``. When two modules share one Parameter (tied weights), each
pops its own contribution and the later one silently replaced the earlier, so
the shared gradient came out too small. The bias takes the same path and hit the
same bug, with the extra twist that the second module's bgrad is often ~0 and so
wiped out a correct contribution.

These tests use only the public ``te.Linear`` API, so they cannot be satisfied by
a shared implementation detail of the fix.
"""

from __future__ import annotations

import pytest
import torch
from torch import nn

import transformer_engine.pytorch as te

SIZE = 16
BATCH = 2
DTYPE = torch.bfloat16

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in c5cf151. The SIZE/BATCH/DTYPE constants are gone, and each test spells out its own sizes and torch.bfloat16.

DEVICE = "cuda"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should go with the test rather than global.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved (0f419b2): the global is gone. _build and _x take device="cuda" as a default, the micro-batch test uses _x(4), and the oracle takes the device from model[0].weight.device.


# The delayed path sums contributions in arrival order while the regular path
# lets autograd accumulate, so with several microbatches the two orders can
# differ by a BF16 ULP. That is not something the fix promises to remove, so the
# tolerance is declared here and applies to the multi-microbatch case only;
# every single-microbatch comparison below stays bit-exact.
MULTI_MICROBATCH_RTOL = 1e-2

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved into test_multiple_microbatches_accumulate, the only test that needs it.

MULTI_MICROBATCH_ATOL = 1e-2


def _tie(model, bias):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def _tie(model, bias):
def _tie(model, *, bias):

otherwise it's hard to understand what _tie(model, True) means

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: _tie(model, *, bias).

"""Re-tie after load_state_dict, which rebinds parameters."""
model[1].weight = model[0].weight
if bias:
model[1].bias = model[0].bias
return model


def _build(delay, tied, bias=False):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: _build(delay, *, bias=False).

model = nn.Sequential(
te.Linear(
SIZE,
SIZE,
bias=bias,
params_dtype=DTYPE,
device=DEVICE,
delay_wgrad_compute=delay,
fuse_wgrad_accumulation=False,
),
te.Linear(
SIZE,
SIZE,
bias=bias,
params_dtype=DTYPE,
device=DEVICE,
delay_wgrad_compute=delay,
fuse_wgrad_accumulation=False,
),
)
return _tie(model, bias) if tied else model

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be separated out of _build so SRP

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: _build now only builds. Tying happens at the call sites, where each test says whether it wants a tied pair or two independent ones.



def _run(model, x, microbatches=1, delay=False, order=(0, 1)):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's order?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed to backward_dw_order and documented: it is the module order used to drain the delayed wgrad queues, which decides which tied module pops its delayed wgrad first.

"""Run the microbatches, then drain the delayed wgrad queues."""
for xb in torch.chunk(x, microbatches, dim=0):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed to microbatch (c5cf151).

model(xb).float().sum().backward()
if delay:
for _ in range(microbatches):
for i in order:
model[i].backward_dw()


def _x(batch=BATCH):
return torch.randn(batch, SIZE, device=DEVICE, dtype=DTYPE, requires_grad=True)


@pytest.fixture(autouse=True)
def _seed():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in c5cf151. Each test calls torch.manual_seed(9) itself.

torch.manual_seed(9)


def test_tied_delayed_wgrad_accumulates():
"""The issue's own case: a tied delayed grad must match the regular path."""
delayed, regular = _build(True, True), _build(False, True)
regular.load_state_dict(delayed.state_dict())
_tie(regular, False)
xd = _x()
_run(delayed, xd, delay=True)
_run(regular, xd.detach().clone().requires_grad_(True))
torch.testing.assert_close(delayed[0].weight.grad, regular[0].weight.grad, rtol=0, atol=0)


def test_non_tied_control_still_passes():
"""Independent parameters keep working."""
delayed, regular = _build(True, False), _build(False, False)
regular.load_state_dict(delayed.state_dict())
xd = _x()
_run(delayed, xd, delay=True)
_run(regular, xd.detach().clone().requires_grad_(True))
for i in (0, 1):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

zip

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in d14c2d2: test_non_tied_linear_gradients now iterates zip(delayed, regular) instead of indexing both models.

torch.testing.assert_close(delayed[i].weight.grad, regular[i].weight.grad, rtol=0, atol=0)


def test_both_backward_dw_orders_match():
"""The shared gradient must not depend on which module pops first."""
a, b = _build(True, True), _build(True, True)
b.load_state_dict(a.state_dict())
_tie(b, False)
xa = _x()
_run(a, xa, delay=True, order=(0, 1))
_run(b, xa.detach().clone().requires_grad_(True), delay=True, order=(1, 0))
torch.testing.assert_close(a[0].weight.grad, b[0].weight.grad, rtol=0, atol=0)


def test_multiple_microbatches_accumulate():
delayed, regular = _build(True, True), _build(False, True)
regular.load_state_dict(delayed.state_dict())
_tie(regular, False)
x = torch.randn(4, SIZE, device=DEVICE, dtype=DTYPE)
_run(delayed, x.clone().requires_grad_(True), microbatches=2, delay=True)
_run(regular, x.clone().requires_grad_(True), microbatches=2)
torch.testing.assert_close(
delayed[0].weight.grad,
regular[0].weight.grad,
rtol=MULTI_MICROBATCH_RTOL,
atol=MULTI_MICROBATCH_ATOL,
)


@pytest.mark.parametrize("set_to_none", [True, False])
def test_two_optimizer_steps_do_not_pollute_each_other(set_to_none):
"""After a reset, the second step's grad must not inherit the first's."""
model = _build(True, True)
params = list({id(p): p for p in model.parameters()}.values())
opt = torch.optim.SGD(params, lr=0.0)

_run(model, torch.randn(BATCH, SIZE, device=DEVICE, dtype=DTYPE), delay=True)
first = model[0].weight.grad.detach().clone()
opt.zero_grad(set_to_none=set_to_none)

_run(model, torch.randn(BATCH, SIZE, device=DEVICE, dtype=DTYPE), delay=True)
second = model[0].weight.grad.detach().clone()

assert not torch.equal(first, second)
assert second.abs().sum() > 0
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


def test_tied_bias_delayed_wgrad_accumulates():
"""The bias shares the pop path, so it must accumulate too."""
delayed, regular = _build(True, True, bias=True), _build(False, True, bias=True)
regular.load_state_dict(delayed.state_dict())
_tie(regular, True)
xd = _x()
_run(delayed, xd, delay=True)
_run(regular, xd.detach().clone().requires_grad_(True))
torch.testing.assert_close(delayed[0].bias.grad, regular[0].bias.grad, rtol=0, atol=0)


def test_matches_pure_pytorch_reference():
"""Independent oracle: plain nn.Linear over the same weight and input."""
model = _build(True, True)
x = _x()
_run(model, x, delay=True)

lin = nn.Linear(SIZE, SIZE, bias=False).to(device=DEVICE, dtype=DTYPE)
with torch.no_grad():
lin.weight.copy_(model[0].weight)
lin(lin(x.detach().clone().requires_grad_(True))).float().sum().backward()
torch.testing.assert_close(model[0].weight.grad, lin.weight.grad, rtol=0, atol=0)
19 changes: 17 additions & 2 deletions transformer_engine/pytorch/module/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2078,11 +2078,26 @@ def backward_dw(self):
(wgrad, bgrad), _ = self.wgrad_store.pop()
if not self.fuse_wgrad_accumulation:
weight_tensor = noop_cat(self._get_weight_tensors())
weight_tensor.grad = wgrad.to(weight_tensor.dtype)
wgrad = wgrad.to(weight_tensor.dtype)
# Multiple modules can share one Parameter (tied weights), and each
# of them pops its own delayed wgrad. Assigning would let the last
# module overwrite the contributions of the earlier ones, so
# accumulate instead: initialise on the first contribution of the
# step and add on every later one.
if weight_tensor.grad is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it safe? There's also zero_grad(set_to_none=False)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. set_to_none=False leaves a zeroed tensor where set_to_none=True leaves None, so the first contribution of the step takes the add path and lands on the same value; nothing in the branch needs grad to be None to start a step. Said so in the comment (7ed69a4).

It also turned out not to be pinned: the test ran both settings but only asserted second != first, which cannot show pollution, because a first-step value carried into the second still differs from the first. It now compares the second step's grad against a fresh model on the same weights and input, bit-exactly.

weight_tensor.grad = wgrad
else:
weight_tensor.grad.add_(wgrad)
if self.use_bias and bgrad is not None and bgrad.numel() != 0:
bias_tensor = noop_cat([getattr(self, name) for name in self.bias_names])
bgrad = bgrad.to(bias_tensor.dtype)
# Same reasoning as for the weight above. A tied bias is shared,
# and a module whose delayed bgrad is (numerically) zero must not
# overwrite the contribution another module already wrote.
if bias_tensor.grad is None:
bias_tensor.grad = bgrad.to(bias_tensor.dtype)
bias_tensor.grad = bgrad
else:
bias_tensor.grad.add_(bgrad)
del wgrad
del bgrad
self._trigger_wgrad_accumulation_and_reduce_hooks()
Expand Down