← Back to Pull requests

Support importing xFormers on PyTorch builds without distributed support #1403

Closed
unknown closed this pull request without merging on Aug 07, 2026 12:33 UTC
View on GitHub
unknown unknown commented on Aug 05, 2026 15:59 UTC
Author

What does this PR do?

Fixes #1378.

Makes xFormers importable on PyTorch builds that were compiled without distributed support, so torch.distributed.is_available() is False. This is the case for the official NVIDIA PyTorch containers for Jetson iGPU devices, for example nvcr.io/nvidia/pytorch:25.03-py3-igpu. Today import xformers.ops dies with an AttributeError on such a build, which takes the whole program down even for users who only want memory-efficient attention.

The crash

When PyTorch is built without distributed support, torch/distributed/__init__.py skips its whole if is_available(): block and defines only two stubs. torch.distributed.Work, torch.distributed.ReduceOp and the submodules that wrap the C++ bindings do not exist.

Repro, which also runs on a normal machine because it just removes the attribute that a real no-distributed build never has:

$ python -c "
import torch, torch.distributed
del torch.distributed.Work
import xformers.ops
"
Traceback (most recent call last):
  File "<string>", line 4, in <module>
  File ".../xformers/ops/__init__.py", line 29, in <module>
    from .modpar_layers import ColumnParallelLinear, RowParallelLinear
  File ".../xformers/ops/modpar_layers.py", line 11, in <module>
    from .differentiable_collectives import (
  File ".../xformers/ops/differentiable_collectives.py", line 27, in <module>
    ) -> Tuple[torch.Tensor, Optional[torch.distributed.Work]]:
                                      ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'torch.distributed' has no attribute 'Work'. Did you mean: '_Work'?

That is the exact traceback from the issue.

Blast radius, and why one line is not enough

Four modules under xformers/ops/ touch torch.distributed at import time, and all four are pulled in by xformers/ops/__init__.py:

1. differentiable_collectives.py annotates signatures with torch.distributed.ProcessGroup and Optional[torch.distributed.Work]. On Python older than 3.14 those annotations are evaluated while the function is being defined, so the module cannot even be created. This is the reported failure.
2. modpar_layers.py has the same problem with torch.distributed.ProcessGroup. It is the module that imports differentiable_collectives, so it is next in line.
3. seqpar.py does from torch.distributed.distributed_c10d import _resolve_process_group, GroupName at module level. distributed_c10d starts with from torch._C._distributed_c10d import ..., a C extension that is not built at all, so this is a hard ModuleNotFoundError that no annotation change can defer. On top of that, GroupName appears in torch.library.custom_op signatures, whose schemas are inferred eagerly at decoration time, so the name genuinely has to exist at import time.
4. sequence_parallel_fused_ops.py does from torch.distributed._symmetric_memory import get_symm_mem_workspace, which also reaches into torch._C._distributed_c10d, and it annotates its custom_op signatures with dist.distributed_c10d.GroupName.

Fixing only item 1 moves the crash to item 3 rather than resolving it. I verified this by simulating a no-distributed PyTorch with just the annotation fix in place: the next failure is seqpar.py line 10.

The fix

Two parts.

Lazy annotations, which is the fix suggested in the issue. differentiable_collectives.py and modpar_layers.py get from __future__ import annotations, so their annotations are stored as strings (PEP 563) and evaluating torch.distributed.Work no longer happens at import. Nothing in either module needs annotations resolved at runtime: there is no dataclass field resolution, no pydantic, no typing.get_type_hints call, and no torch.library.custom_op decorator. Behavior when distributed is available is unchanged, and typing.get_type_hints still resolves the same types:

resolved hints: {'input_': <class 'torch.Tensor'>,
                 'process_group': <class 'torch.distributed.distributed_c10d.ProcessGroup'>,
                 'return': typing.Tuple[torch.Tensor, typing.Optional[torch.distributed.distributed_c10d.Work]]}

Skipping the ops that cannot exist. xformers/ops/__init__.py now guards the model-parallel and sequence-parallel imports with if _HAS_TORCH_DISTRIBUTED := torch.distributed.is_available():. These ops need NCCL collectives and symmetric memory, so they are unusable on such a build no matter what, and their modules cannot be imported at all for the reasons above. This mirrors the _HAS_MSLK pattern already used a few lines higher in the same file for the fmha and rope_padded ops, including the fact that the conditionally imported names stay listed in __all__. It also matches what the issue asks for: unavailable operators degrade to "not available" and partial usage keeps working.

