How to Return Tensor from GPU to CPU in PyTorch
In this article
To move a tensor or model from the GPU back to the CPU in PyTorch, you must explicitly call the .cpu() method on the object. This operation transfers the data from high-speed VRAM to system RAM and changes the device attribute of the tensor to 'cpu'. You need this step primarily when saving models, processing results with non-GPU libraries like NumPy, or preparing data for display. Before attempting the transfer, ensure your PyTorch installation supports CUDA and that the tensor actually resides on a GPU; transferring a CPU tensor to the CPU is redundant but harmless, while trying to move an object that isn't on a GPU will raise an error.
What You'll Need
- A Python environment with PyTorch installed.
- NVIDIA GPU with compatible drivers (if using CUDA).
- Basic understanding of PyTorch tensors and the
deviceattribute. - The
torchlibrary imported asimport torch.
Step-by-Step
- Verify Current Device: Before moving anything, check where your tensor currently lives. Print the device attribute using
print(tensor.device). If it outputs something like 'cuda:0', the tensor is on the GPU. If it says 'cpu', no action is needed. - Create or Load the Tensor: Ensure you have a tensor initialized on the GPU. For example, create a random tensor and move it to the GPU using
tensor = torch.randn(3, 4).to('cuda')ortensor.cuda(). This confirms the data is in VRAM. - Execute the Transfer: Call the
.cpu()method on the tensor. The syntax is simple:cpu_tensor = gpu_tensor.cpu(). This creates a new tensor in system memory. Note that this method does not modify the original tensor in place; it returns a copy on the CPU. - Handle Models: If you are working with a neural network model rather than a single tensor, use
model.cpu(). This recursively moves all parameters and buffers of the model from GPU memory to CPU memory. This is essential before callingtorch.save()if you intend to save the model state dictionary without a GPU available later. - Interact with Non-Tensor Libraries: Once the tensor is on the CPU, you can safely convert it to a NumPy array using
numpy_array = cpu_tensor.numpy(). PyTorch tensors on the GPU cannot be directly converted to NumPy arrays because NumPy operates exclusively on system RAM. Attempting this conversion on a GPU tensor will crash your program. - Manage Memory Cleanup: After moving large tensors or models to the CPU, you may want to free up GPU memory. Use
del gpu_tensorto remove the reference to the GPU tensor and then calltorch.cuda.empty_cache()to release the VRAM back to the pool. This prevents out-of-memory errors during subsequent operations.
Common Mistakes
One of the most frequent errors is assuming .cpu() modifies the original object. In PyTorch, device placement methods return a new object; they do not mutate the existing one. If you write gpu_tensor.cpu() without assigning it to a variable, the CPU copy is discarded, and the GPU tensor remains unchanged. Always assign the result: new_tensor = old_tensor.cpu().
Another common mistake is attempting to perform mathematical operations between a GPU tensor and a CPU tensor simultaneously. PyTorch requires both operands to be on the same device. If you try to add a CPU tensor to a GPU tensor, you will receive a runtime error. You must move both to the same device before computation.
Users often forget that moving a model to the CPU also moves its optimizer states if they are stored in the model's parameters. While this is usually desired for saving, it can lead to unexpected behavior if you plan to resume training immediately on the GPU without re-initializing the optimizer correctly.
Tips
Use context managers or helper functions to manage device placement dynamically. Define a function like get_device() that returns 'cuda' if available and 'cpu' otherwise. This makes your code portable across different machines without hardcoding device strings.
When saving models, it is often safer to save the state dictionary while the model is still on the GPU, provided you have enough RAM to handle the serialization process. However, if you are running low on RAM, moving the model to the CPU first ensures the save operation does not compete for VRAM resources, which can stabilize the process on systems with limited memory headroom.
For large datasets, avoid moving individual tensors to the CPU inside a training loop unless necessary. Batch processing should remain on the GPU for speed. Only move final results or gradients to the CPU for logging or visualization after the batch iteration is complete.
Troubleshooting
If you encounter a RuntimeError: Expected object of scalar type Float but got scalar type Double or similar dtype mismatches during transfer, ensure that your input data types match. While rare, some operations require explicit casting. Usually, the error stems from mixing devices, not dtypes. Check your device attributes again.
If the transfer hangs or takes an unusually long time, check for background processes consuming GPU memory. Use nvidia-smi in your terminal to monitor GPU usage. If another process is holding onto VRAM, your transfer might be waiting for resources or causing swapping.
If you receive a IndexError or CUDA out of memory after moving things around, it may indicate that you deleted the wrong reference. Remember that del only removes the name binding; the memory is freed only when the reference count drops to zero. Ensure no other variables point to the GPU tensor before deleting it.
Frequently Asked Questions
Does .cpu() delete the GPU tensor?
No. It creates a copy on the CPU. The original GPU tensor remains in VRAM until you explicitly delete it or it goes out of scope.
Can I convert a GPU tensor to NumPy directly?
No. You must first move the tensor to the CPU using .cpu(), and then call .numpy(). Direct conversion raises an error.
Is it faster to keep models on the GPU?
Yes, for training and inference, keeping models on the GPU is significantly faster due to parallel processing capabilities. Moving to CPU is only for storage or post-processing.
How do I check if my tensor is on the GPU?
Print the device attribute: print(tensor.device). It will display 'cuda:X' where X is the GPU index, or 'cpu'.
Can I move a model from CPU to GPU and back?
Yes. You can switch devices multiple times using .to('cuda') and .cpu(). Just ensure all related tensors and optimizers are moved together to avoid device mismatch errors.
Why is my transfer slow?
Transferring large amounts of data over PCIe can be a bottleneck. Minimize the frequency of transfers by batching operations on the GPU whenever possible.