5
# The _get_device_index has been moved to torch.utils._get_device_index
6
from torch._utils import _get_device_index as _torch_get_device_index
10
device: Any, optional: bool = False, allow_cpu: bool = False
12
r"""Get the device index from :attr:`device`, which can be a torch.device
13
object, a Python integer, or ``None``.
15
If :attr:`device` is a torch.device object, returns the device index if it
16
is a XPU device. Note that for a XPU device without a specified index,
17
i.e., ``torch.device('xpu')``, this will return the current default XPU
18
device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
19
CPU devices will be accepted and ``-1`` will be returned in this case.
21
If :attr:`device` is a Python integer, it is returned as is.
23
If :attr:`device` is ``None``, this will return the current default XPU
24
device if :attr:`optional` is ``True``.
26
if isinstance(device, int):
28
if isinstance(device, str):
29
device = torch.device(device)
30
if isinstance(device, torch.device):
32
if device.type not in ["xpu", "cpu"]:
33
raise ValueError(f"Expected a xpu or cpu device, but got: {device}")
34
elif device.type != "xpu":
35
raise ValueError(f"Expected a xpu device, but got: {device}")
36
if not torch.jit.is_scripting():
37
if isinstance(device, torch.xpu.device):
39
return _torch_get_device_index(device, optional, allow_cpu)