Skip to content

[c10d] Preserve Python Backend.Options subclasses across split_group - #202176

Closed
d4l3k wants to merge 3 commits into
gh/d4l3k/300/basefrom
gh/d4l3k/300/head
Closed

d4l3k wants to merge 3 commits into
gh/d4l3k/300/basefrom
gh/d4l3k/300/head

Conversation

@d4l3k

@d4l3k d4l3k commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Stack from ghstack (oldest at bottom):

ProcessGroup::splitGroup and mergeRemoteGroup clone the parent backend's options with the virtual Backend::Options::clone() before passing them to the backend. A Python subclass of dist.BackendBase.Options was sliced to a plain C++ Backend::Options, so the child backend received the base type without its Python attributes. Options returned from a PyBackend options property were also referenced only from C++, so their Python attributes were lost once the Python wrapper died. Backends with custom options (e.g. FakeProcessGroup) therefore had to keep their options as C++ structs.

The fix adds a PyBackendOptions pybind trampoline for Backend.Options whose clone() calls the Python object's __copy__, and gives Backend::Options a PyObjectSlot (the same pattern Backend uses) so C++ references keep a Python subclass's object alive. Backend.Options gains __copy__/__deepcopy__: C++ options are copied via clone(), and Python subclasses are copied like copy.copy/copy.deepcopy (same type, subclass __init__ not called, base fields copied via the Backend.Options copy constructor, instance __dict__ and set __slots__ copied; __getstate__/__setstate__ are not used). I hooked clone() to __copy__ rather than exposing an overridable clone method because __copy__ is the standard Python protocol: subclasses customize one method, and copy.copy and split_group use the same hook. A positional-only Backend.Options(other) copy constructor for the base fields is also added.

clone() of a Python subclass raises TypeError instead of aliasing or slicing when __copy__ returns self or an object that is not an instance of the original's type. copy.copy/copy.deepcopy of Backend.Options, its Python subclasses and ProcessGroupGloo._Options previously raised "cannot pickle" (unless a subclass defined its own copy or pickle hooks) and now work. The base __copy__/__deepcopy__ apply the same check, so Python subclasses of Gloo _Options still raise (now "must return a new instance") rather than being sliced; NCCL and FakeProcessGroup options keep their existing __copy__. Python subclasses of other backends' options classes are not supported. split_group handling of C++ options, including C++ subclasses with clone() (NCCL, Gloo, FakeProcessGroup), is unchanged.

BC: split_group with a Python Backend.Options subclass previously succeeded with sliced base options; it now calls the subclass's __copy__ and raises if that fails or returns an invalid copy. I found no out-of-tree Python subclasses. C++ subclasses exist out of tree (e.g. torch_npu HCCL, XCCL, torch_musa, torchcomms); their split_group behavior is unchanged, but Backend::Options gains a member, so they need a rebuild. Without their own __copy__, copy.copy of them now goes through clone() and raises TypeError ("must return a new instance") instead of "cannot pickle" when clone() is not overridden, and the inherited __copy__/__deepcopy__ shadow any pickle or copyreg copy hooks. A C++ holder of a Python Backend.Options subclass must keep its Python object alive (options from the options property are preserved automatically; options a C++ backend stores from split_group(opts=...) or shrink are not); clone() raises once it is gone, where it previously returned sliced base options. Python subclasses that copied through __reduce__, copyreg or __getstate__/__setstate__ now use the inherited __copy__/__deepcopy__ and must override those instead.

Test plan:

python -m pytest test/distributed/test_c10d_pybackend.py
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_common.py
lintrunner -a

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR adds a `PyBackendOptions` trampoline, a `PyObjectSlot` on
`Backend::Options`, and `__copy__`/`__deepcopy__`/copy-constructor bindings, so
Python subclasses of `Backend.Options` keep their type and Python attributes
through `split_group` and `merge_remote_group`. Both findings from the previous
review are fixed at HEAD and no new issues were found. Recommendation: Approve.

Reviewed commit: 9ef9bb2 (NOT the current head 5c5463f)

Review run

🔗 Helpful Links

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

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

❌ 1 Cancelled Job

