Fix "CUDA out of memory" in PyTorch
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacity of 23.65 GiB of which 1.12 GiB is free.
- torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 512.00 MiB
- RuntimeError: CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 7.79 GiB total capacity; 6.12 GiB already allocated)
- RuntimeError: CUDA error: out of memory
- RuntimeError: MPS backend out of memory
The graphics card’s memory (VRAM) is full: PyTorch could not allocate the requested block. Lower the batch size, switch to reduced precision (bf16 or fp16), turn off gradient tracking for inference and free other processes using the GPU.
What this error means
On a GPU, the model weights, each layer’s activations, gradients and optimizer states must all fit in VRAM. PyTorch uses a caching allocator: it reserves large blocks and reuses them. When a new allocation exceeds free memory, it raises torch.OutOfMemoryError (formerly torch.cuda.OutOfMemoryError or RuntimeError). The message shows the requested size, total memory, how much PyTorch allocated and how much is reserved but unused. If that last part is large, memory is fragmented. For scale: 7 billion parameters take about 28 GB in fp32 and 14 GB in bf16, before any activations.
Common causes
- Batch or sequences too large: activation memory grows with batch size and sequence length (quadratically for classic attention).
- Model loaded in fp32 when bf16, fp16 or 8-bit or 4-bit quantization would be enough.
- Gradients tracked during inference: without
torch.inference_mode(), PyTorch keeps the graph and activations in memory. - Tensors kept by mistake:
total_loss += lossinstead ofloss.item(), or outputs stored in a list, keep the whole graph alive. - Another process on the GPU: a Jupyter kernel, an old training run or an inference server is already holding VRAM.
Step-by-step fix
-
See what is using memory
nvidia-smilists processes and their usage. Stop the ones you no longer need or restart the Jupyter kernel. In code,memory_summary()breaks down PyTorch’s usage.nvidia-smi python -c "import torch; print(torch.cuda.memory_summary(abbreviated=True))" -
Lower the batch and compensate with accumulation
Halve the batch size until it fits. To keep the same effective batch, accumulate gradients over several steps, here combined with bf16 mixed precision.
accum_steps = 4 optimizer.zero_grad(set_to_none=True) for i, (x, y) in enumerate(loader): x, y = x.to("cuda"), y.to("cuda") with torch.autocast("cuda", dtype=torch.bfloat16): loss = criterion(model(x), y) / accum_steps loss.backward() if (i + 1) % accum_steps == 0: optimizer.step() optimizer.zero_grad(set_to_none=True) -
Turn off gradients for inference
To generate or evaluate, put the model in eval mode and wrap the call in
torch.inference_mode(). Accumulate metrics with.item()so you do not keep tensors around.model.eval() total_loss = 0.0 with torch.inference_mode(): for x, y in val_loader: out = model(x.to("cuda")) total_loss += criterion(out, y.to("cuda")).item() -
Load the model in reduced precision or quantized
With Hugging Face Transformers, load in bf16 and let
device_map="auto"place the layers (requiresaccelerate). To go further, quantize to 4 bits withbitsandbytes. Before Transformers 4.56, thedtypeparameter was calledtorch_dtype.import torch from transformers import AutoModelForCausalLM, BitsAndBytesConfig model_id = "Qwen/Qwen2.5-7B-Instruct" # bf16: about half the memory of fp32 model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, device_map="auto" ) # 4-bit: about a quarter of bf16 bnb = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, ) model = AutoModelForCausalLM.from_pretrained( model_id, quantization_config=bnb, device_map="auto" ) -
Enable gradient checkpointing for training
Instead of storing every activation, the model recomputes them during backpropagation. You save a lot of memory at the cost of roughly 20 to 30% more compute time.
model.gradient_checkpointing_enable() model.config.use_cache = False # required with checkpointing on most causal LMs -
Free memory and limit fragmentation
Delete references to large tensors, then empty the cache. If the message reports a lot of memory “reserved but unallocated”, enable expandable segments through the environment variable named in the error (Linux). Recent PyTorch versions also accept the name
PYTORCH_ALLOC_CONF.import gc import torch del outputs gc.collect() torch.cuda.empty_cache() # in the shell, before starting the script (Linux): # export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Estimate memory before running: parameters × bytes per parameter, then add activations, gradients and optimizer states (Adam stores two values per parameter).
- Use bf16 by default on recent GPUs and
torch.inference_mode()for everything that is not training. - Watch
torch.cuda.max_memory_allocated()during a short first run to learn your real peak.
Frequently asked questions
Why the error when nvidia-smi shows free memory?
Free memory may be fragmented into pieces too small for the requested block, or grabbed by another process in the meantime. Enable expandable_segments:True and shrink allocations (smaller batch).
Does torch.cuda.empty_cache() fix the error?
Rarely. It returns unused cached memory to the system but does not free tensors that are still referenced. Delete references with del first, then call gc.collect() and empty_cache().
How much VRAM do I need for a 7B model?
About 14 to 16 GB in bf16 for inference, 5 to 6 GB in 4-bit. Full fine-tuning needs much more; LoRA or QLoRA cut that need sharply.
Useful tools for this error
More AI & LLMs errors
- Fix error 429 "Rate limit reached" on OpenAI, Claude and Gemini APIs
- Fix "maximum context length" and "prompt is too long" (context_length_exceeded)
- Fix error 401 "Incorrect API key provided" / "invalid x-api-key"
- Fix "Torch not compiled with CUDA enabled" and torch.cuda.is_available() returning False
- Fix "could not connect to ollama" and connection refused on port 11434
- Fix "JSONDecodeError: Expecting value" when parsing an LLM response
- Fix "You are trying to access a gated repo" (401) on Hugging Face