返回 F5-TTS
device_utils.py
根目录 / src / f5_tts / device_utils.py
1 """Device resolution shared by the inference, API, socket and finetune entry points."""
2
3 import torch
4
5
6 def is_npu_available() -> bool:
7 """Whether an Ascend NPU is usable through a ``torch_npu`` build.
8
9 ``torch.npu`` only exists once ``torch_npu`` has been imported, so the import is
10 attempted lazily and stays invisible to CUDA/XPU/MPS/CPU-only installs.
11 """
12 if not hasattr(torch, "npu"):
13 try:
14 import torch_npu # noqa: F401
15 except ImportError:
16 return False
17 npu = getattr(torch, "npu", None)
18 return npu is not None and bool(npu.is_available())
19
20
21 def get_default_device() -> str:
22 """Return the accelerator to use when the caller does not pick one explicitly.
23
24 ``torch.accelerator`` (PyTorch >= 2.6) reports whichever backend is registered and
25 available, so CUDA, Ascend NPU, XPU and future backends are covered without a
26 per-backend branch. Builds without it fall back to explicit probes.
27 """
28 accelerator = getattr(torch, "accelerator", None)
29 if hasattr(accelerator, "is_available") and hasattr(accelerator, "current_accelerator"):
30 try:
31 # PyTorch 2.6 requires checking availability separately.
32 current = accelerator.current_accelerator() if accelerator.is_available() else None
33 except RuntimeError: # no accelerator available in this build
34 current = None
35 if current is not None:
36 return current.type
37 if torch.cuda.is_available():
38 return "cuda"
39 if is_npu_available():
40 return "npu"
41 if hasattr(torch, "xpu") and torch.xpu.is_available():
42 return "xpu"
43 if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
44 return "mps"
45 return "cpu"
46
46 lines PYTHON