Skip to content

PyTorch CUDA Out of Memory Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about PyTorch CUDA Out of Memory Fix. We cover key concepts, practical examples, and best practices.

PyTorch raises RuntimeError: CUDA out of memory when the GPU memory is insufficient for the model, batch size, or intermediate tensors.

The Wrong Way

import torch

model = LargeModel().cuda()
inputs = torch.randn(64, 3, 224, 224).cuda()
outputs = model(inputs)  # OOM for large batch sizes

Output:

RuntimeError: CUDA out of memory. Tried to allocate 512.00 MiB

The batch size of 64 exceeds available GPU memory.

The Right Way

import torch

model = LargeModel().cuda()
batch_size = 16
inputs = torch.randn(batch_size, 3, 224, 224).cuda()

with torch.no_grad():
    outputs = model(inputs)

Reduce batch size to fit within available GPU memory.

Step-by-Step Fix

1. Reduce batch size

dataloader = DataLoader(dataset, batch_size=16)  # reduce from 64

2. Use gradient accumulation

accumulation_steps = 4
for i, batch in enumerate(dataloader):
    loss = model(batch)
    loss = loss / accumulation_steps
    loss.backward()
    if (i + 1) % accumulation_steps == 0:
        optimizer.step()
        optimizer.zero_grad()

3. Clear cache and empty memory

torch.cuda.empty_cache()

4. Use mixed precision training

scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast():
    outputs = model(inputs)

5. Monitor memory usage

print(torch.cuda.memory_summary())
print(torch.cuda.max_memory_allocated() / 1024**3, "GB")

Prevention Tips

  • Start with a small batch size and increase gradually.
  • Use gradient accumulation to simulate larger batch sizes.
  • Use mixed precision training with torch.cuda.amp.
  • Call torch.cuda.empty_cache() between experiments.
  • Use del to free tensors no longer needed.
  • Avoid holding onto computation graphs unnecessarily.

Common Mistakes with cuda error

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' causing stack overflow on large lists

These mistakes appear frequently in real-world PYTORCH code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is gradient accumulation?

Gradient accumulation runs multiple forward/backward passes before updating weights. It simulates a larger batch size without requiring more GPU memory. Use loss = loss / accumulation_steps before backward().

How does mixed precision help with memory?

Mixed precision (AMP) uses float16 tensors for most operations, reducing memory usage by half compared to float32. It also enables larger batch sizes and faster training on modern GPUs.

Why does OOM persist after reducing batch size?

Memory fragmentation may prevent large contiguous allocations even when total free memory is sufficient. Try restarting the Python kernel or calling torch.cuda.empty_cache() and torch.cuda.reset_max_memory_allocated().

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro