Skip to content

CUDA Out of Memory: 15 Fixes for PyTorch Training, LLM Inference and Stable Diffusion

The complete guide to fixing "CUDA out of memory" errors. Learn to read the error message, find what is using your GPU memory, and apply the right fix for training (batch size, mixed precision, checkpointing, 8-bit optimizers, FSDP), LLM inference (vLLM, llama.cpp, Ollama), image generation, Jupyter leaks and fragmentation, with code, a memory estimator and a decision table.

6 min read

CUDA Out of Memory Fixes — cuda out of memory

Short answer

A CUDA out of memory error (torch.OutOfMemoryError) means your GPU tried to allocate more VRAM than was free. The fastest fixes are: reduce batch size (and use gradient accumulation), train in BF16/FP16 mixed precision, enable gradient checkpointing, use 4-bit or 8-bit quantization, shorten the context or sequence length, and close other processes using the GPU (check with nvidia-smi). If the error says a lot of memory is "reserved but unallocated," set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to reduce fragmentation. For LLM servers, lower gpu_memory_utilization, max_model_len or the number of GPU layers. If none of these work, your model simply needs a bigger GPU or several GPUs.

Step 1: Read the error message

A typical modern PyTorch error looks like this:

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.
Including non-PyTorch memory, this process has 22.50 GiB memory in use.
Of the allocated memory 20.10 GiB is allocated by PyTorch, and 1.90 GiB
is reserved by PyTorch but unallocated. If reserved but unallocated memory
is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
PartWhat it tells youLikely fix
"Tried to allocate X"Size of the request that failedLarge = batch/sequence too big
"of which Y is free"Free VRAM at that momentSmall free + small "this process" = another process is using the GPU
"allocated by PyTorch"Memory held by tensorsReduce model/batch/activations
"reserved but unallocated"Cached but fragmented memoryUse expandable_segments
"non-PyTorch memory"CUDA context, other libraries, other processesClose apps; check nvidia-smi

Step 2: Find what is using memory

nvidia-smi                          # all processes and memory
nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv

In Python:

import torch
print(torch.cuda.memory_allocated() / 1e9, "GB allocated")
print(torch.cuda.memory_reserved() / 1e9, "GB reserved")
print(torch.cuda.max_memory_allocated() / 1e9, "GB peak")
print(torch.cuda.memory_summary())

For deep analysis, record a memory snapshot and open it in PyTorch's memory visualiser:

torch.cuda.memory._record_memory_history()
# ... run the failing step ...
torch.cuda.memory._dump_snapshot("snapshot.pickle")   # view at pytorch.org/memory_viz

See our guide to nvidia-smi.

Step 3: Estimate how much memory you need

WorkloadApproximate VRAM
Inference, FP162 bytes × parameters + KV cache + overhead
Inference, 4-bit~0.55–0.6 bytes × parameters + KV cache
Full training (mixed precision, Adam)~16 bytes × parameters + activations
LoRA (16-bit base)2 bytes × parameters + small adapter states + activations
QLoRA (4-bit base)~0.6 bytes × parameters + adapters + activations

Example: full fine-tuning a 7B model needs about 112 GB before activations, so it will never fit on a 24 GB GPU without LoRA/QLoRA or multi-GPU sharding. Use our VRAM calculator and see how much VRAM for an LLM.

Fixes for training

1. Reduce batch size and use gradient accumulation

accum_steps = 4
for i, (x, y) in enumerate(loader):
    loss = model(x, y) / accum_steps
    loss.backward()
    if (i + 1) % accum_steps == 0:
        optimizer.step()
        optimizer.zero_grad(set_to_none=True)

Same effective batch size, a quarter of the activation memory.

2. Use mixed precision (BF16 or FP16)

with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
    loss = model(x, y)

Halves activation memory and speeds up tensor cores. See mixed precision training.

3. Enable gradient checkpointing

model.gradient_checkpointing_enable()   # Hugging Face models

Recomputes activations during the backward pass, often cutting activation memory by 60–70% at about 20–30% extra compute.

4. Shorten sequence length

Attention and activation memory grow with sequence length. Halving max_length can free a lot of memory. Use FlashAttention (attn_implementation="flash_attention_2" or PyTorch SDPA) to avoid quadratic attention memory. See FlashAttention explained.

5. Use a memory-efficient optimizer

OptimizerOptimizer state per parameter
AdamW (FP32 states)8 bytes
8-bit AdamW (bitsandbytes)~2 bytes
AdafactorMuch less (factored)
SGD with momentum4 bytes
import bitsandbytes as bnb
optimizer = bnb.optim.AdamW8bit(model.parameters(), lr=2e-4)

6. Use LoRA or QLoRA instead of full fine-tuning

Train less than 1% of parameters with a frozen (optionally 4-bit) base model. See What is LoRA?

