|
| 1 | +# Copyright The Lightning AI team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from contextlib import nullcontext |
| 15 | +from typing import Any, Dict, List, Optional, Union |
| 16 | + |
| 17 | +import torch |
| 18 | +from typing_extensions import override |
| 19 | + |
| 20 | +from lightning.fabric.accelerators import _AcceleratorRegistry |
| 21 | +from lightning.fabric.utilities.types import _DEVICE |
| 22 | +from lightning.pytorch.accelerators.accelerator import Accelerator |
| 23 | +from lightning.pytorch.utilities.exceptions import MisconfigurationException |
| 24 | + |
| 25 | + |
| 26 | +class NPUAccelerator(Accelerator): |
| 27 | + """Accelerator for Ascend NPU devices.""" |
| 28 | + |
| 29 | + @override |
| 30 | + def setup_device(self, device: torch.device) -> None: |
| 31 | + """ |
| 32 | + Raises: |
| 33 | + MisconfigurationException: |
| 34 | + If the selected device is not NPU. |
| 35 | + """ |
| 36 | + if device.type != "npu": |
| 37 | + raise MisconfigurationException(f"Device should be NPU, got {device} instead.") |
| 38 | + torch.npu.set_device(device) |
| 39 | + |
| 40 | + @override |
| 41 | + def get_device_stats(self, device: _DEVICE) -> Dict[str, Any]: |
| 42 | + return torch.npu.memory_stats(device) |
| 43 | + |
| 44 | + @override |
| 45 | + def teardown(self) -> None: |
| 46 | + torch.npu.empty_cache() |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + @override |
| 50 | + def parse_devices(devices: Union[int, str, List[int]]) -> Optional[List[int]]: |
| 51 | + """Accelerator device parsing logic. |
| 52 | +
|
| 53 | + -1 or '-1' means use all npus. |
| 54 | +
|
| 55 | + """ |
| 56 | + |
| 57 | + if isinstance(devices, list): |
| 58 | + return devices |
| 59 | + if isinstance(devices, str): |
| 60 | + if devices == "-1": |
| 61 | + return list(range(torch.npu.device_count())) |
| 62 | + if "," in devices: |
| 63 | + return [int(x.strip()) for x in devices.split(",") if len(x) > 0] |
| 64 | + return list(range(int(devices.strip()))) |
| 65 | + if isinstance(devices, int): |
| 66 | + if devices == -1: |
| 67 | + return list(range(torch.npu.device_count())) |
| 68 | + return list(range(devices)) |
| 69 | + |
| 70 | + return None |
| 71 | + |
| 72 | + @staticmethod |
| 73 | + @override |
| 74 | + def get_parallel_devices(devices: List[int]) -> List[torch.device]: |
| 75 | + """Gets parallel devices for the Accelerator.""" |
| 76 | + |
| 77 | + return [torch.device("npu", i) for i in devices] |
| 78 | + |
| 79 | + @staticmethod |
| 80 | + @override |
| 81 | + def auto_device_count() -> int: |
| 82 | + """Get the devices when set to auto.""" |
| 83 | + |
| 84 | + return torch.npu.device_count() |
| 85 | + |
| 86 | + @staticmethod |
| 87 | + @override |
| 88 | + def is_available() -> bool: |
| 89 | + try: |
| 90 | + import torch_npu # noqa: F401 |
| 91 | + |
| 92 | + return torch.npu.device_count() > 0 |
| 93 | + except ImportError: |
| 94 | + # NPU may raise these exceptions if it's not properly configured. |
| 95 | + return False |
| 96 | + |
| 97 | + @override |
| 98 | + def get_distribute_name(self) -> str: |
| 99 | + return "hccl" |
| 100 | + |
| 101 | + @override |
| 102 | + def get_stream_context(self, device_id: List[int]) -> Any: |
| 103 | + return torch.npu.stream(torch.npu.Stream()) if device_id is not None else nullcontext() |
| 104 | + |
| 105 | + @classmethod |
| 106 | + @override |
| 107 | + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: |
| 108 | + accelerator_registry.register( |
| 109 | + "npu", |
| 110 | + cls, |
| 111 | + description=cls.__name__, |
| 112 | + ) |
0 commit comments