Skip to content

[c10d] Move FakeProcessGroup from C++ to a Python PyBackend - #202141

Closed
d4l3k wants to merge 12 commits into
gh/d4l3k/299/basefrom
gh/d4l3k/299/head
Closed

d4l3k wants to merge 12 commits into
gh/d4l3k/299/basefrom
gh/d4l3k/299/head

Conversation

@d4l3k

@d4l3k d4l3k commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

FakeProcessGroup is a test-only backend, but its C++ implementation meant every semantic change needed a C++ rebuild. With dist.BackendBase subclassable from Python, it can live in Python.

Design: torch/distributed/_backends/fake.py reimplements FakeProcessGroup and FakeProcessGroup.Options on dist.BackendBase with the same semantics. It is registered through the torch.distributed.backends entry point (with a built-in fallback), so init_process_group("fake") no longer requires importing a testing module. torch/testing/_internal/distributed/fake_pg.py stays as a re-exporting shim, and torch._C._distributed_c10d.FakeProcessGroup stays as a lazy alias for downstream users. The C++ class is removed; FakeWork remains. _ProcessGroupWrapper (DEBUG=DETAIL) now keeps Python backend objects alive, as _register_backend does.

BC: C++ code using c10d::FakeProcessGroup from the installed header breaks. dist.* calls on a fake group return a plain Work instead of FakeWork.

Depends on #202176 and #202194 (Python Backend.Options through split_group).

Test plan:

python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a

Line changes: implementation +760/-828, tests (test/) +203/-10.

This PR was authored with the help of an AI assistant (Claude).

cc @ezyang @gchanan @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

🟡 AUTOMATED REVIEW - Changes requested:

This PR moves FakeProcessGroup from a C++ c10d::Backend to a Python
dist.BackendBase subclass in torch/distributed/_backends/fake.py and registers
it through a `fake` entry point with a built-in fallback. Recommendation:
Request Changes. Blockers: the after_aot.py import still goes through the
testing shim, the overload-shadowing workaround is kept local to this backend,
and the BC breaks need a label and release notes.

Findings (3):

[major] torch/testing/_internal/distributed/fake_pg.py:16
`torch/_dynamo/repro/after_aot.py:223` still imports from this testing shim: it
runs `from torch.testing._internal.distributed.fake_pg import FakeStore` at
runtime. That goes against the PR's stated goal that non-test code stop
importing `torch.testing`. Importing the shim also still registers the backend
as a side effect (this line), which the PR removed from FSDP. Fix: import
`FakeStore` from `torch.distributed._backends.fake` at after_aot.py:223. Line
558 is inside the generated repro script text and can stay as is, so older
builds can still run repros. The earlier automated review raised this and got no
reply. (after_aot.py isn't in this PR's diff, so this finding is anchored to the
shim.)

[major] torch/distributed/_backends/fake.py:111
`_keep_base_overloads` fixes a general `BackendBase` problem inside one test
backend. `torch/distributed/_nccl4py/backend.py:244-362`
(`NCCL4PyBackend(C10DBackend)`) overrides the same seven methods without this
helper. There, `backend.allreduce(tensor)` and `backend.allgather(outputs,
tensor)` fail with a missing-argument TypeError because the binding's
convenience overloads are hidden. The helper also has rough edges: it hard-codes
the `"opts"` keyword but reads the rest of the signature through `inspect`;
convenience calls return a plain `Work` while canonical calls return `FakeWork`;
and every trampoline call pays for building a dict and walking nested tensor
lists. Fix, either of: make the binding's convenience overloads always dispatch
through the virtual canonical method, or move the helper next to `BackendBase`
in `torch.distributed`, document it as the supported way to override these
methods, and apply it to `NCCL4PyBackend` too. At minimum, explain in the PR why
the fix stays local. This is the third automated review to raise it, with no
reply so far.