As of commit 5c5463f with merge base 19a83d8 (image):

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

  • Triviality
    • New PyBackendOptions trampoline in PyBackend.hpp makes clone() call Python __copy__ and preserve the Python object via PyObjectPreservation
    • New copyBackendOptions in init.cpp adds __copy__/__deepcopy__ and a copy constructor to public Backend.Options
    • Lifetime and refcount logic through pyobj_slot_ and CopyResetPyObjectSlot in Backend.hpp is a design a human should review
  • Socialization
    • Backend::Options gains a pyobj_slot_ member, so out-of-tree C++ backends must rebuild
    • split_group with a Python Backend.Options subclass now calls __copy__ and can raise TypeError where it used to return sliced options
  • Breaking behavior
    • Inherited __copy__/__deepcopy__ now take precedence over pickle and copyreg copy hooks on subclasses, which changes copy.copy results for existing users

reason: not_trivial
Reviewed commit: 9ef9bb2 (NOT the current head 5c5463f)

Inference job

🐛 Report a wrong verdict

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

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

@pytorch-bot pytorch-bot Bot added the release notes: distributed (c10d) release notes category label Oct 27, 2026
@d4l3k
d4l3k marked this pull request as ready for review October 27, 2026 01:48
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 27, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 27, 2026
github-actions[bot]

This comment was marked as outdated.

…ake with entry point; review fixes

[ghstack-poisoned]

@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 9ef9bb2: nothing blocking; ready for human review.

This PR adds a PyBackendOptions trampoline, a PyObjectSlot on Backend::Options, and __copy__/__deepcopy__/copy-constructor bindings, so Python subclasses of Backend.Options keep their type and Python attributes through split_group and merge_remote_group. Both findings from the previous review are fixed at HEAD and no new issues were found. Recommendation: Approve.

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

@github-actions
github-actions Bot dismissed their stale review October 27, 2026 05:51

Withdrawn: the automated review of 9ef9bb2 found nothing blocking.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 27, 2026
…oc; fake registration fallback

[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Oct 27, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #202194

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #202194

pytorchmergebot pushed a commit that referenced this pull request Oct 29, 2026
)

`ProcessGroup::splitGroup` and `mergeRemoteGroup` dereference `Backend::getBackendOptions()`. For a Python backend that comes from its `options` property, and when that returns None (no backend-specific options) `castAndPreserve` yields a null pointer and `split_group` / `merge_remote_group` crash. C++ backends with nullable options, like the C++ FakeProcessGroup, avoid this by returning fresh default options from `getBackendOptions` while their Python `.options` stays None; test_device_mesh relies on that None to tell whether an options override was supplied.

`PyBackend::getBackendOptions` now returns default `Backend::Options` named after the backend when the Python `options` property returns None, so Python backends can keep the same nullable `.options` contract. This is needed by the next PR, which moves FakeProcessGroup to Python. The alternative of making FakeProcessGroup's `.options` always non-None would change its observable behavior.

Test plan:

```
python -m pytest test/distributed/test_c10d_pybackend.py
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).
Pull Request resolved: #202194
Approved by: https://github.com/kapilsh
ghstack dependencies: #202176
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
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 +757/-828, tests (`test/`) +294/-8.

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

ghstack-source-id: 763d965
Pull-Request: #202141
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 +757/-828, tests (`test/`) +289/-8.

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

ghstack-source-id: 0127eb6
Pull-Request: #202141
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 +757/-828, tests (`test/`) +289/-8.

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

ghstack-source-id: fac4d96
Pull-Request: #202141
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/`) +294/-8.

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

