Skip to content

get_total_norm: add a dtype argument for the accumulation, add default dim, keepdim for aten._foreach_norm.Scalar type - #194033

Closed
QIU023 wants to merge 8 commits into
pytorch:mainfrom
QIU023:get-total-norm-dtype
Closed

QIU023 wants to merge 8 commits into
pytorch:mainfrom
QIU023:get-total-norm-dtype

Conversation

@QIU023

@QIU023 QIU023 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

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 Failures

As of commit e2ce6d7 with merge base 9db5978 (image):

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.

@pytorch-bot pytorch-bot Bot added ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category labels Aug 19, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan
  • ciflow/dtensor

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
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan
  • ciflow/dtensor

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.

@QIU023

QIU023 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

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 sylvesterkaczmarek left a comment

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.

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.

@QIU023
QIU023 force-pushed the get-total-norm-dtype branch 2 times, most recently from 31559d8 to 64ec4af Compare September 3, 2026 08:32
@QIU023

QIU023 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Hi @sylvesterkaczmarek Sylvester, thanks for your feedback and response! I have added the CI test coverage you required, please check, thanks!

@janeyx99 janeyx99 left a comment

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.

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):

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 this already covered/can this be covered by an existing test as a parametrization?

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, 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).

Comment thread test/test_nn.py Outdated
# 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:

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.

move these to be more explicit skips

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, 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.

Comment thread test/test_nn.py Outdated
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)

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.

why the atol here?

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.

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.

Comment thread test/test_nn.py Outdated
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)

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 is a pretty large atol for 1e-4

is there not a test that can test the intended reference + the current behavior more precisely?

@QIU023 QIU023 Sep 14, 2026 •

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.

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.float32 the 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.

Comment thread torch/nn/utils/clip_grad.py Resolved
@QIU023

QIU023 commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Hi Jane, thanks for the review! @janeyx99

Rebased onto current main and addressed all comments: the get_total_norm test now asserts exact values with no tolerance, the DTensor case is a parametrization of the existing test_foreach_norm, and all comment string suggestions are applied. Please LMK if this looks good to you!

@janeyx99

Copy link
Copy Markdown
Contributor

@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

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

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

  • Fetch base and read the full diff
  • Check each of @janeyx99's previous comments was addressed
  • Review the test coverage for correctness / precision claims
  • Post review

All five review comments are addressed (one only partially — the DTensor test is a for loop + subTest, not a real @parametrize). The change itself is correct and minimal. My two substantive findings: aten._foreach_powsum.Scalar has the identical dim/dtype schema bug that commit 1 fixes for _foreach_norm.Scalar and is left unfixed, and the new atol=0 test runs on every device type while asserting bf16 values that depend on CPU/CUDA-specific internal accumulation.

Full review

1. Status of each previous comment

Comment Status
test_math_ops.py: "can this be covered by an existing test as a parametrization?" Partially. Separate test removed and folded into test_foreach_norm (test/distributed/tensor/test_math_ops.py:842) — but as a for loop + self.subTest, not a parametrization. See note below.
test_nn.py: "move these to be more explicit skips" Done. subtest(True, decorators=[skipXLA, skipMPS]) at test/test_nn.py:13634, skipXLA imported at test/test_nn.py:51. In-body raise SkipTest is gone.
test_nn.py: "why the atol here?" / "this is a pretty large atol for 1e-4" Done. No tolerances remain; both comparisons are atol=0, rtol=0 against exact values, and the "today" behavior is pinned to literal 258.0 / 256.0.
_math_ops.py: comment suggestion Applied verbatim at torch/distributed/tensor/_ops/_math_ops.py:952-953 (author added the closing paren your snippet was missing).
clip_grad.py: docstring suggestion Applied verbatim at torch/nn/utils/clip_grad.py:73-76.

On the subTest point: since MultiProcessTestCase.run_test invokes the test method directly rather than through TestCase.run(), self._outcome is None in the child process, so subTest degrades to a bare yield — failures still propagate, so correctness is fine. But it buys nothing over a plain loop and it isn't the parametrization you asked for (no independently-runnable test id). If you want a real one, test_math_ops.py currently has no @parametrize infrastructure wired up, which is presumably why the author went this way.

2. _foreach_powsum.Scalar has the same bug and isn't fixed

