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.