[major] torch/distributed/_backends/fake.py:156
The BC breaks need the `module: bc-breaking` label and a release-notes entry
(labels couldn't be checked offline). The breaks: `c10d::FakeProcessGroup` and
its `Options` are removed from the installed `FakeProcessGroup.hpp` with no
deprecation period, and the PR says this breaks xLLM-AI/xllm. `dist.*`
collectives on a fake group now return a `PyWorkHolder`-wrapped `Work` instead
of `FakeWork`, so `isinstance(w, FakeWork)` and `w.seq_id` stop working. The
tensor ops now run as Python calls, so an active `TorchFunctionMode` sees them.
`torch._C._distributed_c10d.FakeProcessGroup` is gone from `dir(...)` and its
`__module__` changed. Importing FSDP no longer registers `fake` or its
`hpu`/`xpu` entries in `default_device_backend_map`. `Options` no longer rejects
non-int `fake_option` values. The PR description, which becomes the commit
message, is also wrong on one point: it says the options "no longer reject
unknown attribute names", but `fake.py:198` adds `__slots__` to reject them and
`test_option_defaults_to_off` checks this. Fix the description so the release
note doesn't list a break that doesn't exist.

Reviewed commit: acf979a

Review run

🔗 Helpful Links

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

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

✅ No Failures

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

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Scope
    • The diff exceeds the size cap the automated reviewer can read in full
    • The size gate declined it before any review ran, so nothing in it was examined
    • A human reviewer should assess this change

reason: scope_too_large
Reviewed commit: 76c1d86 (NOT the current head acf979a)

Inference job

🐛 Report a wrong verdict

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

[ghstack-poisoned]
d4l3k added a commit that referenced this pull request Oct 27, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This rewrites `torch/testing/_internal/distributed/fake_pg.py` so `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype). It still returns the C++ `FakeWork` (constructible with an optional result list) so work objects behave as before. Direct construction stays blocked (now a RuntimeError pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on the previous PR in the stack, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed, so C++ code using them must switch to the Python class (no users found).

Suggested review order: `fake_pg.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: `PyBackend::getBackendOptions` falls back to default `Options` when the Python `options` override returns None, matching `_create_internal(..., options=None)`. The ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing `torch.testing`.

Known limitation: when calling the fake backend object directly, the Python overrides shadow the `Backend` binding's convenience overloads (e.g. `backend.allreduce(tensors, op)`, `backend.reduce(t, root)`) and some keyword names differ from the binding (e.g. `alltoall`, `all_to_all_single`). `dist.*` APIs and positional calls with options objects are unaffected; no direct callers were found.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), or removing the `torch._C` name outright (breaks downstream users).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k Backend
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: a9b12a3
Pull-Request: #202141
…ake with entry point; review fixes

[ghstack-poisoned]
d4l3k added a commit that referenced this pull request Oct 27, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This moves the implementation to `torch/distributed/_backends/fake.py`, where `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype); `_create_internal` with non-fake options still raises TypeError and `split` with them still raises RuntimeError. Collectives still create the C++ `FakeWork` (now constructible with an optional result list), but PyBackend wraps any Python-returned work in a `PyWorkHolder`, so callers of `dist.*` now get a plain `Work` rather than a `FakeWork` and cannot read `seq_id` from it; no users of that were found. Direct construction stays blocked (still a TypeError, now with a message pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on the first PR in the stack, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `.options` stays None for groups created without options, as in C++; the previous PR makes `split_group` handle that for Python backends. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

The backend is registered through a `fake` entry in the `torch.distributed.backends` entry point group like the other built-in backends, so `init_process_group(backend="fake", store=...)` no longer requires importing a testing module first. As with gloo, lookup now depends on up-to-date package metadata, including for `store=None`, which previously registered the backend implicitly by importing the testing module: a source tree whose editable install predates this change fails with "Unknown c10d backend type FAKE" until `pip install -e .` is rerun, and non-pip builds (e.g. Buck) need the equivalent entry point. `torch/testing/_internal/distributed/fake_pg.py` stays as a shim that re-exports `FakeProcessGroup`/`FakeStore`/`_create_fake_pg` and still registers the backend on import, so existing imports keep working in either case. Importing FSDP no longer registers the backend (and its device mappings) as a side effect, since it now imports the new module; the test helpers in `common_distributed.py`/`common_fsdp.py` import the shim explicitly.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed. This breaks C++ code that subclasses or constructs it from the installed header (e.g. xLLM-AI/xllm's `process_group_batch_test.cpp`); such code should use its own test backend or the Python class.

Suggested review order: `_backends/fake.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: the ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing the backend eagerly. It no longer appears in `dir(torch._C._distributed_c10d)` and its `__module__` is now `torch.distributed._backends.fake`.

`split` accepts a base `Backend.Options` whose backend is `fake` (what C++ passes for a group without options) and fills the fake fields from this group; C++ rejected base options, but it never produced them for its own groups. Other options are rejected, as in C++.

Python overrides shadow the `Backend` binding's convenience overloads of the same name (e.g. `backend.allreduce(tensor, op)`, `backend.allgather(outputs, tensor)`), so broadcast, allreduce, reduce, allgather, gather, scatter and reduce_scatter check each argument against the canonical signature (tensor lists of the expected nesting, then an options object) and forward any other call to the base binding, which re-enters the Python method canonically or raises pybind's TypeError. Parameter names match the binding so keyword calls keep working. Calling the backend object directly differs slightly: the convenience overloads return a plain `Work` (canonical calls still return `FakeWork`), and the other methods no longer type-check their arguments. The tensor ops the backend runs (`copy_`, `mul_`, ...) are now Python calls, so an active `TorchFunctionMode` sees them, as with any Python backend.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), removing the `torch._C` name outright (breaks downstream users), or leaving the implementation under `torch.testing` (non-test code such as FSDP and `init_process_group` would keep importing the testing package).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Run on CPU; `test_fake_collectives.py` skips without CUDA/XPU.

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: ecbc916
Pull-Request: #202141
d4l3k added a commit that referenced this pull request Oct 27, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This moves the implementation to `torch/distributed/_backends/fake.py`, where `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype); `_create_internal` with non-fake options still raises TypeError and `split` with them still raises RuntimeError. Collectives still create the C++ `FakeWork` (now constructible with an optional result list), but PyBackend wraps any Python-returned work in a `PyWorkHolder`, so callers of `dist.*` now get a plain `Work` rather than a `FakeWork` and cannot read `seq_id` from it; no users of that were found. Direct construction stays blocked (still a TypeError, now with a message pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on the first PR in the stack, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `.options` stays None for groups created without options, as in C++; the previous PR makes `split_group` handle that for Python backends. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

The backend is registered through a `fake` entry in the `torch.distributed.backends` entry point group like the other built-in backends, so `init_process_group(backend="fake", store=...)` no longer requires importing a testing module first. As with gloo, lookup now depends on up-to-date package metadata, including for `store=None`, which previously registered the backend implicitly by importing the testing module: a source tree whose editable install predates this change fails with "Unknown c10d backend type FAKE" until `pip install -e .` is rerun, and non-pip builds (e.g. Buck) need the equivalent entry point. `torch/testing/_internal/distributed/fake_pg.py` stays as a shim that re-exports `FakeProcessGroup`/`FakeStore`/`_create_fake_pg` and still registers the backend on import, so existing imports keep working in either case. Importing FSDP no longer registers the backend (and its device mappings) as a side effect, since it now imports the new module; the test helpers in `common_distributed.py`/`common_fsdp.py` import the shim explicitly.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed. This breaks C++ code that subclasses or constructs it from the installed header (e.g. xLLM-AI/xllm's `process_group_batch_test.cpp`); such code should use its own test backend or the Python class.

Suggested review order: `_backends/fake.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: the ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing the backend eagerly. It no longer appears in `dir(torch._C._distributed_c10d)` and its `__module__` is now `torch.distributed._backends.fake`.

