プリンキピア

第6章構築者のための手引き

6.7.1. Computing Devices6.7.1 計算デバイス

We can specify devices, such as CPUs and GPUs, for storage and calculation. By default, tensors are created in the main memory and then the CPU is used for calculations.
英語のヒント
保存と計算のために、CPUやGPUといったデバイスを指定できる。既定では、テンソルはメインメモリに作られ、計算にはCPUが使われる。
In PyTorch, the CPU and GPU can be indicated by torch.device('cpu') and torch.device('cuda'). It should be noted that the cpu device means all physical CPUs and memory. This means that PyTorch’s calculations will try to use all CPU cores. However, a gpu device only represents one card and the corresponding memory. If there are multiple GPUs, we use torch.device(f'cuda:{i}') to represent the ith GPU (i starts at 0). Also, gpu:0 and gpu are equivalent.
英語のヒント
PyTorchでは、CPUとGPUはtorch.device('cpu')とtorch.device('cuda')で示せる。cpuデバイスは、物理的なすべてのCPUとメモリを意味することに注意すべきである。つまり、PyTorchの計算は、CPUのすべてのコアを使おうとする。一方、gpuデバイスは、1枚のカードとそれに対応するメモリだけを表す。複数のGPUがあるときは、torch.device(f'cuda:{i}')を使ってithのGPU(iは0から始まる)を表す。また、gpu:0とgpuは同じである。
def cpu():  #@save
    """Get the CPU device."""
    return torch.device('cpu')

def gpu(i=0):  #@save
    """Get a GPU device."""
    return torch.device(f'cuda:{i}')

cpu(), gpu(), gpu(1)
(device(type='cpu'),
 device(type='cuda', index=0),
 device(type='cuda', index=1))
We can query the number of available GPUs.
英語のヒント
使えるGPUの数を問い合わせられる。
def num_gpus():  #@save
    """Get the number of available GPUs."""
    return torch.cuda.device_count()

num_gpus()
2
Now we define two convenient functions that allow us to run code even if the requested GPUs do not exist.
英語のヒント
ここで、要求したGPUが存在しなくてもコードを走らせられるようにする、二つの便利な関数を定義する。
def try_gpu(i=0):  #@save
    """Return gpu(i) if exists, otherwise return cpu()."""
    if num_gpus() >= i + 1:
        return gpu(i)
    return cpu()

def try_all_gpus():  #@save
    """Return all available GPUs, or [cpu(),] if no GPU exists."""
    return [gpu(i) for i in range(num_gpus())]

try_gpu(), try_gpu(10), try_all_gpus()
(device(type='cuda', index=0),
 device(type='cpu'),
 [device(type='cuda', index=0), device(type='cuda', index=1)])