Pytoch directly creates tensors on the GPU and reports an error: Legacy constructor expectations device type: cpubut device type: CUDA was passed
General tensor creation method:
torch.Tensor(x)
However, by default, the tensor is placed in the CPU (memory). If we want to use the GPU to train the model, we must also copy the tensor to the GPU, which will obviously save time
I’ve seen other articles before saying that tensors can be created directly on the GPU, so I’ve also made a try:
MyDevice=torch.device('cuda:0')
x = torch.LongTensor(x, device=MyDevice)
An error is reported when running the program:
legacy constructor expects device type: cpu but device type: cuda was passed
According to the error report analysis, the problem is that the device parameter cannot be passed ‘CUDA’?After checking, I found that the official answer given by pytorch is that tensor class is a subclass of tensor and cannot pass parameters to its device. There is no problem using the tensor class to build
⭐ Therefore, the code is changed as follows:
MyDevice = torch.device('cuda:0')
x = torch.tensor(x, device=MyDevice)
x = x.long()
Now, there will be no more errors.
Read More:
- [Solved] Pytorch Tensor to numpy error: RuntimeError: Can‘t call numpy() on Tensor that requires grad.报错
- Tensor for argument #2 ‘mat1‘ is on CPU, but expected it to be on GPU (while checking arguments for
- [Solved] Pytorch Error: AttributeError: ‘Tensor‘ object has no attribute ‘backword‘
- [Solved] pytorch Error: KeyError: tensor(2, device=‘cuda:0‘)
- Normalize error: TypeError: Input tensor should be a float tensor…
- [Solved] RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dim
- How to Solve QGIS installation paddy GPU error
- [Solved] pytorch loss.backward() Error: RuntimeError: Function AddBackward0 returned an invalid gradient at index 1…
- [Pytorch Error Solution] Pytorch distributed RuntimeError: Address already in use
- pytorch: RuntimeError CUDA error device-side assert triggered
- [Solved] Pytorch-transformers Error: AttributeError: ‘str‘ object has no attribute ‘shape‘
- [CUDA Environment] Python Pytorch Error: CudaSetupArgument
- [Solved] Pytorch Error: RuntimeError: expected scalar type Double but found Float
- [Solved] ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
- [Solved] CUDA failure 999: unknown error ; GPU=-351697408 ; hostname=4f5e6dff58e6 ; expr=cudaSetDevice(info_.device_id);
- [Solved] bushi RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/s
- RuntimeError: stack expects each tensor to be equal size [How to Solve]
- [Solved] PyTorch Error: TypeError: exceptions must derive from BaseException
- Pytorch: error message with chunks of 0 [How to Solve]