Skip to content

PyTorch Tensor Device Mismatch Fix

DodaTech Updated 2026-06-24 2 min read

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 device variable at the start of your script.
  • Use tensor.to(device) and model.to(device) consistently.
  • Move data to the device inside the dataloader loop.
  • Check .device property when debugging device errors.
  • Use torch.cuda.set_device(0) to set the default GPU.

Common Mistakes with tensor device

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

### What is the best way to manage devices in PyTorch?

Create a device variable: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu'). Use model.to(device) and tensor.to(device) throughout the code.

How do I move a dictionary of tensors to a device?

Use a dictionary comprehension: batch = {k: v.to(device) for k, v in batch.items()}. For nested structures, use <a href="/artificial-intelligence/pytorch/">PyTorch</a>_lightning.utilities.apply_to_collection or similar utilities.

Why does .to() not move in-place?

tensor.to(device) returns a new tensor on the target device. The original tensor is unchanged. Always assign the result: tensor = tensor.to(device).

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro