Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198668
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 6335fa3 with merge base 73795c6 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
weifengpy
added a commit
that referenced
this pull request
Sep 25, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 38-39 ms (about 20%), mostly the casts' CPU cost. > > This change defers the upcast to the copy-in in backwards that reduce. When pre_backward runs with gradient reduction enabled, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype, and which has no gradient yet, gets grad_dtype=None, so autograd leaves the gradient in the dtype it produced. post_backward restores the unsharded gradient dtype once it has taken the gradients, and reset_iter_state() restores it after an aborted backward. Backwards without gradient sync don't switch, so no_sync microbatches still accumulate in the wider dtype. A parameter that already holds an accumulated gradient keeps its dtype too, since grad_dtype can't change while a gradient exists, and foreach_reduce then casts the rest of its group as it does for any mixed-dtype group. BF16 to FP32 is exact, so parameters used once per backward reduce bit-identically to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype takes its reduce dtype from its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) and any pending HSDP partial reduction, instead of from the incoming gradients. Using the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. The copy-in into the reduce buffer also replaces #194434's per-gradient promotion to a pending partial reduction's dtype. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so the group keeps the uniform-dtype copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring in every backward would make no_sync microbatches accumulate in BF16 again, which #194434 fixes. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. The narrower dtype is only visible during a reducing backward, since post_backward consumes the unsharded gradients. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) and no_sync microbatches are unchanged. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded, and test_grad_dtype_restored_by_reset_iter_state checks that a no_sync backward after an aborted backward and reset_iter_state() accumulates in FP32. Deferring to the compute dtype, computing the reduce dtype from the incoming gradients, or dropping either restore each makes one of these tests fail. The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. test_fully_shard_mixed_precision.py passes (66 tests). The other FSDP test files haven't been run on this change. The costs above were measured on #194434 against its base; this change hasn't been benchmarked yet. > > ```bash > /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 7964dd8 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 25, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 38-39 ms (about 20%), mostly the casts' CPU cost. > > This change defers the upcast to the copy-in in backwards that reduce. When pre_backward runs with gradient reduction enabled, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype, and which has no gradient yet, gets grad_dtype=None, so autograd leaves the gradient in the dtype it produced. post_backward restores the unsharded gradient dtype once it has taken the gradients, and reset_iter_state() restores it after an aborted backward. Backwards without gradient sync don't switch, so no_sync microbatches still accumulate in the wider dtype. A parameter that already holds an accumulated gradient keeps its dtype too, since grad_dtype can't change while a gradient exists, and foreach_reduce then casts the rest of its group as it does for any mixed-dtype group. BF16 to FP32 is exact, so parameters used once per backward reduce bit-identically to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype takes its reduce dtype from its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) and any pending HSDP partial reduction, instead of from the incoming gradients. Using the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. The copy-in into the reduce buffer also replaces #194434's per-gradient promotion to a pending partial reduction's dtype. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so the group keeps the uniform-dtype copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring in every backward would make no_sync microbatches accumulate in BF16 again, which #194434 fixes. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. The narrower dtype is only visible during a reducing backward, since post_backward consumes the unsharded gradients. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) and no_sync microbatches are unchanged. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded, and test_grad_dtype_restored_by_reset_iter_state checks that a no_sync backward after an aborted backward and reset_iter_state() accumulates in FP32. Deferring to the compute dtype, computing the reduce dtype from the incoming gradients, or dropping either restore each makes one of these tests fail. The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. test_fully_shard_mixed_precision.py passes (66 tests). The other FSDP test files haven't been run on this change. The costs above were measured on #194434 against its base; this change hasn't been benchmarked yet. > > ```bash > /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 3b23b9e Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 38-39 ms (about 20%), mostly the casts' CPU cost. > > This change defers the upcast to the copy-in in backwards that reduce. When pre_backward runs with gradient reduction enabled, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype, and which has no gradient yet, gets grad_dtype=None, so autograd leaves the gradient in the dtype it produced. post_backward restores the unsharded gradient dtype once it has taken the gradients, and reset_iter_state() restores it after an aborted backward. Backwards without gradient sync don't switch, so no_sync microbatches still accumulate in the wider dtype. A parameter that already holds an accumulated gradient keeps its dtype too, since grad_dtype can't change while a gradient exists, and foreach_reduce then casts the rest of its group as it does for any mixed-dtype group. BF16 to FP32 is exact, so parameters used once per backward reduce bit-identically to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype takes its reduce dtype from its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) and any pending HSDP partial reduction, instead of from the incoming gradients. Using the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. The copy-in into the reduce buffer also replaces #194434's per-gradient promotion to a pending partial reduction's dtype. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so the group keeps the uniform-dtype copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring in every backward would make no_sync microbatches accumulate in BF16 again, which #194434 fixes. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. The narrower dtype is only visible during a reducing backward, since post_backward consumes the unsharded gradients. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) and no_sync microbatches are unchanged. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded, and test_grad_dtype_restored_by_reset_iter_state checks that a no_sync backward after an aborted backward and reset_iter_state() accumulates in FP32. Deferring to the compute dtype, computing the reduce dtype from the incoming gradients, or dropping either restore each makes one of these tests fail. The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. test_fully_shard_mixed_precision.py passes (66 tests). The other FSDP test files haven't been run on this change. The costs above were measured on #194434 against its base; this change hasn't been benchmarked yet. > > ```bash > /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 17b68dc Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. > > This change defers the upcast to the copy-in in backwards that reduce. When pre_backward runs with gradient reduction enabled, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype, and which has no gradient yet, gets grad_dtype=None, so autograd leaves the gradient in the dtype it produced. post_backward restores the unsharded gradient dtype once it has taken the gradients, and reset_iter_state() restores it after an aborted backward. Backwards without gradient sync don't switch, so no_sync microbatches still accumulate in the wider dtype. A parameter that already holds an accumulated gradient keeps its dtype too, since grad_dtype can't change while a gradient exists, and the copy-in widens the rest of its group as for any mixed-dtype group. BF16 to FP32 is exact, so parameters used once per backward reduce bit-identically to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring in every backward would make no_sync microbatches accumulate in BF16 again, which #194434 fixes. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. The narrower dtype is only visible during a reducing backward, since post_backward consumes the unsharded gradients. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) and no_sync microbatches are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded, and test_grad_dtype_restored_by_reset_iter_state checks that a no_sync backward after an aborted backward and reset_iter_state() accumulates in FP32. The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > Before the rebase onto the current #194434, deferring to the compute dtype, computing the reduce dtype from the incoming gradients, or dropping either restore each made one of these tests fail, and test_fully_shard_mixed_precision.py passed (66 tests). After the rebase, on two H100s, the mixed-precision grad_dtype tests pass (31 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. The full file, the other FSDP test files and the mutation checks haven't been rerun since. The benchmarks ran the base, #194434 and this change on one build. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q -rfs > /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 17b68dc Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. > > This change defers the upcast to the copy-in in backwards that reduce. When pre_backward runs with gradient reduction enabled, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype, and which has no gradient yet, gets grad_dtype=None, so autograd leaves the gradient in the dtype it produced. post_backward restores the unsharded gradient dtype once it has taken the gradients, and reset_iter_state() restores it after an aborted backward. Backwards without gradient sync don't switch, so no_sync microbatches still accumulate in the wider dtype. A parameter that already holds an accumulated gradient keeps its dtype too, since grad_dtype can't change while a gradient exists, and the copy-in widens the rest of its group as for any mixed-dtype group. BF16 to FP32 is exact, so parameters used once per backward reduce bit-identically to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring in every backward would make no_sync microbatches accumulate in BF16 again, which #194434 fixes. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. The narrower dtype is only visible during a reducing backward, since post_backward consumes the unsharded gradients. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) and no_sync microbatches are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded, and test_grad_dtype_restored_by_reset_iter_state checks that a no_sync backward after an aborted backward and reset_iter_state() accumulates in FP32. The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > Before the rebase onto the current #194434, deferring to the compute dtype, computing the reduce dtype from the incoming gradients, or dropping either restore each made one of these tests fail, and test_fully_shard_mixed_precision.py passed (66 tests). After the rebase, on two H100s, the mixed-precision grad_dtype tests pass (31 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. The full file, the other FSDP test files and the mutation checks haven't been rerun since. The benchmarks ran the base, #194434 and this change on one build. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q -rfs > /home/weif/.conda/envs/code-review/bin/python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: b68c8d9 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > On two H100s, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype pass (35 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward fail at the previous revision of this change. Each of these changes makes one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. The full file and the other FSDP test files haven't been rerun since the rebase onto the current #194434. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k "grad_dtype or grad_acc" -q -rfs > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: b68c8d9 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, the dtype autograd would produce, so a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > On two H100s, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype pass (35 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward fail at the previous revision of this change. Each of these changes makes one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. The full file and the other FSDP test files haven't been rerun since the rebase onto the current #194434. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k "grad_dtype or grad_acc" -q -rfs > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 743c4be Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > On two H100s, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype pass (35 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward fail at the previous revision of this change. Each of these changes makes one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. The full file and the other FSDP test files haven't been rerun since the rebase onto the current #194434. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k "grad_dtype or grad_acc" -q -rfs > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 743c4be Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 26, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in now also runs with reduce_dtype=None and checks the copy-in inputs: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > On two H100s, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype pass (35 passed; the 18 skipped need four GPUs), and lint and the whitespace check pass. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward fail at the previous revision of this change. Each of these changes makes one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. The full file and the other FSDP test files haven't been rerun since the rebase onto the current #194434. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > CUDA_VISIBLE_DEVICES=6,7 /home/weif/.conda/envs/code-review/bin/python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k "grad_dtype or grad_acc" -q -rfs > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 05d85de Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 28, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in checks the copy-in inputs with reduce_dtype=None and torch.float32: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > Results at this revision are pending; lint and the whitespace check pass. Before the rebase onto #194434's reduced tests, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype passed on two H100s (35 passed; the 18 skipped need four GPUs), and each of these changes made one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward also failed at an earlier revision of this change. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in chunk_cat mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 6288c93 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 28, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > test_grad_dtype_copy_in checks the copy-in inputs with reduce_dtype=None and torch.float32: BF16 for fresh gradients, FP32 when an accumulated FP32 gradient is in the group. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_when_sync_disabled_in_backward checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and test_grad_dtype_restored_by_reset_iter_state checks grad_dtype after an aborted backward and reset_iter_state(). The HSDP copy-in case only runs with reduce_dtype=torch.float32: TestFullyShardMixedPrecisionTraining keeps its process groups across tests, and two more HSDP meshes exhaust NVLS multicast memory on an 8-GPU H100 host. > > Results at this revision are pending; lint and the whitespace check pass. Before the rebase onto #194434's reduced tests, the mixed-precision grad_dtype tests and test_grad_acc_with_reduce_dtype passed on two H100s (35 passed; the 18 skipped need four GPUs), and each of these changes made one of the tests above fail: removing the upcast in the restore; removing the restore after a backward with gradient sync, after one without, or in reset_iter_state(); deferring every parameter's first gradient without gradient sync; deferring to the compute dtype instead of None; and computing the reduce dtype from the incoming gradients. test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_when_sync_disabled_in_backward also failed at an earlier revision of this change. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 9fca432 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 28, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > Copy-in recorders check that fresh gradients reach the reduce-scatter copy-in in the compute dtype: over test_compute_dtype's training loop (reduce_dtype=None, BF16 and FP16), whose reduce-scatter dtype check still expects FP32; for parameters unfrozen after lazy init in test_reduce_dtype_after_frozen_first_forward; and in test_grad_dtype_unused_parameters, where the computed and zero gradients of the weights with FP32 grad_dtype stay BF16 while the reduce-scatter stays FP32. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_after_deferred_upcast checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and that reset_iter_state() restores grad_dtype after an aborted backward. > > Results at this revision are pending. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: d53e4c1 Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 28, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > Copy-in recorders check that fresh gradients reach the reduce-scatter copy-in in the compute dtype: over test_compute_dtype's training loop (reduce_dtype=None, BF16 and FP16), whose reduce-scatter dtype check still expects FP32; for parameters unfrozen after lazy init in test_reduce_dtype_after_frozen_first_forward; and in test_grad_dtype_unused_parameters, where the computed and zero gradients of the weights with FP32 grad_dtype stay BF16 while the reduce-scatter stays FP32. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_after_deferred_upcast checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and that reset_iter_state() restores grad_dtype after an aborted backward. > > Results at this revision are pending. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 4cfde7c Pull-Request: #198668
weifengpy
added a commit
that referenced
this pull request
Sep 28, 2026
> Authored with Claude Code. > > #194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in #194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to #194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in #194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as #194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from #194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before #194434, whereas #194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with #194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with #194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with #194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with #194434, at the same peak memory as #194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since #194434 reduces it in FP32. The unchanged configurations above measure the same as with #194434. > > Test Plan > > Copy-in recorders check that fresh gradients reach the reduce-scatter copy-in in the compute dtype: over test_compute_dtype's training loop (reduce_dtype=None, BF16 and FP16), whose reduce-scatter dtype check still expects FP32; for parameters unfrozen after lazy init in test_reduce_dtype_after_frozen_first_forward; and in test_grad_dtype_unused_parameters, where the computed and zero gradients of the weights with FP32 grad_dtype stay BF16 while the reduce-scatter stays FP32. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_after_deferred_upcast checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and that reset_iter_state() restores grad_dtype after an aborted backward. > > At this revision on H100s, test_fully_shard_mixed_precision.py passes on two GPUs (21 tests in 24 s) and on four (51 s), as do the training, dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against #194434's sources, the copy-in recorders and test_grad_dtype_accumulation_skips_upcast fail, while test_grad_dtype_deferred_upcast_keeps_fp32_grad and test_grad_dtype_restored_after_deferred_upcast pass, since they check behavior #194434 already has. Lint passes. The benchmarks ran on one build: the base, #194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches #194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: 4cfde7c Pull-Request: #198668
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 2, 2026
The previous PR sets each persistent unsharded param's grad_dtype to its unsharded grad dtype. With bf16 compute and fp32 accumulation, autograd then casts every gradient to fp32 on the compute stream, one cast kernel per param. That covers reduce_dtype=fp32 with bf16 params, which is Megatron's setup, and fp32 storage with param_dtype=bf16. FlexShard also holds fp32 unsharded grads until the reduce-scatter copy-in. Before, the bf16 grad went straight to the copy-in, which widened it as part of the copy. As in FSDP2 (pytorch/pytorch#198668), gradients now stay in the dtype autograd produces: - In the pre-backward hook, a param whose unsharded grad dtype is wider than its compute dtype gets grad_dtype=None, if the backward reduces or if the param already holds a grad. Fresh grads reach the copy-in in bf16, and fsdp::chunk_cat_mixed_dtype widens them as part of the copy. AccumulateGrad adds a bf16 grad in place into a kept fp32 grad. - A param without a grad in a backward without sync keeps its grad_dtype, so its first grad is cast and the accumulation starts in fp32. - post_backward restores grad_dtype. In a syncing backward it does so after taking the grads. Without sync it does so after resharding, and it upcasts any grad that was deferred but not reduced. reset() restores it after a backward that raised. - Zeros for unused params use the param's current grad_dtype, which is the forward dtype while deferred, so a fresh bucket keeps one dtype. - The bucket still reduces in the promoted accumulation dtype of its trainable params. That dtype is fixed per bucket and the same on every rank, unlike the incoming grads' dtypes. Difference from the previous PR, as in FSDP2: a param used more than once in a syncing backward sums its contributions in its compute dtype before the copy-in widens the total. Only a backward without sync that starts a param's accumulation casts each contribution first. The two multi-use tests therefore accumulate in a backward without sync first. Configurations whose unsharded grad dtype is not wider than the compute dtype are unchanged, and so is compile. Tests: test_mixed_precision_policy checks that a syncing backward without a kept grad passes the bf16 grad to the reduce-scatter and restores grad_dtype=fp32. Reverting the deferral, or the restore, fails it. Full suite: 100 passed on 4x H100. Benchmarks on H100, with bf16 params and reduce_dtype=fp32 (accumulation wider than compute). Numbers are base (main) / previous PR / this PR. Megatron (TE, shape S, DP 4, interleaved repetitions on GPUs without other jobs; ms/it is the mean of two runs' medians over iterations >= 20): - F1, GBS 8: 233.8 / 238.4 / 234.8 ms/it. Peak allocated: 6617 / 6661 / 6617 MB. - F2, GBS 8: 216.9 / 218.6 / 220.1 ms/it (base runs 221.2 and 212.6). Peak allocated: 9006 / 9095 / 9006 MB. - F2, GBS 32: 813.2 / 827.8 / 809.0 ms/it. - F2 with --flex-shard-no-sync --flex-shard-no-reshard-after-backward, GBS 8: 195.2 / 199.6 / 194.9 ms/it. Peak allocated: 13525 / 13528 / 13525 MB. Microbenchmark (2 ranks; median per backward, mean of two rounds): - 1500 Linear(256, 256) (3000 params) in 30 buckets, syncing backward: 136.2 / 155.0 / 133.2 ms. Peak above the backward's start: 208.5 / 396.6 / 208.5 MiB. - Same model, a syncing backward after one without sync: 152.4 / 171.8 / 148.2 ms. - 8 Linear(2048, 2048) in one bucket, syncing backward peak: 223.7 / 287.7 / 223.7 MiB. Like FSDP2, this PR still casts each param's first grad in a backward without sync, so that backward peaks as in the previous PR: 396.6 and 151.7 MiB for the two models, versus 208.5 and 95.7 MiB in the base, where #18 upcast after resharding. This shows only when post-backward runs at the end of backward, as in these models, whose buckets hook the root. Megatron's per-layer buckets peak the same in all three. ghstack-source-id: 463ddf7 ghstack-comment-id: 5959893944 Pull-Request: #21
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 2, 2026
The previous PR sets each persistent unsharded param's grad_dtype to its unsharded grad dtype. With bf16 compute and fp32 accumulation, autograd then casts every gradient to fp32 on the compute stream, one cast kernel per param. That covers reduce_dtype=fp32 with bf16 params, which is Megatron's setup, and fp32 storage with param_dtype=bf16. FlexShard also holds fp32 unsharded grads until the reduce-scatter copy-in. Before, the bf16 grad went straight to the copy-in, which widened it as part of the copy. As in FSDP2 (pytorch/pytorch#198668), gradients now stay in the dtype autograd produces: - In the pre-backward hook, a param whose unsharded grad dtype is wider than its compute dtype gets grad_dtype=None, if the backward reduces or if the param already holds a grad. Fresh grads reach the copy-in in bf16, and fsdp::chunk_cat_mixed_dtype widens them as part of the copy. AccumulateGrad adds a bf16 grad in place into a kept fp32 grad. - A param without a grad in a backward without sync keeps its grad_dtype, so its first grad is cast and the accumulation starts in fp32. - post_backward restores grad_dtype. In a syncing backward it does so after taking the grads. Without sync it does so after resharding, and it upcasts any grad that was deferred but not reduced. reset() restores it after a backward that raised. - Zeros for unused params use the param's current grad_dtype, which is the forward dtype while deferred, so a fresh bucket keeps one dtype. - The bucket still reduces in the promoted accumulation dtype of its trainable params. That dtype is fixed per bucket and the same on every rank, unlike the incoming grads' dtypes. Difference from the previous PR, as in FSDP2: a param used more than once in a syncing backward sums its contributions in its compute dtype before the copy-in widens the total. Only a backward without sync that starts a param's accumulation casts each contribution first. The two multi-use tests therefore accumulate in a backward without sync first. Configurations whose unsharded grad dtype is not wider than the compute dtype are unchanged, and so is compile. Tests: test_mixed_precision_policy checks that a syncing backward without a kept grad passes the bf16 grad to the reduce-scatter and restores grad_dtype=fp32. Reverting the deferral, or the restore, fails it. Full suite: 100 passed on 4x H100. Benchmarks on H100, with bf16 params and reduce_dtype=fp32 (accumulation wider than compute). Numbers are base (main) / previous PR / this PR. Megatron (TE, shape S, DP 4, interleaved repetitions on GPUs without other jobs; ms/it is the mean of two runs' medians over iterations >= 20): - F1, GBS 8: 233.8 / 238.4 / 234.8 ms/it. Peak allocated: 6617 / 6661 / 6617 MB. - F2, GBS 8: 216.9 / 218.6 / 220.1 ms/it (base runs 221.2 and 212.6). Peak allocated: 9006 / 9095 / 9006 MB. - F2, GBS 32: 813.2 / 827.8 / 809.0 ms/it. - F2 with --flex-shard-no-sync --flex-shard-no-reshard-after-backward, GBS 8: 195.2 / 199.6 / 194.9 ms/it. Peak allocated: 13525 / 13528 / 13525 MB. Microbenchmark (2 ranks; median per backward, mean of two rounds): - 1500 Linear(256, 256) (3000 params) in 30 buckets, syncing backward: 136.2 / 155.0 / 133.2 ms. Peak above the backward's start: 208.5 / 396.6 / 208.5 MiB. - Same model, a syncing backward after one without sync: 152.4 / 171.8 / 148.2 ms. - 8 Linear(2048, 2048) in one bucket, syncing backward peak: 223.7 / 287.7 / 223.7 MiB. Like FSDP2, this PR still casts each param's first grad in a backward without sync, so that backward peaks as in the previous PR: 396.6 and 151.7 MiB for the two models, versus 208.5 and 95.7 MiB in the base, where #18 upcast after resharding. This shows only when post-backward runs at the end of backward, as in these models, whose buckets hook the root. Megatron's per-layer buckets peak the same in all three. ghstack-source-id: d797fb0 ghstack-comment-id: 5959893944 Pull-Request: #21
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 2, 2026
The previous PR sets each persistent unsharded param's grad_dtype to its unsharded grad dtype. With bf16 compute and fp32 accumulation, autograd then casts every gradient to fp32 on the compute stream, one cast kernel per param. That covers reduce_dtype=fp32 with bf16 params, which is Megatron's setup, and fp32 storage with param_dtype=bf16. FlexShard then holds fp32 unsharded grads until the reduce-scatter copy-in, or, in a backward without sync, while the unsharded params are still allocated. On main, the bf16 grad went straight to the copy-in, which widened it as part of the copy, and grads kept without sync were upcast after resharding (#18). As in FSDP2, gradients now stay in the dtype autograd produces. This follows pytorch/pytorch#198668 (landed) and #199242 (open): - In the pre-backward hook, every param whose unsharded grad dtype is wider than its compute dtype gets grad_dtype=None, in every backward. - In a syncing backward, fresh grads reach the copy-in in bf16, and fsdp::chunk_cat_mixed_dtype widens them as part of the copy. - AccumulateGrad adds a bf16 grad in place into a kept fp32 grad. - post_backward restores grad_dtype: - In a syncing backward, it does so after taking the grads. - Without sync, it reshards first and then upcasts each new bf16 grad once, so the widened copies never coexist with the unsharded params. - reset() restores it after a backward that raised. - Zeros for unused params use the param's current grad_dtype, which is the forward dtype while deferred, so a fresh bucket keeps one dtype. - The bucket still reduces in the promoted accumulation dtype of its trainable params. That dtype is fixed per bucket and the same on every rank, unlike the incoming grads' dtypes. Differences from the previous PR, as in FSDP2: - A param used more than once in a backward sums its contributions in its compute dtype before the upcast. Accumulation across backwards stays in the wider dtype. - Configurations whose unsharded grad dtype is not wider than the compute dtype are unchanged, and so is compile. Tests: - test_grads_accumulate_in_unsharded_grad_dtype and test_bucket_reduces_in_promoted_grad_dtype now accumulate across backwards, where a grad of 256 and then 1 gives 257 only in fp32, instead of across uses in one backward. Their test modules are now single-use. - The accumulation test also checks that a backward without sync still holds the compute-dtype grad when it reshards, and leaves the accumulation-dtype grad after. Deferring only as #198668 does fails it, and so does upcasting before resharding. - test_mixed_precision_policy checks that a syncing backward passes the bf16 grad to the reduce-scatter and restores grad_dtype=fp32. Reverting the deferral, or the restore, fails it. - Full suite: 100 passed on 4x H100. Benchmarks on H100, with bf16 params and reduce_dtype=fp32 (accumulation wider than compute). Numbers are base (main) / previous PR / this PR. Microbenchmark, 2 ranks. Medians; two rounds agree to within 1%. GPU kernel time excludes NCCL kernels, whose time includes waiting for the other rank: - 1500 Linear(256, 256) (3000 params) in 30 buckets: - Syncing backward: GPU kernel time 15.7 / 19.3 / 15.8 ms. Peak above the backward's start: 208.5 / 396.6 / 208.5 MiB. - First backward without sync: 16.0 / 15.1 / 16.0 ms, peak 208.5 / 396.6 / 208.5 MiB. - Syncing backward after it: 25.3 / 24.0 / 25.3 ms. - 8 Linear(2048, 2048) in one bucket: - Syncing backward: 0.31 / 0.38 / 0.31 ms, peak 223.7 / 287.7 / 223.7 MiB. - First backward without sync: 0.22 / 0.18 / 0.22 ms, peak 95.7 / 151.7 / 95.7 MiB. Megatron (TE, shape S, DP 4), peak allocated: - F1, GBS 8: 6617 / 6661 / 6617 MB. - F2, GBS 8 and 32: 9006 / 9095 / 9006 MB. - F2 with --flex-shard-no-sync --flex-shard-no-reshard-after-backward: 13525 / 13528 / 13525 MB. On a quiet node, a revision with the same syncing backward (deferral only as #198668 does) measured: - F1, GBS 8: 233.8 / 238.4 / 234.8 ms/it. - F2, GBS 32: 813.2 / 827.8 / 809.0 ms/it. The latest wall-clock runs differ by no more than their run-to-run noise. Other jobs kept the node's load average at 70-180. ghstack-source-id: d797fb0 Pull-Request: #21
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 2, 2026
The previous PR sets each persistent unsharded param's grad_dtype to its unsharded grad dtype. With bf16 compute and fp32 accumulation, autograd then casts every gradient to fp32 on the compute stream, one cast kernel per param. That covers reduce_dtype=fp32 with bf16 params, which is Megatron's setup, and fp32 storage with param_dtype=bf16. FlexShard then holds fp32 unsharded grads until the reduce-scatter copy-in, or, in a backward without sync, while the unsharded params are still allocated. On main, the bf16 grad went straight to the copy-in, which widened it as part of the copy, and grads kept without sync were upcast after resharding (#18). As in FSDP2, gradients now stay in the dtype autograd produces. This follows pytorch/pytorch#198668 (landed) and #199242 (open): - In the pre-backward hook, every param whose unsharded grad dtype is wider than its compute dtype gets grad_dtype=None, in every backward. - In a syncing backward, fresh grads reach the copy-in in bf16, and fsdp::chunk_cat_mixed_dtype widens them as part of the copy. - AccumulateGrad adds a bf16 grad in place into a kept fp32 grad. - post_backward restores grad_dtype: - In a syncing backward, it does so after taking the grads. - Without sync, it reshards first and then upcasts each new bf16 grad once, so the widened copies never coexist with the unsharded params. - reset() restores it after a backward that raised. - Zeros for unused params use the param's current grad_dtype, which is the forward dtype while deferred, so a fresh bucket keeps one dtype. - The bucket still reduces in the promoted accumulation dtype of its trainable params. That dtype is fixed per bucket and the same on every rank, unlike the incoming grads' dtypes. Differences from the previous PR, as in FSDP2: - A param used more than once in a backward sums its contributions in its compute dtype before the upcast. Accumulation across backwards stays in the wider dtype. - Configurations whose unsharded grad dtype is not wider than the compute dtype are unchanged, and so is compile. Tests: - test_grads_accumulate_in_unsharded_grad_dtype and test_bucket_reduces_in_promoted_grad_dtype now accumulate across backwards, where a grad of 256 and then 1 gives 257 only in fp32, instead of across uses in one backward. Their test modules are now single-use. - The accumulation test also checks that a backward without sync still holds the compute-dtype grad when it reshards, and leaves the accumulation-dtype grad after. Deferring only as #198668 does fails it, and so does upcasting before resharding. - test_mixed_precision_policy checks that a syncing backward passes the bf16 grad to the reduce-scatter and restores grad_dtype=fp32. Reverting the deferral, or the restore, fails it. - Full suite: 100 passed on 4x H100. Benchmarks on H100, with bf16 params and reduce_dtype=fp32 (accumulation wider than compute). Numbers are base (main) / previous PR / this PR. Microbenchmark, 2 ranks. Medians; two rounds agree to within 1%. GPU kernel time excludes NCCL kernels, whose time includes waiting for the other rank: - 1500 Linear(256, 256) (3000 params) in 30 buckets: - Syncing backward: GPU kernel time 15.7 / 19.3 / 15.8 ms. Peak above the backward's start: 208.5 / 396.6 / 208.5 MiB. - First backward without sync: 16.0 / 15.1 / 16.0 ms, peak 208.5 / 396.6 / 208.5 MiB. - Syncing backward after it: 25.3 / 24.0 / 25.3 ms. - 8 Linear(2048, 2048) in one bucket: - Syncing backward: 0.31 / 0.38 / 0.31 ms, peak 223.7 / 287.7 / 223.7 MiB. - First backward without sync: 0.22 / 0.18 / 0.22 ms, peak 95.7 / 151.7 / 95.7 MiB. Megatron (TE, shape S, DP 4), peak allocated: - F1, GBS 8: 6617 / 6661 / 6617 MB. - F2, GBS 8 and 32: 9006 / 9095 / 9006 MB. - F2 with --flex-shard-no-sync --flex-shard-no-reshard-after-backward: 13525 / 13528 / 13525 MB. On a quiet node, a revision with the same syncing backward (deferral only as #198668 does) measured: - F1, GBS 8: 233.8 / 238.4 / 234.8 ms/it. - F2, GBS 32: 813.2 / 827.8 / 809.0 ms/it. The latest wall-clock runs differ by no more than their run-to-run noise. Other jobs kept the node's load average at 70-180. ghstack-source-id: d797fb0 Pull-Request: #21
rishisinhanj
added a commit
to rishisinhanj/torchtitan
that referenced
this pull request
Oct 5, 2026
…orch nightly bump Since 2026-10-02, llama3_fsdp+tp+cp, llama3_fsdp+tp+cp+region_ac, gpt_oss_fsdp+tp+ep, and qwen3_moe_fsdp+tp+cp+ep_param_groups have been failing their loss-parity check (--assert-equal) on ROCm, at step 2 instead of step 1. No torchtitan commit explains it: the same SHA (6f716fe) passed CI at 08:57Z and failed at 12:16Z with nothing else changed. Both CI workflows install torch unpinned, and the resolved wheel moved from dev20261001 to dev20261002 in that window. Likely cause upstream: pytorch/pytorch#198668, which changes how FSDP2 accumulates gradients for params that get multiple contributions per backward (CP ring-attention, EP expert FFNs, activation-checkpoint recompute) - exactly the flavors affected here. Regenerates the 3 affected mi350x loss files (llama3, gpt_oss, qwen3) from a current ROCm CI run on main (commit e392936, run 37166905940).
tianyu-l
pushed a commit
to pytorch/torchtitan
that referenced
this pull request
Oct 5, 2026
…ightly bump (#5048) ## Summary Since Friday, all these tests have been failing on CUDA and ROCm: `llama3_fsdp+tp+cp`, `llama3_fsdp+tp+cp+region_ac`, `gpt_oss_fsdp+tp+ep`, and `qwen3_moe_fsdp+tp+cp+ep_param_groups` it is likely from upstream: pytorch/pytorch#198668, which changes how FSDP2 accumulates gradients for params that get multiple contributions per backward. This PR regenerates the 3 affected loss files on ROCm from a current CI run on main (commit `e3929368edd2`).
This was referenced Oct 6, 2026
weifengpy
added a commit
that referenced
this pull request
Oct 7, 2026
> Authored with Claude Code. > > #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph. > > This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral. > > Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype. > > Test Plan > > test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct. > > On B200s, with this revision's Python on a PyTorch build from a few days earlier, test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 29 s) and on four (80 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: a5a3242 Pull-Request: #200196
weifengpy
added a commit
that referenced
this pull request
Oct 7, 2026
> Authored with Claude Code. > > #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph. > > This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral. > > Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype. > > Test Plan > > test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct. > > On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: a5a3242 Pull-Request: #200196
weifengpy
added a commit
that referenced
this pull request
Oct 7, 2026
> Authored with Claude Code. > > #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph. > > This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral. > > Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype. > > Test Plan > > test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct. > > On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: a5a3242 Pull-Request: #200196
weifengpy
added a commit
that referenced
this pull request
Oct 7, 2026
> Authored with Claude Code. > > #198668 defers gradient upcasts by setting each deferring unsharded parameter's grad_dtype to None in pre_backward, and post_backward restores the unsharded gradient dtype. torch.compile traces a region's backward during its forward, when the parameter still has the restored dtype. With #199856, the compiled backward follows the leaf's grad_dtype as of that trace, so it casts every gradient to FP32 and compiled regions lose the deferral. #199856 also has to decide which grad_dtype changes between a compiled forward and its backward are safe: it checks only parameters whose gradient the traced backward narrowed, found by matching cast nodes in the graph. > > This change sets grad_dtype=None once, when the unsharded parameter is created, for parameters that defer, and never changes it. FSDPParam.defers_grad_upcast holds the predicate that _fsdp_params_with_wider_grad_dtype used. pre_backward no longer sets grad_dtype, and post_backward and reset_iter_state() no longer restore it. post_backward still widens a deferred gradient that the backward doesn't reduce, now in _upcast_unreduced_grads, so accumulation across backwards without gradient sync stays in FP32. grad_dtype then can't change between a forward and its backward, including when one microbatch's backward runs after another's post_backward, as in a pipeline schedule's cooldown, where restoring in post_backward would change it. #199856 can then require that grad_dtype not change between a compiled forward and its backward, and compiled regions keep the deferral. > > Differences from #198668: a parameter's first gradient in a backward without gradient sync, which #198668 has autograd cast, is now cast in post_backward. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients. A parameter used more than once in that backward now sums its contributions in BF16 before post_backward widens the total, as #198668 already does in every other backward. Whether to defer no longer depends on reduce_grads or on an existing gradient at pre_backward, so disabling gradient sync between forward and backward needs no special handling. Parameters whose gradient may be reduced outside DP, e.g. the TP all-reduce of a SequenceParallel norm weight's Partial gradient, keep their FP32 grad_dtype, so that reduction stays in FP32. Compiled autograd, which captures gradient metadata before pre_backward and so kept the FP32 cast, now defers too. Between backwards, the unsharded parameter's grad_dtype reads None instead of the unsharded gradient dtype. > > Test Plan > > test_grad_dtype_accumulation_skips_upcast now expects BF16 for all three gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, with grad_dtype None after each, and still checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_upcasts_unreduced_grad, renamed from test_grad_dtype_restored_after_deferred_upcast, checks that a gradient deferred in a backward that disables gradient sync partway ends up FP32 with grad_dtype None, and that grad_dtype stays None through an aborted backward and reset_iter_state(). The new test_grad_dtype_fixed_across_interleaved_microbatches runs two forwards and then their backwards, the first without gradient sync, and checks that grad_dtype is None during both backwards and that the gradient is correct. > > On B200s, with PyTorch built at this change's base (2eb7361), test_fully_shard_mixed_precision.py passes on two GPUs (27 tests in 37 s) and on four (65 s), as do the training (59 passed, 5 skipped), dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against the base's sources, the three changed tests fail. Lint passes. > > Benchmarks ran on two B200s with one build of the base, the base's runs loading its _fsdp_param.py and _fsdp_param_group.py, with FP32 parameters, param_dtype=torch.bfloat16 and reduce_dtype=torch.float32. Each step runs two backwards without gradient sync, then one that reduces; times are the wall time of loss.backward(), the median of 30 steps after 5 warmup steps. For 3000 parameters from 1500 Linear(256, 256) in 30 groups, the first backward, where the upcast moves from autograd to post_backward, takes 6.7 ms less than in the base (median over six alternating runs; per-run differences from +1.1 to -19.7 ms, out of about 160-195 ms). The second and the final backward, which defer in both, differ by -2.8 and +0.8 ms, within the runs' noise of about 15 ms. For 8 Linear(2048, 2048) layers in one group, the two backwards without gradient sync take 1.07-1.16 ms versus 1.32-1.51 ms in the base, over two runs each, and the one that reduces 3.19-3.20 ms versus 3.18 ms. Peak memory above each backward's start is unchanged, except in the first backward for the 3000 parameters: 385.1 MiB versus 391.2 MiB, since fresh gradients stay BF16 until post_backward. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=0,1 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` ghstack-source-id: a5a3242 Pull-Request: #200196
weifengpy
added a commit
that referenced
this pull request
Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32 * TP grad reduction stays in FP32 > Authored with Claude Code. > > #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856. > > The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. > > Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral. > > Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Code that reads grad_dtype during forward, such as torchtitan's MXFP8 linear, sees None in a forward that defers and produces BF16 weight gradients there instead of FP32. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs. > > The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms. > > Test Plan > > test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. > > On B200 GPUs, the mixed precision file (29 tests), the training and compile selections (3 and 7) and the pipeline-with-FSDP mixed precision cases, including the zero-bubble schedules (8), pass on the previous local revision, which differs from this one only in the list's name and two comments. At this revision lint passes, and a single-rank CPU (gloo) run of the zero-bubble, chunked-loss, interleaved-microbatch and multi-use scenarios gives the results described above. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision" > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp" > $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP" > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > ``` ghstack-source-id: 231c3e8 Pull-Request: #200196
weifengpy
added a commit
that referenced
this pull request
Oct 8, 2026
* accumulation across backwards without gradient sync stays in FP32 * TP grad reduction stays in FP32 > Authored with Claude Code. > > #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856. > > The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16. > > Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral. > > Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs. > > The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms. > > Test Plan > > test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None. > > At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision" > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp" > $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP" > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > ``` ghstack-source-id: 28eaeed Pull-Request: #200196
pytorchmergebot
pushed a commit
that referenced
this pull request
Oct 9, 2026
…rd (#200196) ---- * accumulation across backwards without gradient sync stays in FP32 * TP grad reduction stays in FP32 > Authored with Claude Code. > > #198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. #199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of #199856's table), undoing #198668 under compile. This PR is the FSDP-side prerequisite for #199856. > > The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16. > > Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral. > > Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once #199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since #199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so #199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs. > > The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms. > > Test Plan > > test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None. > > At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision" > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp" > $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP" > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > ``` Pull Request resolved: #200196 Approved by: https://github.com/anshul-si, https://github.com/anijain2305
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 9, 2026
…ts a grad, as FSDP2 does FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 0007150 ghstack-comment-id: 6072382915 Pull-Request: #62
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 9, 2026
…ts a grad, as FSDP2 does FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 0007150 ghstack-comment-id: 6072382915 Pull-Request: #62
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 9, 2026
…ts a grad, as FSDP2 does FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 0007150 ghstack-comment-id: 6072382915 Pull-Request: #62
cyyever
pushed a commit
to BakeLab/pytorch
that referenced
this pull request
Oct 11, 2026
…#198668) > Authored with Claude Code. > > pytorch#194434 sets the unsharded parameter's grad_dtype to its unsharded gradient dtype. With FP32 parameters and param_dtype=torch.bfloat16, that dtype is FP32 whether reduce_dtype is None or torch.float32 (torchtitan's default). Autograd therefore casts every BF16 gradient to FP32 on the compute stream, one cast per parameter, and FSDP holds FP32 unsharded gradients until the reduce-scatter copy-in. With reduce_dtype=torch.float32, the BF16 gradient used to go straight to the copy-in, which widens it into the FP32 reduce-scatter buffer as part of the copy. Compared with the base, on H100s this adds about 0.7 ms of GPU time per Llama3-8B layer per backward, holds 436 MB more gradient memory per layer until the copy-in, and slows the backward of a model with 3000 small parameters by 28.5 ms (15%), mostly the casts' CPU cost. Backwards that add to gradients accumulated without gradient sync also cast each new gradient before adding it, where the base's post_backward ran one mixed-dtype add per parameter; for the 3000 parameters, that costs 30-32 ms (15-17%) per backward. > > This change leaves gradients in the dtype autograd produces, except for a parameter's first gradient in a backward without gradient sync. In pre_backward, each unsharded parameter whose unsharded gradient dtype is a larger floating-point dtype than its compute dtype gets grad_dtype=None if the backward reduces or if it already holds a gradient. In a backward that reduces, the reduce-scatter copy-in widens fresh gradients. grad_dtype can be unset while a gradient exists, and AccumulateGrad then adds the new BF16 gradient in place to the FP32 one, the mixed-dtype add the base's post_backward ran. A parameter without a gradient in a backward without gradient sync keeps its grad_dtype, so autograd casts its first gradient and the accumulation stays in FP32, as in pytorch#194434. post_backward restores the unsharded gradient dtype in every backward, after taking the gradients in one that reduces, and reset_iter_state() restores it after an aborted backward. A deferred gradient that isn't reduced, e.g. because gradient sync was disabled during the backward, is upcast first. BF16 to FP32 is exact, so parameters used once per backward get bit-identical gradients to pytorch#194434. > > Since gradients can now arrive narrower than their accumulation dtype, a group without reduce_dtype promotes over its parameters' unsharded gradient dtypes (the incoming dtype for grad_dtype=None parameters) instead of the incoming gradients' dtypes, still including any pending HSDP partial's dtype; this moves into FSDPParamGroup._get_reduce_dtype. Promoting over the incoming gradients would quietly reduce in BF16 with reduce_dtype=None, and could pick different dtypes on different ranks, since whether a parameter still holds an accumulated FP32 gradient is rank-local. Zero gradients for pending or unused parameters use the unsharded parameter's current grad_dtype, as in pytorch#194434, so in a backward that reduces they are BF16 like the fresh gradients, and a fresh group keeps a single dtype and ATen's fused copy-in. > > Setting grad_dtype to the compute dtype instead of None would round gradients that autograd produces in FP32, such as a BF16 weight multiplied by an FP32 buffer; None keeps them as pytorch#194434 does. Deferring a parameter's first gradient in a backward without gradient sync too would only move its cast into post_backward, which has to widen it before the next backward adds to it; the base cast it there as well. > > Differences from pytorch#194434: a parameter used more than once in a backward sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total, as before pytorch#194434, whereas pytorch#194434 casts each contribution to FP32 first; only the first backward that accumulates a parameter's gradient still does. Compiled autograd captures gradient metadata before FSDP's pre-backward hook runs, so it keeps the FP32 cast, with the same result. Unsharded gradients are only BF16 during a backward that reduces, since post_backward consumes them; accumulated ones stay FP32. Configurations whose unsharded gradient dtype isn't wider than the compute dtype (no mixed precision, reduce_dtype=torch.bfloat16, BF16 grad_dtype) are unchanged. > > On two H100s with param_dtype=torch.bfloat16 and reduce_dtype=torch.float32, the backward costs what it did in the base. For 8 Linear(2048, 2048) layers in one group, the backward's copy, add and chunk_cat kernels take 117 us of GPU time and it peaks 125.8 MiB above where it started, as in the base, versus 182 us and 189.8 MiB with pytorch#194434. For 3000 parameters from 256x256 linears in 30 groups, the backward takes 188.9 ms, versus 193.1 ms in the base (within run-to-run noise) and 221.6 ms with pytorch#194434; the two loops that switch grad_dtype account for about 2.2 ms of it. With two backwards without gradient sync before one that reduces, the second takes 170.7 ms for the 3000 parameters, versus 171.2 ms in the base and 199.6 ms with pytorch#194434, and the final one 209.8, 208.6 and 243.7 ms. For the 8 layers, those two backwards' kernels take 174 and 293 us, versus 218 and 344 us in the base and 200 and 320 us with pytorch#194434, at the same peak memory as pytorch#194434. With reduce_dtype=None, param_dtype=torch.bfloat16 now costs what the base's reduce_dtype=torch.float32 did, since pytorch#194434 reduces it in FP32. The unchanged configurations above measure the same as with pytorch#194434. > > Test Plan > > Copy-in recorders check that fresh gradients reach the reduce-scatter copy-in in the compute dtype: over test_compute_dtype's training loop (reduce_dtype=None, BF16 and FP16), whose reduce-scatter dtype check still expects FP32; for parameters unfrozen after lazy init in test_reduce_dtype_after_frozen_first_forward; and in test_grad_dtype_unused_parameters, where the computed and zero gradients of the weights with FP32 grad_dtype stay BF16 while the reduce-scatter stays FP32. test_grad_dtype_accumulation_skips_upcast records the gradients AccumulateGrad receives over two backwards without gradient sync and one that reduces, FP32 for the first and BF16 after it, and checks that 256 + 1 - 256 accumulates to 1. test_grad_dtype_deferred_upcast_keeps_fp32_grad checks that an FP32 gradient from a BF16 weight times an FP32 buffer isn't rounded. test_grad_dtype_restored_after_deferred_upcast checks that a gradient deferred in a backward that disables gradient sync after pre_backward ends up FP32 with grad_dtype restored, and that reset_iter_state() restores grad_dtype after an aborted backward. > > At this revision on H100s, test_fully_shard_mixed_precision.py passes on two GPUs (21 tests in 24 s) and on four (51 s), as do the training, dtensor, memory and spmd_types files. test_fully_shard_comm.py passes except test_fully_shard_alloc_from_pg, which also fails on the base. Against pytorch#194434's sources, the copy-in recorders and test_grad_dtype_accumulation_skips_upcast fail, while test_grad_dtype_deferred_upcast_keeps_fp32_grad and test_grad_dtype_restored_after_deferred_upcast pass, since they check behavior pytorch#194434 already has. Lint passes. The benchmarks ran on one build: the base, pytorch#194434 and the previous revision of this change, then the base, the previous revision and this change for the backwards without gradient sync, where the previous revision matches pytorch#194434. GPU times are the backward's copy, add and chunk_cat kernels in one profiled backward; the 3000-parameter times are backward wall time, the median of 30 steps averaged over two rounds. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > T=test/distributed/_composable/fsdp > for f in mixed_precision training comm dtensor; do CUDA_VISIBLE_DEVICES=6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > for f in mixed_precision memory spmd_types; do CUDA_VISIBLE_DEVICES=4,5,6,7 $PY -m pytest $T/test_fully_shard_$f.py -q -rfs; done > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > git diff HEAD~1 --check > ``` Pull Request resolved: pytorch#198668 Approved by: https://github.com/anijain2305
cyyever
pushed a commit
to BakeLab/pytorch
that referenced
this pull request
Oct 11, 2026
…rd (pytorch#200196) ---- * accumulation across backwards without gradient sync stays in FP32 * TP grad reduction stays in FP32 > Authored with Claude Code. > > pytorch#198668 defers gradient upcasts by setting an unsharded parameter's grad_dtype to None when the backward reduces or the parameter already holds a gradient, so autograd doesn't cast every BF16 gradient to FP32. It chooses in pre_backward, so a forward sees FP32 while its backward runs with None. On trunk a compiled backward doesn't depend on grad_dtype: it casts leaf gradients to the parameter's dtype, and the autograd engine then applies the grad_dtype set when the backward runs. pytorch#199856 makes the compiled backward cast to the grad_dtype seen while tracing the forward, and guards on it. With the pre_backward choice, every compiled backward would then cast its BF16 weight gradients to FP32 inside the graph (the fourth row of pytorch#199856's table), undoing pytorch#198668 under compile. This PR is the FSDP-side prerequisite for pytorch#199856. > > The choice moves to pre_forward, after the unshard, and holds until post_backward, so a forward and its backward see the same grad_dtype. The rule is unchanged: None if the group reduces gradients or the parameter already holds a gradient, else the unsharded gradient dtype. It is now set either way rather than only to None, so a choice from an earlier forward can't carry over. post_backward and reset_iter_state() restore the unsharded gradient dtype and widen a deferred gradient that wasn't reduced, as on trunk; after a backward that reduces, this restore is what returns grad_dtype to FP32. No-grad forwards skip the choice, since no backward would restore it, and so does recomputation under activation checkpointing, so a backward keeps its forward's choice. The predicate moves to FSDPParam.defers_grad_upcast, and the group's list is renamed after it. Parameters whose sharded tensor implements FSDP's all-gather extension (fsdp_pre_all_gather) never defer: an extension runs its own compute, which may read grad_dtype to pick the dtype its backward produces, so grad_dtype stays the unsharded gradient dtype for them. torchtitan's MXFP8 linear reads it in forward and writes its weight gradient in that dtype; under the pre_forward choice alone it would see None and write BF16. > > Outside a forward and its backward, grad_dtype is the unsharded gradient dtype, as on trunk, so gradients deposited without FSDP's hooks still accumulate in FP32. That covers a zero-bubble schedule's weight passes, which run after their input pass's post_backward and assign or add dW themselves in stage_backward_weight, and gradients computed from unsharded parameters without calling their module. The previous revision of this PR set grad_dtype=None for the parameter's lifetime instead, and consecutive weight passes, e.g. on ScheduleInterleavedZeroBubble's last rank, then accumulated in BF16. A fixed FP32 grad_dtype would also keep forward and backward consistent, but gives up the deferral. > > Differences from trunk: in a backward whose forward chose None, a parameter used more than once sums its contributions in BF16 before the copy-in or AccumulateGrad widens the total. Trunk already does this in a backward that reduces, and parameters used once per backward get bit-identical gradients. It now also happens for pipeline microbatches forwarded before the step's first backward disables gradient sync, and in the synced backward of a group like fully_shard([norm, head]) used for a chunked loss, whose pre_backward trunk ran only after the per-chunk contributions had been cast. Extension-backed parameters no longer defer. For one whose backward writes grad_dtype, such as torchtitan's MXFP8 linear, nothing changes. One that hard-codes a BF16 weight gradient, such as torchtitan's NVFP4 linear, now gets autograd's per-parameter cast to FP32 and holds the FP32 gradient until the copy-in; pytorch/torchtitan#5180 makes NVFP4 write its weight gradient in grad_dtype, which removes the cast. Other code that reads grad_dtype during forward sees None in a forward that defers. Once pytorch#199856 lands, a compiled module whose forward runs both with FP32 (a first microbatch without gradient sync) and with None will compile once for each, since pytorch#199856 guards on grad_dtype. Extension-backed parameters keep a fixed grad_dtype, so they add no recompiles. FSDP only sets None or the wider dtype, so pytorch#199856's narrowing check can't fire, even when a later post_backward restores FP32 before an earlier-traced backward runs. > > The choice is the same loop over the group's parameters that trunk ran in pre_backward. For 3000 four-element parameters in one group on CPU, it takes 0.6 ms with gradient sync and 0.9 ms without, versus 0.9 and 0.7 ms for trunk's loop; the post_backward restore is unchanged at 0.9 ms. On a B200, the 3000 BF16-to-FP32 cast kernels the deferral avoids take 17.6 ms. > > Test Plan > > test_grad_dtype_chosen_in_forward checks that a backward sees its forward's grad_dtype when gradient sync changes in between, and that grad_dtype and the gradient are FP32 afterwards. test_grad_dtype_zero_bubble_weight_passes runs four input passes and then four weight passes over residual blocks, as on a zero-bubble schedule's last stage, and checks that the gradient is FP32 after each weight pass and equals FP32 accumulation. test_grad_dtype_outside_forward_and_backward checks that after a no-grad forward, gradients from the unsharded weight accumulate 256 + 1 to 257. All three fail on the previous revision of this PR; the zero-bubble test fails at its dtype check after the first weight pass (bfloat16 != float32). test_grad_dtype_accumulation_skips_upcast and test_grad_dtype_restored_after_deferred_upcast keep trunk's expectations. test_grad_dtype_fixed_for_all_gather_extensions attaches a plain all-gather extension and checks that the forward sees FP32 in two microbatches without gradient sync and a synced one, that autograd delivers FP32 gradients each time, and that 256 + 1 - 256 accumulates to 1. test_grad_dtype_seen_by_all_gather_extension_compute uses a custom autograd Function that, like torchtitan's MXFP8 linear, picks its weight gradient's dtype in forward; it sees FP32, and the reduced gradient keeps (1 + 2^-7)^2 exactly. Both fail without the extension rule, where the forward sees None. > > At this revision on B200 GPUs, the mixed precision file (31 tests), the all-gather extensions file (7), and the training and pipeline-with-FSDP mixed precision selections (3 and 8, including the zero-bubble schedules) pass, and lint passes. The compile selection (7) passed on the previous revision; the extension rule doesn't change those tests. The zero-bubble, chunked-loss, interleaved-microbatch and multi-use claims above come from a single-rank CPU (gloo) script, run before the extension rule, which doesn't affect those scenarios. > > ```bash > PY=/home/weif/.conda/envs/code-review/bin/python > $PY test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py > $PY test/distributed/_composable/fsdp/test_fully_shard_extensions.py > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_training.py -k "grad_dtype or mixed_precision" > $PY -m pytest -q -p no:cacheprovider test/distributed/_composable/fsdp/test_fully_shard_compile.py -k "mixed_precision or mp" > $PY -m pytest -q -p no:cacheprovider test/distributed/test_composability.py -k "test_pp_fsdp and FSDP_MP" > PATH=/home/weif/.conda/envs/code-review/bin:$PATH lintrunner -a $(git diff HEAD~1 --name-only --diff-filter=d) > ``` Pull Request resolved: pytorch#200196 Approved by: https://github.com/anshul-si, https://github.com/anijain2305
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 20, 2026
…ts a grad, as FSDP2 does Re-land of #62. On 2026-10-19 #62 was squash-merged into the head branch of #61 instead of main, so its change never reached main. FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 34e5374 ghstack-comment-id: 6283451761 Pull-Request: #103
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 20, 2026
…ts a grad, as FSDP2 does Re-land of #62. On 2026-10-19 #62 was squash-merged into the head branch of #61 instead of main, so its change never reached main. FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 0b380bb ghstack-comment-id: 6283451761 Pull-Request: #103
weifengpy
added a commit
to meta-pytorch/flex_shard
that referenced
this pull request
Oct 20, 2026
…ts a grad, as FSDP2 does Re-land of #62. On 2026-10-19 #62 was squash-merged into the head branch of #61 instead of main, so its change never reached main. FlexShard defers the upcast of grads whose unsharded grad dtype is wider than their compute dtype (grad_dtype=None during backward), as FSDP2 does since pytorch/pytorch#198668 and #199242. It deferred in every backward. FSDP2 defers only when the backward reduces or adds to a kept grad (_set_unsharded_grad_dtypes: `if grad is not None or self.reduce_grads`). In a backward without sync that starts a param's grad, FSDP2 keeps grad_dtype, so autograd casts each use's grad before summing them. The difference shows for a param used more than once in a forward, such as DeepSeek V3's embedding under multi-token prediction: - FlexShard summed its uses in bf16 in the first microbatch, then upcast; - FSDP2 summed them in fp32. With bf16 params and fp32 grads, the embedding's grads differed from FSDP2's by about 1e-3 relative under gradient accumulation. FlexShard now applies FSDP2's condition. Tests: test_flex_shard_fsdp2_parity's block uses its scale param twice, so its grad sums two uses in each backward. All configurations, including bf16 params with fp32 grads over 2 microbatches without sync, stay bitwise equal to fully_shard. Without the fix, that configuration's reduce-scatter inputs and scale grads differ. ghstack-source-id: 0b380bb ghstack-comment-id: 6283451761 Pull-Request: #103
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):