GPU & CUDA · PyTorch / CUDA
PyTorch CUDA Out of Memory
Error message
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocateWhy it happens
Model weights, activations, or batch tensors exceed free GPU VRAM, or PyTorch's caching allocator cannot find a contiguous block due to memory fragmentation.
How to fix it
- Lower batch size or sequence length, and use gradient accumulation across smaller micro-batches.
- Reduce fragmentation before starting Python: export PYTORCH_ALLOC_CONF=expandable_segments:True (replaces older PYTORCH_CUDA_ALLOC_CONF).
- Enable mixed precision with torch.amp.autocast('cuda', dtype=torch.bfloat16): and wrap inference in torch.no_grad().
- Convert logged tensors with loss.item() or .detach() so autograd graphs are not retained across steps, and call torch.cuda.empty_cache() between stages.
- Run nvidia-smi to check for other processes or stale Python sessions holding VRAM and stop them.
PYTORCH_ALLOC_CONF=expandable_segments:True python train.pySeeing a different message? Paste it into the Error Code Fixer
Related errors
- PyTorch Cannot Detect CUDA GPU
- PyTorch Installed Without CUDA
- Connection refused on port 11434
- Model requires more system memory
Fixes are reviewed by ComputerTech against current documentation, and software changes fast. If a step differs on your version, tell us. Back up important data before changing drivers, BIOS or system files.