`split` accepts a base `Backend.Options` whose backend is `fake` (what C++ passes for a group without options) and fills the fake fields from this group; C++ rejected base options, but it never produced them for its own groups. Other options are rejected, as in C++.

Python overrides shadow the `Backend` binding's convenience overloads of the same name (e.g. `backend.allreduce(tensor, op)`, `backend.allgather(outputs, tensor)`), so broadcast, allreduce, reduce, allgather, gather, scatter and reduce_scatter check each argument against the canonical signature (tensor lists of the expected nesting, then an options object) and forward any other call to the base binding, which re-enters the Python method canonically or raises pybind's TypeError. Parameter names match the binding so keyword calls keep working. Calling the backend object directly differs slightly: the convenience overloads return a plain `Work` (canonical calls still return `FakeWork`), and the other methods no longer type-check their arguments. The tensor ops the backend runs (`copy_`, `mul_`, ...) are now Python calls, so an active `TorchFunctionMode` sees them, as with any Python backend.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), removing the `torch._C` name outright (breaks downstream users), or leaving the implementation under `torch.testing` (non-test code such as FSDP and `init_process_group` would keep importing the testing package).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Run on CPU; `test_fake_collectives.py` skips without CUDA/XPU.

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: 132fd8a
Pull-Request: #202141
…oc; fake registration fallback

[ghstack-poisoned]
d4l3k added a commit that referenced this pull request Oct 27, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This moves the implementation to `torch/distributed/_backends/fake.py`, where `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype); `_create_internal` with non-fake options still raises TypeError and `split` with them still raises RuntimeError. Collectives still create the C++ `FakeWork` (now constructible with an optional result list), but PyBackend wraps any Python-returned work in a `PyWorkHolder`, so callers of `dist.*` now get a plain `Work` rather than a `FakeWork` and cannot read `seq_id` from it; no users of that were found. Direct construction stays blocked (still a TypeError, now with a message pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on the first PR in the stack, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `.options` stays None for groups created without options, as in C++; the previous PR makes `split_group` handle that for Python backends. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

The backend is registered through a `fake` entry in the `torch.distributed.backends` entry point group like the other built-in backends, so `init_process_group(backend="fake", store=...)` no longer requires importing a testing module first. When no `fake` entry point is found (stale editable installs, Buck), `Backend._ensure_backend_registered` falls back to registering the built-in backend directly, so `init_process_group("fake")` keeps working without importing the testing module. `torch/testing/_internal/distributed/fake_pg.py` stays as a shim that re-exports `FakeProcessGroup`/`FakeStore`/`_create_fake_pg` and still registers the backend on import, so existing imports keep working in either case. Importing FSDP no longer registers the backend (and its device mappings) as a side effect, since it now imports the new module; lookup by name still registers it on demand; the test helpers in `common_distributed.py`/`common_fsdp.py` import the shim explicitly.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed. This breaks C++ code that subclasses or constructs it from the installed header (e.g. xLLM-AI/xllm's `process_group_batch_test.cpp`); such code should use its own test backend or the Python class.

Suggested review order: `_backends/fake.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: the ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing the backend eagerly. It no longer appears in `dir(torch._C._distributed_c10d)` and its `__module__` is now `torch.distributed._backends.fake`.