I deliberately did not touch seqpar.py or sequence_parallel_fused_ops.py. Making them importable would mean stubbing GroupName and _resolve_process_group so that their custom_op registrations still succeed, which is more code and more risk for ops that can never run there anyway.

Tests

tests/test_import_without_torch_distributed.py spawns a child interpreter with sys.executable, makes torch.distributed look like a build without distributed support before xFormers is imported for the first time, then imports the target module and asserts the child exits cleanly. The simulation mirrors what PyTorch itself does when is_available() is False: is_available returns False, the availability-gated attributes are removed, GroupName and ProcessGroup are replaced by stubs, and torch._C._distributed_c10d, torch.distributed.distributed_c10d and torch.distributed._symmetric_memory are made unimportable by putting None in sys.modules. It is parametrized over xformers, xformers.ops and xformers.ops.differentiable_collectives, and skips cleanly if the child cannot set the simulation up.

Note that on Python 3.14 the annotation half of this bug is hidden by PEP 649, since annotations are lazy by default there. The test still catches the import failures on 3.14 because of the eager submodule imports, and it catches the original AttributeError on 3.9 through 3.13, which is where the reporter is (Python 3.12).

Fail before, pass after

Environment: macOS arm64, CPU-only, Python 3.12.12, torch 2.13.0 CPU wheel. The test only imports pure-Python modules, so the compiled extensions are not needed.

Base ref restored with git checkout upstream/main -- xformers/ops/__init__.py xformers/ops/differentiable_collectives.py xformers/ops/modpar_layers.py:

########## FAIL-BEFORE (upstream/main sources, python 3.12) ##########
E           File ".../xformers/ops/__init__.py", line 29, in <module>
E           File ".../xformers/ops/modpar_layers.py", line 11, in <module>
E           File ".../xformers/ops/differentiable_collectives.py", line 27, in <module>
E             ) -> Tuple[torch.Tensor, Optional[torch.distributed.Work]]:
E         AttributeError: module 'torch.distributed' has no attribute 'Work'. Did you mean: '_Work'?
E       assert 1 == 0
=========================== short test summary info ============================
FAILED tests/test_import_without_torch_distributed.py::test_import_without_torch_distributed[xformers.ops]
FAILED tests/test_import_without_torch_distributed.py::test_import_without_torch_distributed[xformers.ops.differentiable_collectives]
2 failed, 1 passed in 7.82s

Fix restored with git checkout HEAD -- <same files>:

########## PASS-AFTER (python 3.12) ##########
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0
collected 3 items

tests/test_import_without_torch_distributed.py::test_import_without_torch_distributed[xformers] PASSED [ 33%]
tests/test_import_without_torch_distributed.py::test_import_without_torch_distributed[xformers.ops] PASSED [ 66%]
tests/test_import_without_torch_distributed.py::test_import_without_torch_distributed[xformers.ops.differentiable_collectives] PASSED [100%]

============================== 3 passed in 5.97s ===============================

Same three tests also pass on Python 3.14.3.

No regression when distributed is available. Every name in xformers.ops.__all__ that resolved before still resolves, _HAS_TORCH_DISTRIBUTED is True, and ColumnParallelLinear, sequence_parallel_leading_matmul and fused_allgather_and_linear are all present. The existing suites that cover the touched modules still pass or skip as they did before, on CPU:

$ python -m pytest tests/test_seqpar.py tests/test_sequence_parallel_fused_ops.py \
    tests/test_unbind.py tests/test_attention_patterns.py \
    tests/test_import_without_torch_distributed.py -q
159 passed, 172 skipped, 1 warning in 5.46s

The skips are the CUDA-only and multi-GPU cases, which this machine cannot run.

pre-commit run --files ... passes on every changed file with the pinned hook versions from .pre-commit-config.yaml, ufmt 2.8.0 with black 26.3.1 and usort 1.0.8.post1, flake8 6.1.0, mypy 1.10.0.

Before submitting

  • Did you have fun?

  • Did you read the contributor guideline?

  • Was this discussed/approved via a Github issue? Yes, #1378.

  • Did you make sure to update the docs?

  • - [x] N/A, no documented behavior changes on builds that have distributed support.
  • Did you write any new necessary tests? Yes, tests/test_import_without_torch_distributed.py.

  • Did you update the changelog? Yes, a Fixed entry under 0.0.36.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: lw Review duration: 2674m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1403"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%