7. Shard across GPUs (FSDP or DeepSpeed ZeRO)

If the model and optimizer states don't fit on one GPU, shard them across several. Note that plain DDP replicates the full model on every GPU, so it doesn't save memory. See distributed training parallelism.

8. Don't keep the computation graph alive

running_loss += loss.item()      # not: running_loss += loss
preds.append(out.detach().cpu()) # not: preds.append(out)

Use torch.inference_mode() (or torch.no_grad()) for validation.

Fixes for fragmentation and leaks

9. Set expandable segments

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

Helps when "reserved but unallocated" memory is large, especially with variable input sizes. Recent PyTorch versions also accept the device-generic PYTORCH_ALLOC_CONF.

10. Free memory properly (especially in Jupyter)

del model, optimizer, outputs
import gc; gc.collect()
torch.cuda.empty_cache()

empty_cache() only releases cached blocks no longer referenced; if variables still point to tensors (including Jupyter's _ and Out history), memory stays used. Restarting the kernel is the surest reset.

Fixes for LLM inference

11. vLLM

vllm serve <model> --gpu-memory-utilization 0.85 --max-model-len 8192 --max-num-seqs 64
  • vLLM pre-allocates most VRAM for the KV cache by default; lower --gpu-memory-utilization if other processes share the GPU.
  • Reduce --max-model-len (context) and --max-num-seqs (concurrent sequences).
  • Use FP8 or 4-bit weights, FP8 KV cache (--kv-cache-dtype fp8), or --tensor-parallel-size 2. See vLLM vs SGLang.

12. llama.cpp, Ollama and LM Studio

ToolFix
llama.cppLower -ngl (layers on GPU), reduce -c (context), quantize KV cache (--cache-type-k q8_0), offload MoE experts (--n-cpu-moe)
OllamaReduce num_ctx, choose a smaller quantization tag, set OLLAMA_NUM_PARALLEL=1
LM StudioLower GPU offload slider and context length

See run an LLM locally and LLM quantization.

13. Use a smaller or more quantized model

Going from FP16 to 4-bit cuts weight memory by about 70%. See KV cache explained for context-length memory.

Fixes for Stable Diffusion and image models

14. Use memory-saving options

ToolOptions
Diffuserspipe.enable_model_cpu_offload(), pipe.enable_attention_slicing(), pipe.vae.enable_tiling(), FP16/FP8 weights
AUTOMATIC1111 / Forge--medvram or --lowvram
ComfyUI--lowvram, quantized (GGUF/FP8) models

Lower resolution and batch size also help. See best GPU for Stable Diffusion.

When nothing works

15. Use a bigger GPU (or more GPUs)

Sometimes the workload genuinely needs more memory. Options:

NeedOption
24 GBRTX 3090/4090; see used RTX 3090 for AI
32 GBRTX 5090; see RTX 5090 for AI
48–96 GBL40S, RTX PRO 6000; see RTX PRO 6000 for AI
80–141 GBH100, H200 in the cloud; see NVIDIA H200 specs

Renting is cheap for short jobs: on December 1, 2026, our GPU price report listed A100s from $0.89/hour and H100s from $1.80/hour.

Quick decision table

SymptomMost likely fix
OOM on the first batchBatch size, sequence length, quantization or LoRA
OOM after several batchesGraph kept alive (loss.item()), growing tensors, variable lengths (use expandable segments)
OOM only during validationMissing torch.no_grad() / inference_mode()
Large "reserved but unallocated"expandable_segments:True
Little free memory but your process uses littleAnother process: check nvidia-smi
OOM when loading a modelModel too big: quantize, offload or use a bigger GPU
Jupyter OOM after re-running cellsRestart kernel

Frequently asked questions

What does "CUDA out of memory" mean?

Your GPU didn't have enough free VRAM for an allocation PyTorch (or another CUDA program) requested.

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

Rarely on its own. It releases unused cached memory to other processes, but memory held by live tensors stays allocated.

Why do I get CUDA out of memory with free memory showing?

Usually fragmentation (free memory split into blocks too small for the request) or another process using memory. Try expandable_segments:True and check nvidia-smi.

How do I fix CUDA out of memory in Stable Diffusion?

Lower resolution and batch size, use --medvram/--lowvram, attention slicing, VAE tiling or CPU offload, and FP16/FP8 models.

Can I use system RAM when the GPU runs out?

Some tools can offload layers to CPU RAM (llama.cpp, Accelerate's device_map="auto", ComfyUI low-VRAM modes), but it is much slower.

Sources and further reading

Think you understand it now? Prove it.

Solve real Tensor Core math in the TensorCore.si Challenge and earn a certificate with your name.

Take the challenge

Leave a Reply

Your email address will not be published. Required fields are marked *