`split` accepts a base `Backend.Options` whose backend is `fake` (what C++ passes for a group without options) and fills the fake fields from this group; C++ rejected base options, but it never produced them for its own groups. Other options are rejected, as in C++.

Python overrides shadow the `Backend` binding's convenience overloads of the same name (e.g. `backend.allreduce(tensor, op)`, `backend.allgather(outputs, tensor)`), so broadcast, allreduce, reduce, allgather, gather, scatter and reduce_scatter check each argument against the canonical signature (tensor lists of the expected nesting, then an options object) and forward any other call to the base binding, which re-enters the Python method canonically or raises pybind's TypeError. Parameter names match the binding so keyword calls keep working. Calling the backend object directly differs slightly: the convenience overloads return a plain `Work` (canonical calls still return `FakeWork`), and the other methods no longer type-check their arguments. The tensor ops the backend runs (`copy_`, `mul_`, ...) are now Python calls, so an active `TorchFunctionMode` sees them, as with any Python backend.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), removing the `torch._C` name outright (breaks downstream users), or leaving the implementation under `torch.testing` (non-test code such as FSDP and `init_process_group` would keep importing the testing package).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Run on CPU; `test_fake_collectives.py` skips without CUDA/XPU.

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: 4cf040d
Pull-Request: #202141
@d4l3k
d4l3k marked this pull request as ready for review October 29, 2026 00:19
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 29, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 29, 2026
github-actions[bot]

This comment was marked as outdated.

d4l3k added a commit that referenced this pull request Oct 29, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This moves the implementation to `torch/distributed/_backends/fake.py`, where `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype); `_create_internal` with non-fake options still raises TypeError and `split` with them still raises RuntimeError. Collectives still create the C++ `FakeWork` (now constructible with an optional result list), but PyBackend wraps any Python-returned work in a `PyWorkHolder`, so callers of `dist.*` now get a plain `Work` rather than a `FakeWork` and cannot read `seq_id` from it; no users of that were found. Direct construction stays blocked (still a TypeError, now with a message pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on #202176, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `.options` stays None for groups created without options, as in C++; #202194 makes `split_group` handle that for Python backends. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

The backend is registered through a `fake` entry in the `torch.distributed.backends` entry point group like the other built-in backends, so `init_process_group(backend="fake", store=...)` no longer requires importing a testing module first. When no `fake` entry point is found (stale editable installs, Buck), `Backend._ensure_backend_registered` falls back to registering the built-in backend directly, so `init_process_group("fake")` keeps working without importing the testing module. `torch/testing/_internal/distributed/fake_pg.py` stays as a shim that re-exports `FakeProcessGroup`/`FakeStore`/`_create_fake_pg` and still registers the backend on import, so existing imports keep working in either case. Importing FSDP no longer registers the backend (and its device mappings) as a side effect, since it now imports the new module; lookup by name still registers it on demand; the test helpers in `common_distributed.py`/`common_fsdp.py` import the shim explicitly.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed. This breaks C++ code that subclasses or constructs it from the installed header (e.g. xLLM-AI/xllm's `process_group_batch_test.cpp`); such code should use its own test backend or the Python class.

Under `TORCH_DISTRIBUTED_DEBUG=DETAIL`, `_ProcessGroupWrapper` held the wrapped backend only in C++, so a Python backend's object was freed once group creation returned and later calls lost its overrides (e.g. an internal assert in `getBackendName`). The wrapper's init now preserves the Python object as `_register_backend` does, through `PyBackend::initSlotAndCast` (made public). Fake collectives under DETAIL still raise "does not yet support sequence numbers", as with the C++ backend.

Suggested review order: `_backends/fake.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: the ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing the backend eagerly. It no longer appears in `dir(torch._C._distributed_c10d)` and its `__module__` is now `torch.distributed._backends.fake`.

`split` accepts a base `Backend.Options` whose backend is `fake` (what C++ passes for a group without options) and fills the fake fields from this group; C++ rejected base options, but it never produced them for its own groups. Other options are rejected, as in C++.

Python overrides shadow the `Backend` binding's convenience overloads of the same name (e.g. `backend.allreduce(tensor, op)`, `backend.allgather(outputs, tensor)`), so broadcast, allreduce, reduce, allgather, gather, scatter and reduce_scatter check each argument against the canonical signature (tensor lists of the expected nesting, then an options object) and forward any other call to the base binding, which re-enters the Python method canonically or raises pybind's TypeError. Parameter names match the binding so keyword calls keep working. Calling the backend object directly differs slightly: the convenience overloads return a plain `Work` (canonical calls still return `FakeWork`), and the other methods no longer type-check their arguments. The tensor ops the backend runs (`copy_`, `mul_`, ...) are now Python calls, so an active `TorchFunctionMode` sees them, as with any Python backend.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), removing the `torch._C` name outright (breaks downstream users), or leaving the implementation under `torch.testing` (non-test code such as FSDP and `init_process_group` would keep importing the testing package).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Run on CPU; `test_fake_collectives.py` skips without CUDA/XPU.