powsum_single_dim_strategy sits ~10 lines below the function being fixed, is registered for aten._foreach_powsum.Scalar (torch/distributed/tensor/_ops/_math_ops.py:1009-1014), and reads dim from args_schema[2] (torch/distributed/tensor/_ops/_math_ops.py:996) — while _foreach_powsum.Scalar's schema is (Tensor[] self, Scalar ord=2, ScalarType? dtype=None) (aten/src/ATen/native/native_functions.yaml:11436), identical in shape to _foreach_norm.Scalar. So torch._foreach_powsum(dtensors, ord, dtype=torch.float32) should fail the same way _foreach_norm does today. It's latent (no in-tree caller passes dtype, and test_foreach_powsum_sharded at test/distributed/tensor/test_math_ops.py:974 doesn't), but it's the same defect one function away.

Since the fix is now duplicated logic in two places, I'd rather see it expressed once — e.g. skip the positional read for any overload whose schema has no dim argument, instead of an op-identity check in each strategy:

if op in (aten._foreach_norm.Scalar, aten._foreach_powsum.Scalar):

Fix this →

3. The new test_nn.py test is device-generic but asserts CPU/CUDA-specific bf16 values

test_get_total_norm_dtype lands in TestNNDeviceType, which is instantiated for every device type including MPS (allow_mps=True, test/test_nn.py:17336), XPU, HPU and privateuse1. The atol=0 assertions at test/test_nn.py:13658-13659 encode a specific rounding chain:

  • sqrt(66050) = 257.00194... accumulated in fp32 internally, then rounded to bf16 → 258
  • split: sqrt(66049) = 257 exactly → bf16 ties-to-even → 256, then sqrt(256² + 1) → 256

Both depend on the backend accumulating bf16 reductions in fp32 (true for the ATen CPU/CUDA acc_type path and for foreach_tensor_norm_cuda's opmath) and on ties-to-even at 257. If a backend accumulates in bf16 instead, the "whole" value is 256, not 258, and the test fails rather than flakes. The dtype=torch.float32 half is more defensible — the inputs are exactly representable and p ∈ {1, 2} avoids the pow(1/p) path — but bit-exactness against a Python double sqrt on an arbitrary accelerator is still an assumption.

Suggest restricting the exact-value assertions to native device types (@onlyNativeDeviceTypes), or keeping atol=0 for the dtype=fp32 comparisons while asserting the defect structurally for the default case (whole_default != split_default) rather than pinning literals. The structural form is arguably a better regression test anyway: split-dependence is the thing the argument removes, and it doesn't care what the two values happen to be.

Fix this →

4. Smaller notes (non-blocking)

  • clip_grads_with_norm_ interop is fine, worth knowing. Feeding an fp32 total_norm into _clip_grads_with_norm_ with bf16 grads reaches torch._foreach_mul_(device_grads, clip_coef_clamped.to(device)) (torch/nn/utils/clip_grad.py:181). Promotion between a dimensioned bf16 tensor and a 0-dim fp32 tensor resolves to bf16, so the in-place mul does not raise — the decomposed API composes correctly.
  • dtype is constrained, and the docstring doesn't say so. Both linalg_vector_norm and the _foreach_norm CUDA path enforce promoteTypes(input_dtype, dtype) == dtype (aten/src/ATen/native/cuda/ForeachReduceOp.cu:402), so dtype=torch.bfloat16 with fp32 grads raises rather than downcasting. One clause noting it must be a floating dtype at least as wide as the inputs would save a confusing error.
  • Free side effect. With dtype=None, mixed-dtype grad lists break at the torch.stack on torch/nn/utils/clip_grad.py:114 (norms have different dtypes). Passing dtype incidentally makes that case work. Pre-existing, not introduced here — just an upside worth knowing.
  • Neighbors still use in-body skips. test_clip_grad_value (test/test_nn.py:13607) and test_clip_grad_norm (test/test_nn.py:13667) still raise SkipTest for the XLA/MPS foreach case. Converting them to the pattern the new test now uses would be a nice follow-up, but is out of scope here.
  • clip_grad_norm_ does not expose dtype. Only the decomposed get_total_norm path benefits, so torchtitan-style callers must decompose. Reasonable scoping given the motivation, just flagging the API asymmetry in case you'd rather plumb it through now.

5. Verification I could and could not do

Read: the full diff against merge base b8c2b362, the _foreach_norm/_foreach_powsum/linalg_vector_norm ATen schemas, the CUDA and slow-path foreach norm kernels, the DTensor single-dim-strategy expansion (to confirm op is the outer _foreach_norm.Scalar inside expanded_foreach_strategy, so the op == check does fire on the foreach path), the sharding-prop cache key path, and MultiProcessTestCase.run_test.

I did not execute anything — no built torch in this checkout, and pip install -e . plus 8-GPU distributed runs are out of reach here. So the bf16 rounding chain in §3 and the _foreach_powsum failure in §2 are derived from reading the kernels and schemas, not observed. The author's own repro numbers in the PR description are consistent with my reading. Worth having CI (or the author) confirm test_get_total_norm_dtype on MPS specifically, since that's the device most likely to disagree with the literals.

| Branch: [`get-total-norm-dtype`](https://github.com/pytorch/pytorch/tree/get-total-norm-dtype)

@janeyx99

Copy link
Copy Markdown
Contributor

@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.

@QIU023

QIU023 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@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 onlyOn from the file's imports, and this test still used it, so test_nn failed to import on every shard (the NameError) and ruff flagged F821. The above fix commit restores the import;

@janeyx99

janeyx99 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

I see…ideally this test can be device agnostic so we wouldn’t need onlyOn anymore.

approved the ci

@albanD
albanD removed their request for review October 1, 2026 14:20
QIU023 and others added 7 commits October 1, 2026 21:51
…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.
@QIU023
QIU023 force-pushed the get-total-norm-dtype branch from 6245bda to 7f64b20 Compare October 1, 2026 21:52
@QIU023

QIU023 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Hi Jane @janeyx99, saw have 3 CI still failing and pushed test according to your comments to make test device agnostic, please check, thanks!

@QIU023
QIU023 requested a review from janeyx99 October 2, 2026 01:31
Comment thread test/test_nn.py Outdated
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'):

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.

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

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, 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?

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.

Yes, not your issue

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.
@janeyx99

janeyx99 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@janeyx99

janeyx99 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@janeyx99

janeyx99 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@QIU023 thank you for the change, this is now merged! (it will be in the 2.16 release)

@QIU023

QIU023 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot Jane!

cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (dtensor) release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants