Is there any difference between x.to('cuda') vs x.cuda()? Which one should I use?

I’m quite new to PyTorch, so there may be more to it than this, but I think that one advantage of using x.to(device) is that you can do something like this:

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
x = x.to(device)

Then if you’re running your code on a different machine that doesn’t have a GPU, you won’t need to make any changes. If you explicitly do x = x.cuda() or even x = x.to('cuda') then you’ll have to make changes for CPU-only machines.

5 Likes