ghstack-source-id: 19b3c66
Pull-Request: #202141
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
pytorchmergebot pushed a commit that referenced this pull request Oct 30, 2026
`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).

Pull Request resolved: #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
…ytorch#202176)

`ProcessGroup::splitGroup` and `mergeRemoteGroup` clone the parent backend's options with the virtual `Backend::Options::clone()` before passing them to the backend. A Python subclass of `dist.BackendBase.Options` was sliced to a plain C++ `Backend::Options`, so the child backend received the base type without its Python attributes. Options returned from a PyBackend `options` property were also referenced only from C++, so their Python attributes were lost once the Python wrapper died. Backends with custom options (e.g. `FakeProcessGroup`) therefore had to keep their options as C++ structs.

The fix adds a `PyBackendOptions` pybind trampoline for `Backend.Options` whose `clone()` calls the Python object's `__copy__`, and gives `Backend::Options` a `PyObjectSlot` (the same pattern `Backend` uses) so C++ references keep a Python subclass's object alive. `Backend.Options` gains `__copy__`/`__deepcopy__`: C++ options are copied via `clone()`, and Python subclasses are copied like `copy.copy`/`copy.deepcopy` (same type, subclass `__init__` not called, base fields copied via the `Backend.Options` copy constructor, instance `__dict__` and set `__slots__` copied; `__getstate__`/`__setstate__` are not used). I hooked `clone()` to `__copy__` rather than exposing an overridable `clone` method because `__copy__` is the standard Python protocol: subclasses customize one method, and `copy.copy` and `split_group` use the same hook. A positional-only `Backend.Options(other)` copy constructor for the base fields is also added.

`clone()` of a Python subclass raises `TypeError` instead of aliasing or slicing when `__copy__` returns `self` or an object that is not an instance of the original's type. `copy.copy`/`copy.deepcopy` of `Backend.Options`, its Python subclasses and `ProcessGroupGloo._Options` previously raised "cannot pickle" (unless a subclass defined its own copy or pickle hooks) and now work. The base `__copy__`/`__deepcopy__` apply the same check, so Python subclasses of Gloo `_Options` still raise (now "must return a new instance") rather than being sliced; NCCL and FakeProcessGroup options keep their existing `__copy__`. Python subclasses of other backends' options classes are not supported. `split_group` handling of C++ options, including C++ subclasses with `clone()` (NCCL, Gloo, FakeProcessGroup), is unchanged.

BC: `split_group` with a Python `Backend.Options` subclass previously succeeded with sliced base options; it now calls the subclass's `__copy__` and raises if that fails or returns an invalid copy. I found no out-of-tree Python subclasses. C++ subclasses exist out of tree (e.g. torch_npu HCCL, XCCL, torch_musa, torchcomms); their `split_group` behavior is unchanged, but `Backend::Options` gains a member, so they need a rebuild. Without their own `__copy__`, `copy.copy` of them now goes through `clone()` and raises `TypeError` ("must return a new instance") instead of "cannot pickle" when `clone()` is not overridden, and the inherited `__copy__`/`__deepcopy__` shadow any pickle or `copyreg` copy hooks. A C++ holder of a Python `Backend.Options` subclass must keep its Python object alive (options from the `options` property are preserved automatically; options a C++ backend stores from `split_group(opts=...)` or `shrink` are not); `clone()` raises once it is gone, where it previously returned sliced base options. Python subclasses that copied through `__reduce__`, `copyreg` or `__getstate__`/`__setstate__` now use the inherited `__copy__`/`__deepcopy__` and must override those instead.

Test plan:

```
python -m pytest test/distributed/test_c10d_pybackend.py
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_common.py
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#202176
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
…rch#202194)

`ProcessGroup::splitGroup` and `mergeRemoteGroup` dereference `Backend::getBackendOptions()`. For a Python backend that comes from its `options` property, and when that returns None (no backend-specific options) `castAndPreserve` yields a null pointer and `split_group` / `merge_remote_group` crash. C++ backends with nullable options, like the C++ FakeProcessGroup, avoid this by returning fresh default options from `getBackendOptions` while their Python `.options` stays None; test_device_mesh relies on that None to tell whether an options override was supplied.

`PyBackend::getBackendOptions` now returns default `Backend::Options` named after the backend when the Python `options` property returns None, so Python backends can keep the same nullable `.options` contract. This is needed by the next PR, which moves FakeProcessGroup to Python. The alternative of making FakeProcessGroup's `.options` always non-None would change its observable behavior.

Test plan:

