|
| 1 | +"""XPU Accelerator.""" |
| 2 | + |
| 3 | +# Copyright (C) 2025 Intel Corporation |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | + |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import torch |
| 9 | +from lightning.pytorch.accelerators import Accelerator, AcceleratorRegistry |
| 10 | + |
| 11 | + |
| 12 | +class XPUAccelerator(Accelerator): |
| 13 | + """Support for a XPU, optimized for large-scale machine learning.""" |
| 14 | + |
| 15 | + accelerator_name = "xpu" |
| 16 | + |
| 17 | + @staticmethod |
| 18 | + def setup_device(device: torch.device) -> None: |
| 19 | + """Sets up the specified device.""" |
| 20 | + if device.type != "xpu": |
| 21 | + msg = f"Device should be xpu, got {device} instead" |
| 22 | + raise RuntimeError(msg) |
| 23 | + |
| 24 | + torch.xpu.set_device(device) |
| 25 | + |
| 26 | + @staticmethod |
| 27 | + def parse_devices(devices: str | list | torch.device) -> list: |
| 28 | + """Parses devices for multi-GPU training.""" |
| 29 | + if isinstance(devices, list): |
| 30 | + return devices |
| 31 | + return [devices] |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def get_parallel_devices(devices: list) -> list[torch.device]: |
| 35 | + """Generates a list of parrallel devices.""" |
| 36 | + return [torch.device("xpu", idx) for idx in devices] |
| 37 | + |
| 38 | + @staticmethod |
| 39 | + def auto_device_count() -> int: |
| 40 | + """Returns number of XPU devices available.""" |
| 41 | + return torch.xpu.device_count() |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def is_available() -> bool: |
| 45 | + """Checks if XPU available.""" |
| 46 | + return hasattr(torch, "xpu") and torch.xpu.is_available() |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def get_device_stats(device: str | torch.device) -> dict[str, Any]: |
| 50 | + """Returns XPU devices stats.""" |
| 51 | + del device # Unused |
| 52 | + return {} |
| 53 | + |
| 54 | + def teardown(self) -> None: |
| 55 | + """Teardown the XPU accelerator. |
| 56 | +
|
| 57 | + This method is empty as it needs to be overridden otherwise the base class will throw an error. |
| 58 | + """ |
| 59 | + |
| 60 | + |
| 61 | +AcceleratorRegistry.register( |
| 62 | + XPUAccelerator.accelerator_name, |
| 63 | + XPUAccelerator, |
| 64 | + description="Accelerator supports XPU devices", |
| 65 | +) |
0 commit comments