Tensor not being moved to GPU.. What am I doing wrong?

data_preprocess = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

def preprocess_input(img):
  print(img.shape)
  x = data_preprocess(img)
  x.unsqueeze_(0)
  x.to(device)
  print("x.size(): ",x.size(),x.type())
  return x

output:

(375, 500, 3)
x.size():  torch.Size([1, 3, 375, 500]) torch.FloatTensor

Hence getting the Error:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

fixed it by returning x.to(device):

def preprocess_input(img):
  print(img.shape)
  x = data_preprocess(img)
  x.unsqueeze_(0)
  #x.to(device)
  print("x.size(): ",x.size(),x.type())
  return x.to(device)

Yes, the .to() operation is not inplace. So you need to use the returned value!

1 Like