Line changes: implementation +752/-828, tests (`test/`) +286/-8.

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: fc5f152
Pull-Request: #202141
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed their stale review October 29, 2026 01:46

Withdrawn: the automated review of d505fc6 found nothing blocking.

github-actions[bot]

This comment was marked as outdated.

@d4l3k d4l3k added the module: bc-breaking Related to a BC-breaking change label Oct 29, 2026
@pytorch-bot pytorch-bot Bot added the topic: bc breaking topic category label Oct 29, 2026
d4l3k added a commit that referenced this pull request Oct 29, 2026
`FakeProcessGroup` was a C++ `c10d::Backend` subclass with every collective implemented in C++. It is a test-only backend, and keeping it in C++ meant every semantic change (uniform-rank simulation, split support, size checks) required a C++ rebuild and duplicated logic that is easier to read and extend in Python. With `dist.BackendBase` now subclassable from Python via the PyBackend trampoline, the backend can live in Python.

This moves the implementation to `torch/distributed/_backends/fake.py`, where `FakeProcessGroup` subclasses `dist.BackendBase` and implements all collectives, p2p, coalescing and `split` with the same semantics as the C++ version. Error messages match except minor wording differences (e.g. PREMUL_SUM dtype); `_create_internal` with non-fake options still raises TypeError and `split` with them still raises RuntimeError. Collectives still create the C++ `FakeWork` (now constructible with an optional result list), but PyBackend wraps any Python-returned work in a `PyWorkHolder`, so callers of `dist.*` now get a plain `Work` rather than a `FakeWork` and cannot read `seq_id` from it; no users of that were found. Direct construction stays blocked (still a TypeError, now with a message pointing at the supported paths); use `init_process_group(backend="fake")` or `FakeProcessGroup._create_internal`.

`FakeProcessGroup.Options` becomes a Python subclass of `dist.BackendBase.Options` with the same fields and defaults (`fake_option=0`, `error_on_collective=False`, `simulate_uniform_ranks=False`). This relies on #202176, which makes `split_group` preserve Python `Backend.Options` subclasses instead of slicing them to the C++ base. `.options` stays None for groups created without options, as in C++; #202194 makes `split_group` handle that for Python backends. `copy.copy` and `split_group` still produce a `FakeProcessGroup.Options` copy. As a plain Python class, the options no longer reject unknown attribute names or non-int `fake_option` values.

The backend is registered through a `fake` entry in the `torch.distributed.backends` entry point group like the other built-in backends, so `init_process_group(backend="fake", store=...)` no longer requires importing a testing module first. When no `fake` entry point is found (stale editable installs, Buck), `Backend._ensure_backend_registered` falls back to registering the built-in backend directly, so `init_process_group("fake")` keeps working without importing the testing module. `torch/testing/_internal/distributed/fake_pg.py` stays as a shim that re-exports `FakeProcessGroup`/`FakeStore`/`_create_fake_pg` and still registers the backend on import, so existing imports keep working in either case. Importing FSDP no longer registers the backend (and its device mappings) as a side effect, since it now imports the new module; lookup by name still registers it on demand; the test helpers in `common_distributed.py`/`common_fsdp.py` import the shim explicitly.

