import torch


def get_device_safe(gpu_index: int):
    """
    Given a gpu index, retrieve the target device if it is available.
    Raises RuntimeError if the
    Args:
        gpu_index: The index of gpu device to retrieve.
    Returns:
        The PyTorch device specified.
    """
    if gpu_index < 0:
        raise ValueError("Cannot specify negative index as gpu device index")
    if torch.cuda.is_available() and gpu_index - 1 <= torch.cuda.device_count():
        return torch.device(f"cuda:{gpu_index}")
    raise RuntimeError(f"The specified gpu at index: '{gpu_index}' is not available")