Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194434
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (3 Unrelated Failures)As of commit 55bb0a8 with merge base 7310405 ( FLAKY - The following jobs failed but were likely due to flakiness present on trunk:
UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…y-in cost Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through fully_shard. The PR below it is an unmodified copy of that work, pushed only so this change diffs cleanly; #172074 itself is untouched and is the one that should be reviewed and landed. Fold these corrections into it, or land them after it. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). ghstack-source-id: 5b41084 Pull-Request: #194434
…y-in cost Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through fully_shard. The PR below it is an unmodified copy of that work, pushed only so this change diffs cleanly; #172074 itself is untouched and is the one that should be reviewed and landed. Fold these corrections into it, or land them after it. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). ghstack-source-id: 5b41084 Pull-Request: #194434
…y-in cost Stacked on a duplicate of #172074, which propagates Tensor.grad_dtype through fully_shard. The PR below it is an unmodified copy of that work, pushed only so this change diffs cleanly; #172074 itself is untouched and is the one that should be reviewed and landed. Fold these corrections into it, or land them after it. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). ghstack-source-id: 5b41084 Pull-Request: #194434
Supersedes and includes #172074 by @arkadip-maitra, which propagates Tensor.grad_dtype through fully_shard, plus four corrections found while reviewing it. #172074 is the original change and remains open; this PR carries its commit verbatim as the first half of the diff so the whole feature can be reviewed and landed as one unit. If #172074 lands first, only the corrections below are needed and this PR should be rebased down to them. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). Co-authored-by: Arkadip Maitra <[email protected]> ghstack-source-id: f04402d Pull-Request: #194434
Supersedes and includes #172074 by @arkadip-maitra, which propagates Tensor.grad_dtype through fully_shard, plus four corrections found while reviewing it. #172074 is the original change and remains open; this PR carries its commit verbatim as the first half of the diff so the whole feature can be reviewed and landed as one unit. If #172074 lands first, only the corrections below are needed and this PR should be rebased down to them. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). Co-authored-by: Arkadip Maitra <[email protected]> ghstack-source-id: f04402d Pull-Request: #194434
2cc5d46 to
b1060f9
Compare
Supersedes and includes #172074 by @arkadip-maitra, which propagates Tensor.grad_dtype through fully_shard, plus four corrections found while reviewing it. #172074 is the original change and remains open; this PR carries its commit verbatim as the first half of the diff so the whole feature can be reviewed and landed as one unit. If #172074 lands first, only the corrections below are needed and this PR should be rebased down to them. Four issues, found while reviewing #172074 and each reproduced on 2xH100. Microbatch accumulation ran at reduce_dtype, not grad_dtype. This is the one that matters. to_accumulated_grad_if_needed casts the unsharded gradient to reduce_dtype before summing microbatches. That was written as an upcast (bf16 compute gradients into an fp32 reduce buffer), but with an explicit grad_dtype wider than reduce_dtype it becomes a downcast: with bf16 parameters, grad_dtype=fp32 and MixedPrecisionPolicy(reduce_dtype=bf16), every microbatch sum happened in bf16 and was cast back up to fp32 at the end. param.grad.dtype was fp32 as requested while the precision grad_dtype exists to provide was gone, so nothing surfaced the loss. An explicit grad_dtype now takes precedence; for that config the gradients simply stay on _unsharded_param.grad, which is the path already taken when reduce_dtype is unset. grad_dtype = None was conflated with unset. grad_dtype is tri-state: a dtype, None meaning any gradient dtype is allowed, or never assigned, in which case the getter mirrors param.dtype. In foreach_reduce a None read back off the parameter made target_dtype None, which turns _to_dtype_if_needed into a no-op and leaves the gradient in reduce_dtype. With fp32 parameters and reduce_dtype=bf16 that silently produced a bf16 param.grad where it had been fp32, with no error, because grad_dtype=None also disables the dtype check on gradient assignment. Fixed by reading the construction-time snapshot rather than the live parameter, since the snapshot is what was propagated onto the parameter autograd produced these gradients for. An explicit None is treated as unset: the only thing that relaxation buys is skipping the dtype check when someone assigns param.grad, and FSDP always assigns a gradient it just cast to orig_dtype, so that check never fires. A user hand-assigning a mismatched-dtype gradient afterwards now gets a clear error from the setter instead of silent divergence. The reduce-scatter copy-in staging buffer is not needed. It was added on the premise that _chunk_cat rejects narrowing casts. It does not: torch._chunk_cat(out=) lowers to at::cat_out, whose only dtype constraint is canCast(out_dtype, result.scalar_type()), and canCast rejects complex to real, float to integral, and non-bool to bool, so fp32 to bf16 is allowed. The guard also fired on the pre-existing MixedPrecisionPolicy(reduce_dtype=bfloat16) recipe with fp32 parameters, which has nothing to do with grad_dtype, adding a full-size gradient copy to every reduce-scatter. Separately, torch.promote_types raises on float8 rather than returning a result, so for float8 gradients the guard itself would have thrown. reset_sharded_param re-stamped unconditionally. grad_dtype lives on the parameter's autograd metadata and survives an in-place .data swap, so the re-stamp is only required when _apply or load_state_dict(assign=True) installs a replacement Parameter object. Re-stamping unconditionally could also raise from the grad_dtype setter when a gradient of a different dtype was already present, in a function that previously never raised there. Moved inside the object-replacement branch. Review the _fsdp_param.py state change first (the two snapshot fields), then its consumers in _fsdp_collectives.py and _fsdp_param_group.py, then the accumulation fix, then the tests. Test Plan: Full mixed-precision suite on 2 GPUs: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 19 passed in 116.67s ``` FSDP gradient accumulation, the path the accumulation fix touches: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_training.py -q -k gradient_accumulation # 1 passed, 38 deselected in 45.66s ``` Confirming the new coverage fails without the fix, by reverting only the torch/ changes: ``` git stash push -- torch/ python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k grad_dtype -q git stash pop # 3 failed, 3 passed: # FAILED test_grad_dtype_none_keeps_orig_dtype # FAILED test_grad_dtype_numerics_grad_acc # FAILED test_grad_dtype_preserved_grad_acc ``` test_grad_dtype_none_keeps_orig_dtype covers grad_dtype=None set both before and after fully_shard; only the after case reproduces the stale live read, so both are exercised. test_grad_dtype_preserved_across_apply passes either way; it is added as coverage for the reset_sharded_param path, not as a regression test. Accumulation precision, measured against a reference that mirrors FSDP's reduce exactly (accumulate at grad_dtype, cast to reduce_dtype, all-reduce, cast back) so the residual error is attributable to the accumulation dtype alone. bf16 parameters, grad_dtype=fp32, reduce_dtype=bf16, 8 microbatches, 2 ranks: before: max relative error 5.747e-03 after: max relative error 0.000e+00 Copy-in staging buffer, on fp32 parameters + reduce_dtype=bf16 with no grad_dtype set anywhere. 134M parameters over 8 FSDP groups, 10 iterations, 2 ranks: before: 37183 MiB allocated, 13.24 ms/iter after: 32052 MiB allocated, 12.75 ms/iter Peak allocated memory is unchanged at 736.7 MiB either way; the cost was allocator traffic and step time, not peak capacity. Authored with assistance from Claude Code (Anthropic). ghstack-source-id: f04402d Pull-Request: #194434 Co-authored-by: Arkadip Maitra <[email protected]>
b1060f9 to
6d0ca81
Compare
6d0ca81 to
823a593
Compare
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. The buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely; the guard compares itemsize rather than calling torch.promote_types, which raises for float8. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 20 passed in 126.12s ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic).
823a593 to
41ddee0
Compare
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. The buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely; the guard compares itemsize rather than calling torch.promote_types, which raises for float8. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 20 passed in 126.12s ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic).
41ddee0 to
a214515
Compare
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. The buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely; the guard compares itemsize rather than calling torch.promote_types, which raises for float8. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 20 passed in 126.12s ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic).
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the no-collectives no-sync path uses, so the two accumulators cannot drift apart: the buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q # 20 passed in 126.12s ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic).
a214515 to
80bbeeb
Compare
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the no-collectives no-sync path uses, so the two accumulators cannot drift apart: the buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic).
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the no-collectives no-sync path uses, so the two accumulators cannot drift apart: the buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic). Pull-Request: #194546
80bbeeb to
e6a9054
Compare
Stacked on #194434. With HSDP and set_requires_all_reduce(False), the reduce-scatter still runs every microbatch and the partial sums are held in partial_reduce_output across backward calls until the deferred all-reduce. That buffer is allocated at reduce_dtype, so each microbatch's contribution is rounded into it and the error compounds with the microbatch count, even when the user asked for a wider grad_dtype. This is distinct from the accumulation fix in #194434, which covers set_requires_gradient_sync(False) -- the mode that runs no collectives at all. The two no-sync modes take different paths and only the first was addressed. An explicit grad_dtype now widens the partial buffer so only the final all-reduce rounds. It reuses FSDPParam._accumulate_grad_dtype, the same rule the no-collectives no-sync path uses, so the two accumulators cannot drift apart: the buffer is never narrowed below reduce_dtype, which would make accumulation worse than ignoring grad_dtype entirely. When grad_dtype is unset or is not wider than reduce_dtype this is a no-op, so nobody who did not ask for the precision pays the extra memory -- the buffer is sharded-gradient sized and held for the whole accumulation window, so widening it is not free. The all-reduce still runs at reduce_dtype, so one rounding remains by design; widening it would contradict an explicit reduce_dtype. Test Plan: ``` python -m pytest test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -q ``` The new test fails without the torch/ change (`git stash push -- torch/`): ``` AssertionError: Set comparison failed: Items in the first set but not the second 1 failed, 19 deselected ``` Measured on 4xH100, 2x2 mesh, bf16 params, grad_dtype=fp32, reduce_dtype=bf16, against a reference that mirrors the reduce pipeline but accumulates in fp32: microbatches before after 8 7.143e-03 5.814e-03 32 1.143e-02 5.714e-03 The point is not the ratio but the shape: after the change the error no longer grows with the microbatch count. The residual ~5.7e-3 is the per-microbatch reduce-scatter rounding, which is inherent to reduce_dtype=bf16. Authored with assistance from Claude Code (Anthropic). Pull-Request: #194546
e6a9054 to
338a55b
Compare
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
what's fixed in this PR
I took the risk of nccl hang because i don't want to hard error on existing callsites of .grad_dtype = None |
|
Starting merge as part of PR stack under #198668 |
|
@pytorchmergebot merge |
|
fixed rocm unit test error and landing again |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
Starting merge as part of PR stack under #198668 |
Stack from ghstack (oldest at bottom):
Fixes #170648
feature 0: when mp_policy.reduce_dtype is None, it follows orig model.parameters() .grad_dtype. .grad_dtype were silently ignored before this PR
this is BC breaking: mp_policy.reduce_dtype=None no longer defaults to mp_policy.param_dtype
how to deal with BC: explicitly set mp_policy.reduce_dtype
feature 1: in grad accumulation (no reduce-scatter), the unsharded param's .grad always holds the accumulated value, visible via model.parameters() while unsharded. Before this PR, .grad was None when reduce_dtype was set and differed from param_dtype (FSDP kept the sum in a hidden reduce_dtype buffer)
memory difference
perf difference
this PR does per-param 16 casts: increasing copy-time by ~50% ( 124 / (58 + 124) )
Co-authored-by: Arkadip Maitra [email protected]