`FakeProcessGroup.hpp` now only holds `FakeWork`; the C++ `c10d::FakeProcessGroup` class and its options are removed. This breaks C++ code that subclasses or constructs it from the installed header (e.g. xLLM-AI/xllm's `process_group_batch_test.cpp`); such code should use its own test backend or the Python class.

Under `TORCH_DISTRIBUTED_DEBUG=DETAIL`, `_ProcessGroupWrapper` held the wrapped backend only in C++, so a Python backend's object was freed once group creation returned and later calls lost its overrides (e.g. an internal assert in `getBackendName`). The wrapper's init now preserves the Python object as `_register_backend` does, through `PyBackend::initSlotAndCast` (made public). Fake collectives under DETAIL still raise "does not yet support sequence numbers", as with the C++ backend.

Suggested review order: `_backends/fake.py` (the new implementation), then `init.cpp`/`FakeProcessGroup.hpp`, then the small supporting changes: the ReduceOp `factor` getter now raises instead of dereferencing an undefined supplement, since the Python path reads it for PREMUL_SUM. `torch._C._distributed_c10d.FakeProcessGroup` is kept as a lazy module `__getattr__` alias to the Python class because external code (e.g. meta-recsys) imports it from there; this keeps `import torch` from importing the backend eagerly. It no longer appears in `dir(torch._C._distributed_c10d)` and its `__module__` is now `torch.distributed._backends.fake`.

`split` accepts a base `Backend.Options` whose backend is `fake` (what C++ passes for a group without options) and fills the fake fields from this group; C++ rejected base options, but it never produced them for its own groups. Other options are rejected, as in C++.

Python overrides shadow the `Backend` binding's convenience overloads of the same name (e.g. `backend.allreduce(tensor, op)`, `backend.allgather(outputs, tensor)`), so broadcast, allreduce, reduce, allgather, gather, scatter and reduce_scatter check each argument against the canonical signature (tensor lists of the expected nesting, then an options object) and forward any other call to the base binding, which re-enters the Python method canonically or raises pybind's TypeError. Parameter names match the binding so keyword calls keep working. Calling the backend object directly differs slightly: the convenience overloads return a plain `Work` (canonical calls still return `FakeWork`), and the other methods no longer type-check their arguments. The tensor ops the backend runs (`copy_`, `mul_`, ...) are now Python calls, so an active `TorchFunctionMode` sees them, as with any Python backend.

Alternatives considered: keeping the C++ class with a Python wrapper (keeps the duplication), removing the `torch._C` name outright (breaks downstream users), or leaving the implementation under `torch.testing` (non-test code such as FSDP and `init_process_group` would keep importing the testing package).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Run on CPU; `test_fake_collectives.py` skips without CUDA/XPU.

Line changes: implementation +760/-828, tests (`test/`) +203/-10.

This PR was authored with the help of an AI assistant (Claude).

ghstack-source-id: 9650e8d
Pull-Request: #202141
@d4l3k

d4l3k commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 29, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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

@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 acf979a: changes requested before human review.

This PR moves FakeProcessGroup from a C++ c10d::Backend to a Python dist.BackendBase subclass in torch/distributed/_backends/fake.py and registers it through a fake entry point with a built-in fallback. Recommendation: Request Changes. Blockers: the after_aot.py import still goes through the testing shim, the overload-shadowing workaround is kept local to this backend, and the BC breaks need a label and release notes.

🔴 3 blocking findings are attached to the code below.

Please address the findings and push; a new commit normally gets a fresh automated review.

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

extended_api=True,
devices=["cpu", "cuda", "hpu", "xpu"],
)
_register_fake_backend()

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.

🔴 torch/_dynamo/repro/after_aot.py:223 still imports from this testing shim: it runs from torch.testing._internal.distributed.fake_pg import FakeStore at runtime. That goes against the PR's stated goal that non-test code stop importing torch.testing. Importing the shim also still registers the backend as a side effect (this line), which the PR removed from FSDP. Fix: import FakeStore from torch.distributed._backends.fake at after_aot.py:223. Line 558 is inside the generated repro script text and can stay as is, so older builds can still run repros. The earlier automated review raised this and got no reply. (after_aot.py isn't in this PR's diff, so this finding is anchored to the shim.)

)


def _keep_base_overloads(*depths: int):

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.

🔴 _keep_base_overloads fixes a general BackendBase problem inside one test backend. torch/distributed/_nccl4py/backend.py:244-362 (NCCL4PyBackend(C10DBackend)) overrides the same seven methods without this helper. There, backend.allreduce(tensor) and backend.allgather(outputs, tensor) fail with a missing-argument TypeError because the binding's convenience overloads are hidden. The helper also has rough edges: it hard-codes the "opts" keyword but reads the rest of the signature through inspect; convenience calls return a plain Work while canonical calls return FakeWork; and every trampoline call pays for building a dict and walking nested tensor lists. Fix, either of: make the binding's convenience overloads always dispatch through the virtual canonical method, or move the helper next to BackendBase in torch.distributed, document it as the supported way to override these methods, and apply it to NCCL4PyBackend too. At minimum, explain in the PR why the fix stays local. This is the third automated review to raise it, with no reply so far.

_SCATTER_OPTS = ScatterOptions()


class FakeProcessGroup(dist.BackendBase):

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.

