Repository navigation
Conversation
[ghstack-poisoned]
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Reviewed commit: 🔗 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 JobAs of commit 5c5463f with merge base 19a83d8 ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: CANCELLED JOB - The following job was cancelled. Please retry:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
…ake with entry point; review fixes [ghstack-poisoned]
There was a problem hiding this comment.
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.
Withdrawn: the automated review of 9ef9bb2 found nothing blocking.
…oc; fake registration fallback [ghstack-poisoned]
|
Starting merge as part of PR stack under #202194 |
1 similar comment
|
Starting merge as part of PR stack under #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: #202194 Approved by: https://github.com/kapilsh ghstack dependencies: #202176
`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
`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
`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
`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
`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
`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
`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
…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
…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
…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
…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
…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
…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
Stack from ghstack (oldest at bottom):
ProcessGroup::splitGroupandmergeRemoteGroupclone the parent backend's options with the virtualBackend::Options::clone()before passing them to the backend. A Python subclass ofdist.BackendBase.Optionswas sliced to a plain C++Backend::Options, so the child backend received the base type without its Python attributes. Options returned from a PyBackendoptionsproperty 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
PyBackendOptionspybind trampoline forBackend.Optionswhoseclone()calls the Python object's__copy__, and givesBackend::OptionsaPyObjectSlot(the same patternBackenduses) so C++ references keep a Python subclass's object alive.Backend.Optionsgains__copy__/__deepcopy__: C++ options are copied viaclone(), and Python subclasses are copied likecopy.copy/copy.deepcopy(same type, subclass__init__not called, base fields copied via theBackend.Optionscopy constructor, instance__dict__and set__slots__copied;__getstate__/__setstate__are not used). I hookedclone()to__copy__rather than exposing an overridableclonemethod because__copy__is the standard Python protocol: subclasses customize one method, andcopy.copyandsplit_groupuse the same hook. A positional-onlyBackend.Options(other)copy constructor for the base fields is also added.clone()of a Python subclass raisesTypeErrorinstead of aliasing or slicing when__copy__returnsselfor an object that is not an instance of the original's type.copy.copy/copy.deepcopyofBackend.Options, its Python subclasses andProcessGroupGloo._Optionspreviously 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_Optionsstill 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_grouphandling of C++ options, including C++ subclasses withclone()(NCCL, Gloo, FakeProcessGroup), is unchanged.BC:
split_groupwith a PythonBackend.Optionssubclass 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); theirsplit_groupbehavior is unchanged, butBackend::Optionsgains a member, so they need a rebuild. Without their own__copy__,copy.copyof them now goes throughclone()and raisesTypeError("must return a new instance") instead of "cannot pickle" whenclone()is not overridden, and the inherited__copy__/__deepcopy__shadow any pickle orcopyregcopy hooks. A C++ holder of a PythonBackend.Optionssubclass must keep its Python object alive (options from theoptionsproperty are preserved automatically; options a C++ backend stores fromsplit_group(opts=...)orshrinkare not);clone()raises once it is gone, where it previously returned sliced base options. Python subclasses that copied through__reduce__,copyregor__getstate__/__setstate__now use the inherited__copy__/__deepcopy__and must override those instead.Test plan:
This PR was authored with the help of an AI assistant (Claude).