|
| 1 | +# Copyright 2026 The HuggingFace Team. All rights reserved. |
| 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 | +""" |
| 15 | +GPU calls that are device-agnostic. |
| 16 | +""" |
| 17 | + |
| 18 | +try: |
| 19 | + import torch |
| 20 | +except Exception: |
| 21 | + torch = None |
| 22 | + |
| 23 | + |
| 24 | +class AgnosticGPU: |
| 25 | + @staticmethod |
| 26 | + def configure() -> "AgnosticGPU": |
| 27 | + return ( |
| 28 | + NoGPU() |
| 29 | + if torch is None |
| 30 | + else CUDAGPU() |
| 31 | + if torch.cuda.is_available() |
| 32 | + else XPUGPU() |
| 33 | + if (hasattr(torch, "xpu") and torch.xpu.is_available()) |
| 34 | + else MPSGPU() |
| 35 | + if (hasattr(torch.backends, "mps") and torch.backends.mps.is_available()) |
| 36 | + else NoGPU() |
| 37 | + ) |
| 38 | + |
| 39 | + name: str |
| 40 | + |
| 41 | + def is_accelerator_available(self) -> bool: |
| 42 | + return False |
| 43 | + |
| 44 | + def current_device(self) -> int: |
| 45 | + return 0 |
| 46 | + |
| 47 | + def device_count(self) -> int: |
| 48 | + return 0 |
| 49 | + |
| 50 | + |
| 51 | +class CUDAGPU(AgnosticGPU): |
| 52 | + def __init__(self): |
| 53 | + assert torch is not None |
| 54 | + self.name = "cuda" |
| 55 | + self.is_accelerator_available = torch.cuda.is_available |
| 56 | + self.current_device = torch.cuda.current_device |
| 57 | + self.device_count = torch.cuda.device_count |
| 58 | + |
| 59 | + |
| 60 | +class XPUGPU(AgnosticGPU): |
| 61 | + def __init__(self): |
| 62 | + assert torch is not None |
| 63 | + self.name = "xpu" |
| 64 | + self.is_accelerator_available = torch.xpu.is_available |
| 65 | + self.current_device = torch.xpu.current_device |
| 66 | + self.device_count = torch.xpu.device_count |
| 67 | + |
| 68 | + |
| 69 | +class MPSGPU(AgnosticGPU): |
| 70 | + def __init__(self): |
| 71 | + assert torch is not None |
| 72 | + self.name = "mps" |
| 73 | + self.is_accelerator_available = torch.mps.is_available |
| 74 | + # self.current_device = torch.mps.current_device |
| 75 | + self.device_count = torch.mps.device_count |
| 76 | + |
| 77 | + |
| 78 | +class NoGPU(AgnosticGPU): |
| 79 | + def __init__(self) -> None: |
| 80 | + self.name = "cpu" |
| 81 | + |
| 82 | + |
| 83 | +gpu = AgnosticGPU.configure() |
0 commit comments