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

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 因为我将设备作为参数传递给 class 火车

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 上缺少什么还是我的代码有误。

希望你能帮助我!

你能试试这个吗

step_output, loss = self.forward_to_loss(step_images.to(self.device), step_labels.to(self.device))