Skip to content

[DO NOT MERGE - Pending Upstream PyTorch PR 194033 merge] clip_grad_norm_: compute the total norm in float32 so it does not depend on the parallelism partition - #4135

Closed
QIU023 wants to merge 1 commit into
pytorch:mainfrom
QIU023:grad-norm-fp32

Conversation

@QIU023

@QIU023 QIU023 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

get_total_norm returns the norm in the input tensors' dtype, so with training.dtype="bfloat16" both call sites compute the per-tensor norms and the norm-of-norms in bf16 (3-4 significant digits). The rounding happens per group, so under PP/EP the total depends on how params are grouped across ranks: two runs with bit-identical gradients but different pipeline splits report different grad_norm and clip differently. The default training.dtype="float32" is unaffected.

Evidence

At f4e78188e, 4 GPUs, both dtypes, patch on/off:

torchrun --nproc_per_node=4 -m torchtitan.train --module llama3 --config llama3_debugmodel \
  --debug.seed 42 --debug.deterministic --metrics.log_freq 1 --training.steps 2 \
  --training.dtype bfloat16 --parallelism.data_parallel_shard_degree 2 \
  --parallelism.pipeline_parallel_degree 2 --training.local-batch-size 2
--training.dtype patch step 1 step 2
float32 before / after 1.4509 1.6336
bfloat16 before 1.4453 1.6328
bfloat16 after 1.4508 1.6343

float32 is byte-identical before/after; patched bf16 lands next to float32 (1.4508 vs 1.4509).

Fix

Run those two norm ops with dtype=torch.float32 via a local _get_total_norm_fp32 that otherwise mirrors get_total_norm; gradients and the clip multiply are unchanged. It lives in this file rather than torch.nn.utils because get_total_norm has no dtype parameter and adding one is a PyTorch API change — happy to propose that upstream, at which point this helper reduces to a one-line call.

…end on the parallelism partition

torch.nn.utils.get_total_norm returns the norm in the input tensors' dtype. Both call
sites here pass gradients straight in, so with bfloat16 gradients the per-tensor norms
and the norm-of-norms are both bf16 -- three to four significant digits.

Two consequences. The reported grad_norm is wrong by a few tenths of a percent, and the
error depends on how the tensors are GROUPED: under PP each rank norms its own share and
the results are combined across pp_mesh, under EP the parameters are split into an EP
group and a non-EP group. So the value depends on where the model was cut, not only on
the gradients. With max_norm small enough that clipping fires every step, the clip factor
is max_norm / total_norm, so that error is an error in the step's effective learning rate
and two runs with identical gradients but different partitions take different-sized steps.

Gradients are float32 by default, so this is inert in the default configuration:
llama3_debugmodel at dp_shard=2 x pp=2 reports 1.4509 / 1.6336 before and after. With
--training.dtype bfloat16 the same run moves 1.4453 -> 1.4508, landing within 1e-4 of
what the float32 configuration reports.

Co-Authored-By: Claude Opus 5 <[email protected]>
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 13, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

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



