_utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from typing import Any
  2. import torch
  3. # The _get_device_index has been moved to torch.utils._get_device_index
  4. from torch._utils import _get_device_index as _torch_get_device_index
  5. def _get_device_index(
  6. device: Any, optional: bool = False, allow_cpu: bool = False
  7. ) -> int:
  8. r"""Get the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``.
  9. If :attr:`device` is a torch.device object, returns the device index if it
  10. is a CUDA device. Note that for a CUDA device without a specified index,
  11. i.e., ``torch.device('cuda')``, this will return the current default CUDA
  12. device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
  13. CPU devices will be accepted and ``-1`` will be returned in this case.
  14. If :attr:`device` is a Python integer, it is returned as is.
  15. If :attr:`device` is ``None``, this will return the current default CUDA
  16. device if :attr:`optional` is ``True``.
  17. """
  18. if isinstance(device, int):
  19. return device
  20. if isinstance(device, str):
  21. device = torch.device(device)
  22. if isinstance(device, torch.device):
  23. if allow_cpu:
  24. if device.type not in ["cuda", "cpu"]:
  25. raise ValueError(f"Expected a cuda or cpu device, but got: {device}")
  26. elif device.type != "cuda":
  27. raise ValueError(f"Expected a cuda device, but got: {device}")
  28. if not torch.jit.is_scripting():
  29. if isinstance(device, torch.cuda.device):
  30. return device.idx
  31. return _torch_get_device_index(device, optional, allow_cpu)