This:
JavaScript
x
7
1
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
2
model.to(device)
3
4
for data in dataloader:
5
inputs, labels = data
6
outputs = model(inputs)
7
Gives the error:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same
Advertisement
Answer
You get this error because your model is on the GPU, but your data is on the CPU. So, you need to send your input tensors to the GPU.
JavaScript
1
3
1
inputs, labels = data # this is what you had
2
inputs, labels = inputs.cuda(), labels.cuda() # add this line
3
Or like this, to stay consistent with the rest of your code:
JavaScript
1
4
1
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
2
3
inputs, labels = inputs.to(device), labels.to(device)
4
The same error will be raised if your input tensors are on the GPU but your model weights aren’t. In this case, you need to send your model weights to the GPU.
JavaScript
1
5
1
model = MyModel()
2
3
if torch.cuda.is_available():
4
model.cuda()
5