Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197372
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (4 Unrelated Failures)As of commit 301594a with merge base 3fda599 ( UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 8fbe9a2 Pull-Request: #197372
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 8fbe9a2 Pull-Request: #197372
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 09c5086 Pull-Request: #197372
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 09c5086 Pull-Request: #197372
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 09c5086 Pull-Request: #197372
weifengpy
added a commit
that referenced
this pull request
Sep 17, 2026
> AI-assisted draft prepared with Codex. > > Extract the existing all-gather destination preparation and reduce-scatter input preparation into helpers and call them directly from the collective implementations. Preserve collective signatures, allocations, reorder operations, padding, native copy kernels, and gradient lifetimes. > > This is a behavior-preserving refactor covered by the existing tests. The stacked PR adds configurable callbacks, setter methods, contiguous-view implementations, and their tests. > > Test Plan: > ```bash > CUDA_VISIBLE_DEVICES=1,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShardShareCommContext.test_share_comm_context -v > CUDA_VISIBLE_DEVICES=3,4 python test/distributed/_composable/fsdp/test_fully_shard_extensions.py TestFullyShardAllGatherExtensionsMultiProcess.test_all_gather_extensions_train_parity -v > spin quicklint -a > git diff --check > ``` > All four targeted test methods and lint passed. ghstack-source-id: 09c5086 Pull-Request: #197372
weifengpy
marked this pull request as ready for review
September 17, 2026 22:42
anijain2305
approved these changes
Sep 18, 2026
Contributor
Author
|
@pytorchmergebot merge |
Collaborator
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 |
weifengpy
added a commit
that referenced
this pull request
Oct 15, 2026
Keep the original AG/RS preparation and copying as defaults. > AI-assisted implementation and summary prepared with Codex and Claude Code for the requested change above. > > FSDP now prepares each collective copy separately from executing it, so the next PR can register native copies. To review, start with `Note [All-gather output fn]` and `Note [Reduce-scatter input fn]` in `_fsdp_collectives.py` and `AllGatherInput` in `_fsdp_api.py`, then read `_AllGatherOutputLayout`, `_get_extension_all_gather_inputs` and `_get_all_gather_output_layouts` in `_fsdp_param.py`, then `_fsdp_param_group.py`, then the tests. > > For the all-gather, every parameter records a layout per payload: the size that `fsdp_post_all_gather` receives the output viewed as, and the number of rows over which the copy-out concatenates the ranks' chunks. That number is the product of the dims before the gather dim, the padded sharded parameter's for Tensor payloads, or 1 when a flat copy suffices, as for a single rank, an empty payload or a post-forward shard. `foreach_all_gather_copy_out` reads those layouts, allocates the outputs, and calls an all-gather output fn with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a reduce-scatter input fn that returns the copy-in to run once the buffer is allocated. The two Notes document both contracts, and the callbacks stay plain `Callable`s so their signatures can still change. 2.15 ships the private hooks that #197372 added with their earlier signatures. The callbacks keep those hooks' names, and FSDP passes their sizes and world size by keyword, so a callback written for the earlier signatures fails loudly rather than being ignored or misreading its arguments. The default callbacks keep the original split, rank reassembly and chunk-cat copies, and reassemble typed tensors also when the all-gather buffer holds bytes. > > The two PRs below fix resharding to a smaller mesh after forward and the single-rank copy of extensions with several payloads. Here, post-forward shards get a flat layout, which replaces the flat copy that the post-forward fix adds to main's copy-out. > > `fsdp_pre_all_gather` may now return `AllGatherInput` records that declare each payload's concatenation dim, independent of the parameter's shard dim. This PR keeps them in the private `_fsdp_api` module, and #197701 exports them from `torch.distributed.fsdp.experimental`. Their `dim` is required, since a default would silently gather differently from a plain tensor of a Shard(i>0) parameter, and may be any integer except a tensor. Their number, element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs. Tensor payloads are still flattened with `view(-1)` and passed viewed as `(-1, *size[1:])`, and may become uint8 byte views of their whole outputs or, for parameters with a single row, i.e. whose dims before the shard dim multiply to 1, such as Shard(0) ones, shrink after their first call, keeping nonzero trailing dims, and fill a prefix of their output. Those of other Shard(i>0) parameters are read as rows of the padded sharded parameter: with more than one shard rank, main required its element count, and they may now instead keep only its dims before the shard dim, e.g. packed uint8 rows or byte views from the first call, or be empty. FSDP checks the payloads before the collective and caches the result for up to four combinations of their kinds, dims, sizes and dtypes, so payloads that alternate between shapes, like MXFP8 tensors that send rowwise data in forward and columnwise data in backward, are not checked again on every all-gather. > > Alternatives: FSDP doesn't detect payloads that move the shard dim to dim 0, as torchtitan's quantized tensors do, since a shape-based check would also reject reshapes that keep the rows, which main accepts; those payloads still come back permuted, as on main, until they return `AllGatherInput(dim=0)`. Shard(i>0) Tensor payloads that keep only the leading dims are accepted rather than rejected because they are copied correctly and get the `(-1, *size[1:])` view that main gives every Shard(i>0) Tensor payload. The copy-out checks each output's element count instead of catching the error of a mismatched view, which costs about 0.1 us per output but saves about 13 us per output of a shrunk payload. The post-forward check runs on every post-forward reshard rather than once, so that it needs no state to invalidate, and the layout cache empties when it fills, which bounds it for payloads whose sizes keep changing. > > On CPU, measured with an out-of-tree A/B harness over 1000 to 3000 parameters, a Shard(0) copy-out costs about 0.15 to 0.3 us more per parameter than on main, also when the all-gather buffer holds bytes, while a Shard(1) copy-out costs about 5 to 8 us less. Extension inputs cost about 0.15 us more per parameter and all-gather with one payload and about 0.25 to 0.5 us with two, also when they alternate between shapes, but about 10 to 20 us more with the garbage collector on (5 to 9 us with it off) when their sizes change on every call or alternate among more than four combinations, which FSDP then checks again. > > Release notes: the private `FSDPParamGroup._all_gather_output_fn` and `_prepare_reduce_scatter_inputs` callbacks take new signatures, and callbacks written for 2.15's raise a `TypeError`. Extension payloads that FSDP cannot copy now raise a `ValueError` that names the parameter before the collective: > - a changed payload count, for which main raised a `RuntimeError` after the collective, or, on a size-1 shard mesh, copied only the first payload; > - a payload larger than on its first call, which main copied as wrong data with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; > - a dtype change other than to uint8, for which main raised a `RuntimeError` after the collective in a uniform-dtype group, copied the bytes, wrongly if they grew or, for Shard(i>0) parameters with several rows, shrank, when the group gathered bytes, or, on a size-1 shard mesh, cast silently if its element count was unchanged and otherwise failed in `copy_`; > - a uint8 payload smaller than its typed output, which main copied into a prefix of the output's bytes, or reassembled with ranks mixed up for Shard(i>0) parameters with several rows, with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; ROCm TransformerEngine sends one after a first all-gather outside fp8 autocast, and then computed with fp8 bytes in a typed weight; > - Tensor payloads whose trailing dims cannot view their output, which main failed on, and, with more than one shard rank, nonempty Tensor payloads of Shard(i>0) parameters with several rows that are not uint8 payloads of typed outputs and have neither the padded sharded element count nor its dims before the shard dim, which main failed on after the collective on a first call and, on later calls, treated like the size and dtype changes above and below; > - Tensor payloads that shrink of Shard(i>0) parameters with several rows, which main reassembled with ranks mixed up, or failed on in `copy_` on a size-1 shard mesh. > > Three of these break cases that main handled. When the group gathered bytes, main copied a payload whose dtype changed byte for byte if its bytes stayed the same, e.g. fp8 e4m3 to e5m2 next to fp32 scales or a typed payload after a byte view, and, for parameters with a single row, into a prefix with a resize warning if they shrank. Returning uint8 byte views of the whole outputs keeps those whose bytes stay the same working. On a size-1 shard mesh, main also handled a payload count drop, where only the first payload remained, and cast a payload whose dtype changed to one other than uint8, but not its element count, into the first call's dtype, exactly when representable. The padded-size check for unevenly sharded parameters now raises a `ValueError` instead of an `AssertionError`, and also runs on ranks without padding, so payloads that lack the padded size everywhere, e.g. flattened ones, fail on every rank. An extension that returns its unpadded local shard still passes on ranks whose shard needs no padding, which then hang, as before. > > Fixed: payloads with a zero-size trailing dim, which failed in `view(-1, 0)` (since #122908) or, for Shard(i>0) parameters with more than one shard rank, in the rank reassembly, and now get an explicit leading size; Tensor payloads that shrink, of Shard(0) parameters and of Shard(i>0) ones with a single row, which main resized with a deprecation warning and, on a size-1 shard mesh, failed on; and, with more than one shard rank, Tensor payloads of the latter without the padded sharded element count on their first call, which main failed on after the collective and which are now copied flat. > > Test Plan: > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveOps -k TestFullyShardCollectiveCopies -k TestFullyShardDefaultAllGatherOutputFn > python test/distributed/_composable/fsdp/test_fully_shard_memory.py -k test_unsharded_grads_freed_after_copy_in > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_grad_dtype -k test_compute_dtype > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k test_dp_state_dict_save_load > ``` > All pass on B200s. On main, `test_all_gather_extension_shard_dim1_byte_views` fails for byte views from the first call. > > Each new check also fails when the code it covers is removed or broken, as checked with mutants: the prefix slice, the skip of empty all-gathers, the layout cache's key and bound, `del copy_in`, the keyword-only sizes, the payload and dim checks, the rows rule's restriction to several ranks and rows, the `replicate()` mesh guard and the flat post-forward layout. ghstack-source-id: 73c5685 Pull-Request: #200034
weifengpy
added a commit
that referenced
this pull request
Oct 15, 2026
Keep the original AG/RS preparation and copying as defaults. > AI-assisted implementation and summary prepared with Codex and Claude Code for the requested change above. > > FSDP now prepares each collective copy separately from executing it, so the next PR can register native copies. To review, start with `Note [All-gather output fn]` and `Note [Reduce-scatter input fn]` in `_fsdp_collectives.py` and `AllGatherInput` in `_fsdp_api.py`, then read `_AllGatherOutputLayout`, `_get_extension_all_gather_inputs` and `_get_all_gather_output_layouts` in `_fsdp_param.py`, then `foreach_all_gather_copy_out` and `foreach_reduce` in `_fsdp_collectives.py`, then the tests. > > For the all-gather, every parameter records a layout per payload: the size that `fsdp_post_all_gather` receives the output viewed as, and the number of rows over which the copy-out concatenates the ranks' chunks. That number is the product of the dims before the gather dim, the padded sharded parameter's for Tensor payloads, or 1 when a flat copy suffices, as for a single rank, an empty payload or a post-forward shard. `foreach_all_gather_copy_out` reads those layouts, allocates the outputs, and calls an all-gather output fn with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a reduce-scatter input fn that returns the copy-in to run once the buffer is allocated. The two Notes document both contracts, and the callbacks stay plain `Callable`s so their signatures can still change. 2.15 ships the private hooks that #197372 added with their earlier signatures. The callbacks keep those hooks' names, and FSDP passes their sizes and world size by keyword, so a callback written for the earlier signatures fails loudly rather than being ignored or misreading its arguments. The default callbacks keep the original split, rank reassembly and chunk-cat copies, and reassemble typed tensors also when the all-gather buffer holds bytes. > > The two PRs below fix resharding to a smaller mesh after forward and make a size-1 shard mesh copy every extension payload, smaller ones of an unchanged dtype into a prefix. Here, post-forward shards get a flat layout, which replaces the flat copy that the post-forward fix adds to main's copy-out. > > `fsdp_pre_all_gather` may now return `AllGatherInput` records that declare each payload's concatenation dim, independent of the parameter's shard dim. This PR keeps them in the private `_fsdp_api` module, and #197701 exports them from `torch.distributed.fsdp.experimental`. Their `dim` is required, since a default would silently gather differently from a plain tensor of a Shard(i>0) parameter, and may be any integer except a tensor. Their number, element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs. Tensor payloads are still flattened with `view(-1)` and passed viewed as `(-1, *size[1:])`, and may become uint8 byte views of their whole outputs or, for parameters with a single row, i.e. whose dims before the shard dim multiply to 1, such as Shard(0) ones, shrink after their first call, keeping nonzero trailing dims, and fill a prefix of their output. Those of other Shard(i>0) parameters are read as rows of the padded sharded parameter: with more than one shard rank, main required its element count, and they may now instead keep only its dims before the shard dim, e.g. packed uint8 rows or byte views from the first call, or be empty. FSDP checks the payloads before the collective and caches the result for up to four combinations of their kinds, dims, sizes and dtypes, so payloads that alternate between shapes, like MXFP8 tensors that send rowwise data in forward and columnwise data in backward, are not checked again on every all-gather. > > Alternatives: FSDP doesn't detect payloads that move the shard dim to dim 0, as torchtitan's quantized tensors do, since a shape-based check would also reject reshapes that keep the rows, which main accepts; those payloads still come back permuted, as on main, until they return `AllGatherInput(dim=0)`. Shard(i>0) Tensor payloads that keep only the leading dims are accepted rather than rejected because they are copied correctly and get the `(-1, *size[1:])` view that main gives every Shard(i>0) Tensor payload. The copy-out checks each output's element count instead of catching the error of a mismatched view, which costs about 0.1 us per output but saves about 13 us per output of a shrunk payload. The layout cache empties when it fills, which bounds it for payloads whose sizes keep changing. > > On CPU, measured with an out-of-tree A/B harness over 1000 to 3000 parameters, a Shard(0) copy-out costs about 0.15 to 0.3 us more per parameter than on main, also when the all-gather buffer holds bytes, while a Shard(1) copy-out costs about 5 to 8 us less, and the reduce-scatter about 1 to 1.5 us less. At 1000 parameters, extension inputs cost about 0.15 us more per parameter and all-gather with one payload and about 0.25 to 0.5 us with two, also when they alternate between shapes, but about 10 to 25 us more with the garbage collector on (5 to 9 us with it off) when their sizes change on every call or alternate among more than four combinations, which FSDP then checks again. > > Release notes: the private `FSDPParamGroup._all_gather_output_fn` and `_prepare_reduce_scatter_inputs` callbacks take new signatures, and callbacks written for 2.15's raise a `TypeError`. Extension payloads that FSDP cannot copy now raise a `ValueError` that names the parameter before the collective: > - a changed payload count, for which main raised a `RuntimeError` after the collective, or, on a size-1 shard mesh, an unnamed `ValueError` from `zip`; > - a payload larger than on its first call, which main copied as wrong data with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; > - a dtype change other than to uint8, for which main raised a `RuntimeError` after the collective in a uniform-dtype group, copied the bytes, wrongly if they grew or, for Shard(i>0) parameters with several rows, shrank, when the group gathered bytes, or, on a size-1 shard mesh, cast silently if its element count was unchanged, broadcast it if it had one element, and otherwise failed in `copy_`; > - a uint8 payload smaller than its typed output, which main copied into a prefix of the output's bytes, or reassembled with ranks mixed up for Shard(i>0) parameters with several rows, with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; ROCm TransformerEngine sends one after a first all-gather outside fp8 autocast, and then computed with fp8 bytes in a typed weight; > - Tensor payloads whose trailing dims cannot view their output, which main failed on, and, with more than one shard rank, nonempty Tensor payloads of Shard(i>0) parameters with several rows that are not uint8 payloads of typed outputs and have neither the padded sharded element count nor its dims before the shard dim, which main failed on after the collective on a first call and, on later calls, treated like the size and dtype changes above and below; > - Tensor payloads that shrink of Shard(i>0) parameters with several rows, which main reassembled with ranks mixed up, or, on a size-1 shard mesh, copied into a prefix of their output. > > Three of these break cases that main handled. When the group gathered bytes, main copied a payload whose dtype changed byte for byte if its bytes stayed the same, e.g. fp8 e4m3 to e5m2 next to fp32 scales or a typed payload after a byte view, and, for parameters with a single row, into a prefix with a resize warning if they shrank. Returning uint8 byte views of the whole outputs keeps those whose bytes stay the same working. On a size-1 shard mesh, main also cast a payload whose dtype changed to one other than uint8, but not its element count, into the first call's dtype, exactly when representable, and copied shrinking Tensor payloads of Shard(i>0) parameters with several rows into a prefix, which FSDP now rejects on every mesh since more shard ranks would mix up their rows. The padded-size check for unevenly sharded parameters now raises a `ValueError` instead of an `AssertionError`, and also runs on ranks without padding, so payloads that lack the padded size everywhere, e.g. flattened ones, fail on every rank. An extension that returns its unpadded local shard still passes on ranks whose shard needs no padding, which then hang, as before. > > Fixed: payloads with a zero-size trailing dim, which failed in `view(-1, 0)` (since #122908) or, for Shard(i>0) parameters with more than one shard rank, in the rank reassembly, and now get an explicit leading size; Tensor payloads that shrink, of Shard(0) parameters and of Shard(i>0) ones with a single row, which main resized with a deprecation warning; and, with more than one shard rank, Tensor payloads of the latter without the padded sharded element count on their first call, which main failed on after the collective and which are now copied flat. > > Test Plan: > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveOps -k TestFullyShardCollectiveCopies -k TestFullyShardDefaultAllGatherOutputFn > python test/distributed/_composable/fsdp/test_fully_shard_memory.py -k test_unsharded_grads_freed_after_copy_in > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_grad_dtype -k test_compute_dtype > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k test_dp_state_dict_save_load > ``` > All pass on B200s. Before this PR, `test_all_gather_extension_shard_dim1_byte_views` fails for byte views from the first call, and `test_all_gather_extension_smaller_payload` and `test_all_gather_extension_uneven_sharding` fail because the errors they expect are new. > > Each new check also fails when the code it covers is removed or broken, as checked with mutants: the prefix slice, the skip of empty all-gathers, the layout cache's key and bound, `del copy_in`, the keyword-only sizes, the payload and dim checks, the rows rule's restriction to several ranks and rows, the `replicate()` mesh guard, the flat post-forward layout, the empty layouts of an extension without payloads and the restriction of byte buffers to uint8. ghstack-source-id: e995d7b Pull-Request: #200034
pytorchmergebot
pushed a commit
that referenced
this pull request
Oct 20, 2026
Keep the original AG/RS preparation and copying as defaults. > AI-assisted implementation and summary prepared with Codex and Claude Code for the requested change above. > > FSDP now prepares each collective copy separately from executing it, so the next PR can register native copies. To review, start with `Note [All-gather output fn]` and `Note [Reduce-scatter input fn]` in `_fsdp_collectives.py` and `AllGatherInput` in `_fsdp_api.py`, then read `_AllGatherOutputLayout`, `_get_extension_all_gather_inputs` and `_get_all_gather_output_layouts` in `_fsdp_param.py`, then `foreach_all_gather_copy_out` and `foreach_reduce` in `_fsdp_collectives.py`, then the tests. > > For the all-gather, every parameter records a layout per payload: the size that `fsdp_post_all_gather` receives the output viewed as, and the number of rows over which the copy-out concatenates the ranks' chunks. That number is the product of the dims before the gather dim, the padded sharded parameter's for Tensor payloads, or 1 when a flat copy suffices, as for a single rank, an empty payload or a post-forward shard. `foreach_all_gather_copy_out` reads those layouts, allocates the outputs, and calls an all-gather output fn with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a reduce-scatter input fn that returns the copy-in to run once the buffer is allocated. The two Notes document both contracts, and the callbacks stay plain `Callable`s so their signatures can still change. 2.15 ships the private hooks that #197372 added with their earlier signatures. The callbacks keep those hooks' names, and FSDP passes their sizes and world size by keyword, so a callback written for the earlier signatures fails loudly rather than being ignored or misreading its arguments. The default callbacks keep the original split, rank reassembly and chunk-cat copies, and reassemble typed tensors also when the all-gather buffer holds bytes. > > The two PRs below fix resharding to a smaller mesh after forward and make a size-1 shard mesh copy every extension payload, smaller ones of an unchanged dtype into a prefix. Here, post-forward shards get a flat layout, which replaces the flat copy that the post-forward fix adds to main's copy-out. > > `fsdp_pre_all_gather` may now return `AllGatherInput` records that declare each payload's concatenation dim, independent of the parameter's shard dim. This PR keeps them in the private `_fsdp_api` module, and #197701 exports them from `torch.distributed.fsdp.experimental`. Their `dim` is required, since a default would silently gather differently from a plain tensor of a Shard(i>0) parameter, and may be any integer except a tensor. Their number, element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs. Tensor payloads are still flattened with `view(-1)` and passed viewed as `(-1, *size[1:])`, and may become uint8 byte views of their whole outputs or, for parameters with a single row, i.e. whose dims before the shard dim multiply to 1, such as Shard(0) ones, shrink after their first call, keeping nonzero trailing dims, and fill a prefix of their output. Those of other Shard(i>0) parameters are read as rows of the padded sharded parameter: with more than one shard rank, main required its element count, and they may now instead keep only its dims before the shard dim, e.g. packed uint8 rows or byte views from the first call, or be empty. FSDP checks the payloads before the collective and caches the result for up to four combinations of their kinds, dims, sizes and dtypes, so payloads that alternate between shapes, like MXFP8 tensors that send rowwise data in forward and columnwise data in backward, are not checked again on every all-gather. > > Alternatives: FSDP doesn't detect payloads that move the shard dim to dim 0, as torchtitan's quantized tensors do, since a shape-based check would also reject reshapes that keep the rows, which main accepts; those payloads still come back permuted, as on main, until they return `AllGatherInput(dim=0)`. Shard(i>0) Tensor payloads that keep only the leading dims are accepted rather than rejected because they are copied correctly and get the `(-1, *size[1:])` view that main gives every Shard(i>0) Tensor payload. The copy-out checks each output's element count instead of catching the error of a mismatched view, which costs about 0.1 us per output but saves about 13 us per output of a shrunk payload. The layout cache empties when it fills, which bounds it for payloads whose sizes keep changing. > > On CPU, measured with an out-of-tree A/B harness over 1000 to 3000 parameters, a Shard(0) copy-out costs about 0.15 to 0.3 us more per parameter than on main, also when the all-gather buffer holds bytes, while a Shard(1) copy-out costs about 5 to 8 us less, and the reduce-scatter about 1 to 1.5 us less. At 1000 parameters, extension inputs cost about 0.15 us more per parameter and all-gather with one payload and about 0.25 to 0.5 us with two, also when they alternate between shapes, but about 10 to 25 us more with the garbage collector on (5 to 9 us with it off) when their sizes change on every call or alternate among more than four combinations, which FSDP then checks again. > > Release notes: the private `FSDPParamGroup._all_gather_output_fn` and `_prepare_reduce_scatter_inputs` callbacks take new signatures, and callbacks written for 2.15's raise a `TypeError`. Extension payloads that FSDP cannot copy now raise a `ValueError` that names the parameter before the collective: > - a changed payload count, for which main raised a `RuntimeError` after the collective, or, on a size-1 shard mesh, an unnamed `ValueError` from `zip`; > - a payload larger than on its first call, which main copied as wrong data with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; > - a dtype change other than to uint8, for which main raised a `RuntimeError` after the collective in a uniform-dtype group, copied the bytes, wrongly if they grew or, for Shard(i>0) parameters with several rows, shrank, when the group gathered bytes, or, on a size-1 shard mesh, cast silently if its element count was unchanged, broadcast it if it had one element, and otherwise failed in `copy_`; > - a uint8 payload smaller than its typed output, which main copied into a prefix of the output's bytes, or reassembled with ranks mixed up for Shard(i>0) parameters with several rows, with an out= resize warning, or, on a size-1 shard mesh, failed on in `copy_`; ROCm TransformerEngine sends one after a first all-gather outside fp8 autocast, and then computed with fp8 bytes in a typed weight; > - Tensor payloads whose trailing dims cannot view their output, which main failed on, and, with more than one shard rank, nonempty Tensor payloads of Shard(i>0) parameters with several rows that are not uint8 payloads of typed outputs and have neither the padded sharded element count nor its dims before the shard dim, which main failed on after the collective on a first call and, on later calls, treated like the size and dtype changes above and below; > - Tensor payloads that shrink of Shard(i>0) parameters with several rows, which main reassembled with ranks mixed up, or, on a size-1 shard mesh, copied into a prefix of their output. > > Three of these break cases that main handled. When the group gathered bytes, main copied a payload whose dtype changed byte for byte if its bytes stayed the same, e.g. fp8 e4m3 to e5m2 next to fp32 scales or a typed payload after a byte view, and, for parameters with a single row, into a prefix with a resize warning if they shrank. Returning uint8 byte views of the whole outputs keeps those whose bytes stay the same working. On a size-1 shard mesh, main also cast a payload whose dtype changed to one other than uint8, but not its element count, into the first call's dtype, exactly when representable, and copied shrinking Tensor payloads of Shard(i>0) parameters with several rows into a prefix, which FSDP now rejects on every mesh since more shard ranks would mix up their rows. The padded-size check for unevenly sharded parameters now raises a `ValueError` instead of an `AssertionError`, and also runs on ranks without padding, so payloads that lack the padded size everywhere, e.g. flattened ones, fail on every rank. An extension that returns its unpadded local shard still passes on ranks whose shard needs no padding, which then hang, as before. > > Fixed: payloads with a zero-size trailing dim, which failed in `view(-1, 0)` (since #122908) or, for Shard(i>0) parameters with more than one shard rank, in the rank reassembly, and now get an explicit leading size; Tensor payloads that shrink, of Shard(0) parameters and of Shard(i>0) ones with a single row, which main resized with a deprecation warning; and, with more than one shard rank, Tensor payloads of the latter without the padded sharded element count on their first call, which main failed on after the collective and which are now copied flat. > > Test Plan: > ```bash > python test/distributed/_composable/fsdp/test_fully_shard_extensions.py > python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k TestFullyShardCollectiveOps -k TestFullyShardCollectiveCopies -k TestFullyShardDefaultAllGatherOutputFn > python test/distributed/_composable/fsdp/test_fully_shard_memory.py -k test_unsharded_grads_freed_after_copy_in > python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_grad_dtype -k test_compute_dtype > python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference -k test_share_comm_context > python test/distributed/_composable/fsdp/test_fully_shard_state_dict.py -k test_dp_state_dict_save_load > ``` > All pass on B200s. Before this PR, `test_all_gather_extension_shard_dim1_byte_views` fails for byte views from the first call, and `test_all_gather_extension_smaller_payload` and `test_all_gather_extension_uneven_sharding` fail because the errors they expect are new. > > Each new check also fails when the code it covers is removed or broken, as checked with mutants: the prefix slice, the skip of empty all-gathers, the layout cache's key and bound, `del copy_in`, the keyword-only sizes, the payload and dim checks, the rows rule's restriction to several ranks and rows, the `replicate()` mesh guard, the flat post-forward layout, the empty layouts of an extension without payloads and the restriction of byte buffers to uint8. Pull Request resolved: #200034 Approved by: https://github.com/anshul-si ghstack dependencies: #200985, #200986
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):
pure code refactoring - no perf inidication, no new feature
the goal is to let user register custom Ag/RS copy fn in next PR for better Shard(1) perf