Lightning-AI/pytorch-lightning · error · ModuleNotFoundError

{str(_XLA_AVAILABLE)}

Error message

{str(_XLA_AVAILABLE)}

What it means

SingleXLAStrategy.__init__ checks the _XLA_AVAILABLE flag (a ModuleNotFoundError captured at import time) and re-raises it when torch_xla is not installed. Using any XLA strategy requires the torch_xla package.

Source

Thrown at src/lightning/fabric/strategies/single_xla.py:39

from lightning.fabric.plugins import CheckpointIO, Precision, XLAPrecision
from lightning.fabric.plugins.io.xla import XLACheckpointIO
from lightning.fabric.strategies import _StrategyRegistry
from lightning.fabric.strategies.single_device import SingleDeviceStrategy
from lightning.fabric.utilities.types import _DEVICE


class SingleDeviceXLAStrategy(SingleDeviceStrategy):
    """Strategy for training on a single XLA device."""

    def __init__(
        self,
        device: _DEVICE,
        accelerator: Optional[Accelerator] = None,
        checkpoint_io: Optional[XLACheckpointIO] = None,
        precision: Optional[XLAPrecision] = None,
    ):
        if not _XLA_AVAILABLE:
            raise ModuleNotFoundError(str(_XLA_AVAILABLE))
        if isinstance(device, torch.device):
            # unwrap the `torch.device` in favor of `xla_device`
            device = device.index

        import torch_xla.core.xla_model as xm

        super().__init__(
            accelerator=accelerator,
            device=xm.xla_device(device),
            checkpoint_io=checkpoint_io,
            precision=precision,
        )

    @property
    @override
    def checkpoint_io(self) -> XLACheckpointIO:
        plugin = self._checkpoint_io
        if plugin is not None:

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. pip install lightning[xla] (or install a torch_xla build matching your torch version)
  2. Verify import: python -c 'import torch_xla' and resolve any reported dependency errors
  3. If TPUs were not intended, switch strategy/accelerator (e.g. single-device or DDP on GPU)

Example fix

# before
strategy = SingleXLAStrategy(device='xla:0')  # ModuleNotFoundError: No module named 'torch_xla'
# after (shell)
# pip install lightning[xla]
strategy = SingleXLAStrategy(device='xla:0')
Defensive patterns

Strategy: validation

Validate before calling

try:
    import torch_xla  # noqa: F401
    xla_ok = True
except ImportError:
    xla_ok = False
assert xla_ok, 'torch_xla required for XLA strategies; pip install lightning[xla]'

Type guard

def xla_available() -> bool:
    try:
        import torch_xla  # noqa: F401
        return True
    except ImportError:
        return False

Prevention

When it happens

Trigger: Instantiating SingleXLAStrategy (or XLA parallel variants, or Fabric(accelerator='tpu', ...)) in an environment without torch_xla installed; the captured import error message is surfaced verbatim.

Common situations: Running TPU/colab workflows in a CPU/GPU environment; missing or version-mismatched torch_xla installation; wrong environment/conda env activated.

Understand the failure class

Background: "X is not installed. Please install it with pip install Y": missing optional dependency errors — ImportError/ValueError raised when a library's optional extra was never installed — this error's family across 22 libraries.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/d5a753c6b4987430. Report an issue: GitHub.