Skip to content

[FSDP2] Added pre/post-all-gather extensions (subclass) - #122908

Closed
awgu wants to merge 12 commits into
gh/awgu/550/basefrom
gh/awgu/550/head
Closed

awgu wants to merge 12 commits into
gh/awgu/550/basefrom
gh/awgu/550/head

Conversation

@awgu

@awgu awgu commented Mar 28, 2024 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Overview
This PR adds pre/post-all-gather extensions to FSDP2.

  • The pre/post-all-gather extensions are specified at the tensor-level on the sharded_param._local_tensor (i.e. the tensor wrapped by the sharded DTensor). If the user has a tensor-subclass parameter on the module passed to FSDP that preserves the subclass through the sharding ops (e.g. new_zeros, chunk, etc.), then the sharded_param._local_tensor will naturally be of that subclass.
  • The pre-all-gather function has signature:
    def fsdp_pre_all_gather(self) -> Tuple[Tuple[torch.Tensor, ...], Any]
    
    • The first return value is a Tuple[torch.Tensor, ...] of the all-gather inputs. It is a tuple since a subclass could contribute >1 inner tensors.
    • The second return value is any optional metadata needed to pass through to the post-all-gather.
  • The post all-gather function has signature:
    def fsdp_post_all_gather(
        self,
        all_gather_outputs: Tuple[torch.Tensor, ...],
        metadata: Any,
        param_dtype: torch.dtype,
        *,
        out: Optional[torch.Tensor] = None,
    ) -> Union[Tuple[torch.Tensor, Tuple[torch.Tensor, ...]], None]:
    
    • The all_gather_outputs are exactly the all-gathered versions of the fsdp_pre_all_gather 1st return value (representing the all-gather inputs). We make sure to unflatten these back to ND for the user.
    • The metadata is the fsdp_pre_all_gather 2nd return value, untouched.
    • The param_dtype is the parameter dtype based on the passed-in MixedPrecisionPolicy. Namely, if no policy is passed in, then param_dtype is the original dtype, and otherwise, it is the MixedPrecisionPolicy.param_dtype.
    • If out is not specified, then the return value has type Tuple[torch.Tensor, Tuple[torch.Tensor, ...]]. The first tuple item is the unsharded parameter (e.g. re-wrapping into some subclass). The second tuple item is a tuple of unsharded inner tensors that FSDP should free during reshard. These should be derived from the all-gather outputs.
    • The out argument is required due to FSDP's resize_ usage. We require an in-place variant for the backward all-gather. Here, out will be exactly the object returned as the first tuple item in the out-of-place variant mentioned before. The unsharded inner tensors will be allocated before calling fsdp_post_all_gather. When out is specified, the fsdp_post_all_gather should return None. If the post-all-gather does not do any out-of-place ops, then the out variant can just be a no-op since the unsharded inner tensors will be the same as the all-gather outputs, which FSDP directly writes to after all-gather. (E.g., this is the case for both float8 and NF4Tensor.)
  • We check for fsdp_pre_all_gather and fsdp_post_all_gather directly via hasattr to accommodate monkey patching so that we do not strictly require the user to use a tensor subclass. The monkey patch must happen after the local tensors have been finalized (after applying FSDP and after any meta-device init).
  • For now, we require that all gradients in one FSDP parameter group share the same dtype. This is fine for float8 and NF4Tensor use cases. If this requirement is too strict, then in the future we can issue 1 reduce-scatter per dtype per group.

Design Notes

  • We assume that the sharded_param._local_tensor is padded on dim-0.
    • This assumption should not block immediate use cases, and when we pad the DTensor._local_tensor by default, this assumption will always be true.
    • This assumption allows us to call sharded_param._local_tensor.fsdp_pre_all_gather(); i.e. it tells us from which tensor object to invoke fsdp_pre_all_gather().
    • Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather(), where _local_tensor.to("cuda") should return an instance of the subclass so that it still defines fsdp_pre_all_gather(). Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have .to("cuda") move any cached values too.
  • fsdp_post_all_gather can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    • If the unsharded parameter aliases with the all-gather output, then we should not free the all-gather output in unshard.
    • If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in unshard to avoid holding the unneeded temporary.
    • One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in reshard.

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @chauhang