@torch.no_grad()
def _get_total_norm_fp32(

@tianyu-l tianyu-l Aug 13, 2026 •

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.

sorry I couldn't really understand the PR summary which seems to be written by AI.

Before vs. after this change, what ops that are used to performed in bf16 are not performed in fp32?

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

Hi Tianyu, sorry for above unclean PR summary, will make sure to send clear and simple conclusion for further fix PRs content during collaborating with AI for K3 support, I have also simplified above PR summary

the answer is:

The norm operator computation is structurally identical before and after — per-tensor norms, then each group's norm-of-norms, then the cross-mesh combine;

The fix only changes the dtype those two norm ops accumulate in (get_total_norm keeps the input dtype, so with bf16 grads they ran in bf16). Each group's partial norm is rounded before the combine in both cases — at bf16's $2^{-8}$ step that rounding is large enough that different PP/EP layouts of the same gradients yield visibly different totals, at fp32's $2^{-23}$ it is negligible, so all layouts agree. The gradients themselves stay bf16.

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.

I guess the problem is that torch.nn.utils.get_total_norm doesn't support configurable norm dtype, or default to the safer fp32. Is that correct?

@janeyx99 do you think we can improve this from pytorch core side?

@QIU023 QIU023 Aug 15, 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.

Yes! on torchtitan side I think we can always use the safer fp32 for gradient reduction across the parallelism mesh to minimize the rounding during mesh reduction for safety

once the pytorch core torch.nn.utils.get_total_norm supports input dtype arg, this PR mirror helper function can be deleted with a cleanup PR, LMK if you agree with this proposal and I can add some docstring in this PR for reminding cleanups waiting torch.nn.utils.get_total_norm

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@QIU023 I think it's worth opening an issue for it on the pytorch/pytorch side. I wish GH was working rn so I can see how you implemented the fp32 version, but it may need design given no precedent on ops taking in "dtype" argument. Some questions I would have for design:

  • is it unambiguous if we have a parameter "accumulate_dtype" which operations are done in this dtype and not?
  • does this require changing the apis of vector_norm and _foreach_norm? (based on your lines change, I'm thinking no?)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ah GH is loading now! Nice it looks like only the norm ops get the dtype and they already support taking in dtypes. I'm more confident this can be resolved in pytorch/pytorch if you open an issue/PR and tag me!

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.

Sure Jane! Will raise the PR for the dtype arg adding for torch.nn.utils.get_total_norm in pytorch/pytorch very soon! all verifications are done there and once that part is merged I will update this titan PR so @tianyu-l can review the new content diff with the duplicate helper function deleted after the next pytorch nightly release available for torchtitan

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.

Hi Jane! @janeyx99 upstream pytorch PR opened: pytorch/pytorch#194033, please check over there, thanks! this one I will add pending note so Tianyu can review it later

@QIU023 QIU023 changed the title clip_grad_norm_: compute the total norm in float32 so it does not depend on the parallelism partition [DO NOT MERGE - Pending Upstream PyTorch PR 194033 merge] clip_grad_norm_: compute the total norm in float32 so it does not depend on the parallelism partition Aug 19, 2026
tianyu-l pushed a commit that referenced this pull request Sep 3, 2026
### Summary

Enables expert parallelism for Kimi K3 on the existing all-to-all token
dispatcher. Expert parallel comes off the unsupported list; the
dispatcher backend is a spec parameter, `moe_comm_backend`, threaded
from `model_registry` to `make_token_dispatcher_config` the way
deepseek_v3 and gpt_oss do it: `standard` (PyTorch all-to-all) by
default, `deepep`, `hybridep` and `minimal_async_ep` selectable as on
those models. The tables below are measured on `standard`. MoonEP (the
report's balanced EP with online redundant-expert planning) is not here;
it needs its own dispatcher and backend.

### EP Design

#### Design points

- `set_moe_sharding_config` declares the routed-expert layout, `w1_EFD
S(1), w2_EDF S(2), w3_EFD S(1)`, on the expert axis
(`sharding.py:26-46`, `set_expert_parallel_sharding_config`).
- `set_decoder_sharding_config` sits above it so the activations
reaching the MoE boundary are DTensors that can be redistributed onto
the expert mesh.
- parallelize builds the expert-data-parallel mesh, `efsdp`, that
excludes the expert axis and hands it to `apply_fsdp_to_decoder` with
`ep_degree` (`parallelize.py:67-69`, `parallelize.py:104`): the shape
`deepseek_v3` already resolves, so expert parameters shard on `(dp_shard
x cp x tp) / ep` and everything else on the full data axis.
- Without `expert_parallel_degree > 1` none of this executes.

### K3 EP runs:

To reproduce, from the torchtitan checkout root on this branch, 8 GPUs.
Every cell loads the same seed checkpoint; run each cell twice and read
the second run (a cold compile cache moves step 1). The runner we used,
with the seed-load assertion and a disk gate, is
https://github.com/QIU023/torchtitan_attention_residual/blob/611385d4e123d4d0527c6d08b06f8d701bb63e21/phase13_k3like_48b_posttrain/matrix_scripts/mx3.sh.

```sh
COMMON="-m torchtitan.train --module kimi_k3 --config kimi_k3_debugmodel --debug.seed 42 --debug.deterministic --training.num-tokens-per-train-step 8192 --training.num-tokens-per-microbatch-per-dp-rank 256 --checkpoint.enable"
torchrun --nproc_per_node=1 $COMMON --training.steps 1 --parallelism.data_parallel_shard_degree 1 --checkpoint.create_seed_checkpoint --dump-folder seed
cell() { d=$1; n=$2; shift 2; rm -rf $d; mkdir -p $d; cp -r seed/checkpoint $d/; torchrun --nproc_per_node=$n $COMMON --training.steps 10 --metrics.log_freq 1 --checkpoint.interval 100000 "$@" --dump-folder $d; }
D="--parallelism.data_parallel_shard_degree"; E="--parallelism.expert_parallel_degree"
cell dp1 1 $D 1;  cell dp2 2 $D 2;  cell ep2_fsdp2 2 $D 2 $E 2
cell dp4 4 $D 4;  cell ep4_fsdp4 4 $D 4 $E 4;  cell dp8 8 $D 8;  cell ep8_fsdp8 8 $D 8 $E 8
```

EP shards experts inside the data axis, so each cell is compared against
the pure-data-parallel run at the same world size. `kimi_k3_debugmodel`,
seed 42, `--debug.deterministic`, one seed checkpoint loaded by every
cell; at step 2 the EP cells are 3.3e-3, 9.0e-3 and 1.6e-5 from their
own-degree baseline, against 1.7e-2, 2.5e-2 and 5.2e-2 for the dp2, dp4
and dp8 rows measured the same way against dp1 -- sharding the experts
moves the loss less than changing the data-parallel degree does, at
every degree:

| cell | world | step 1 | step 3 | step 10 |
|---|---|---|---|---|
| dp1 | 1 | 12.59245 | 7.46936 | 3.18111 |
| dp2 | 2 | 12.58904 | 7.61204 | 3.33502 |
| ep2 x fsdp2 | 2 | 12.59108 | 7.59337 | 3.29070 |
| dp4 | 4 | 12.58372 | 7.65474 | 3.24291 |
| ep4 x fsdp4 | 4 | 12.58128 | 7.59719 | 3.17962 |
| dp8 | 8 | 12.60943 | 8.26416 | 3.35955 |
| ep8 x fsdp8 | 8 | 12.61045 | 8.38947 | 3.20613 |

### Changed files

    torchtitan/models/common/
      token_dispatcher.py    +4/-1  a hidden_dim set on the dispatcher
config wins; model dim is only the default
                                   (K3 dispatches the latent stream)
      config_utils.py           +1  the minimal_async_ep factory branch
                                   forwards hidden_dim
    torchtitan/models/kimi_k3/
sharding.py +47 set_expert_parallel_sharding_config: the
routed-expert layout (new file, following
                                   qwen3_5/sharding.py)
      model.py                  +3  the one call under the ep>1 gate
__init__.py +23/-6 moe_comm_backend threads from model_registry
to core's dispatcher factory: standard by
default, deepep / hybridep / minimal_async_ep
                                   selectable as on deepseek_v3
      parallelize.py         +17/-2 the efsdp mesh, ep_degree through to
apply_fsdp_to_decoder, expert parallel off
the unsupported list, and a comment naming
                                   the backends this model runs
    tests/integration_tests/models.py       the model test gains ep2
    torchtitan_recipes/tests/models.py    its configuration

### CI/CD Coverage

The existing kimi_k3 model integration test becomes fsdp2 x ep2 on the
same 2 GPUs.

### Numerical Correction run with unmerged upstream grad-norm precision
forced to FP32

The same matrix with the grad-norm reduction carried in float32
(#4135, a separate change not
on this branch): dp1, dp4 and ep4 move (largest 2.0e-2 at step 3, on the
dp1 baseline itself) and the other four cells are bitwise unchanged. The
total norm is reduced over an expert group and a non-expert group
separately, and which cells cross a bf16 rounding boundary shifts with
what is in the groups -- the vision tower's parameters are part of the
non-expert group here.

| cell | world | step 1 | step 3 | step 10 |
|---|---|---|---|---|
| dp1 | 1 | 12.59245 | 7.62176 | 3.19563 |
| dp2 | 2 | 12.58904 | 7.61204 | 3.32351 |
| ep2 x fsdp2 | 2 | 12.59108 | 7.59337 | 3.28553 |
| dp4 | 4 | 12.58372 | 7.61710 | 3.23680 |
| ep4 x fsdp4 | 4 | 12.58128 | 7.61100 | 3.14353 |
| dp8 | 8 | 12.60943 | 8.26416 | 3.33049 |
| ep8 x fsdp8 | 8 | 12.61045 | 8.38947 | 3.20156 |

### EP backend verify result

2 x H100 SXM (NVLink), torch 2.15.0.dev20260827+cu130, DeepEP v2 at the
commit CI pins (`01dc3aa`). `kimi_k3_debugmodel`, seed 42,
`--debug.deterministic`, one seed checkpoint loaded by every cell.
MinimalAsyncEP requires full activation checkpointing, so a `standard`
full-AC row isolates that. `hybridep` is not run: it lives on DeepEP's
`hybrid-ep` branch and targets GB200 / NVL72.

The backend is a `model_registry` parameter rather than a flavor, so the
cells select it in a configuration function rather than on the command
line:

```python
# torchtitan_recipes/k3_ep_backends.py
from torchtitan.models.kimi_k3 import model_registry
from torchtitan.models.kimi_k3.config_registry import kimi_k3_debugmodel

def _backend(name: str) -> Trainer.Config:
    config = kimi_k3_debugmodel()
    config.model_spec = model_registry("debugmodel", moe_comm_backend=name)
    return config

def k3_deepep() -> Trainer.Config: return _backend("deepep")
def k3_minimal_async_ep() -> Trainer.Config: return _backend("minimal_async_ep")
```

```sh
BACKEND_COMMON="-m torchtitan.train --module torchtitan_recipes.k3_ep_backends --debug.seed 42 --debug.deterministic --training.steps 10 --metrics.log_freq 1 --training.num-tokens-per-train-step 8192 --training.num-tokens-per-microbatch-per-dp-rank 256 --parallelism.data_parallel_shard_degree 2 --parallelism.expert_parallel_degree 2"
torchrun --nproc_per_node=2 $BACKEND_COMMON --config k3_minimal_async_ep
# DeepEP v2 on a host with no RDMA NIC needs its own environment:
CUDA_HOME=/usr/local/cuda-13.0 NCCL_NVLS_ENABLE=0 EP_DISABLE_GIN=1 EP_REUSE_NCCL_COMM=0 \
  NVSHMEM_REMOTE_TRANSPORT=none NVSHMEM_DISABLE_MNNVL=1 \
  torchrun --nproc_per_node=2 $BACKEND_COMMON --config k3_deepep
```

| cell | backend | AC | step 1 | step 3 | step 10 |
|---|---|---|---|---|---|
| dp2 | - | selective | 12.59951 | 7.45599 | 3.26481 |
| ep2 x fsdp2 | standard | selective | 12.59951 | 7.43228 | 3.30036 |
| ep2 x fsdp2 | standard | full | 12.59951 | 7.43228 | 3.30036 |
| ep2 x fsdp2 | minimal_async_ep | full | 12.59768 | 7.56392 | 3.29721 |
| ep2 x fsdp2 | deepep | selective | 12.59438 | 7.46660 | 3.24408 |

Re-measured on the review-round head (`hidden_dim` set at construction):
dp2, `standard` and `standard` full-AC reproduce the rows above to every
printed digit, so the dispatcher-config change is numerically inert.

`standard` prints dp2's step-1 loss to every digit and its full-AC twin
matches it through step 10; `deepep` differs by ordinary backend
arithmetic. `minimal_async_ep`'s step-3 gap is an upstream
MinimalAsyncEP bug, not K3's: the expert GEMM saves a view of the
recycled receive buffer that the combine backward overwrites, so the
routed `w1_EFD` / `w3_EFD` gradients are lost; the one-line
owned-dispatch fix goes in a separate PR, and with it the same cell is
back in the noise band.
@tianyu-l tianyu-l closed this Oct 7, 2026
pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Oct 7, 2026
…t dim, keepdim for aten._foreach_norm.Scalar type (#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: #194033
Approved by: https://github.com/janeyx99

Co-authored-by: Jane (Yuan) Xu <[email protected]>
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/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants