mirror of
https://github.com/zebrajr/pytorch.git
synced 2025-12-07 00:21:07 +01:00
Summary: Use it from both __init__ and streams to define dummy types when CUDA is missing Fix accidental reference of global `storage_name` from `_dummy_type` Add type annotations Pull Request resolved: https://github.com/pytorch/pytorch/pull/40177 Differential Revision: D22106922 Pulled By: malfet fbshipit-source-id: 52fbfd91d70a78eb14d7ffda109c02ad1231497e
45 lines
1.6 KiB
Python
45 lines
1.6 KiB
Python
import torch
|
|
import torch._six
|
|
from typing import Union
|
|
|
|
|
|
def _get_device_index(device: Union[str, torch.device, int, None], optional=False) -> int:
|
|
r"""Gets the device index from :attr:`device`, which can be a torch.device
|
|
object, a Python integer, or ``None``.
|
|
|
|
If :attr:`device` is a torch.device object, returns the device index if it
|
|
is a CUDA device. Note that for a CUDA device without a specified index,
|
|
i.e., ``torch.device('cuda')``, this will return the current default CUDA
|
|
device if :attr:`optional` is ``True``.
|
|
|
|
If :attr:`device` is a Python integer, it is returned as is.
|
|
|
|
If :attr:`device` is ``None``, this will return the current default CUDA
|
|
device if :attr:`optional` is ``True``.
|
|
"""
|
|
if isinstance(device, torch._six.string_classes):
|
|
device = torch.device(device)
|
|
if isinstance(device, torch.device):
|
|
dev_type = device.type
|
|
if device.type != 'cuda':
|
|
raise ValueError('Expected a cuda device, but got: {}'.format(device))
|
|
device_idx = device.index
|
|
else:
|
|
device_idx = device
|
|
if device_idx is None:
|
|
if optional:
|
|
# default cuda device index
|
|
return torch.cuda.current_device()
|
|
else:
|
|
raise ValueError('Expected a cuda device with a specified index '
|
|
'or an integer, but got: {}'.format(device))
|
|
return device_idx
|
|
|
|
|
|
def _dummy_type(name: str) -> type:
|
|
def init_err(self):
|
|
class_name = self.__class__.__name__
|
|
raise RuntimeError(
|
|
"Tried to instantiate dummy base class {}".format(class_name))
|
|
return type(name, (object,), {"__init__": init_err})
|