import torch


def get_device(gpu = -1):
  """Get a device, among those available, on which to compute.

  Args:
    $gpu$ (`int`): The gpu to use. Set to -1 to use the last GPU
        found when GPUs are present; set this to -2 to override
        using a found GPU and instead use the (first) CPU. Defa-
        ult: `-1`.

  Returns:
    `torch.device`. An instance of `torch.device` which can then
        be passed to `torch` tensors and modules (using their `to`
        method).
  """
  if gpu > -2:
    return torch.device("cuda:{0}".format(
               (torch.cuda.device_count() + gpu) % torch.cuda.device_count()
           )) if torch.cuda.is_available() else torch.device('cpu:0')
  else:
    return torch.device('cpu:0')