mirror of
https://github.com/zebrajr/pytorch.git
synced 2025-12-06 12:20:52 +01:00
This reverts commit fb02b40d27.
Reverted https://github.com/pytorch/pytorch/pull/140542 on behalf of https://github.com/huydhn due to Sorry for reverting your change, but I need to revert this in order to revert https://github.com/pytorch/pytorch/pull/133572#issuecomment-2537204202 due to a conflict ([comment](https://github.com/pytorch/pytorch/pull/140542#issuecomment-2537253665))
29 lines
944 B
Python
29 lines
944 B
Python
from typing import Optional, Union
|
|
|
|
import torch
|
|
from torch import device as _device
|
|
|
|
|
|
_device_t = Union[_device, str, int, None]
|
|
|
|
|
|
def _get_device_index(device: _device_t, optional: bool = False) -> int:
|
|
if isinstance(device, int):
|
|
return device
|
|
if isinstance(device, str):
|
|
device = torch.device(device)
|
|
device_index: Optional[int] = None
|
|
if isinstance(device, torch.device):
|
|
if torch.accelerator.current_accelerator() != device.type:
|
|
raise ValueError(
|
|
f"{device.type} doesn't match the current accelerator {torch.accelerator.current_accelerator()}."
|
|
)
|
|
device_index = device.index
|
|
if device_index is None:
|
|
if not optional:
|
|
raise ValueError(
|
|
f"Expected a torch.device with a specified index or an integer, but got:{device}"
|
|
)
|
|
return torch.accelerator.current_device_idx()
|
|
return device_index
|