GPU & CUDA · PyTorch / CUDA

PyTorch CUDA Out of Memory

Error messagetorch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate

Why 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

  1. Lower batch size or sequence length, and use gradient accumulation across smaller micro-batches.
  2. Reduce fragmentation before starting Python: export PYTORCH_ALLOC_CONF=expandable_segments:True (replaces older PYTORCH_CUDA_ALLOC_CONF).
  3. Enable mixed precision with torch.amp.autocast('cuda', dtype=torch.bfloat16): and wrap inference in torch.no_grad().
  4. Convert logged tensors with loss.item() or .detach() so autograd graphs are not retained across steps, and call torch.cuda.empty_cache() between stages.
  5. 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.py

Seeing a different message? Paste it into the Error Code Fixer

Related errors

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.