TechBuzzPro

Free GPU Memory in PyTorch: How to Clear VRAM

· 4 min read · Windows & PC

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To free GPU memory in PyTorch, you must delete the tensor variables holding the data and then call torch.cuda.empty_cache(). This process removes the references to the memory and signals the PyTorch caching allocator to release the unused memory back to the GPU, preventing "Out of Memory" (OOM) errors during training or inference.

What You'll Need

  • A Python environment with PyTorch installed.
  • A CUDA-enabled NVIDIA GPU.
  • A script or Jupyter Notebook where VRAM is currently being consumed.

Step-by-Step

  1. Identify Large Tensors: Locate the variables that are consuming the most VRAM. These are typically your model weights, large input batches, and gradients stored during the backward pass.
  2. Delete the Variables: Use the Python del keyword to remove the reference to the tensor. For example, if you have a variable named output or loss that is no longer needed, run del output and del loss.
  3. Clear the PyTorch Cache: Deleting the variable only removes the reference; PyTorch keeps the memory in a cache for faster reallocation. To actually free this memory for other processes or new tensors, run torch.cuda.empty_cache().
  4. Force Garbage Collection: In some cases, Python's garbage collector does not trigger immediately. Import the gc module and run gc.collect() before calling the empty cache command to ensure all unreachable objects are cleared.
  5. Verify Memory Release: Use torch.cuda.memory_allocated() or nvidia-smi in your terminal to confirm that the VRAM usage has decreased.

Common Mistakes

  • Forgetting .detach(): A common mistake is keeping a tensor that is still attached to the computational graph. If you only need the value of a tensor for logging, use tensor.detach().cpu().item(). Otherwise, the entire graph stays in VRAM.
  • Storing Tensors in Lists: Appending loss tensors to a list for tracking (e.g., losses.append(loss)) keeps the entire history of the graph for every batch, quickly filling the VRAM. Always append loss.item() instead.
  • Over-reliance on empty_cache(): Calling empty_cache() inside a training loop can significantly slow down your code because it forces the GPU to re-allocate memory constantly. Use it only between major phases (e.g., between training and validation).

Tips

  • Use torch.no_grad(): When performing inference or validation, wrap your code in with torch.no_grad():. This prevents PyTorch from storing gradients, which reduces VRAM usage by nearly half.
  • Implement Gradient Accumulation: If your batch size is too large for your VRAM, use a smaller batch size and accumulate gradients over several steps before calling optimizer.step().
  • Mixed Precision Training: Use torch.cuda.amp.autocast() to use float16 instead of float32. This reduces the memory footprint of tensors and speeds up computation.
  • Move Models to CPU: If you need to keep a model but aren't using it, move it to the CPU using model.cpu() to free up the GPU for other tasks.

Troubleshooting

If torch.cuda.empty_cache() does not seem to reduce the memory usage in nvidia-smi, try these steps:

  • Restart the Kernel: If you are using Jupyter Notebooks, variables often persist in the background. Restart the kernel (Kernel > Restart) to completely wipe the VRAM.
  • Check for Zombie Processes: Sometimes a crashed script leaves a process running on the GPU. Use nvidia-smi to find the PID (Process ID) and kill it using kill -9 [PID] on Linux or via Task Manager on Windows.
  • Reduce Batch Size: If you get an OOM error immediately upon starting a loop, your batch size is simply too large for your hardware. Lower it and try again.

Frequently Asked Questions

Does torch.cuda.empty_cache() delete my model?

No. It only releases unused memory that PyTorch was holding onto in its cache. It does not delete any tensors that are still being referenced by your variables.

Why is my VRAM still full after deleting variables?

Python uses reference counting. If a tensor is referenced in multiple places (like a list and a variable), del only removes one reference. The memory is only freed when all references are gone and the cache is cleared.

Will clearing the cache slow down my training?

Yes, if done frequently. The cache exists to avoid the overhead of requesting memory from the GPU driver repeatedly. Only clear it when transitioning between different stages of your pipeline.

What is the difference between memory_allocated and memory_reserved?

memory_allocated is the amount of VRAM currently holding tensors. memory_reserved is the total amount the PyTorch caching allocator has taken from the GPU, including the empty space it keeps for future use.