Mixed precision uses `torch.autocast("cuda")` for custom accelerators and `Accelerator` instances, silently running fp32
Bug description
_AcceleratorConnector._check_and_init_precision chooses the autocast device from the accelerator flag:
device = self._accelerator_flag if self._accelerator_flag in ("cpu", "mps") else "cuda"
return MixedPrecision(self._precision_flag, device)So with precision="bf16-mixed" (or "16-mixed"), any accelerator that isn't the exact string "cpu" or "mps" gets torch.autocast("cuda"), whatever device the model is on. That includes:
- accelerators registered by name through
AcceleratorRegistry(e.g. third-partyxpu/npuaccelerators) - any
Acceleratorpassed as an instance, including the built-inCPUAccelerator()
The model then trains in fp32 while Lightning logs "Using bfloat16 Automatic Mixed Precision (AMP)". Lightning itself doesn't warn. PyTorch prints "CUDA is not available … Disabling autocast" only when the machine has no CUDA; on a machine that also has an NVIDIA GPU there is no warning at all. With 16-mixed, the GradScaler is disabled as well.
Lightning Fabric has the same line in fabric/connector.py; there, Fabric(accelerator=CPUAccelerator(), precision="bf16-mixed") fails with RuntimeError: mat1 and mat2 must have the same dtype because inputs are cast to bf16 while autocast is off.
This is the general form of #14358 (fixed for the "mps" string only in #21209, and for Fabric in #20876).
What version are you seeing the problem on?
v2.1, v2.2, v2.3, v2.4, v2.5, v2.6, master (tested on 2.6.6; the line has been "cpu" if flag == "cpu" else "cuda" since 2.0.0, with "mps" added in 2.6.0)
How to reproduce the bug
Runs on any machine, no special hardware needed:
import torch
import lightning.pytorch as pl
from lightning.pytorch.accelerators import AcceleratorRegistry, CPUAccelerator
class MyCPU(CPUAccelerator):
"""Stand-in for any third-party accelerator (xpu, npu, ...) registered by name."""
@classmethod
def register_accelerators(cls, registry):
registry.register("mycpu", cls)
MyCPU.register_accelerators(AcceleratorRegistry)
class M(pl.LightningModule):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(8, 8)
def predict_step(self, batch):
return self.layer(batch).dtype
data = torch.utils.data.DataLoader(torch.randn(4, 8), batch_size=4)
for accelerator in ["cpu", CPUAccelerator(), "mycpu"]:
trainer = pl.Trainer(accelerator=accelerator, devices=1, precision="bf16-mixed",
logger=False, enable_progress_bar=False, enable_model_summary=False)
dtype = trainer.predict(M(), data)[0]
label = accelerator if isinstance(accelerator, str) else f"{type(accelerator).__name__}()"
print(f"accelerator={label!r:<18} autocast device={trainer.precision_plugin.device!r:<7} output dtype={dtype}")Error messages and logs
accelerator='cpu' autocast device='cpu' output dtype=torch.bfloat16
accelerator='CPUAccelerator()' autocast device='cuda' output dtype=torch.float32
accelerator='mycpu' autocast device='cuda' output dtype=torch.float32(Same output with CUDA_VISIBLE_DEVICES="", plus PyTorch's "CUDA is not available or torch_xla is imported. Disabling autocast." warning.)
Environment
Current environment#- PyTorch Lightning Version: 2.6.6 (lightning package; also pytorch_lightning 2.6.6)
#- PyTorch Version: 2.14.0+cu130 (also 2.14.0+xpu on an Intel Arc Pro B70)
#- Python version: 3.12.14
#- OS: Linux (Debian/Ubuntu, x86_64)
#- CUDA/cuDNN version: CUDA 13.0
#- GPU models and configuration: RTX 3060 (repro above); Intel Arc Pro B70 (xpu cases)
#- How you installed Lightning: pipMore info
Real-world impact. Intel GPUs (torch.xpu) have no built-in Lightning accelerator, so projects register their own and hit this. Measured on an Arc Pro B70 with OpenFold-3's Intel GPU PR (aqlaboratory/openfold-3#415, its own initial_training.yml with precision: bf16-mixed): training ran entirely in fp32 (0 of 15,529 nn.Linear calls in bf16, vs 4,189 on an NVIDIA GPU with the same code). With the autocast device fixed, a training step at the config's 384-token crop went from 23.8 s / 26.1 GiB to 17.0 s / 22.5 GiB. Details in that PR's comments. Several projects already patch around this downstream (e.g. mir-group/nequip, RosettaCommons/foundry, open-edge-platform/geti), and I hit it adding Intel GPU support to Boltz (Novel-Therapeutics/boltz-community#20).
Related: #10821 (closed 2023) set out to replace name/enum checks with isinstance checks so custom accelerators and plugins work; this device choice looks like one that was missed. #20349 (open PR adding device-type plumbing for third-party backends; per its diff it derives the device only for accelerator instances), #20938 (Intel GPU support), #21815 (FSDPPrecision hardcodes "cuda").
Possible fix. Take the autocast device from the device the strategy actually runs on rather than from the flag, e.g. self.strategy.root_device.type once the accelerator and strategy are resolved, falling back to the current behaviour where that isn't available. Failing that, a warning when the autocast device doesn't match the model's device would at least make it visible. Happy to open a PR with a test if you'd like either approach.
I used Claude to help investigate this; I've reproduced and checked the results myself.
Source: Lightning-AI/pytorch-lightning