预计所有张量都在同一个设备上,但发​​现至少有两个设备,cpu 和 cuda:0!关于数据知识

社会演员多 pytorch 452

原文标题Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! on DataLore

我正在使用 IntelliJ DataLore 训练基本的 VGG16 CNN,但是当我尝试使用 GPU 机器进行训练时,出现以下错误:

Traceback (most recent call last):
  at block 20, line 1
  at /data/workspace_files/train/trainer/training.py, line 115, in train(self, max_epochs)
  at /data/workspace_files/train/trainer/training.py, line 46, in train_epoch(self, train_loader)
  at /data/workspace_files/train/trainer/training.py, line 94, in forward_to_loss(self, step_images, step_labels)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/modules/module.py, line 1102, in _call_impl(self, *input, **kwargs)
  at /data/workspace_files/models/vgg.py, line 49, in forward(self, x)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/modules/module.py, line 1102, in _call_impl(self, *input, **kwargs)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/modules/container.py, line 141, in forward(self, input)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/modules/module.py, line 1102, in _call_impl(self, *input, **kwargs)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/modules/linear.py, line 103, in forward(self, input)
  at /opt/python/envs/default/lib/python3.8/site-packages/torch/nn/functional.py, line 1848, in linear(input, weight, bias)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_addmm)

这是我的代码,所以你们可以查看它。

use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
model = model.to(device)

在这段代码中,我使用 self.device 因为我将设备作为参数传递给类 Train

for _, (data, target) in tqdm(enumerate(train_loader, 1)):
            self.optimizer.zero_grad()
            step_images, step_labels = data.to(
                self.device), target.to(self.device)
            step_output, loss = self.forward_to_loss(step_images, step_labels)

我以前没有遇到过这个问题,所以我不知道 DataLore 是否缺少某些内容或我的代码有误。

希望你能帮我!

原文链接:https://stackoverflow.com//questions/71443214/expected-all-tensors-to-be-on-the-same-device-but-found-at-least-two-devices-c

回复

共1条回复 我来回复
  • Prajot Kuvalekar的头像
    Prajot Kuvalekar 评论

    你能试试这个吗

    step_output, loss = self.forward_to_loss(step_images.to(self.device), step_labels.to(self.device))
    
    2年前 0条评论