🔴 The BC breaks need the module: bc-breaking label and a release-notes entry (labels couldn't be checked offline). The breaks: c10d::FakeProcessGroup and its Options are removed from the installed FakeProcessGroup.hpp with no deprecation period, and the PR says this breaks xLLM-AI/xllm. dist.* collectives on a fake group now return a PyWorkHolder-wrapped Work instead of FakeWork, so isinstance(w, FakeWork) and w.seq_id stop working. The tensor ops now run as Python calls, so an active TorchFunctionMode sees them. torch._C._distributed_c10d.FakeProcessGroup is gone from dir(...) and its __module__ changed. Importing FSDP no longer registers fake or its hpu/xpu entries in default_device_backend_map. Options no longer rejects non-int fake_option values. The PR description, which becomes the commit message, is also wrong on one point: it says the options "no longer reject unknown attribute names", but fake.py:198 adds __slots__ to reject them and test_option_defaults_to_off checks this. Fix the description so the release note doesn't list a break that doesn't exist.

@d4l3k

d4l3k commented Oct 29, 2026

Copy link
Copy Markdown
Member Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

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

twthighd added a commit to twthighd/pytorch that referenced this pull request Oct 30, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
pytorchmergebot pushed a commit that referenced this pull request Nov 3, 2026
…ter_aot (#203096)

#202141 moved FakeProcessGroup/FakeStore to `torch.distributed._backends.fake`, leaving `torch/testing/_internal/distributed/fake_pg.py` as a compatibility shim. `after_aot.py` was its last user in `torch/` outside `torch/testing`. `setup_fake_process_groups` now imports from the new module; the `fake` backend is registered on demand by `init_process_group`, so the shim's import-time registration isn't needed. The `FakeStore` import emitted into generated repros is dropped: it has been unused since repros started calling `setup_fake_process_groups`, and dropping it rather than repointing it keeps generated repros runnable on released torch (2.11+), which lacks `torch.distributed._backends.fake`.

Test plan:

```
python -m pytest test/dynamo/test_fx_graph_runnable.py
lintrunner -a --skip CLANGTIDY torch/_dynamo/repro/after_aot.py
```

22 passed; the collective and multi-process-group tests run the generated repro in a fresh subprocess.

Line changes: implementation +1/-2, tests +0/-0.

This PR was authored with the help of an AI assistant (Claude).

Pull Request resolved: #203096
Approved by: https://github.com/pytorchgreenlight
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…202141)

`FakeProcessGroup` is a test-only backend, but its C++ implementation meant every semantic change needed a C++ rebuild. With `dist.BackendBase` subclassable from Python, it can live in Python.

Design: `torch/distributed/_backends/fake.py` reimplements `FakeProcessGroup` and `FakeProcessGroup.Options` on `dist.BackendBase` with the same semantics. It is registered through the `torch.distributed.backends` entry point (with a built-in fallback), so `init_process_group("fake")` no longer requires importing a testing module. `torch/testing/_internal/distributed/fake_pg.py` stays as a re-exporting shim, and `torch._C._distributed_c10d.FakeProcessGroup` stays as a lazy alias for downstream users. The C++ class is removed; `FakeWork` remains. `_ProcessGroupWrapper` (DEBUG=DETAIL) now keeps Python backend objects alive, as `_register_backend` does.

BC: C++ code using `c10d::FakeProcessGroup` from the installed header breaks. `dist.*` calls on a fake group return a plain `Work` instead of `FakeWork`.

Depends on pytorch#202176 and pytorch#202194 (Python `Backend.Options` through `split_group`).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Line changes: implementation +760/-828, tests (`test/`) +203/-10.

This PR was authored with the help of an AI assistant (Claude).

Pull Request resolved: pytorch#202141
Approved by: https://github.com/fduwjj, https://github.com/kapilsh
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ter_aot (pytorch#203096)

pytorch#202141 moved FakeProcessGroup/FakeStore to `torch.distributed._backends.fake`, leaving `torch/testing/_internal/distributed/fake_pg.py` as a compatibility shim. `after_aot.py` was its last user in `torch/` outside `torch/testing`. `setup_fake_process_groups` now imports from the new module; the `fake` backend is registered on demand by `init_process_group`, so the shim's import-time registration isn't needed. The `FakeStore` import emitted into generated repros is dropped: it has been unused since repros started calling `setup_fake_process_groups`, and dropping it rather than repointing it keeps generated repros runnable on released torch (2.11+), which lacks `torch.distributed._backends.fake`.

Test plan:

```
python -m pytest test/dynamo/test_fx_graph_runnable.py
lintrunner -a --skip CLANGTIDY torch/_dynamo/repro/after_aot.py
```

22 passed; the collective and multi-process-group tests run the generated repro in a fresh subprocess.

Line changes: implementation +1/-2, tests +0/-0.

This PR was authored with the help of an AI assistant (Claude).

Pull Request resolved: pytorch#203096
Approved by: https://github.com/pytorchgreenlight
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…202141)

`FakeProcessGroup` is a test-only backend, but its C++ implementation meant every semantic change needed a C++ rebuild. With `dist.BackendBase` subclassable from Python, it can live in Python.

Design: `torch/distributed/_backends/fake.py` reimplements `FakeProcessGroup` and `FakeProcessGroup.Options` on `dist.BackendBase` with the same semantics. It is registered through the `torch.distributed.backends` entry point (with a built-in fallback), so `init_process_group("fake")` no longer requires importing a testing module. `torch/testing/_internal/distributed/fake_pg.py` stays as a re-exporting shim, and `torch._C._distributed_c10d.FakeProcessGroup` stays as a lazy alias for downstream users. The C++ class is removed; `FakeWork` remains. `_ProcessGroupWrapper` (DEBUG=DETAIL) now keeps Python backend objects alive, as `_register_backend` does.

BC: C++ code using `c10d::FakeProcessGroup` from the installed header breaks. `dist.*` calls on a fake group return a plain `Work` instead of `FakeWork`.

Depends on pytorch#202176 and pytorch#202194 (Python `Backend.Options` through `split_group`).

Test plan:

```
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_pybackend.py test/distributed/test_c10d_common.py test/dynamo/test_fake_distributed.py test/dynamo/test_fx_graph_runnable.py
python -m pytest test/dynamo/test_guard_serialization.py -k "Backend or unsupported_types_prune"
python -m pytest test/distributed/test_fake_backend_new_group.py test/distributed/_tools/test_fake_collectives.py
python -m pytest test/test_testing.py -k "test_circular_dependencies or no_warning_on_import"
lintrunner -a
```

Line changes: implementation +760/-828, tests (`test/`) +203/-10.

This PR was authored with the help of an AI assistant (Claude).

Pull Request resolved: pytorch#202141
Approved by: https://github.com/fduwjj, https://github.com/kapilsh
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ter_aot (pytorch#203096)

pytorch#202141 moved FakeProcessGroup/FakeStore to `torch.distributed._backends.fake`, leaving `torch/testing/_internal/distributed/fake_pg.py` as a compatibility shim. `after_aot.py` was its last user in `torch/` outside `torch/testing`. `setup_fake_process_groups` now imports from the new module; the `fake` backend is registered on demand by `init_process_group`, so the shim's import-time registration isn't needed. The `FakeStore` import emitted into generated repros is dropped: it has been unused since repros started calling `setup_fake_process_groups`, and dropping it rather than repointing it keeps generated repros runnable on released torch (2.11+), which lacks `torch.distributed._backends.fake`.

Test plan:

```
python -m pytest test/dynamo/test_fx_graph_runnable.py
lintrunner -a --skip CLANGTIDY torch/_dynamo/repro/after_aot.py
```

22 passed; the collective and multi-process-group tests run the generated repro in a fresh subprocess.

Line changes: implementation +1/-2, tests +0/-0.

This PR was authored with the help of an AI assistant (Claude).

Pull Request resolved: pytorch#203096
Approved by: https://github.com/pytorchgreenlight
twthighd added a commit to twthighd/pytorch that referenced this pull request Nov 23, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
twthighd added a commit to twthighd/pytorch that referenced this pull request Dec 3, 2026
…label classes

Summary:
- Split the mixed TestFakePG class: the fake-PG mechanism tests
  (copy semantics, requires_grad propagation, validation errors,
  dispatch tracing) stay in TestFakePG labeled GENERIC, while the
  nine accelerator-path tests (FSDP/TP e2e, functional-collectives
  tracing, split_group) move to a new TestFakePGDevice labeled
  ACCELERATOR.
- TestFakePGDevice is instantiated via instantiate_device_type_tests
  with allow_xpu=True, and the moved methods take the injected device
  parameter instead of the module-level device_type = get_devtype().type
  (deleted).
- Gate the nine methods with the variant-aware @onlyAccelerator instead
  of excluding the CPU variant: the CPU variant is collected and skips
  cleanly on every host (the guard reads the running variant's
  device_type), so CPU-only machines report explicit skips instead of
  the class being invisible, while accelerator variants run unchanged.
  Same gating form as the landed pytorch#192712 and pytorch#191905. @skipIfHpu
  blacklist guards are kept.
- Rebase absorption: keep pytorch#202253's six compile-sync methods in the
  GENERIC TestFakePG (14 expanded cases, parametrizations and gloo
  availability guards intact; their config strings naming cuda/nccl do
  not exercise device-tensor paths) and pytorch#202141's whole-file adjustments
  (fake backend moved to a Python PyBackend, new GENERIC
  debug-wrapper/alias/split-options tests, updated assertion patterns);
  the unittest/unittest.mock imports the new tests use are kept.

This allows the accelerator-path tests to run on any out-of-tree
accelerator variant instead of being skipped wherever HAS_ACCELERATOR
is False, while the device-agnostic fake-PG mechanics stay in a
GENERIC class that runs everywhere.

Verified on an old-snapshot verify host (its C++ fake backend predates
the Python PyBackend move):
- The generated CPU class collects 15 cases, all skipped with the exact
  reason "onlyAccelerator: doesn't run on CPU or meta devices" (OK,
  0 errors).
- A whole-file run is not obtainable there: a newly absorbed GENERIC
  test crashes the old C++ fake backend.
- The PrivateUse1 variant fails there at the fake backend's
  device-type lookup (observed error).

Full-file validation on the rebased stack remains pending. GENERIC/CPU
and accelerator coverage will be checked in the corresponding CI jobs
where selected. PrivateUse1 execution additionally requires pytorch#202363 at
the new registration site, with the backend plugin loaded before fake
registration, and a compatible verification environment; ordinary
CPU/CUDA CI does not cover it.
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 GL/superseded GreenLight review is superseded by changes in progress PR is being worked on by the author, until the automated review accepts it Merged module: bc-breaking Related to a BC-breaking change module: dynamo release notes: distributed (c10d) release notes category topic: bc breaking topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants