当我们有 model.to('CUDA') 时,为什么我们需要 image.to('CUDA')

Mih*_* L. 1 python pytorch

我正在上一门课程PyTorch。我想知道为什么我们需要单独告诉torch.utils.data.DataLoader它在运行的设备上输出。如果模型已经启动,CUDA为什么它不自动相应地更改输入?这种模式对我来说似乎很有趣:

model.to(device)

for ii, (inputs, labels) in enumerate(trainloader):

    # Move input and label tensors to the GPU
    inputs, labels = inputs.to(device), labels.to(device)
Run Code Online (Sandbox Code Playgroud)

是否存在我希望模型在 GPU 上运行但我的输入在 CPU 模式上运行的用例,反之亦然?

blu*_*nox 7

当您调用model.to(device) (假设device是 GPU)时,您的模型参数将被移动到您的 GPU。关于您的评论:然后它们从 CPU 内存移至 GPU 内存。

如果没有另外指定,默认情况下新创建的张量是在 CPU 上创建的。所以这也适用于您的inputslabels

这里的问题是一个操作的所有 操作数都需要位于同一设备上!如果您省略to并使用 CPU 张量作为输入,您将收到一条错误消息。

这是一个用于说明的简短示例:

import torch

# device will be 'cuda' if a GPU is available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# creating a CPU tensor
cpu_tensor = torch.rand(10)
# moving same tensor to GPU
gpu_tensor = cpu_tensor.to(device)

print(cpu_tensor, cpu_tensor.dtype, type(cpu_tensor), cpu_tensor.type())
print(gpu_tensor, gpu_tensor.dtype, type(gpu_tensor), gpu_tensor.type())

print(cpu_tensor*gpu_tensor)
Run Code Online (Sandbox Code Playgroud)

输出:

tensor([0.8571, 0.9171, 0.6626, 0.8086, 0.6440, 0.3682, 0.9920, 0.4298, 0.0172,
        0.1619]) torch.float32 <class 'torch.Tensor'> torch.FloatTensor
tensor([0.8571, 0.9171, 0.6626, 0.8086, 0.6440, 0.3682, 0.9920, 0.4298, 0.0172,
        0.1619], device='cuda:0') torch.float32 <class 'torch.Tensor'> torch.cuda.FloatTensor
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-15-ac794171c178> in <module>()
     12 print(gpu_tensor, gpu_tensor.dtype, type(gpu_tensor), gpu_tensor.type())
     13 
---> 14 print(cpu_tensor*gpu_tensor)

RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument #2 'other'
Run Code Online (Sandbox Code Playgroud)