@pytorch-bot

pytorch-bot Bot commented Mar 28, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/122908

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 8ad33ab with merge base 7cd7a7a (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added oncall: distributed Add this issue/PR to distributed oncall triage queue release notes: distributed (fsdp) release notes category labels Mar 28, 2024
awgu pushed a commit that referenced this pull request Mar 28, 2024
ghstack-source-id: fdcc4a4
Pull Request resolved: #122908
@awgu awgu added release notes: distributed (fsdp2) release notes category and removed release notes: distributed (fsdp) release notes category labels Mar 28, 2024
awgu pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Mar 28, 2024
cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
awgu pushed a commit that referenced this pull request Apr 2, 2024
ghstack-source-id: ddae73d
Pull Request resolved: #122908
**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
awgu pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Apr 2, 2024
**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
awgu pushed a commit that referenced this pull request Apr 2, 2024
ghstack-source-id: 80e9d71
Pull Request resolved: #122908

def _init_extensions(self) -> None:
inner_tensor = self._sharded_local_tensor
has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Note: I am thinking to always check this via hasattr(inner_tensor, "fsdp_pre_all_gather") to leave a backdoor if somehow we can monkey patch this method onto the tensor without making it a subclass.

**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

cc mrshenli pritamdamania87 zhaojuanmao satgera rohan-varma gqchen aazzolini osalpekar jiayisuse H-Huang kwen2501 penguinwu fegin XilunWu wanchaol fduwjj wz337 tianyu-l wconstab yf225 chauhang

[ghstack-poisoned]
awgu pushed a commit that referenced this pull request Apr 4, 2024
ghstack-source-id: 6fdeffc
Pull Request resolved: #122908
awgu pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Apr 15, 2024
This PR requires pytorch/pytorch#122908.

This PR adds an option for FSDP fp8 all-gather with FSDP2, focusing on correctness first.
- We add a config option `enable_fsdp_fp8_all_gather: bool = False` in `float8_experimental.config` that can be set to `True` to enable the new behavior.
- We only support `Float8DynamicLinear` for now.
- For the fp8 all-gather, we make `Float8DynamicLinear.weight` to be a tensor subclass `Float8DynamicLinearWeightTensor`. This can be thought of as a `torch.Tensor` weight that knows how to cast itself to fp8. Since the cast logic is specific to dynamic scaling (i.e. it would not be the exact same for delayed scaling), I preferred to simply name the subclass `Float8DynamicLinearWeightTensor`.
- The subclass is a `__torch_dispatch__` wrapper subclass since that is the kind of subclass most compatible with `torch.compile`.
- The subclass defines `fsdp_pre_all_gather()` and `fsdp_post_all_gather()` to implement the fp8 all-gather.
- We include unit testing that covers eager-mode correctness and memory usage.


[ghstack-poisoned]
pytorchmergebot pushed a commit that referenced this pull request Apr 15, 2024
This PR adds a `mesh: DeviceMesh` argument to `fsdp_pre_all_gather()` so that the extension can know over which mesh the all-gather is happening. This can be useful in recovering the post-all-gather tensor size in the `fsdp_post_all_gather()` (e.g. for `NF4Tensor`).

Pull Request resolved: #123953
Approved by: https://github.com/Skylion007, https://github.com/wanchaol
ghstack dependencies: #119302, #122908
awgu pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Apr 16, 2024
…ling (subclass)"


This PR requires pytorch/pytorch#122908.

This PR adds an option for FSDP fp8 all-gather with FSDP2, focusing on correctness first.
- We add a config option `enable_fsdp_fp8_all_gather: bool = False` in `float8_experimental.config` that can be set to `True` to enable the new behavior.
- We only support `Float8DynamicLinear` for now.
- For the fp8 all-gather, we make `Float8DynamicLinear.weight` to be a tensor subclass `Float8DynamicLinearWeightTensor`. This can be thought of as a `torch.Tensor` weight that knows how to cast itself to fp8. Since the cast logic is specific to dynamic scaling (i.e. it would not be the exact same for delayed scaling), I preferred to simply name the subclass `Float8DynamicLinearWeightTensor`.
- The subclass is a `__torch_dispatch__` wrapper subclass since that is the kind of subclass most compatible with `torch.compile`.
- The subclass defines `fsdp_pre_all_gather()` and `fsdp_post_all_gather()` to implement the fp8 all-gather.
- We include unit testing that covers eager-mode correctness and memory usage.


[ghstack-poisoned]
awgu pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Apr 16, 2024
This PR requires pytorch/pytorch#122908.

This PR adds an option for FSDP fp8 all-gather with FSDP2, focusing on correctness first.
- We add a config option `enable_fsdp_fp8_all_gather: bool = False` in `float8_experimental.config` that can be set to `True` to enable the new behavior.
- We only support `Float8DynamicLinear` for now.
- For the fp8 all-gather, we make `Float8DynamicLinear.weight` to be a tensor subclass `Float8DynamicLinearWeightTensor`. This can be thought of as a `torch.Tensor` weight that knows how to cast itself to fp8. Since the cast logic is specific to dynamic scaling (i.e. it would not be the exact same for delayed scaling), I preferred to simply name the subclass `Float8DynamicLinearWeightTensor`.
- The subclass is a `__torch_dispatch__` wrapper subclass since that is the kind of subclass most compatible with `torch.compile`.
- The subclass defines `fsdp_pre_all_gather()` and `fsdp_post_all_gather()` to implement the fp8 all-gather.
- We include unit testing that covers eager-mode correctness and memory usage.


[ghstack-poisoned]
facebook-github-bot pushed a commit to meta-pytorch/float8_experimental that referenced this pull request Apr 16, 2024
Summary:
Pull Request resolved: #247

This PR requires pytorch/pytorch#122908.

This PR adds an option for FSDP fp8 all-gather with FSDP2, focusing on correctness first.
- We add a config option `enable_fsdp_fp8_all_gather: bool = False` in `float8_experimental.config` that can be set to `True` to enable the new behavior.
- We only support `Float8DynamicLinear` for now.
- For the fp8 all-gather, we make `Float8DynamicLinear.weight` to be a tensor subclass `Float8DynamicLinearWeightTensor`. This can be thought of as a `torch.Tensor` weight that knows how to cast itself to fp8. Since the cast logic is specific to dynamic scaling (i.e. it would not be the exact same for delayed scaling), I preferred to simply name the subclass `Float8DynamicLinearWeightTensor`.
- The subclass is a `__torch_dispatch__` wrapper subclass since that is the kind of subclass most compatible with `torch.compile`.
- The subclass defines `fsdp_pre_all_gather()` and `fsdp_post_all_gather()` to implement the fp8 all-gather.
- We include unit testing that covers eager-mode correctness and memory usage.

imported-using-ghimport

Test Plan: Imported from OSS

Reviewed By: vkuzo

Differential Revision: D56192107

Pulled By: awgu

fbshipit-source-id: b9e36fde0e39ca59658ddef86932a0b1ed2ca461
sanketpurandare pushed a commit to sanketpurandare/pytorch that referenced this pull request Apr 22, 2024
**Overview**
This PR adds pre/post-all-gather extensions to FSDP2.
- The pre/post-all-gather extensions are specified at the tensor-level on the `sharded_param._local_tensor` (i.e. the tensor wrapped by the sharded `DTensor`). If the user has a tensor-subclass parameter on the module passed to FSDP that preserves the subclass through the sharding ops (e.g. `new_zeros`, `chunk`, etc.), then the `sharded_param._local_tensor` will naturally be of that subclass.
- The pre-all-gather function has signature:
  ```
  def fsdp_pre_all_gather(self) -> Tuple[Tuple[torch.Tensor, ...], Any]
  ```
    - The first return value is a `Tuple[torch.Tensor, ...]` of the all-gather inputs. It is a tuple since a subclass could contribute >1 inner tensors.
    - The second return value is any optional metadata needed to pass through to the post-all-gather.
- The post all-gather function has signature:
  ```
  def fsdp_post_all_gather(
      self,
      all_gather_outputs: Tuple[torch.Tensor, ...],
      metadata: Any,
      param_dtype: torch.dtype,
      *,
      out: Optional[torch.Tensor] = None,
  ) -> Union[Tuple[torch.Tensor, Tuple[torch.Tensor, ...]], None]:
  ```
    - The `all_gather_outputs` are exactly the all-gathered versions of the `fsdp_pre_all_gather` 1st return value (representing the all-gather inputs). We make sure to unflatten these back to ND for the user.
    - The `metadata` is the `fsdp_pre_all_gather` 2nd return value, untouched.
    - The `param_dtype` is the parameter dtype based on the passed-in `MixedPrecisionPolicy`. Namely, if no policy is passed in, then `param_dtype` is the original dtype, and otherwise, it is the `MixedPrecisionPolicy.param_dtype`.
    - If `out` is not specified, then the return value has type `Tuple[torch.Tensor, Tuple[torch.Tensor, ...]]`. The first tuple item is the unsharded parameter (e.g. re-wrapping into some subclass). The second tuple item is a tuple of unsharded inner tensors that FSDP should free during reshard. These should be derived from the all-gather outputs.
    - The `out` argument is required due to FSDP's `resize_` usage. We require an in-place variant for the backward all-gather. Here, `out` will be exactly the object returned as the first tuple item in the out-of-place variant mentioned before. The unsharded inner tensors will be allocated before calling `fsdp_post_all_gather`. When `out` is specified, the `fsdp_post_all_gather` should return `None`. If the post-all-gather does not do any out-of-place ops, then the `out` variant can just be a no-op since the unsharded inner tensors will be the same as the all-gather outputs, which FSDP directly writes to after all-gather. (E.g., this is the case for both float8 and `NF4Tensor`.)
- We check for `fsdp_pre_all_gather` and `fsdp_post_all_gather` directly via `hasattr` to accommodate monkey patching so that we do not strictly require the user to use a tensor subclass. The monkey patch must happen after the local tensors have been finalized (after applying FSDP and after any meta-device init).
- For now, we require that all gradients in one FSDP parameter group share the same dtype. This is fine for float8 and `NF4Tensor` use cases. If this requirement is too strict, then in the future we can issue 1 reduce-scatter per dtype per group.

**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

Pull Request resolved: pytorch#122908
Approved by: https://github.com/weifengpy, https://github.com/wanchaol
ghstack dependencies: pytorch#119302
sanketpurandare pushed a commit to sanketpurandare/pytorch that referenced this pull request Apr 22, 2024
This PR adds a `mesh: DeviceMesh` argument to `fsdp_pre_all_gather()` so that the extension can know over which mesh the all-gather is happening. This can be useful in recovering the post-all-gather tensor size in the `fsdp_post_all_gather()` (e.g. for `NF4Tensor`).

Pull Request resolved: pytorch#123953
Approved by: https://github.com/Skylion007, https://github.com/wanchaol
ghstack dependencies: pytorch#119302, pytorch#122908
petrex pushed a commit to petrex/pytorch that referenced this pull request May 3, 2024
**Overview**
This PR adds pre/post-all-gather extensions to FSDP2.
- The pre/post-all-gather extensions are specified at the tensor-level on the `sharded_param._local_tensor` (i.e. the tensor wrapped by the sharded `DTensor`). If the user has a tensor-subclass parameter on the module passed to FSDP that preserves the subclass through the sharding ops (e.g. `new_zeros`, `chunk`, etc.), then the `sharded_param._local_tensor` will naturally be of that subclass.
- The pre-all-gather function has signature:
  ```
  def fsdp_pre_all_gather(self) -> Tuple[Tuple[torch.Tensor, ...], Any]
  ```
    - The first return value is a `Tuple[torch.Tensor, ...]` of the all-gather inputs. It is a tuple since a subclass could contribute >1 inner tensors.
    - The second return value is any optional metadata needed to pass through to the post-all-gather.
- The post all-gather function has signature:
  ```
  def fsdp_post_all_gather(
      self,
      all_gather_outputs: Tuple[torch.Tensor, ...],
      metadata: Any,
      param_dtype: torch.dtype,
      *,
      out: Optional[torch.Tensor] = None,
  ) -> Union[Tuple[torch.Tensor, Tuple[torch.Tensor, ...]], None]:
  ```
    - The `all_gather_outputs` are exactly the all-gathered versions of the `fsdp_pre_all_gather` 1st return value (representing the all-gather inputs). We make sure to unflatten these back to ND for the user.
    - The `metadata` is the `fsdp_pre_all_gather` 2nd return value, untouched.
    - The `param_dtype` is the parameter dtype based on the passed-in `MixedPrecisionPolicy`. Namely, if no policy is passed in, then `param_dtype` is the original dtype, and otherwise, it is the `MixedPrecisionPolicy.param_dtype`.
    - If `out` is not specified, then the return value has type `Tuple[torch.Tensor, Tuple[torch.Tensor, ...]]`. The first tuple item is the unsharded parameter (e.g. re-wrapping into some subclass). The second tuple item is a tuple of unsharded inner tensors that FSDP should free during reshard. These should be derived from the all-gather outputs.
    - The `out` argument is required due to FSDP's `resize_` usage. We require an in-place variant for the backward all-gather. Here, `out` will be exactly the object returned as the first tuple item in the out-of-place variant mentioned before. The unsharded inner tensors will be allocated before calling `fsdp_post_all_gather`. When `out` is specified, the `fsdp_post_all_gather` should return `None`. If the post-all-gather does not do any out-of-place ops, then the `out` variant can just be a no-op since the unsharded inner tensors will be the same as the all-gather outputs, which FSDP directly writes to after all-gather. (E.g., this is the case for both float8 and `NF4Tensor`.)
- We check for `fsdp_pre_all_gather` and `fsdp_post_all_gather` directly via `hasattr` to accommodate monkey patching so that we do not strictly require the user to use a tensor subclass. The monkey patch must happen after the local tensors have been finalized (after applying FSDP and after any meta-device init).
- For now, we require that all gradients in one FSDP parameter group share the same dtype. This is fine for float8 and `NF4Tensor` use cases. If this requirement is too strict, then in the future we can issue 1 reduce-scatter per dtype per group.

**Design Notes**
- We assume that the `sharded_param._local_tensor` is padded on dim-0.
    - This assumption should not block immediate use cases, and when we pad the `DTensor._local_tensor` by default, this assumption will always be true.
    - This assumption allows us to call `sharded_param._local_tensor.fsdp_pre_all_gather()`; i.e. it tells us from which tensor object to invoke `fsdp_pre_all_gather()`.
    - Suppose we want to compose with CPU offloading. Then, CPU offloading's H2D copy should run first, i.e. `sharded_param._local_tensor.to("cuda").fsdp_pre_all_gather()`, where `_local_tensor.to("cuda")` should return an instance of the subclass so that it still defines `fsdp_pre_all_gather()`. Note that in this case, the subclass instance on GPU is a temporary, which means caching values on it would not be possible. One possibility would be to have `.to("cuda")` move any cached values too.
- `fsdp_post_all_gather` can either return an unsharded parameter that aliases with the all-gather output or does not alias, but there is no way to know a priori.
    - If the unsharded parameter aliases with the all-gather output, then we should _not_ free the all-gather output in `unshard`.
    - If the unsharded parameter does not alias with the all-gather output, then we prefer to free the all-gather output in `unshard` to avoid holding the unneeded temporary.
    - One approach is for eager-mode to check for this alias (by comparing data pointers). However, this might be adversarial to full-graph compilation. The compromise for simplicity can be to always free the all-gather output in `reshard`.

Pull Request resolved: pytorch#122908
Approved by: https://github.com/weifengpy, https://github.com/wanchaol
ghstack dependencies: pytorch#119302
petrex pushed a commit to petrex/pytorch that referenced this pull request May 3, 2024
This PR adds a `mesh: DeviceMesh` argument to `fsdp_pre_all_gather()` so that the extension can know over which mesh the all-gather is happening. This can be useful in recovering the post-all-gather tensor size in the `fsdp_post_all_gather()` (e.g. for `NF4Tensor`).

Pull Request resolved: pytorch#123953
Approved by: https://github.com/Skylion007, https://github.com/wanchaol
ghstack dependencies: pytorch#119302, pytorch#122908
@github-actions
github-actions Bot deleted the gh/awgu/550/head branch May 16, 2024 01:57
weifengpy added a commit that referenced this pull request Oct 5, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: e936be0
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 5, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: e936be0
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 5, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: e936be0
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 5, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: e936be0
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 6, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: 6d1d15e
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 6, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: 6d1d15e
Pull-Request: #197204
weifengpy added a commit that referenced this pull request Oct 6, 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. For the all-gather, every parameter records a layout per payload (its gathered shape, and the product of the dims before the dim that ranks are concatenated along). `foreach_all_gather` carries those outer sizes in `AllGatherResult`, and `foreach_all_gather_copy_out` allocates the outputs and then calls an `AllGatherOutputFn` with plain tensors and sizes. For the reduce-scatter, `foreach_reduce` sizes the buffer from the padded sharded parameter sizes and calls a `PrepareReduceScatterInputsFn` that returns the copy-in to run once the buffer is allocated. Both contracts are documented on their type aliases. The default callbacks keep the original split, rank reassembly, and chunk-cat copies. Because a post-forward shard is a flat chunk of the unsharded data, its layout copies it directly, which also fixes the `IndexError` that resharding Shard(i>0) parameters to a smaller post-forward mesh (`reshard_after_forward=int`) has raised in the pre-backward all-gather since #137496. Copying every payload in the single-rank path and giving each payload an explicit gathered shape also fix two older extension bugs: a size-1 shard mesh copied only the first payload (since #160135), and a payload with a zero-size trailing dim failed in `view(-1, 0)` (since #122908).
>
> `fsdp_pre_all_gather` may return `AllGatherInput` records that declare each payload's concatenation dim and gathered shape, independent of the parameter's shard dim. Their element counts and dtypes must stay fixed across calls so FSDP can reuse their outputs, and FSDP checks this before the collective. Tensor-only hooks keep their behavior, including payloads smaller than their cached outputs: the default copy now writes those into a prefix view instead of relying on the deprecated out= resize, and reassembles them from a zero-filled buffer instead of an uninitialized one. A changed payload count, a payload larger than its cached output, or a payload dtype change other than to bytes now raises `ValueError` before the collective rather than failing inside the copy.
>
> Test Plan:
> ```bash
> python test/distributed/_composable/fsdp/test_fully_shard_comm.py
> python test/distributed/_composable/fsdp/test_fully_shard_extensions.py
> python test/distributed/_composable/fsdp/test_fully_shard_memory.py
> python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py
> python test/distributed/_composable/fsdp/test_fully_shard_training.py
> ```
> Results pending.

ghstack-source-id: 99d6fd1
Pull-Request: #197204
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged oncall: distributed Add this issue/PR to distributed oncall triage queue release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants