To fix the RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! When predicting with my model error, use the “input.to(dev)” function to replace input with the input to your model.
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! When predicting with my model error occurs when the input tensors and the model are on different devices (e.g., CPU and GPU).
Follow the below steps to fix the error.
Load your model and move it to the desired device (GPU in this case)
import torch
from transformers import AutoModel
model = AutoModel.from_pretrained("model_name")
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
Move your input tokens to the same device
tokens = tokenizer("Your input text", return_tensors="pt")
tokens = tokens.to(device)
Perform the prediction with both the model and input tokens on the same device
with torch.no_grad():
output = model(**tokens)
By ensuring that both the model and input tokens are on the same device, you should no longer encounter the RuntimeError.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.