Cannot construct tensor directly on GPU in torch 1.10.1

torch version == 1.10.1


device = 'cuda:0'

If I try:

x = torch.Tensor([1.0], device=device)

I got the following error:

RuntimeError: legacy constructor expects device type: cpu but device type: cuda was passed

What am I doing wrong ?

I solved this by doing:

x = torch.Tensor([1.0]).to(device)

which works, but I would like to know why I can directly initialize the Tensor on GPU device.

Additional Information:

This error occurs only with torch.Tensor
The following works:

x = torch.zeros(1, device=device)
y = torch.ones(1, device=device)

Use torch.tensor([1.0], device='cuda') (lowercase t) and it should work.
I would not recommend to use the legacy torch.Tensor, torch.FloatTensor etc. constructors.

1 Like

Thank you!

Can you also please explain me what is the difference between the two ? Or post a link to the explanation ?

The main difference is that torch.tensor is the supported and right way and torch.Tensor the legacy and unsupported.
The docs for torch.tensor show all input arguments while the docs for torch.Tensor point to ways to initialize tensors.

1 Like