Error fixMachine Learning · 3 min read · Updated 6 Dec 2026

PyTorch "CUDA out of memory": Causes and Fixes

Fix "torch.cuda.OutOfMemoryError: CUDA out of memory": smaller batches, mixed precision, gradient accumulation, checkpointing and freeing memory properly.

QUICK ANSWER"CUDA out of memory" means the GPU cannot fit the model, activations, gradients and optimizer state for the current batch. The quickest fixes are a smaller batch size, mixed precision (bf16/fp16), and gradient accumulation to keep the effective batch size. For large models, add gradient checkpointing, use parameter-efficient fine-tuning (LoRA/QLoRA) or quantisation, and make sure you are not keeping tensors alive between steps.

Learn this hands-on: covered in Week 6: Deep learning with PyTorch of our 12-week AI and Machine Learning course, with live labs and a trainer to help. See the full syllabus →

PyTorch CUDA out of memory: causes and fixes
PyTorch CUDA out of memory: causes and fixes

What uses GPU memory

ItemGrows with
Model weightsNumber of parameters x bytes per parameter
GradientsSame size as trainable weights
Optimizer state (Adam)About 2x the trainable weights
ActivationsBatch size x sequence length / image size x layers
Fragmentation and cacheMany differently sized allocations

Fix it step by step

  1. Halve the batch size until it fits; keep the effective batch with gradient accumulation (e.g. batch 8 x 4 steps = 32).
  2. Turn on mixed precision: torch.autocast("cuda", dtype=torch.bfloat16) (or fp16 with a GradScaler on older GPUs).
  3. For inference, wrap code in torch.no_grad() (or torch.inference_mode()) so no activations are stored for backprop.
  4. Do not accumulate tensors with graphs: log loss.item(), not loss.
  5. Enable gradient checkpointing for big models (model.gradient_checkpointing_enable() in Hugging Face).
  6. Fine-tune with LoRA or QLoRA (4-bit quantised base model) instead of full fine-tuning.
  7. Shorten sequence length or image resolution if the task allows.
  8. Still not enough: use a bigger GPU, or shard the model across GPUs (FSDP, DeepSpeed ZeRO).

Check memory while you work

import torch
print(torch.cuda.memory_allocated() / 1e9, "GB allocated")
print(torch.cuda.max_memory_allocated() / 1e9, "GB peak")
print(torch.cuda.memory_summary(abbreviated=True))
# in a terminal: nvidia-smi

If memory keeps rising across steps, something is being kept alive. If the error mentions fragmentation, setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True can help.

In notebooks

Jupyter keeps variables alive between cells. After an OOM, delete large objects (del model, optimizer), run gc.collect() and torch.cuda.empty_cache(), or simply restart the kernel. empty_cache() does not free memory still referenced by Python variables.

Questions

Does torch.cuda.empty_cache() fix out of memory?

Rarely. It only returns cached, unused memory to the driver. You must first delete references to the tensors themselves.

How much GPU memory do I need to fine-tune a 7B model?

Full fine-tuning needs well over 80 GB. QLoRA can fine-tune a 7B model on a single GPU with roughly 16-24 GB, depending on sequence length and settings.