PyTorch CUDA Out of Memory Fix
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
delto free tensors no longer needed. - Avoid holding onto computation graphs unnecessarily.
Common Mistakes with cuda error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro