PyTorch - 尽管检测到 CUDA 支持,但张量不使用 GPU

PyTorch - GPU is not used by tensors despite CUDA support is detected

正如问题的标题所描述的那样,即使torch.cuda.is_available() returns True,张量也使用CPU而不是GPU。在定义 device 之后,我通过 images.to(device) 函数调用将张量的 device 设置为 GPU。当我调试我的代码时,我能够看到 device 设置为 cuda:0;但是张量的 device 仍然设置为 cpu.

正在定义设备:

use_cuda = torch.cuda.is_available()  # returns True
device = torch.device('cuda:0' if use_cuda else 'cpu')

确定张量的设备:

for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images.to(device)
        labels.to(device)
        # both of images and labels' devices are set to cpu

软件堆栈:

Python 3.7.1
torch 1.0.1
Windows 10 64-bit

p.s。 PyTorch 安装有 Cuda 9.0 支持选项

tensor.to() 不会就地修改张量。它 returns 存储的一个新张量 在指定的设备中。

改用以下内容。

 images = images.to(device)
 labels = labels.to(device)