Skip to content

[FSDP2] Add experimental native collective copy opt-in - #197701

Closed
weifengpy wants to merge 81 commits into
gh/weifengpy/192/basefrom
gh/weifengpy/192/head
Closed

weifengpy wants to merge 81 commits into
gh/weifengpy/192/basefrom
gh/weifengpy/192/head

Conversation

@weifengpy

@weifengpy weifengpy commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

BC-breaking?

No: adds an experimental setter and module; FSDP's default copies are unchanged.

Summary (human written only)

better perf for Shard(1)/Shard(2) to unblock torchtitan EFSDP sharding

Agent details (if applicable)

AI-assisted implementation and summary prepared with Codex and Claude Code.

Add an FSDPModule.set_reduce_scatter_input_fn setter, and call the native all-gather copy-out (fsdp::_all_gather_copy_out_, #197204) and reduce-scatter copy-in (fsdp::chunk_cat_mixed_dtype with num_leading_dims, #200179) through torch.distributed.fsdp.experimental, which exports AllGatherInput, all_gather_output_fn_with_native_copy and reduce_scatter_input_fn_with_native_copy. The original intermediate copies remain the defaults. The all-gather copy-out has no setter here: #199726 installs it through set_all_gather_layout as DefaultAllGatherLayout(all_gather_output_fn_with_native_copy); until then, the tests here install it through the private FSDPParamGroup._all_gather_output_fn hook.

The all-gather op copies within one dtype, so its callback copies mixed-dtype groups as bytes, and it requires exact output sizes, so the callback uses the default copy-out for groups with a Tensor payload smaller than its cached output. The reduce-scatter copy-in takes mixed gradient dtypes, such as a deferred bf16 Shard(1) weight gradient next to an fp32 norm gradient, so it needs no dtype fallback; noncontiguous gradients sharded on a nonzero dim still use the chunk-and-concatenate reorder.

Native copying writes contiguous tensors without intermediate buffers and benefits wide CUDA tensors with small outer_size, such as Shard(1) over [2,F,D]. Its CPU time, GPU time and metadata memory grow with a group's total outer size, and strided collective buffers take a slower path, so the documentation recommends benchmarking the target workload.

Test Plan:

python test/distributed/_composable/fsdp/test_fully_shard_comm.py -k test_strided_allocation -k test_reduce_scatter_input_fn_setter -k TestFullyShardNativeReduceScatterInputFn
python test/distributed/_composable/fsdp/test_fully_shard_extensions.py -k test_all_gather_input_layouts -k test_all_gather_extension_smaller_payload
python test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py -k test_reduce_dtype -k test_native_copy_in_mixed_grad_dtypes
python test/distributed/_composable/fsdp/test_fully_shard_training.py -k test_train_parity_single_group -k test_inference
python test/test_public_bindings.py -k test_correct_module_names

All pass on this revision. test_native_copy_in_mixed_grad_dtypes fails if the callback falls back to the default copy-in for mixed gradient dtypes, test_strided_allocation if a copy reorders its input, test_reduce_scatter_input_fn_setter if the setter ignores recurse or None, test_all_gather_input_layouts if the native all-gather copy falls back to the default one, and test_all_gather_extension_smaller_payload if it has no fallback for smaller payloads.

Measured on one B200 with world-size-8 layouts (copies only, native time / default time): a [2, 8192, 4096] Shard(1) group copies out in 0.53x GPU and 0.41x CPU time and copies in in 0.38 to 0.45x GPU and 0.67 to 0.70x CPU time; Shard(1) experts [2/8, 1408, 2048] x3 copy out in 0.36 to 0.51x GPU time; native copies of contiguous tensors also skip the intermediate buffers, lowering a Shard(1)/Shard(2) group's peak memory by about 24 to 830 MB. Groups with many rows before the shard dim are slower: Shard(2) experts copy out in 1.7 to 1.8x GPU time and up to 5.6x CPU time, and a Llama-8B block's Shard(1) parameters (outer size 43010) copy out in 0.74 to 0.78x GPU but 3.2 to 4.4x CPU time, which is why the documentation recommends benchmarking.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Sep 19, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 Cancelled Job, 1 Unrelated Failure

As of commit 6198779 with merge base 0e73fc6 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Public API addition
    • Adds public FSDPModule.set_reduce_scatter_input_fn in torch/distributed/fsdp/_fully_shard/_fully_shard.py, a design a reviewer should weigh
    • New public module torch/distributed/fsdp/experimental/__init__.py exports three APIs and rewrites AllGatherInput.__module__
  • No trivial class fits
    • New production logic in reduce_scatter_input_fn_with_native_copy and all_gather_output_fn_with_native_copy (contiguity and size fallbacks) is a feature, not a bugfix or refactor
    • Docs hunk in docs/source/distributed.fsdp.fully_shard.md documents the new surface rather than existing code
  • Scope
    • Touches 4 FSDP test files plus production code and docs; the opt-in performance tradeoffs need a human reviewer's call

reason: not_trivial
Reviewed commit: 6198779

Inference job

🐛 Report a wrong verdict

CANCELLED JOB - The following job was cancelled. Please retry:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

Comment thread aten/src/ATen/native/TensorShape.cpp Outdated
int64_t num_chunks) {
check_split_with_sizes_copy_with_prefixes_inputs(
self, split_sizes, num_prefixes, num_chunks, out);
std::vector<int64_t> sizes;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

These can have reserve called on them

srcs.reserve(num_inputs);
// block_idx_to_tensor_idx cannot be reserved since the number of blocks is
// data dependent
std::vector<int64_t> block_idx_to_tensor_idx;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could also have reserve called on this actually

actual_tensor_sizes.reserve(num_tensors);
tensor_idx_to_start_tensor_bytes.reserve(num_tensors + 1);
srcs.reserve(num_tensors);
pad_tensor_chunk_sizes.reserve(num_inputs);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Are these correct reserve calls now or is it num_tensors * num_prefixes?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks for review - this is still ai sloppy so far. I updating PR with a more localized change

[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 19, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: bdf2f29
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 19, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: a6d0102
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 19, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 941b2d3
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 19, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 1319812
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 19, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 442d371
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 1b089d3
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 77446fa
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 1ff87f2
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 57b959f
Pull-Request: #197701
weifengpy added a commit that referenced this pull request Sep 20, 2026
draf the change as a peer PR to HEAD, so i can compare alternatives side by side

> AI-assisted implementation and description prepared with Codex. This is an alternative to #197701 on the same parent, #197204.
>
> The opt-in Shard(1+) copy callbacks can spend more CPU time creating Tensor views than submitting the copy. Extend the existing ATen `split_with_sizes_copy` and `_chunk_cat` families with `.prefix_out` overloads accepting the original tensors and concrete layout metadata. Native CUDA implementations prepare raw descriptors and launch the existing kernels.
>
> `split_with_sizes_copy.prefix_out` treats its input as `num_chunks` flat rows. `split_sizes` partitions each row, and `num_prefixes[i]` divides an output into contiguous regions collecting the corresponding pieces from all rows. With uint8 input, split sizes count bytes and output dtypes may differ. `_chunk_cat.prefix_out` uses each input's `num_leading_dims` as its shard dimension and packs its prefixes into output rows. Nonzero shard dimensions require even division; dimension zero retains the existing padding behavior.
>
> Descriptor preparation, validation, and fallback implementations now live in ATen. The separate FSDP prefix-copy operators and C++ files are removed, with no build-list changes relative to the parent. `ReduceScatterInput` and the opt-in callbacks remain; the default FSDP copy operator and existing ATen overloads retain their behavior. Review the native schemas and common validation first, the CUDA descriptor path next, then the FSDP call sites and tests.
>
> `CompositeImplicitAutograd` provides the common decomposition for other backends and FakeTensor/compiler tracing. Two explicit Functionalize registrations use that same decomposition. Two exact Python-binding exclusions leave these caller-allocated operations accessible through `torch.ops.aten` without generating top-level Python bindings that require matching allocating variants. The new overloads also enforce out-operation autograd and version/inference rules.
>
> On B200, using 224 MiB BF16 [N, F, D] inputs, Shard(1), eight shards, and FP32 reduce-scatter output, graph GPU medians differed by at most 0.31% from the previous #197784 implementation (`d307e02db7b2`) across two candidate runs. Each phase used one CUDA kernel and one metadata H2D copy; peak and retained CUDA allocations and view counts matched exactly. Eager times in microseconds were:
>
> | N | AG: previous #197784 | AG: native runs | RS: previous #197784 | RS: native runs |
> | ---: | ---: | ---: | ---: | ---: |
> | 2 | 102.12 | 101.99 / 102.34 | 349.77 | 348.46 / 348.57 |
> | 128 | 103.65 | 102.46 / 101.76 | 353.69 | 355.58 / 360.09 |
> | 8192 | 264.17 | 281.62 / 265.32 | 625.00 | 619.67 / 616.97 |
>
> N=2 and N=128 eager timings stayed within 2%; host submission was lower in both candidate runs. N=8192 all-gather eager time increased 6.61% in the first run and 0.44% on repeat, with host time 196.82 / 176.10 us versus 182.90 us. Exact CPU parity is not established. These separate-build measurements include submission/backpressure but exclude NCCL and model work. The baseline above is the prior #197784 implementation. Earlier #197701 measurements remain historical context: N=8192 AG/RS eager times were 244.04/594.08 us, so these results do not establish equal CPU performance with #197701 either.
>
> Test Plan:
>
> The CUDA 13 / SM100 editable build, `lintrunner -a`, and `git diff --check` passed. The regression suites ran 272 cases: 265 passed and seven expected skips. Coverage includes CPU/CUDA copies, mixed dtypes, noncontiguous fallback, device/stream handling, CUDA graphs, autograd and inference semantics, Functionalize, FakeTensor, fullgraph aot_eager compilation, and FSDP training parity. Both benchmark runs passed all three exact correctness cases.
>
> ```bash
> bash agent_space/fsdp_aten_overloads/build.sh
> CUDA_VISIBLE_DEVICES=4,6 python test/test_shape_ops.py TestPrefixCopyCPU TestPrefixCopyCUDA -v
> CUDA_VISIBLE_DEVICES=7 python agent_space/fsdp_aten_overloads/dispatch_smoke.py -v
> CUDA_VISIBLE_DEVICES=5 python test/distributed/_composable/fsdp/test_fully_shard_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> CUDA_VISIBLE_DEVICES=3 python test/test_ops.py TestCommonCUDA -k _chunk_cat -v
> CUDA_VISIBLE_DEVICES=1 python test/test_torch.py TestTorch.test_split_with_sizes_copy_out -v
> CUDA_VISIBLE_DEVICES=5 FSDP_BENCH_LABEL=candidate python agent_space/fsdp_aten_overloads/benchmark.py TestATenOverloadsCUDA -v
> CUDA_VISIBLE_DEVICES=5 FSDP_BENCH_LABEL=candidate_repeat python agent_space/fsdp_aten_overloads/benchmark.py TestATenOverloadsCUDA -v
> lintrunner -a
> git diff --check
> ```
>
> The build script invokes `pip install -e . -v --no-build-isolation` with the saved local CUDA configuration. Scripts under `agent_space/` are local validation artifacts and are not committed. ROCm and Windows builds were not run locally.

ghstack-source-id: 0ae74e7
Pull-Request: #197784
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: af1e1a1
Pull-Request: #197701
[ghstack-poisoned]
weifengpy added a commit that referenced this pull request Sep 20, 2026
what if we do view and metadata manipulation at cpp level ?

> AI-assisted implementation and summary prepared with Codex. The question above is the author's request motivating this follow-up to #197204.
>
> The opt-in nonzero-dimension shard callbacks create one Python Tensor view per contiguous prefix. For Shard(1) over [N, F, D], that CPU work can outweigh the faster GPU copies: at N=128, the Python-view path takes 334 us for eager all-gather copy-out, versus 181 us for the default reorder path.
>
> Pass the original tensors and prefix metadata to private native operators instead. CUDA builds pointer/size descriptors directly and reuses the existing copy kernels. Reduce-scatter accepts an internal preparation result without expanding gradients into Python views; custom callbacks returning padded sizes remain supported. Preserve version counters, dtype conversion, padding, and composite fallbacks.
>
> On B200 with 224 MiB BF16 input, eight shards, and FP32 reduction, N=128 eager all-gather falls from 334 to 104 us. N=2 remains about 104 us. CUDA kernel counts and temporary allocation peaks match the Python-view path. Keep opt-in: at N=8192, native all-gather takes 302 us versus 264 us for the default path, although it improves on Python views' 17.74 ms.
>
> Test Plan:
> ```bash
> CUDA_VISIBLE_DEVICES=5 python test/test_prefix_copy.py -v
> CUDA_VISIBLE_DEVICES=0,2 python test/distributed/_composable/fsdp/test_fully_shard_training.py \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_dim0 \
>   TestFullyShard1DTrainingCore.test_train_parity_single_group_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiProcess.test_train_parity_shard_placement_fn_shard_largest_dim \
>   TestFullyShardShardPlacementFnMultiThread.test_shard_placement_fn_contiguous_params_grads -v
> lintrunner -a
> git diff --check
> ```
> Passed 184 native CPU/CUDA cases (2 expected skips) and all four FSDP training tests. Coverage includes mixed shard dimensions/dtypes, noncontiguous fallback, inference/version counters, functionalization, and CUDA graph replay. A separate two-rank [2,14336,4096] W13 forward/backward run preserved exact loss and gradients and improved about 10% versus the default copy path.

ghstack-source-id: 8ff2380
Pull-Request: #197701
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

@anshul-si anshul-si left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15)

Details for Dev Infra team

Raised by workflow job

@weifengpy

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp2) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants