_utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import torch
  2. from typing import Any
  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(device: Any, optional: bool = False,
  6. allow_cpu: bool = False) -> int:
  7. r"""Gets the device index from :attr:`device`, which can be a torch.device
  8. 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, str):
  19. device = torch.device(device)
  20. if isinstance(device, torch.device):
  21. if allow_cpu:
  22. if device.type not in ['cuda', 'cpu']:
  23. raise ValueError('Expected a cuda or cpu device, but got: {}'.format(device))
  24. elif device.type != 'cuda':
  25. raise ValueError('Expected a cuda device, but got: {}'.format(device))
  26. if not torch.jit.is_scripting():
  27. if isinstance(device, torch.cuda.device):
  28. return device.idx
  29. return _torch_get_device_index(device, optional, allow_cpu)
  30. def _dummy_type(name: str) -> type:
  31. def init_err(self):
  32. class_name = self.__class__.__name__
  33. raise RuntimeError(
  34. "Tried to instantiate dummy base class {}".format(class_name))
  35. return type(name, (object,), {"__init__": init_err})