Keep PyTorch models and inputs on the same device

A device-mismatch error usually means that one operand stayed on the CPU while another moved to a GPU. Solve it by choosing the execution device once and carrying that choice through model construction, data loading and temporary tensors. Changing the global default tensor type makes the source of a mismatch harder to see.

Choose the device at the boundary

Use Python 3.14 and PyTorch 2.15. Install a build compatible with your operating system and accelerator. The following example works on CPU and selects CUDA only when the installed build reports it as available. It does not install a GPU driver or verify a particular CUDA deployment.

Tensor.to() returns the tensor on the requested device and with the requested dtype. When a conversion is needed it returns another tensor, so keep that return value. Module device moves operate on registered parameters and buffers. Move the model before constructing an optimizer that holds references to its parameters. Tensor conversion reference , Module reference .

Move the model and each batch

Save this as devices.py and run it with Python.

Python
import torch
from torch import nn

class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("feature_center", torch.tensor([1.0, 2.0]))
        self.output = nn.Linear(2, 2)

    def forward(self, x):
        return self.output(x - self.feature_center)

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = Classifier().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

cpu_features = torch.tensor([[1.0, 3.0], [4.0, 2.0]])
cpu_labels = torch.tensor([0, 1], dtype=torch.long)
features = cpu_features.to(device=device, dtype=torch.float32)
labels = cpu_labels.to(device=device)

assert next(model.parameters()).device == features.device
assert model.feature_center.device == features.device
assert labels.dtype == torch.long

optimizer.zero_grad(set_to_none=True)
loss = nn.CrossEntropyLoss()(model(features), labels)
loss.backward()
optimizer.step()

print("Device:", device)
print("Finite loss:", bool(torch.isfinite(loss)))

Expect the selected device and Finite loss: True. The numeric loss is deliberately not fixed because the layer uses random initialization. This is one training step with synthetic data, so it proves the tensors can participate in the calculation rather than that the classifier has learned a useful task.

The class labels remain integers. Applying .to(other_tensor) indiscriminately can copy both the other tensor's device and dtype, which is wrong for class-index labels if the reference tensor is floating-point. Move labels by device explicitly.

Keep hidden tensors with their owner

The feature center is a registered buffer. It is not optimized, but it belongs to the model and moves with it. A plain tensor stored in an ordinary attribute does not acquire this behavior merely because it is inside a module.

For a temporary tensor created during forward, inherit the input's device and dtype when that is the intended contract. For example, scratch = x.new_zeros((x.shape[0], 4)) creates a suitable work tensor. If the temporary value is an index, specify an integer dtype instead. Tensor.new_zeros reference .

Inspect the first failing operation

Log the device, dtype and shape of the operands immediately before the reported operation. Check nested batch dictionaries and masks as well as the main feature tensor. Moving the outer Python container does not move its contents. Multiple GPUs also have distinct device identities, so cuda:0 and cuda:1 are not interchangeable.

CUDA transfer and execution can be asynchronous, which changes how timing measurements should be interpreted. Establish correct placement before adding pinned memory, nonblocking copies or performance measurements. CUDA semantics .

The full example was executed on CPU. Its CUDA branch was not executed, and no GPU throughput claim is made.

Question provenance

This article addresses RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same , asked by Guillermina on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.

Author: Herman Schoenfeld