-
Notifications
You must be signed in to change notification settings - Fork 618
/
Copy pathdevice_utils.py
166 lines (129 loc) · 4.34 KB
/
device_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# Copyright 2022-2023 XProbe Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import Dict, Literal, Union
import torch
DeviceType = Literal["cuda", "mps", "xpu", "npu", "cpu"]
DEVICE_TO_ENV_NAME = {
"cuda": "CUDA_VISIBLE_DEVICES",
"npu": "ASCEND_RT_VISIBLE_DEVICES",
}
def is_xpu_available() -> bool:
return hasattr(torch, "xpu") and torch.xpu.is_available()
def is_npu_available() -> bool:
try:
import torch
import torch_npu # noqa: F401
return torch.npu.is_available()
except ImportError:
return False
def get_available_device() -> DeviceType:
if torch.cuda.is_available():
return "cuda"
elif torch.backends.mps.is_available():
return "mps"
elif is_xpu_available():
return "xpu"
elif is_npu_available():
return "npu"
return "cpu"
def is_device_available(device: str) -> bool:
if device == "cuda":
return torch.cuda.is_available()
elif device == "mps":
return torch.backends.mps.is_available()
elif device == "xpu":
return is_xpu_available()
elif device == "npu":
return is_npu_available()
elif device == "cpu":
return True
return False
def move_model_to_available_device(model):
device = get_available_device()
if device == "cpu":
return model
return model.to(device)
def get_device_preferred_dtype(device: str) -> Union[torch.dtype, None]:
if device == "cpu":
return torch.float32
elif device == "cuda" or device == "mps" or device == "npu":
return torch.float16
elif device == "xpu":
return torch.bfloat16
return None
def is_hf_accelerate_supported(device: str) -> bool:
return device == "cuda" or device == "xpu" or device == "npu"
def empty_cache():
if torch.cuda.is_available():
torch.cuda.empty_cache()
if torch.backends.mps.is_available():
torch.mps.empty_cache()
if is_xpu_available():
torch.xpu.empty_cache()
if is_npu_available():
torch.npu.empty_cache()
def get_available_device_env_name():
return DEVICE_TO_ENV_NAME.get(get_available_device())
def gpu_count():
if torch.cuda.is_available():
cuda_visible_devices_env = os.getenv("CUDA_VISIBLE_DEVICES", None)
if cuda_visible_devices_env is None:
return torch.cuda.device_count()
cuda_visible_devices = (
cuda_visible_devices_env.split(",") if cuda_visible_devices_env else []
)
return min(torch.cuda.device_count(), len(cuda_visible_devices))
elif is_xpu_available():
return torch.xpu.device_count()
elif is_npu_available():
return torch.npu.device_count()
else:
return 0
def _get_nvidia_gpu_mem_info(gpu_id: int) -> Dict[str, float]:
from pynvml import (
nvmlDeviceGetHandleByIndex,
nvmlDeviceGetMemoryInfo,
nvmlDeviceGetName,
nvmlDeviceGetUtilizationRates,
)
handler = nvmlDeviceGetHandleByIndex(gpu_id)
gpu_name = nvmlDeviceGetName(handler)
mem_info = nvmlDeviceGetMemoryInfo(handler)
utilization = nvmlDeviceGetUtilizationRates(handler)
return {
"name": gpu_name,
"total": mem_info.total,
"used": mem_info.used,
"free": mem_info.free,
"util": utilization.gpu,
}
def get_nvidia_gpu_info() -> Dict:
from pynvml import nvmlDeviceGetCount, nvmlInit, nvmlShutdown
try:
nvmlInit()
device_count = nvmlDeviceGetCount()
res = {}
for i in range(device_count):
res[f"gpu-{i}"] = _get_nvidia_gpu_mem_info(i)
return res
except:
# TODO: add log here
# logger.debug(f"Cannot init nvml. Maybe due to lack of NVIDIA GPUs or incorrect installation of CUDA.")
return {}
finally:
try:
nvmlShutdown()
except:
pass