Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194033
Note: Links to docs will display an error until the docs builds have been completed. ❌ 4 Cancelled Jobs, 4 Unrelated FailuresAs of commit e2ce6d7 with merge base 9db5978 ( CANCELLED JOBS - The following jobs were cancelled. Please retry:
FLAKY - The following jobs failed but were likely due to flakiness present on trunk:
UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
1 similar comment
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
|
cc @janeyx99 Hi Jane, seems forgot to tag you in this PR for review, could you please review when you are available ? Thanks a lot! |
sylvesterkaczmarek
left a comment
There was a problem hiding this comment.
Could we add in-tree regression coverage for both parts of this change?
The new dtype argument is specifically intended to make low-precision norm accumulation independent of how tensors are partitioned, while the DTensor fix relies on _foreach_norm.Scalar treating schema position 2 as dtype rather than dim.
A small bf16 grouping test with dtype=torch.float32, plus a DTensor _foreach_norm(..., dtype=...) test, would pin both behaviours in PyTorch CI rather than relying on the external repro scripts.
31559d8 to
64ec4af
Compare
|
Hi @sylvesterkaczmarek Sylvester, thanks for your feedback and response! I have added the CI test coverage you required, please check, thanks! |
janeyx99
left a comment
There was a problem hiding this comment.
thanks for opening the change! left some comments. i think the test can be made a lot clearer, the atols are unexpected
| self.assertEqual(sharded_out.full_tensor(), out) | ||
|
|
||
| @with_comms | ||
| def test_foreach_norm_dtype(self): |
There was a problem hiding this comment.
is this already covered/can this be covered by an existing test as a parametrization?
There was a problem hiding this comment.
Yes, removed the separate test;
dtype is now covered inside the existing test_foreach_norm, which runs (float32 input, no dtype) and (bfloat16 input, dtype=torch.float32).
The second case is the one that exercises the schema, since _foreach_norm.Scalar is (self, ord, *, dtype).
| # Without it each norm accumulates in bf16 and the total is returned in bf16. | ||
| if torch.device(device).type == 'xla' and foreach: | ||
| raise SkipTest('foreach not supported on XLA') | ||
| if torch.device(device).type == 'mps' and foreach: |
There was a problem hiding this comment.
move these to be more explicit skips
There was a problem hiding this comment.
Moved, the in-body SkipTest checks are replaced by subtest(True, decorators=[skipXLA, skipMPS]) on the foreach parameter, only the foreach variant is skipped on XLA / MPS.
| get_total_norm(grads[5:], **kwargs)] | ||
| grouped = get_total_norm(group_norms, **kwargs) | ||
| self.assertEqual(grouped.dtype, torch.float32) | ||
| self.assertEqual(total, grouped, atol=1e-5, rtol=1e-5) |
There was a problem hiding this comment.
The old test used random bfloat16 inputs, and the one-call total and the norm of the per-group norms add the same float32 values in a different order, so they agreed only to float32 rounding.
Removed now: the inputs are small integers (bfloat16 [255, 32, 1]) whose float32 sums are exact, so every comparison is atol=0, rtol=0.
| reference = torch.linalg.vector_norm(torch.cat([g.float().flatten() for g in grads]), norm_type) | ||
| # The reference sums in one pass; the total is a norm of per-tensor norms. Both are | ||
| # fp32, so they agree to fp32 rounding, not to the last ulp. | ||
| self.assertEqual(total, reference, atol=1e-4, rtol=1e-4) |
There was a problem hiding this comment.
this is a pretty large atol for 1e-4
is there not a test that can test the intended reference + the current behavior more precisely?
There was a problem hiding this comment.
Agreed. It covered the same float32 reordering against a flattened float32 reference and the atol was looser than it needed to be.
Have rewritten the test to check both precisely,
- With
dtype=torch.float32the total of the whole tensor and of the split[g[:2], g[2:]]both equal the exactly rounded norm (288 for p=1,sqrt(66050)for p=2). - Without
dtype(current behavior) the result is bfloat16 and, for p=2, depends on the split: 258 for the whole tensor vs 256 for the split, because the first part's norm 257 rounds to 256 before the parts are combined. That split dependence is what the new argument removes.
64ec4af to
1ad4f16
Compare
|
Hi Jane, thanks for the review! @janeyx99 Rebased onto current main and addressed all comments: the |
|
@claude can you review this PR and confirm that all my previous comments have been addressed? Can you also verify that the change has been properly tested? |
|
Claude finished @janeyx99's task in 31m 25s —— View job Review complete: all five of @janeyx99's comments are addressed; two things worth a second look before merge
All five review comments are addressed (one only partially — the DTensor test is a Full review1. Status of each previous comment
On the 2.
|
|
@QIU023 Hello! Could you rebase + fix the errors? For the review, I am curious about your thoughts on point 3 and "dtype is constrained, and the docstring doesn't say so" under 4. |
|
@janeyx99 Hi Jane, fixed in above commit, could you please retry CI? Thanks! The rebase onto main landed after the device-agnostic test_nn refactor removed |
|
I see…ideally this test can be device agnostic so we wouldn’t need onlyOn anymore. approved the ci |
…o dim vector_norm_single_dim_strategy is registered for linalg_vector_norm, norm.Scalar, and _foreach_norm.Scalar. The first two have schema (input, ord, dim, keepdim, *, dtype); the strategy reads args_schema[2] as dim. But _foreach_norm.Scalar is (self, ord, *, dtype), so its position 2 is dtype -- and torch._foreach_norm(tensors, ord, dtype=torch.float32) lands the dtype in the dim slot, where normalize_dim raises '>=' not supported between instances of torch.dtype and int. _foreach_norm reduces each tensor fully and dtype does not affect placement, so this sets dim=None for that overload and leaves vector_norm/norm unchanged. Without the dtype kwarg the bug is latent because position 2 is out of range and dim defaults to None.
get_total_norm returns the norm in the input tensors' dtype and accumulates in it too, so for bfloat16 gradients the total depends on how the tensors are grouped: two runs with bit-identical gradients but different pipeline or expert-parallel splits report different norms and, under gradient clipping, take different-sized steps. Measured at world 1/2/4/8, the pipeline split moves 256.000 -> 255.505 (relative spread 1.9e-3) against a float64 truth of 255.682. The dtype argument accumulates the per-tensor norms and the norm-of-norms in that dtype and returns in it, so passing torch.float32 makes the result grouping-independent -- the same split then reads 255.682 at every world size. Default None is byte-for-byte the previous behaviour: vector_norm and _foreach_norm both treat dtype=None as a no-op, and the empty case returns torch.tensor(0.0, dtype=dtype). Threads dtype straight into the three norm ops with no special-casing. DTensor gradients (the FSDP case) go through this unchanged now that _foreach_norm.Scalar's sharding strategy no longer misreads dtype as a dim.
…(..., dtype=) get_total_norm with dtype=torch.float32 must give the same total for bf16 gradients whether they are reduced in one call or as a norm of per-group norms; without dtype the total stays in bf16. _foreach_norm.Scalar's schema is (self, ord, *, dtype), so a DTensor call with dtype must not read position 2 as a reduction dim.
…im by schema position _foreach_powsum.Scalar is (self, ord, dtype) like _foreach_norm.Scalar, and its strategy read args_schema[2] as dim, so a dtype= call failed the same way. Both strategies now take dim and keepdim from the positions the op's schema gives them, which replaces the op identity check. test_foreach_powsum_sharded gains a bfloat16 input with dtype=torch.float32.
The device-agnostic test_nn refactor removed onlyOn from the imports once its last other use became onlyAccelerator. The rebase kept this test's @OnlyOn(["cpu", "cuda"]) without the import, so test_nn failed to import (NameError) and ruff reported F821. The test stays on CPU and CUDA: its bfloat16 values are those of kernels that accumulate in float32 and round to nearest even.
The default path's bfloat16 values are those of the CPU and CUDA kernels, so they are asserted only there; foreach is skipped on MPS and XLA as in test_clip_grad_norm, and the float32 totals use the default tolerance, which still fails a total rounded through bfloat16 by about 1. onlyOn is no longer imported.
6245bda to
7f64b20
Compare
|
Hi Jane @janeyx99, saw have 3 CI still failing and pushed test according to your comments to make test device agnostic, please check, thanks! |
| split_default = get_total_norm(split, norm_type=norm_type, foreach=foreach) | ||
| self.assertEqual(whole_default.dtype, torch.bfloat16) | ||
| self.assertEqual(split_default.dtype, torch.bfloat16) | ||
| if norm_type == 2.0 and torch.device(device).type in ('cpu', 'cuda'): |
There was a problem hiding this comment.
Moving the skipping to inside the test is not better than just skipping the tests from the start....
Is there no clever solution that'd work on all backends? If not then I'd prefer the skip on other devices explicitly
There was a problem hiding this comment.
Yes, let me push a new commit to adjust the test, I do see repetitive ci failures, is it because my change or some unstable test case?
foreach=None takes the foreach path on the devices that have it and the per-tensor path elsewhere, so the test needs no device skip. The bfloat16 values of the default path are no longer asserted: they depend on how a backend rounds, and the float32 checks on the split input already fail when a norm is rounded through bfloat16.
|
@pytorchbot merge -i |
|
@pytorchbot merge -i |
|
@QIU023 thank you for the change, this is now merged! (it will be in the 2.16 release) |
|
Thanks a lot Jane! |
…t dim, keepdim for aten._foreach_norm.Scalar type (pytorch#194033) `get_total_norm` accumulates in the input tensors' dtype. With bf16 gradients split across ranks, each rank's partial norm is rounded before the partials are combined, so under pipeline parallelism the reported total depends on how many stages the model was cut into rather than only on the gradients. This PR adds a `dtype` argument that accumulates the per-tensor norms and the norm of norms in that dtype. Moved here from [torchtitan PR](pytorch/torchtitan#4135). ### Commit 1: DTensor `_foreach_norm.Scalar` does not read `dtype` as `dim` `_foreach_norm.Scalar` shares `vector_norm`'s DTensor sharding strategy, which reads `args_schema[2]` as `dim`, while `_foreach_norm`'s schema is `(self, ord, *, dtype)`: position 2 is `dtype`, so `torch._foreach_norm(tensors, ord, dtype=...)` on DTensors raises today. Setting `dim=None` for that overload fixes every `_foreach_norm(dtype=)` DTensor caller, the FSDP gradients `get_total_norm` sees included, and keeps `get_total_norm` a plain passthrough with no DTensor special-casing. ### Commit 2: `get_total_norm(..., dtype=)` `dtype` is passed through to the three norm calls the function already makes (`torch._foreach_norm`, the per-tensor `torch.linalg.vector_norm` and the norm of norms); both ops already accept `dtype`. `dtype=None` keeps today's behavior. ### Commit 3: tests - `test_nn.py::test_get_total_norm_dtype`: bfloat16 `[255, 32, 1]`, whole and split into `[g[:2], g[2:]]`, foreach on and off, p in {1, 2}. With `dtype=torch.float32` both give the exactly rounded norm (`atol=0, rtol=0`); without it the result is bfloat16 and, for p=2, depends on the split (258 whole, 256 split). - `test/distributed/tensor/test_math_ops.py::test_foreach_norm`: the existing DTensor test also runs bfloat16 input with `dtype=torch.float32` and checks the output dtype; without commit 1 it raises. ### The two splits 512 bf16 gradients, byte-identical at every world size; the only thing that changes is how they are divided across ranks. Both divisions come from real training: - **FSDP.** Every gradient is a DTensor `Shard(0)` over the mesh. `get_total_norm` returns a DTensor carrying `_NormPartial`, and `full_tensor()` performs the cross-rank combine. - **Pipeline.** Rank `r` owns `grads[r::world]` as plain tensors, which is what a stage holds. Each rank norms its own, then the partials are all-reduced. The reference is float64 over the whole set, computed identically on every rank, so it does not depend on the world size. Neither should the reported norm. ### Reproducing nccl, 8 GPUs, torch 2.14, both source commits built: ``` python repro_get_total_norm_dtype.py --module torch/nn/utils/clip_grad.py --world 1,2,4,8 ``` Script: https://github.com/QIU023/torchtitan_attention_residual/blob/315b1a247bd9f1f81526ae84f6a92373f096643e/Raising_PRs/PR26_torchtitan_grad_norm_low_precision/repro_get_total_norm_dtype.py The two `today` rows need no patch and reproduce on stock torch (drop `--module`). The fp32 DTensor row needs commit 1 built in, not just the `clip_grad.py` change; without it that case raises instead of printing: ``` RuntimeError: '>=' not supported between instances of 'torch.dtype' and 'int' torch._foreach_norm(device_tensors, norm_type, dtype=dtype) -> _propagate_op_sharding_dispatch_slow_path ``` ### Result ``` world=1 world=2 world=4 world=8 spread(rel) dtensor today 256.000 256.000 256.000 256.000 0.00e+00 dtensor fp32 255.682 255.682 255.682 255.682 0.00e+00 pp today 256.000 255.973 255.505 255.631 1.93e-03 pp fp32 255.682 255.682 255.682 255.682 5.97e-08 float64 truth 255.682226 ``` The pipeline row is the defect: the same gradients report a different norm depending only on how many stages the model was cut into, so clipping takes a different-sized step for a reason that has nothing to do with the gradients. The DTensor row does not vary with the world size but sits 0.12% off the truth, bf16 having snapped the total to 256. Passing `dtype=torch.float32` puts both on the truth. ### Default unchanged `dtype=None` is bitwise identical to today in all 144 cases: 4 shapes including empty, x {bf16, fp16, fp32, fp64}, x foreach {None, True, False}, x p in {1, 2, inf}. ``` python probe_default_unchanged.py --module torch/nn/utils/clip_grad.py ``` Script: https://github.com/QIU023/torchtitan_attention_residual/blob/d30054f81f2d5bda8165bba6bd0ffb314d812645/Raising_PRs/PR26_torchtitan_grad_norm_low_precision/probe_default_unchanged.py Pull Request resolved: pytorch#194033 Approved by: https://github.com/janeyx99 Co-authored-by: Jane (Yuan) Xu <[email protected]>
get_total_normaccumulates in the input tensors' dtype. With bf16 gradients split across ranks, each rank's partial norm is rounded before the partials are combined, so under pipeline parallelism the reported total depends on how many stages the model was cut into rather than only on the gradients. This PR adds adtypeargument that accumulates the per-tensor norms and the norm of norms in that dtype. Moved here from torchtitan PR.Commit 1: DTensor
_foreach_norm.Scalardoes not readdtypeasdim_foreach_norm.Scalarsharesvector_norm's DTensor sharding strategy, which readsargs_schema[2]asdim, while_foreach_norm's schema is(self, ord, *, dtype): position 2 isdtype, sotorch._foreach_norm(tensors, ord, dtype=...)on DTensors raises today. Settingdim=Nonefor that overload fixes every_foreach_norm(dtype=)DTensor caller, the FSDP gradientsget_total_normsees included, and keepsget_total_norma plain passthrough with no DTensor special-casing.Commit 2:
get_total_norm(..., dtype=)dtypeis passed through to the three norm calls the function already makes (torch._foreach_norm, the per-tensortorch.linalg.vector_normand the norm of norms); both ops already acceptdtype.dtype=Nonekeeps today's behavior.Commit 3: tests
test_nn.py::test_get_total_norm_dtype: bfloat16[255, 32, 1], whole and split into[g[:2], g[2:]], foreach on and off, p in {1, 2}. Withdtype=torch.float32both give the exactly rounded norm (atol=0, rtol=0); without it the result is bfloat16 and, for p=2, depends on the split (258 whole, 256 split).test/distributed/tensor/test_math_ops.py::test_foreach_norm: the existing DTensor test also runs bfloat16 input withdtype=torch.float32and checks the output dtype; without commit 1 it raises.The two splits
512 bf16 gradients, byte-identical at every world size; the only thing that changes is how they are divided across ranks. Both divisions come from real training:
Shard(0)over the mesh.get_total_normreturns a DTensor carrying_NormPartial, andfull_tensor()performs the cross-rank combine.rownsgrads[r::world]as plain tensors, which is what a stage holds. Each rank norms its own, then the partials are all-reduced.The reference is float64 over the whole set, computed identically on every rank, so it does not depend on the world size. Neither should the reported norm.
Reproducing
nccl, 8 GPUs, torch 2.14, both source commits built:
Script: https://github.com/QIU023/torchtitan_attention_residual/blob/315b1a247bd9f1f81526ae84f6a92373f096643e/Raising_PRs/PR26_torchtitan_grad_norm_low_precision/repro_get_total_norm_dtype.py
The two
todayrows need no patch and reproduce on stock torch (drop--module). The fp32 DTensor row needs commit 1 built in, not just theclip_grad.pychange; without it that case raises instead of printing:Result
The pipeline row is the defect: the same gradients report a different norm depending only on how many stages the model was cut into, so clipping takes a different-sized step for a reason that has nothing to do with the gradients. The DTensor row does not vary with the world size but sits 0.12% off the truth, bf16 having snapped the total to 256. Passing
dtype=torch.float32puts both on the truth.Default unchanged
dtype=Noneis bitwise identical to today in all 144 cases: 4 shapes including empty, x {bf16, fp16, fp32, fp64}, x foreach {None, True, False}, x p in {1, 2, inf}.Script: https://github.com/QIU023/torchtitan_attention_residual/blob/d30054f81f2d5bda8165bba6bd0ffb314d812645/Raising_PRs/PR26_torchtitan_grad_norm_low_precision/probe_default_unchanged.py