PyTorch Tensor Device Mismatch Fix
In this tutorial, you'll learn about PyTorch Tensor Device Mismatch Fix. We cover key concepts, practical examples, and best practices.
PyTorch raises RuntimeError: Expected all tensors to be on the same device when you perform operations on tensors located on different devices (CPU vs GPU).
The Wrong Way
import torch
model = torch.nn.Linear(10, 5).cuda()
inputs = torch.randn(3, 10) # on CPU
outputs = model(inputs)
Output:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
The model is on GPU but the input is on CPU.
The Right Way
import torch
model = torch.nn.Linear(10, 5).cuda()
inputs = torch.randn(3, 10).cuda() # move to GPU
outputs = model(inputs)
print(outputs)
Output:
tensor([[...]], device='cuda:0', grad_fn=<...>)
Ensure both model and inputs are on the same device.
Step-by-Step Fix
1. Check device of tensors and model
print(f"Model device: {next(model.parameters()).device}")
print(f"Input device: {inputs.device}")
2. Create a device-agnostic helper
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs = inputs.to(device)
3. Move entire batches to device
for batch in dataloader:
batch = {k: v.to(device) for k, v in batch.items()}
outputs = model(batch)
4. Use torch.cuda.device context
with torch.cuda.device(0):
model = Model().cuda()
inputs = inputs.cuda()
5. Use .to() consistently
labels = labels.to(inputs.device) # match the input device
Prevention Tips
- Define a
devicevariable at the start of your script. - Use
tensor.to(device)andmodel.to(device)consistently. - Move data to the device inside the dataloader loop.
- Check
.deviceproperty when debugging device errors. - Use
torch.cuda.set_device(0)to set the default GPU.
Common Mistakes with tensor device
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTORCH code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro