Skip to content

[FSDP][AMD] Sharded Relay for All Reduce/Reduce Scatter (#203312) - #203312

Closed
kausv wants to merge 1 commit into
pytorch:mainfrom
kausv:export-D125970002
Closed

kausv wants to merge 1 commit into
pytorch:mainfrom
kausv:export-D125970002

Conversation

@kausv

@kausv kausv commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
X-link: meta-pytorch/torchrec#5008

AMD XGMI links has no switches. AllReduce/ReduceScatter takes longer with the reduced b/w.
Relay sharding was implemented for TorchRec DMP in meta-pytorch/torchrec#4207

Add AllReduce(Comm) and DefaultAllReduce(DefaultAllocMixin, AllReduce) alongside the existing all-gather and reduce-scatter interfaces. Each FSDP parameter group starts with a concrete default all-reduce primitive and invokes it unconditionally by keyword. FSDPModule.set_custom_all_reduce overrides HSDP or replicate_with_fsdp gradient replication; passing None restores the default. FSDP retains gradient scaling, accumulation, stream dependencies, and buffer lifetime management, and the existing post-all-reduce hook still runs after the replacement collective.

Add TorchRec sharded relay adapters for all-reduce and reduce-scatter on AMD GPUs. They use the native multi-group relay backend shared with distributed model parallelism, validate group order and tensor metadata, and require all communicator ranks to follow the same bucket sequence. Synchronous SUM and AVG use relay; asynchronous calls and other reduction operations retain the process-group implementation and its native Work handle.

Add a four- or eight-GPU AMD benchmark comparing standard collectives with relay for FSDP and HSDP, including graph replay and gradient/optimizer parity. Large payloads can benefit from helper GPUs, while shard reduce-scatter and replica all-reduce need independent routing decisions based on their tensor sizes. No automatic routing threshold is introduced.

Update SimpleFSDP to explicitly reject the new custom all-reduce API, consistent with its other unsupported custom collectives, and recognize the method in its API override guard so existing SimpleFSDP consumers remain importable.

Add a mocked HSDP all-reduce regression test covering the callback set/unset paths, SUM/AVG forwarding, post-all-reduce hook ordering, and averaged gradient correctness. Align the FSDP import formatting with the upstream Python formatter.

Test Plan:
Commands were run locally from fbcode/ on devgpu288.prn2.facebook.com with eight AMD Instinct MI300X GPUs (gfx942). GPU builds and tests used fbcode//mode/opt-amd-gpu -m rocm70. Remote test execution was disabled. The relay benchmark attempt exposed four local GPUs. The test suite ran on source revision 06b20473fcf1; benchmark builds and scheduling checks include the subsequent four-GPU update. The fetched remote version has identical source to that starting revision.

Local AMD tests

HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 buck2 test fbcode//mode/opt-amd-gpu -m rocm70 -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm fbcode//caffe2/torch/distributed/fb/simple_fsdp/tests:simple_fsdp_test fbcode//apf/utils/torchdynamo/tests:torch_dynamo_utils_test

Pass 199, Fail 1, Fatal 0, Skip 2. https://www.internalfb.com/intern/testinfra/testrun/2251800226899398

TestFullyShardSymmMem.test_fully_shard_symm_mem_sum_reduction_False fails in the symmetric-memory all-gather path with RuntimeError: NCCL host communicator for group 0 not found. This test requires NCCL 2.28+ CE collectives and is not exercising the relay adapters or custom all-reduce. The _True variant is skipped after the failure; TestFullyShardAllocFromPG.test_fully_shard_alloc_from_pg is also skipped. The remaining FSDP collective tests, SimpleFSDP tests, and downstream SimpleFSDP API-guard import tests passed. This run is not fully green.

AMD builds and type checking

buck2 build fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking

Build succeeded for all three targets. https://www.internalfb.com/buck2/eaa8126c-01e4-40ba-8196-fafd9d9ce150

Four- and eight-GPU benchmark scheduling

Executed the benchmark's _collectives, _training, and main control flow with mocked collective/model calls and process spawning for both supported GPU counts. Four GPUs schedule 10 collective cases (two groups of two) and 2 training cases (FSDP/HSDP on a (2, 2) mesh). Eight GPUs retain 20 collective cases (groups of two and four) and 4 training cases ((4, 2) and (2, 4) meshes). Verified group partitions, availability of helper groups, and matching process-spawn/world-size arguments. Both scheduling checks passed; these checks do not establish native relay correctness or performance.

Lint

arc lint --only-changed --never-apply-patches --rev .^ passed for the commit. Fast lint and arc lint --only-changed --engine extra --take CITRINEAGENT passed on the relay adapter, benchmark, and both SimpleFSDP files; the benchmark was checked again after the four-GPU update. arc f also passed on the benchmark.

Before/after performance (historical AMD measurements)

These are the recorded 2026-10-18 measurements on devgpu288 with eight AMD GPUs, recovered from the earlier D125970002 commit's test plan. They are not fresh results from the current revision, the four-GPU benchmark update, or the queued MI350 test. The original raw JSON reports are no longer available on this host.

BF16 default sweep: dimension 1024, five warmups, 20 samples. Timings are median GPU-event microseconds after taking the maximum across all ranks per sample. Before uses standard RCCL; After uses sharded relay. The latency reduction is (before - after) / before; speedup is before / after.

Active ranks per group Collective input tensor shape (BF16) Collective Before (us) After (us) Speedup Latency reduction
2 (37,748,736,) All-reduce 1689.5 625.9 2.70x 63.0%
2 (37,748,736,) Reduce-scatter 967.4 371.5 2.60x 61.6%
2 (75,497,472,) All-reduce 3296.9 1155.1 2.85x 65.0%
2 (75,497,472,) Reduce-scatter 1867.5 653.3 2.86x 65.0%
4 (75,497,472,) All-reduce 1742.6 1102.1 1.58x 36.8%
4 (75,497,472,) Reduce-scatter 1040.4 847.1 1.23x 18.6%

Tensor sizes are element counts, not bytes. The flat input lengths above are the recorded BF16 payload sizes divided by two bytes per element. For reduce-scatter, the output length is the input length divided by the active group size. _collective_case creates the flat source, calculates these counts, and times both routes; _models configures the training buckets. Source: https://www.internalfb.com/code/fbsource/fbcode/torchrec/distributed/tests/bench_fsdp_sharded_relay.py . The source permits manual verification of the tensor shapes and timing method; the historical raw timing reports remain unavailable as stated above.

Historical dimension-1024 FSDP/HSDP forward/backward results used BF16 (1,048,576,) full-gradient input buckets (the flattened (1024, 1024) weight gradients). Only before/after ratios were recorded for these training cases; absolute step timings are unavailable:

Training case (replicate, shard) mesh Before / after
Independent FSDP groups, two-rank shards (4, 2) 0.97x
Independent FSDP groups, four-rank shards (2, 4) 0.84x
HSDP (4, 2) 1.01x
HSDP (2, 4) 1.02x

Ratios above 1 favor relay; below 1 favor standard RCCL. The historical results show a collective speedup for the large payloads above, but no consistent end-to-end forward/backward improvement for the small model buckets. No exact routing threshold or current-revision performance improvement is established.

Relay execution blocked by missing native backend

Attempted the built benchmark locally with four AMD GPUs:

HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json

The binary accepts four visible GPUs, then exits at the is_backend_built("rcclx") prerequisite check. https://www.internalfb.com/buck2/9d4d92e4-fc96-4406-9096-51574f8c698d

Attempted again with the native backend enabled:

HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 -m rcclx_dev -c fsdp_relay.native_backend=true fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json

Build analysis fails because fbcode//comms/torchcomms/rcclx:_comms_rcclx and its package are absent at this revision. https://www.internalfb.com/buck2/de6c9c51-0823-45ab-a0c0-33cfaa877e0c

No relay timings, graph replay results, or FSDP/HSDP relay gradient/optimizer parity results were produced. Once the native backend is available, the command above covers the four-GPU cases; expose 0,1,2,3,4,5,6,7 for the eight-GPU cases. Native four-GPU support remains to be verified.

2026-11-04: custom all-reduce callback regression and upstream lint repair

Added TestFullyShardCustomAllReduce.test_custom_all_reduce in both mirrored test_fully_shard_comm.py files. The CPU threaded (replicate, shard) = (2, 2) HSDP test runs with the custom callback set and unset, and with SUM forced or AVG selected normally. A MagicMock delegates to the real collective and verifies one callback per backward, the exact replica process group and reduction operation, the same gradient buffer reaching the post-all-reduce hook, and callback-before-hook ordering. Rank-specific inputs yield the expected averaged full gradient in all cases.

buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Verify custom callback and default HSDP reductions for SUM and AVG with matching gradient results' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu

Passed: 2 reported results, zero failures/fatals/skips; the callback test covers all four set/unset and SUM/AVG combinations. Test evidence: https://www.internalfb.com/intern/testinfra/testrun/21955048248994055 ; build evidence: https://www.internalfb.com/buck2/dc64ce31-8437-40e1-a4fe-2e927799b2af

The failed GitHub job was lintrunner-noclang-partial / lint: https://github.com/pytorch/pytorch/actions/runs/41864084487/job/126693888230 . Reproduced an upstream formatting mismatch in the _fully_shard.py import block and applied the upstream layout in both mirrors. Ruff 0.14.4 (the configured version) checks and formatting pass on all three changed FSDP implementation files and the communication test. The PYFMT adapter emitted no findings locally with isort 6.0.1 and usort 1.0.8.post1; the configured usort 1.1.3 package was unavailable from this host's package index, so this is not a full reproduction of the pinned GitHub environment.

arc lint -a --only-changed --rev .^ and arc f pass. Citrine was invoked on the changed files; no Citrine linters are configured for these paths. The owning FSDP library targets have type checking disabled, so the owning-target Pyrefly command performed no type checking.

The existing GitHub export check additionally requires an approving review on PR #203312; that is a review gate and is not addressed by changing tests or formatting.

2026-11-09: AllReduce interface and PR review fixes

TestFullyShardCustomAllReduce now wraps DefaultAllReduce in a MagicMock, proving that set_custom_all_reduce invokes it exactly once, passes the replica group and SUM/AVG by keyword, and runs the hook afterward on the same tensor. Coverage includes native and custom HSDP, FP16 reduction, forced SUM, a custom divide factor, replicate_with_fsdp, accumulation while all-reduce is disabled, and restoration with None. TestFullyShardCustomAllReduceErrors verifies empty/multiple/non-replication group errors and native Work handle forwarding by DefaultAllReduce.

buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Recheck callback mocks against final keyword invocation and default restoration' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu

Passed: 7 results, zero failures/fatals/skips. https://www.internalfb.com/intern/testinfra/testrun/30399297539428018 ; build: https://www.internalfb.com/buck2/13702631-46a2-4a5b-a1eb-a653988dda43

The following tests ran locally on devgpu155.prn5.facebook.com, with four visible AMD gfx950 GPUs, the AMD optimized build, and ROCm 7.0. These validate FSDP communication and lifetime correctness; they do not rerun the native RCCLX relay benchmark.

buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify custom and native HSDP all-reduce buffer lifetime with mixed precision on four local AMD GPUs' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_memory -- test_ar_buffer_lifetime_mixed_dtype --env HIP_VISIBLE_DEVICES=0,1,2,3

Passed: 2 reported results, zero failures/fatals/skips. The lifetime guard covers BF16/FP16 and native/custom all-reduce subtests, including three delayed custom calls per backward and three repeated slow runs per configuration. https://www.internalfb.com/intern/testinfra/testrun/18295873553729716 ; build: https://www.internalfb.com/buck2/8865e85d-2565-4222-9adb-8b463daf8540

buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Run the repaired existing shared communication context training test on AMD accelerators' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_training -- TestFullyShardShareCommContext --env HIP_VISIBLE_DEVICES=0,1,2,3

Passed: 2 results, zero failures/fatals/skips. This directly verifies that the existing foreach_reduce_with_assert wrapper accepts and forwards all_reduce_comm. https://www.internalfb.com/intern/testinfra/testrun/31243722469561850 ; build: https://www.internalfb.com/buck2/f3aefb73-3587-456e-b71f-5e5ea1293fdf . The earlier CPU attempt skipped this test because that build's test configuration required two accelerator devices; it is not counted as correctness evidence.

Test sources:

buck2 build fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify relay adapters conform to the new AllReduce interface and the benchmark remains type correct' fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking

Both type-checking targets built successfully: https://www.internalfb.com/buck2/958945f0-ef11-470a-a67a-86ee2ec76f16 . Native FSDP owning targets still have type checking disabled; the arc pyrefly check-owning-targets invocation performed zero type checks there.

arc lint -a --only-changed --rev .^ passes. The required Citrine invocation reports no lint issues on the modified ML paths. The repository-packaged Ruff 0.15.4 checks pass on all seven modified native implementation/test files; formatting checks pass on all four FSDP implementation files and the callback test. The upstream configuration pins Ruff 0.14.4, so the repository tool is not an exact reproduction of that CI environment. Existing assertion-message formatting in the training/memory files is preserved.

The currently published PR still needs the latest diff exported: https://www.internalfb.com/intern/opensource/export/preview/D125970002/ . Current red jobs report unsynced source and an outstanding automated review requesting changes, rather than a failed unit test. The new implementation and tests address the synchronized review findings. This test plan does not claim that the external review/export gates have passed.

Reviewed By: weifengpy

Differential Revision: D125970002

@kausv
kausv requested a review from weifengpy as a code owner November 4, 2026 01:26
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Nov 4, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR adds an experimental `AllReduce` comm interface, a `DefaultAllReduce`
default, and `FSDPModule.set_custom_all_reduce`, which replace the HSDP /
`replicate_with_fsdp` gradient all-reduce in `foreach_reduce`. The review's
Recommendation is Approve. It labels every point non-blocking, but asks that the
`None` annotation regression and the reverted docstrings be fixed before
landing.

Findings (7):

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:819
The signature no longer accepts `None`, but the API still documents and relies
on it (non-blocking, changed since last review). This revision changed `comm:
AllReduce | None, /` to `comm: AllReduce`. The docstring (835-836) still says
`comm (Optional[AllReduce])` and "``None`` restores ``DefaultAllReduce``", the
body (848-850) still handles `comm is None`, and the PR's own tests pass `None`
(test_fully_shard_comm.py:316, test_fully_shard_memory.py:496). So the
documented way to restore the default fails type checking in user code. Put back
`AllReduce | None`, matching the sibling `set_reduce_scatter_input_fn(self, fn:
Callable | None, /, ...)`. This appeared in the latest revision, likely from a
stale internal export overwriting 972428e. Fix it before landing.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:804
The PR reverts unrelated upstream docstrings, and the restored text is
inaccurate (non-blocking, changed since last review). This hunk removes "The
comm is not used when the reduce-scatter group has size 1 since no
reduce-scatter runs." That sentence is true: with `skip_reduce_scatter =
world_size == 1`, `reduce_scatter_comm` is never allocated from or called. Drop
this hunk, and check whether the export overwrote anything else from 972428e.
Fix before landing.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:1016
Reverted upstream docstring in `set_reduce_scatter_max_input_buffers`
(non-blocking, changed since last review). This hunk puts back "must wait on the
previous reduce-scatter" and drops the size-1 sentence. For 1-D FSDP with a
size-1 group, no reduce-scatter runs: `reduce_scatter_event` is replaced by
`post_reduce_event` (`_fsdp_collectives.py:906-907`), so the recycle wait is on
the post-reduce ops. The merge-base wording ("until the previous buffer is no
longer in use") was correct. Drop this hunk before landing.

[minor] torch/distributed/fsdp/_fully_shard/_fsdp_api.py:180
The `AllReduce` buffer contract is wrong for one of the two use cases the setter
is documented for (non-blocking). The docstring says the reduce-scatter
primitive allocates the input buffer, and suggests a matching custom
`ReduceScatter` for registered memory. But `replicate_with_fsdp`, and HSDP with
shard size 1, give `foreach_reduce` a None reduce-scatter group with world_size
1. There the buffer comes from `torch.empty_like` (`_fsdp_collectives.py:753`)
and the reduce-scatter comm is never called, so the workaround cannot work.
`Comm.allocate` is also still abstract, so a subclass that defines only
`__call__` raises TypeError, and the only shortcut is the private
`DefaultAllocMixin`. Fix: give `AllReduce` a concrete `allocate` and correct the
docstring, or allocate the skip-reduce-scatter output through
`all_reduce_comm.allocate`. Also state that FSDP calls the comm with the
keywords `tensor=`, `group=`, `op=`.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:843
Error messages are terse and undocumented (non-blocking). The
multiple-param-groups message drops the "(from per-param mesh via
shard_placement_fn)" explanation that all three sibling setters give. "requires
a replication mesh" doesn't say what is accepted (a 2-D HSDP mesh or
`replicate_with_fsdp`). Rejecting 1-D FSDP is reasonable, but a `for m in
model.modules(): m.set_custom_all_reduce(c)` loop over a mixed model will raise,
so the docstring should mention it.

(2 more not shown, see the review run)

Reviewed commit: 324c7a8

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit 324c7a8 with merge base bef8090 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@meta-codesync

meta-codesync Bot commented Nov 4, 2026

Copy link
Copy Markdown

@kausv has exported this pull request. If you are a Meta employee, you can view the originating Diff in D125970002.

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 4, 2026
github-actions[bot]

This comment was marked as outdated.

@kausv
kausv force-pushed the export-D125970002 branch from 5a55e57 to 9d3a9f3 Compare November 4, 2026 16:04
github-actions[bot]

This comment was marked as outdated.

@kausv
kausv force-pushed the export-D125970002 branch from 9d3a9f3 to 972428e Compare November 10, 2026 16:28
@meta-codesync meta-codesync Bot changed the title [FSDP][AMD] Sharded Relay for All Reduce/Reduce Scatter [FSDP][AMD] Sharded Relay for All Reduce/Reduce Scatter (#203312) Nov 10, 2026
kausv added a commit to kausv/pytorch that referenced this pull request Nov 10, 2026
Summary:
Pull Request resolved: pytorch#203312

AMD XGMI links has no switches. AllReduce/ReduceScatter takes longer with the reduced b/w.
Relay sharding was implemented for TorchRec DMP in meta-pytorch/torchrec#4207

Add `AllReduce(Comm)` and `DefaultAllReduce(DefaultAllocMixin, AllReduce)` alongside the existing all-gather and reduce-scatter interfaces. Each FSDP parameter group starts with a concrete default all-reduce primitive and invokes it unconditionally by keyword. `FSDPModule.set_custom_all_reduce` overrides HSDP or `replicate_with_fsdp` gradient replication; passing `None` restores the default. FSDP retains gradient scaling, accumulation, stream dependencies, and buffer lifetime management, and the existing post-all-reduce hook still runs after the replacement collective.

Add TorchRec sharded relay adapters for all-reduce and reduce-scatter on AMD GPUs. They use the native multi-group relay backend shared with distributed model parallelism, validate group order and tensor metadata, and require all communicator ranks to follow the same bucket sequence. Synchronous SUM and AVG use relay; asynchronous calls and other reduction operations retain the process-group implementation and its native `Work` handle.

Add a four- or eight-GPU AMD benchmark comparing standard collectives with relay for FSDP and HSDP, including graph replay and gradient/optimizer parity. Large payloads can benefit from helper GPUs, while shard reduce-scatter and replica all-reduce need independent routing decisions based on their tensor sizes. No automatic routing threshold is introduced.

Update SimpleFSDP to explicitly reject the new custom all-reduce API, consistent with its other unsupported custom collectives, and recognize the method in its API override guard so existing SimpleFSDP consumers remain importable.

Add a mocked HSDP all-reduce regression test covering the callback set/unset paths, SUM/AVG forwarding, post-all-reduce hook ordering, and averaged gradient correctness. Align the FSDP import formatting with the upstream Python formatter.

Test Plan:
Commands were run locally from `fbcode/` on `devgpu288.prn2.facebook.com` with eight AMD Instinct MI300X GPUs (`gfx942`). GPU builds and tests used `fbcode//mode/opt-amd-gpu -m rocm70`. Remote test execution was disabled. The relay benchmark attempt exposed four local GPUs. The test suite ran on source revision `06b20473fcf1`; benchmark builds and scheduling checks include the subsequent four-GPU update. The fetched remote version has identical source to that starting revision.

## Local AMD tests

```bash
HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 buck2 test fbcode//mode/opt-amd-gpu -m rocm70 -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm fbcode//caffe2/torch/distributed/fb/simple_fsdp/tests:simple_fsdp_test fbcode//apf/utils/torchdynamo/tests:torch_dynamo_utils_test
```

Pass 199, Fail 1, Fatal 0, Skip 2. https://www.internalfb.com/intern/testinfra/testrun/2251800226899398

`TestFullyShardSymmMem.test_fully_shard_symm_mem_sum_reduction_False` fails in the symmetric-memory all-gather path with `RuntimeError: NCCL host communicator for group 0 not found`. This test requires NCCL 2.28+ CE collectives and is not exercising the relay adapters or custom all-reduce. The `_True` variant is skipped after the failure; `TestFullyShardAllocFromPG.test_fully_shard_alloc_from_pg` is also skipped. The remaining FSDP collective tests, SimpleFSDP tests, and downstream SimpleFSDP API-guard import tests passed. This run is not fully green.

## AMD builds and type checking

```bash
buck2 build fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking
```

Build succeeded for all three targets. https://www.internalfb.com/buck2/eaa8126c-01e4-40ba-8196-fafd9d9ce150

## Four- and eight-GPU benchmark scheduling

Executed the benchmark's `_collectives`, `_training`, and `main` control flow with mocked collective/model calls and process spawning for both supported GPU counts. Four GPUs schedule 10 collective cases (two groups of two) and 2 training cases (FSDP/HSDP on a `(2, 2)` mesh). Eight GPUs retain 20 collective cases (groups of two and four) and 4 training cases (`(4, 2)` and `(2, 4)` meshes). Verified group partitions, availability of helper groups, and matching process-spawn/world-size arguments. Both scheduling checks passed; these checks do not establish native relay correctness or performance.

## Lint

`arc lint --only-changed --never-apply-patches --rev .^` passed for the commit. Fast lint and `arc lint --only-changed --engine extra --take CITRINEAGENT` passed on the relay adapter, benchmark, and both SimpleFSDP files; the benchmark was checked again after the four-GPU update. `arc f` also passed on the benchmark.

## Before/after performance (historical AMD measurements)

These are the recorded 2026-10-18 measurements on `devgpu288` with eight AMD GPUs, recovered from the earlier D125970002 commit's test plan. They are not fresh results from the current revision, the four-GPU benchmark update, or the queued MI350 test. The original raw JSON reports are no longer available on this host.

BF16 default sweep: dimension 1024, five warmups, 20 samples. Timings are median GPU-event microseconds after taking the maximum across all ranks per sample. `Before` uses standard RCCL; `After` uses sharded relay. The latency reduction is `(before - after) / before`; speedup is `before / after`.

| Active ranks per group | Collective input tensor shape (BF16) | Collective | Before (us) | After (us) | Speedup | Latency reduction |
|---:|---:|---|---:|---:|---:|---:|
| 2 | `(37,748,736,)` | All-reduce | 1689.5 | 625.9 | 2.70x | 63.0% |
| 2 | `(37,748,736,)` | Reduce-scatter | 967.4 | 371.5 | 2.60x | 61.6% |
| 2 | `(75,497,472,)` | All-reduce | 3296.9 | 1155.1 | 2.85x | 65.0% |
| 2 | `(75,497,472,)` | Reduce-scatter | 1867.5 | 653.3 | 2.86x | 65.0% |
| 4 | `(75,497,472,)` | All-reduce | 1742.6 | 1102.1 | 1.58x | 36.8% |
| 4 | `(75,497,472,)` | Reduce-scatter | 1040.4 | 847.1 | 1.23x | 18.6% |

Tensor sizes are element counts, not bytes. The flat input lengths above are the recorded BF16 payload sizes divided by two bytes per element. For reduce-scatter, the output length is the input length divided by the active group size. `_collective_case` creates the flat source, calculates these counts, and times both routes; `_models` configures the training buckets. Source: https://www.internalfb.com/code/fbsource/fbcode/torchrec/distributed/tests/bench_fsdp_sharded_relay.py . The source permits manual verification of the tensor shapes and timing method; the historical raw timing reports remain unavailable as stated above.

Historical dimension-1024 FSDP/HSDP forward/backward results used BF16 `(1,048,576,)` full-gradient input buckets (the flattened `(1024, 1024)` weight gradients). Only before/after ratios were recorded for these training cases; absolute step timings are unavailable:

| Training case | `(replicate, shard)` mesh | Before / after |
|---|---|---:|
| Independent FSDP groups, two-rank shards | `(4, 2)` | 0.97x |
| Independent FSDP groups, four-rank shards | `(2, 4)` | 0.84x |
| HSDP | `(4, 2)` | 1.01x |
| HSDP | `(2, 4)` | 1.02x |

Ratios above 1 favor relay; below 1 favor standard RCCL. The historical results show a collective speedup for the large payloads above, but no consistent end-to-end forward/backward improvement for the small model buckets. No exact routing threshold or current-revision performance improvement is established.

## Relay execution blocked by missing native backend

Attempted the built benchmark locally with four AMD GPUs:

```bash
HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json
```

The binary accepts four visible GPUs, then exits at the `is_backend_built("rcclx")` prerequisite check. https://www.internalfb.com/buck2/9d4d92e4-fc96-4406-9096-51574f8c698d

Attempted again with the native backend enabled:

```bash
HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 -m rcclx_dev -c fsdp_relay.native_backend=true fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json
```

Build analysis fails because `fbcode//comms/torchcomms/rcclx:_comms_rcclx` and its package are absent at this revision. https://www.internalfb.com/buck2/de6c9c51-0823-45ab-a0c0-33cfaa877e0c

No relay timings, graph replay results, or FSDP/HSDP relay gradient/optimizer parity results were produced. Once the native backend is available, the command above covers the four-GPU cases; expose `0,1,2,3,4,5,6,7` for the eight-GPU cases. Native four-GPU support remains to be verified.

## 2026-11-04: custom all-reduce callback regression and upstream lint repair

Added `TestFullyShardCustomAllReduce.test_custom_all_reduce` in both mirrored `test_fully_shard_comm.py` files. The CPU threaded `(replicate, shard) = (2, 2)` HSDP test runs with the custom callback set and unset, and with SUM forced or AVG selected normally. A `MagicMock` delegates to the real collective and verifies one callback per backward, the exact replica process group and reduction operation, the same gradient buffer reaching the post-all-reduce hook, and callback-before-hook ordering. Rank-specific inputs yield the expected averaged full gradient in all cases.

```bash
buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Verify custom callback and default HSDP reductions for SUM and AVG with matching gradient results' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu
```

Passed: 2 reported results, zero failures/fatals/skips; the callback test covers all four set/unset and SUM/AVG combinations. Test evidence: https://www.internalfb.com/intern/testinfra/testrun/21955048248994055 ; build evidence: https://www.internalfb.com/buck2/dc64ce31-8437-40e1-a4fe-2e927799b2af

The failed GitHub job was `lintrunner-noclang-partial / lint`: https://github.com/pytorch/pytorch/actions/runs/41864084487/job/126693888230 . Reproduced an upstream formatting mismatch in the `_fully_shard.py` import block and applied the upstream layout in both mirrors. Ruff 0.14.4 (the configured version) checks and formatting pass on all three changed FSDP implementation files and the communication test. The PYFMT adapter emitted no findings locally with isort 6.0.1 and usort 1.0.8.post1; the configured usort 1.1.3 package was unavailable from this host's package index, so this is not a full reproduction of the pinned GitHub environment.

`arc lint -a --only-changed --rev .^` and `arc f` pass. Citrine was invoked on the changed files; no Citrine linters are configured for these paths. The owning FSDP library targets have type checking disabled, so the owning-target Pyrefly command performed no type checking.

The existing GitHub export check additionally requires an approving review on PR pytorch#203312; that is a review gate and is not addressed by changing tests or formatting.

## 2026-11-09: `AllReduce` interface and PR review fixes

`TestFullyShardCustomAllReduce` now wraps `DefaultAllReduce` in a `MagicMock`, proving that `set_custom_all_reduce` invokes it exactly once, passes the replica group and SUM/AVG by keyword, and runs the hook afterward on the same tensor. Coverage includes native and custom HSDP, FP16 reduction, forced SUM, a custom divide factor, `replicate_with_fsdp`, accumulation while all-reduce is disabled, and restoration with `None`. `TestFullyShardCustomAllReduceErrors` verifies empty/multiple/non-replication group errors and native `Work` handle forwarding by `DefaultAllReduce`.

```bash
buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Recheck callback mocks against final keyword invocation and default restoration' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu
```

Passed: 7 results, zero failures/fatals/skips. https://www.internalfb.com/intern/testinfra/testrun/30399297539428018 ; build: https://www.internalfb.com/buck2/13702631-46a2-4a5b-a1eb-a653988dda43

The following tests ran locally on `devgpu155.prn5.facebook.com`, with four visible AMD `gfx950` GPUs, the AMD optimized build, and ROCm 7.0. These validate FSDP communication and lifetime correctness; they do not rerun the native RCCLX relay benchmark.

```bash
buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify custom and native HSDP all-reduce buffer lifetime with mixed precision on four local AMD GPUs' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_memory -- test_ar_buffer_lifetime_mixed_dtype --env HIP_VISIBLE_DEVICES=0,1,2,3
```

Passed: 2 reported results, zero failures/fatals/skips. The lifetime guard covers BF16/FP16 and native/custom all-reduce subtests, including three delayed custom calls per backward and three repeated slow runs per configuration. https://www.internalfb.com/intern/testinfra/testrun/18295873553729716 ; build: https://www.internalfb.com/buck2/8865e85d-2565-4222-9adb-8b463daf8540

```bash
buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Run the repaired existing shared communication context training test on AMD accelerators' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_training -- TestFullyShardShareCommContext --env HIP_VISIBLE_DEVICES=0,1,2,3
```

Passed: 2 results, zero failures/fatals/skips. This directly verifies that the existing `foreach_reduce_with_assert` wrapper accepts and forwards `all_reduce_comm`. https://www.internalfb.com/intern/testinfra/testrun/31243722469561850 ; build: https://www.internalfb.com/buck2/f3aefb73-3587-456e-b71f-5e5ea1293fdf . The earlier CPU attempt skipped this test because that build's test configuration required two accelerator devices; it is not counted as correctness evidence.

Test sources:
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_comm.py
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_training.py
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_memory.py

```bash
buck2 build fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify relay adapters conform to the new AllReduce interface and the benchmark remains type correct' fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking
```

Both type-checking targets built successfully: https://www.internalfb.com/buck2/958945f0-ef11-470a-a67a-86ee2ec76f16 . Native FSDP owning targets still have type checking disabled; the `arc pyrefly check-owning-targets` invocation performed zero type checks there.

`arc lint -a --only-changed --rev .^` passes. The required Citrine invocation reports no lint issues on the modified ML paths. The repository-packaged Ruff 0.15.4 checks pass on all seven modified native implementation/test files; formatting checks pass on all four FSDP implementation files and the callback test. The upstream configuration pins Ruff 0.14.4, so the repository tool is not an exact reproduction of that CI environment. Existing assertion-message formatting in the training/memory files is preserved.

The currently published PR still needs the latest diff exported: https://www.internalfb.com/intern/opensource/export/preview/D125970002/ . Current red jobs report unsynced source and an outstanding automated review requesting changes, rather than a failed unit test. The new implementation and tests address the synchronized review findings. This test plan does not claim that the external review/export gates have passed.

Differential Revision: D125970002
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed stale reviews from themself November 10, 2026 16:41

Withdrawn: the automated review of 972428e found nothing blocking.

kausv added a commit to kausv/torchrec that referenced this pull request Nov 10, 2026
Summary:
X-link: pytorch/pytorch#203312

AMD XGMI links has no switches. AllReduce/ReduceScatter takes longer with the reduced b/w.
Relay sharding was implemented for TorchRec DMP in meta-pytorch#4207

Add `AllReduce(Comm)` and `DefaultAllReduce(DefaultAllocMixin, AllReduce)` alongside the existing all-gather and reduce-scatter interfaces. Each FSDP parameter group starts with a concrete default all-reduce primitive and invokes it unconditionally by keyword. `FSDPModule.set_custom_all_reduce` overrides HSDP or `replicate_with_fsdp` gradient replication; passing `None` restores the default. FSDP retains gradient scaling, accumulation, stream dependencies, and buffer lifetime management, and the existing post-all-reduce hook still runs after the replacement collective.

Add TorchRec sharded relay adapters for all-reduce and reduce-scatter on AMD GPUs. They use the native multi-group relay backend shared with distributed model parallelism, validate group order and tensor metadata, and require all communicator ranks to follow the same bucket sequence. Synchronous SUM and AVG use relay; asynchronous calls and other reduction operations retain the process-group implementation and its native `Work` handle.

Add a four- or eight-GPU AMD benchmark comparing standard collectives with relay for FSDP and HSDP, including graph replay and gradient/optimizer parity. Large payloads can benefit from helper GPUs, while shard reduce-scatter and replica all-reduce need independent routing decisions based on their tensor sizes. No automatic routing threshold is introduced.

Update SimpleFSDP to explicitly reject the new custom all-reduce API, consistent with its other unsupported custom collectives, and recognize the method in its API override guard so existing SimpleFSDP consumers remain importable.

Add a mocked HSDP all-reduce regression test covering the callback set/unset paths, SUM/AVG forwarding, post-all-reduce hook ordering, and averaged gradient correctness. Align the FSDP import formatting with the upstream Python formatter.

Reviewed By: weifengpy

Differential Revision: D125970002
Summary:
X-link: meta-pytorch/torchrec#5008


AMD XGMI links has no switches. AllReduce/ReduceScatter takes longer with the reduced b/w.
Relay sharding was implemented for TorchRec DMP in meta-pytorch/torchrec#4207

Add `AllReduce(Comm)` and `DefaultAllReduce(DefaultAllocMixin, AllReduce)` alongside the existing all-gather and reduce-scatter interfaces. Each FSDP parameter group starts with a concrete default all-reduce primitive and invokes it unconditionally by keyword. `FSDPModule.set_custom_all_reduce` overrides HSDP or `replicate_with_fsdp` gradient replication; passing `None` restores the default. FSDP retains gradient scaling, accumulation, stream dependencies, and buffer lifetime management, and the existing post-all-reduce hook still runs after the replacement collective.

Add TorchRec sharded relay adapters for all-reduce and reduce-scatter on AMD GPUs. They use the native multi-group relay backend shared with distributed model parallelism, validate group order and tensor metadata, and require all communicator ranks to follow the same bucket sequence. Synchronous SUM and AVG use relay; asynchronous calls and other reduction operations retain the process-group implementation and its native `Work` handle.

Add a four- or eight-GPU AMD benchmark comparing standard collectives with relay for FSDP and HSDP, including graph replay and gradient/optimizer parity. Large payloads can benefit from helper GPUs, while shard reduce-scatter and replica all-reduce need independent routing decisions based on their tensor sizes. No automatic routing threshold is introduced.

Update SimpleFSDP to explicitly reject the new custom all-reduce API, consistent with its other unsupported custom collectives, and recognize the method in its API override guard so existing SimpleFSDP consumers remain importable.

Add a mocked HSDP all-reduce regression test covering the callback set/unset paths, SUM/AVG forwarding, post-all-reduce hook ordering, and averaged gradient correctness. Align the FSDP import formatting with the upstream Python formatter.

Test Plan:
Commands were run locally from `fbcode/` on `devgpu288.prn2.facebook.com` with eight AMD Instinct MI300X GPUs (`gfx942`). GPU builds and tests used `fbcode//mode/opt-amd-gpu -m rocm70`. Remote test execution was disabled. The relay benchmark attempt exposed four local GPUs. The test suite ran on source revision `06b20473fcf1`; benchmark builds and scheduling checks include the subsequent four-GPU update. The fetched remote version has identical source to that starting revision.

## Local AMD tests

```bash
HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 buck2 test fbcode//mode/opt-amd-gpu -m rocm70 -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm fbcode//caffe2/torch/distributed/fb/simple_fsdp/tests:simple_fsdp_test fbcode//apf/utils/torchdynamo/tests:torch_dynamo_utils_test
```

Pass 199, Fail 1, Fatal 0, Skip 2. https://www.internalfb.com/intern/testinfra/testrun/2251800226899398

`TestFullyShardSymmMem.test_fully_shard_symm_mem_sum_reduction_False` fails in the symmetric-memory all-gather path with `RuntimeError: NCCL host communicator for group 0 not found`. This test requires NCCL 2.28+ CE collectives and is not exercising the relay adapters or custom all-reduce. The `_True` variant is skipped after the failure; `TestFullyShardAllocFromPG.test_fully_shard_alloc_from_pg` is also skipped. The remaining FSDP collective tests, SimpleFSDP tests, and downstream SimpleFSDP API-guard import tests passed. This run is not fully green.

## AMD builds and type checking

```bash
buck2 build fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking
```

Build succeeded for all three targets. https://www.internalfb.com/buck2/eaa8126c-01e4-40ba-8196-fafd9d9ce150

## Four- and eight-GPU benchmark scheduling

Executed the benchmark's `_collectives`, `_training`, and `main` control flow with mocked collective/model calls and process spawning for both supported GPU counts. Four GPUs schedule 10 collective cases (two groups of two) and 2 training cases (FSDP/HSDP on a `(2, 2)` mesh). Eight GPUs retain 20 collective cases (groups of two and four) and 4 training cases (`(4, 2)` and `(2, 4)` meshes). Verified group partitions, availability of helper groups, and matching process-spawn/world-size arguments. Both scheduling checks passed; these checks do not establish native relay correctness or performance.

## Lint

`arc lint --only-changed --never-apply-patches --rev .^` passed for the commit. Fast lint and `arc lint --only-changed --engine extra --take CITRINEAGENT` passed on the relay adapter, benchmark, and both SimpleFSDP files; the benchmark was checked again after the four-GPU update. `arc f` also passed on the benchmark.

## Before/after performance (historical AMD measurements)

These are the recorded 2026-10-18 measurements on `devgpu288` with eight AMD GPUs, recovered from the earlier D125970002 commit's test plan. They are not fresh results from the current revision, the four-GPU benchmark update, or the queued MI350 test. The original raw JSON reports are no longer available on this host.

BF16 default sweep: dimension 1024, five warmups, 20 samples. Timings are median GPU-event microseconds after taking the maximum across all ranks per sample. `Before` uses standard RCCL; `After` uses sharded relay. The latency reduction is `(before - after) / before`; speedup is `before / after`.

| Active ranks per group | Collective input tensor shape (BF16) | Collective | Before (us) | After (us) | Speedup | Latency reduction |
|---:|---:|---|---:|---:|---:|---:|
| 2 | `(37,748,736,)` | All-reduce | 1689.5 | 625.9 | 2.70x | 63.0% |
| 2 | `(37,748,736,)` | Reduce-scatter | 967.4 | 371.5 | 2.60x | 61.6% |
| 2 | `(75,497,472,)` | All-reduce | 3296.9 | 1155.1 | 2.85x | 65.0% |
| 2 | `(75,497,472,)` | Reduce-scatter | 1867.5 | 653.3 | 2.86x | 65.0% |
| 4 | `(75,497,472,)` | All-reduce | 1742.6 | 1102.1 | 1.58x | 36.8% |
| 4 | `(75,497,472,)` | Reduce-scatter | 1040.4 | 847.1 | 1.23x | 18.6% |

Tensor sizes are element counts, not bytes. The flat input lengths above are the recorded BF16 payload sizes divided by two bytes per element. For reduce-scatter, the output length is the input length divided by the active group size. `_collective_case` creates the flat source, calculates these counts, and times both routes; `_models` configures the training buckets. Source: https://www.internalfb.com/code/fbsource/fbcode/torchrec/distributed/tests/bench_fsdp_sharded_relay.py . The source permits manual verification of the tensor shapes and timing method; the historical raw timing reports remain unavailable as stated above.

Historical dimension-1024 FSDP/HSDP forward/backward results used BF16 `(1,048,576,)` full-gradient input buckets (the flattened `(1024, 1024)` weight gradients). Only before/after ratios were recorded for these training cases; absolute step timings are unavailable:

| Training case | `(replicate, shard)` mesh | Before / after |
|---|---|---:|
| Independent FSDP groups, two-rank shards | `(4, 2)` | 0.97x |
| Independent FSDP groups, four-rank shards | `(2, 4)` | 0.84x |
| HSDP | `(4, 2)` | 1.01x |
| HSDP | `(2, 4)` | 1.02x |

Ratios above 1 favor relay; below 1 favor standard RCCL. The historical results show a collective speedup for the large payloads above, but no consistent end-to-end forward/backward improvement for the small model buckets. No exact routing threshold or current-revision performance improvement is established.

## Relay execution blocked by missing native backend

Attempted the built benchmark locally with four AMD GPUs:

```bash
HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json
```

The binary accepts four visible GPUs, then exits at the `is_backend_built("rcclx")` prerequisite check. https://www.internalfb.com/buck2/9d4d92e4-fc96-4406-9096-51574f8c698d

Attempted again with the native backend enabled:

```bash
HIP_VISIBLE_DEVICES=0,1,2,3 buck2 run fbcode//mode/opt-amd-gpu -m rocm70 -m rcclx_dev -c fsdp_relay.native_backend=true fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay -- --dtype bf16 --output /tmp/D125970002-fsdp-relay-bf16-4gpu.json
```

Build analysis fails because `fbcode//comms/torchcomms/rcclx:_comms_rcclx` and its package are absent at this revision. https://www.internalfb.com/buck2/de6c9c51-0823-45ab-a0c0-33cfaa877e0c

No relay timings, graph replay results, or FSDP/HSDP relay gradient/optimizer parity results were produced. Once the native backend is available, the command above covers the four-GPU cases; expose `0,1,2,3,4,5,6,7` for the eight-GPU cases. Native four-GPU support remains to be verified.

## 2026-11-04: custom all-reduce callback regression and upstream lint repair

Added `TestFullyShardCustomAllReduce.test_custom_all_reduce` in both mirrored `test_fully_shard_comm.py` files. The CPU threaded `(replicate, shard) = (2, 2)` HSDP test runs with the custom callback set and unset, and with SUM forced or AVG selected normally. A `MagicMock` delegates to the real collective and verifies one callback per backward, the exact replica process group and reduction operation, the same gradient buffer reaching the post-all-reduce hook, and callback-before-hook ordering. Rank-specific inputs yield the expected averaged full gradient in all cases.

```bash
buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Verify custom callback and default HSDP reductions for SUM and AVG with matching gradient results' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu
```

Passed: 2 reported results, zero failures/fatals/skips; the callback test covers all four set/unset and SUM/AVG combinations. Test evidence: https://www.internalfb.com/intern/testinfra/testrun/21955048248994055 ; build evidence: https://www.internalfb.com/buck2/dc64ce31-8437-40e1-a4fe-2e927799b2af

The failed GitHub job was `lintrunner-noclang-partial / lint`: https://github.com/pytorch/pytorch/actions/runs/41864084487/job/126693888230 . Reproduced an upstream formatting mismatch in the `_fully_shard.py` import block and applied the upstream layout in both mirrors. Ruff 0.14.4 (the configured version) checks and formatting pass on all three changed FSDP implementation files and the communication test. The PYFMT adapter emitted no findings locally with isort 6.0.1 and usort 1.0.8.post1; the configured usort 1.1.3 package was unavailable from this host's package index, so this is not a full reproduction of the pinned GitHub environment.

`arc lint -a --only-changed --rev .^` and `arc f` pass. Citrine was invoked on the changed files; no Citrine linters are configured for these paths. The owning FSDP library targets have type checking disabled, so the owning-target Pyrefly command performed no type checking.

The existing GitHub export check additionally requires an approving review on PR pytorch#203312; that is a review gate and is not addressed by changing tests or formatting.

## 2026-11-09: `AllReduce` interface and PR review fixes

`TestFullyShardCustomAllReduce` now wraps `DefaultAllReduce` in a `MagicMock`, proving that `set_custom_all_reduce` invokes it exactly once, passes the replica group and SUM/AVG by keyword, and runs the hook afterward on the same tensor. Coverage includes native and custom HSDP, FP16 reduction, forced SUM, a custom divide factor, `replicate_with_fsdp`, accumulation while all-reduce is disabled, and restoration with `None`. `TestFullyShardCustomAllReduceErrors` verifies empty/multiple/non-replication group errors and native `Work` handle forwarding by `DefaultAllReduce`.

```bash
buck2 test fbcode//mode/opt --agent-context direct_call=true --agent-context 'reason=Recheck callback mocks against final keyword invocation and default restoration' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_comm -- TestFullyShardCustomAllReduce --env PYTORCH_TESTING_DEVICE_ONLY_FOR=cpu
```

Passed: 7 results, zero failures/fatals/skips. https://www.internalfb.com/intern/testinfra/testrun/30399297539428018 ; build: https://www.internalfb.com/buck2/13702631-46a2-4a5b-a1eb-a653988dda43

The following tests ran locally on `devgpu155.prn5.facebook.com`, with four visible AMD `gfx950` GPUs, the AMD optimized build, and ROCm 7.0. These validate FSDP communication and lifetime correctness; they do not rerun the native RCCLX relay benchmark.

```bash
buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify custom and native HSDP all-reduce buffer lifetime with mixed precision on four local AMD GPUs' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_memory -- test_ar_buffer_lifetime_mixed_dtype --env HIP_VISIBLE_DEVICES=0,1,2,3
```

Passed: 2 reported results, zero failures/fatals/skips. The lifetime guard covers BF16/FP16 and native/custom all-reduce subtests, including three delayed custom calls per backward and three repeated slow runs per configuration. https://www.internalfb.com/intern/testinfra/testrun/18295873553729716 ; build: https://www.internalfb.com/buck2/8865e85d-2565-4222-9adb-8b463daf8540

```bash
buck2 test fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Run the repaired existing shared communication context training test on AMD accelerators' -c fbcode.disable_re_tests=True fbcode//caffe2/test/distributed/_composable:fully_shard_training -- TestFullyShardShareCommContext --env HIP_VISIBLE_DEVICES=0,1,2,3
```

Passed: 2 results, zero failures/fatals/skips. This directly verifies that the existing `foreach_reduce_with_assert` wrapper accepts and forwards `all_reduce_comm`. https://www.internalfb.com/intern/testinfra/testrun/31243722469561850 ; build: https://www.internalfb.com/buck2/f3aefb73-3587-456e-b71f-5e5ea1293fdf . The earlier CPU attempt skipped this test because that build's test configuration required two accelerator devices; it is not counted as correctness evidence.

Test sources:
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_comm.py
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_training.py
- https://www.internalfb.com/code/fbsource/fbcode/caffe2/test/distributed/_composable/fsdp/test_fully_shard_memory.py


```bash
buck2 build fbcode//mode/opt-amd-gpu -m rocm70 --agent-context direct_call=true --agent-context 'reason=Verify relay adapters conform to the new AllReduce interface and the benchmark remains type correct' fbcode//torchrec/distributed:fsdp_sharded_relay-type-checking fbcode//torchrec/distributed/tests:bench_fsdp_sharded_relay-library-type-checking
```

Both type-checking targets built successfully: https://www.internalfb.com/buck2/958945f0-ef11-470a-a67a-86ee2ec76f16 . Native FSDP owning targets still have type checking disabled; the `arc pyrefly check-owning-targets` invocation performed zero type checks there.

`arc lint -a --only-changed --rev .^` passes. The required Citrine invocation reports no lint issues on the modified ML paths. The repository-packaged Ruff 0.15.4 checks pass on all seven modified native implementation/test files; formatting checks pass on all four FSDP implementation files and the callback test. The upstream configuration pins Ruff 0.14.4, so the repository tool is not an exact reproduction of that CI environment. Existing assertion-message formatting in the training/memory files is preserved.

The currently published PR still needs the latest diff exported: https://www.internalfb.com/intern/opensource/export/preview/D125970002/ . Current red jobs report unsynced source and an outstanding automated review requesting changes, rather than a failed unit test. The new implementation and tests address the synchronized review findings. This test plan does not claim that the external review/export gates have passed.

Reviewed By: weifengpy

Differential Revision: D125970002
@kausv
kausv force-pushed the export-D125970002 branch from 972428e to 324c7a8 Compare November 10, 2026 23:57

@github-actions github-actions Bot 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.

Automated review of 324c7a8: nothing blocking; ready for human review.

The PR adds an experimental AllReduce comm interface, a DefaultAllReduce default, and FSDPModule.set_custom_all_reduce, which replace the HSDP / replicate_with_fsdp gradient all-reduce in foreach_reduce. The review's Recommendation is Approve. It labels every point non-blocking, but asks that the None annotation regression and the reverted docstrings be fixed before landing.

⚪ 7 non-blocking findings

def set_custom_all_reduce(self, comm: AllReduce) -> None:

The signature no longer accepts None, but the API still documents and relies on it (non-blocking, changed since last review). This revision changed comm: AllReduce | None, / to comm: AllReduce. The docstring (835-836) still says comm (Optional\[AllReduce\]) and "None restores DefaultAllReduce", the body (848-850) still handles comm is None, and the PR's own tests pass None (test_fully_shard_comm.py:316, test_fully_shard_memory.py:496). So the documented way to restore the default fails type checking in user code. Put back AllReduce | None, matching the sibling set_reduce_scatter_input_fn(self, fn: Callable | None, /, ...). This appeared in the latest revision, likely from a stale internal export overwriting 972428e. Fix it before landing.


See `Comm` and `ReduceScatter` for details.

The PR reverts unrelated upstream docstrings, and the restored text is inaccurate (non-blocking, changed since last review). This hunk removes "The comm is not used when the reduce-scatter group has size 1 since no reduce-scatter runs." That sentence is true: with skip_reduce_scatter = world_size == 1, reduce_scatter_comm is never allocated from or called. Drop this hunk, and check whether the export overwrote anything else from 972428e. Fix before landing.


must wait on the previous reduce-scatter before the next copy-in can

Reverted upstream docstring in set_reduce_scatter_max_input_buffers (non-blocking, changed since last review). This hunk puts back "must wait on the previous reduce-scatter" and drops the size-1 sentence. For 1-D FSDP with a size-1 group, no reduce-scatter runs: reduce_scatter_event is replaced by post_reduce_event (_fsdp_collectives.py:906-907), so the recycle wait is on the post-reduce ops. The merge-base wording ("until the previous buffer is no longer in use") was correct. Drop this hunk before landing.


The input buffer is allocated by the reduce-scatter primitive, so FSDP

The AllReduce buffer contract is wrong for one of the two use cases the setter is documented for (non-blocking). The docstring says the reduce-scatter primitive allocates the input buffer, and suggests a matching custom ReduceScatter for registered memory. But replicate_with_fsdp, and HSDP with shard size 1, give foreach_reduce a None reduce-scatter group with world_size 1. There the buffer comes from torch.empty_like (_fsdp_collectives.py:753) and the reduce-scatter comm is never called, so the workaround cannot work. Comm.allocate is also still abstract, so a subclass that defines only __call__ raises TypeError, and the only shortcut is the private DefaultAllocMixin. Fix: give AllReduce a concrete allocate and correct the docstring, or allocate the skip-reduce-scatter output through all_reduce_comm.allocate. Also state that FSDP calls the comm with the keywords tensor=, group=, op=.


"set_custom_all_reduce is not supported with multiple param groups"

Error messages are terse and undocumented (non-blocking). The multiple-param-groups message drops the "(from per-param mesh via shard_placement_fn)" explanation that all three sibling setters give. "requires a replication mesh" doesn't say what is accepted (a 2-D HSDP mesh or replicate_with_fsdp). Rejecting 1-D FSDP is reasonable, but a for m in model.modules(): m.set_custom_all_reduce(c) loop over a mixed model will raise, so the docstring should mention it.


Some test configs and assertions cannot catch regressions (non-blocking). The only divide-factor config, (torch.float32, True, 8.0), also forces SUM, so the rule that a divide factor alone switches the all-reduce to SUM (_fsdp_collectives.py:1069-1073) is never exercised. The expected-op expression at :276-281 would wrongly predict AVG for (fp32, False, factor). Add (fp32, False, 2.0) on HSDP, or any factor in test_custom_all_reduce_replicate. In the use_custom_all_reduce=False branch the mock is never installed, so the call_count == 0 check (:262) and assert_not_called() (:284) always pass. The \[\] case in test_invalid_parameter_groups (:180, :191-192) is now a success case inside an "invalid" test, with subTest(message=None). Give it a descriptive label or move it into its own test.


def set_custom_all_reduce(self, comm: AllReduce) -> None:

The title and description don't match the diff (non-blocking). The title ("[FSDP][AMD] Sharded Relay for All Reduce/Reduce Scatter") and body describe TorchRec relay adapters, an AMD benchmark and SimpleFSDP changes. None of these are in the diff, which adds a device-agnostic all-reduce override and does not change reduce-scatter behavior. The test plan says TestFullyShardCustomAllReduceErrors covers "empty group errors", but empty groups now return silently (_fully_shard.py:839-840). Since the PR carries release notes: distributed (fsdp), retitle it to describe what lands, e.g. "[FSDP2] Add experimental AllReduce comm and set_custom_all_reduce".

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 11, 2026
meta-codesync Bot pushed a commit to meta-pytorch/torchrec that referenced this pull request Nov 11, 2026
Summary:
Pull Request resolved: #5008

X-link: pytorch/pytorch#203312

AMD XGMI links has no switches. AllReduce/ReduceScatter takes longer with the reduced b/w.
Relay sharding was implemented for TorchRec DMP in #4207

Add `AllReduce(Comm)` and `DefaultAllReduce(DefaultAllocMixin, AllReduce)` alongside the existing all-gather and reduce-scatter interfaces. Each FSDP parameter group starts with a concrete default all-reduce primitive and invokes it unconditionally by keyword. `FSDPModule.set_custom_all_reduce` overrides HSDP or `replicate_with_fsdp` gradient replication; passing `None` restores the default. FSDP retains gradient scaling, accumulation, stream dependencies, and buffer lifetime management, and the existing post-all-reduce hook still runs after the replacement collective.

Add TorchRec sharded relay adapters for all-reduce and reduce-scatter on AMD GPUs. They use the native multi-group relay backend shared with distributed model parallelism, validate group order and tensor metadata, and require all communicator ranks to follow the same bucket sequence. Synchronous SUM and AVG use relay; asynchronous calls and other reduction operations retain the process-group implementation and its native `Work` handle.

Add a four- or eight-GPU AMD benchmark comparing standard collectives with relay for FSDP and HSDP, including graph replay and gradient/optimizer parity. Large payloads can benefit from helper GPUs, while shard reduce-scatter and replica all-reduce need independent routing decisions based on their tensor sizes. No automatic routing threshold is introduced.

Update SimpleFSDP to explicitly reject the new custom all-reduce API, consistent with its other unsupported custom collectives, and recognize the method in its API override guard so existing SimpleFSDP consumers remain importable.

Add a mocked HSDP all-reduce regression test covering the callback set/unset paths, SUM/AVG forwarding, post-all-reduce hook ordering, and averaged gradient correctness. Align the FSDP import formatting with the upstream Python formatter.

Reviewed By: weifengpy

Differential Revision: D125970002

fbshipit-source-id: 660db2f98f0fd53c103b7bec61f4abdf5f33625b
@meta-codesync

meta-codesync Bot commented Nov 11, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@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

@izaitsevfb

Copy link
Copy Markdown
Contributor

✴️ iz2: acting on a press of an iz2 alert's button for the PyTorch release engineering oncall (ref 767cc1a8)
@pytorchbot 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

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

Labels

ciflow/h100-symm-mem ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request in progress PR is being worked on by the author, until the automated review accepts it Merged meta-exported release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants