Repository navigation
Accumulate delayed wgrads into shared (tied) parameters #3552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
0ece9cc
74ec700
b01490f
8da7fe6
73aec37
0b11be3
6a4839a
80c5ae2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
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
There are no files selected for viewing
| 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 | ||||||
| DEVICE = "cuda" | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should go with the test rather than global.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Moved (0f419b2): the global is gone. |
||||||
|
|
||||||
| # 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 | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ditto
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Moved into |
||||||
| MULTI_MICROBATCH_ATOL = 1e-2 | ||||||
|
|
||||||
|
|
||||||
| def _tie(model, bias): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
otherwise it's hard to understand what
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done: |
||||||
| """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): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ditto
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done: |
||||||
| 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 | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be separated out of
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done: |
||||||
|
|
||||||
|
|
||||||
| def _run(model, x, microbatches=1, delay=False, order=(0, 1)): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What's
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Renamed to |
||||||
| """Run the microbatches, then drain the delayed wgrad queues.""" | ||||||
| for xb in torch.chunk(x, microbatches, dim=0): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Renamed to |
||||||
| 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(): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Removed in c5cf151. Each test calls |
||||||
| 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): | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. zip
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done in d14c2d2: |
||||||
| 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 | ||||||
|
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) | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it safe? There's also
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes. It also turned out not to be pinned: the test ran both settings but only asserted |
||
| 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() | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://testing.googleblog.com/2019/12/testing-on-toilet-tests-too-dry-make.html
There was a problem hiding this comment.
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/DTYPEconstants are gone, and each test spells out its own sizes andtorch.bfloat16.