```
python -m pytest test/distributed/test_c10d_pybackend.py
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#202194
Approved by: https://github.com/kapilsh
ghstack dependencies: pytorch#202176
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 9, 2026
…ytorch#202176)

`ProcessGroup::splitGroup` and `mergeRemoteGroup` clone the parent backend's options with the virtual `Backend::Options::clone()` before passing them to the backend. A Python subclass of `dist.BackendBase.Options` was sliced to a plain C++ `Backend::Options`, so the child backend received the base type without its Python attributes. Options returned from a PyBackend `options` property were also referenced only from C++, so their Python attributes were lost once the Python wrapper died. Backends with custom options (e.g. `FakeProcessGroup`) therefore had to keep their options as C++ structs.

The fix adds a `PyBackendOptions` pybind trampoline for `Backend.Options` whose `clone()` calls the Python object's `__copy__`, and gives `Backend::Options` a `PyObjectSlot` (the same pattern `Backend` uses) so C++ references keep a Python subclass's object alive. `Backend.Options` gains `__copy__`/`__deepcopy__`: C++ options are copied via `clone()`, and Python subclasses are copied like `copy.copy`/`copy.deepcopy` (same type, subclass `__init__` not called, base fields copied via the `Backend.Options` copy constructor, instance `__dict__` and set `__slots__` copied; `__getstate__`/`__setstate__` are not used). I hooked `clone()` to `__copy__` rather than exposing an overridable `clone` method because `__copy__` is the standard Python protocol: subclasses customize one method, and `copy.copy` and `split_group` use the same hook. A positional-only `Backend.Options(other)` copy constructor for the base fields is also added.

`clone()` of a Python subclass raises `TypeError` instead of aliasing or slicing when `__copy__` returns `self` or an object that is not an instance of the original's type. `copy.copy`/`copy.deepcopy` of `Backend.Options`, its Python subclasses and `ProcessGroupGloo._Options` previously raised "cannot pickle" (unless a subclass defined its own copy or pickle hooks) and now work. The base `__copy__`/`__deepcopy__` apply the same check, so Python subclasses of Gloo `_Options` still raise (now "must return a new instance") rather than being sliced; NCCL and FakeProcessGroup options keep their existing `__copy__`. Python subclasses of other backends' options classes are not supported. `split_group` handling of C++ options, including C++ subclasses with `clone()` (NCCL, Gloo, FakeProcessGroup), is unchanged.

BC: `split_group` with a Python `Backend.Options` subclass previously succeeded with sliced base options; it now calls the subclass's `__copy__` and raises if that fails or returns an invalid copy. I found no out-of-tree Python subclasses. C++ subclasses exist out of tree (e.g. torch_npu HCCL, XCCL, torch_musa, torchcomms); their `split_group` behavior is unchanged, but `Backend::Options` gains a member, so they need a rebuild. Without their own `__copy__`, `copy.copy` of them now goes through `clone()` and raises `TypeError` ("must return a new instance") instead of "cannot pickle" when `clone()` is not overridden, and the inherited `__copy__`/`__deepcopy__` shadow any pickle or `copyreg` copy hooks. A C++ holder of a Python `Backend.Options` subclass must keep its Python object alive (options from the `options` property are preserved automatically; options a C++ backend stores from `split_group(opts=...)` or `shrink` are not); `clone()` raises once it is gone, where it previously returned sliced base options. Python subclasses that copied through `__reduce__`, `copyreg` or `__getstate__`/`__setstate__` now use the inherited `__copy__`/`__deepcopy__` and must override those instead.

Test plan:

```
python -m pytest test/distributed/test_c10d_pybackend.py
python -m pytest test/distributed/test_fake_pg.py test/distributed/test_device_mesh.py test/distributed/test_c10d_common.py
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#202176
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
…rch#202194)

`ProcessGroup::splitGroup` and `mergeRemoteGroup` dereference `Backend::getBackendOptions()`. For a Python backend that comes from its `options` property, and when that returns None (no backend-specific options) `castAndPreserve` yields a null pointer and `split_group` / `merge_remote_group` crash. C++ backends with nullable options, like the C++ FakeProcessGroup, avoid this by returning fresh default options from `getBackendOptions` while their Python `.options` stays None; test_device_mesh relies on that None to tell whether an options override was supplied.

`PyBackend::getBackendOptions` now returns default `Backend::Options` named after the backend when the Python `options` property returns None, so Python backends can keep the same nullable `.options` contract. This is needed by the next PR, which moves FakeProcessGroup to Python. The alternative of making FakeProcessGroup's `.options` always non-None would change its observable behavior.

Test plan:

```
python -m pytest test/distributed/test_c10d_pybackend.py
lintrunner -a
```

This PR was authored with the help of an AI assistant (Claude).
Pull Request resolved: pytorch#202194
Approved by: https://github.com/kapilsh
ghstack dependencies: pytorch#202176
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants