You start a training run or load a model, and it stops with torch.cuda.OutOfMemoryError. The cause is not always a GPU that is too small. Sometimes the VRAM is really full. Sometimes PyTorch holds free memory in small pieces that it cannot use.
Each case needs a different fix. This guide shows you how to fix CUDA out of memory on a GPU server step by step.
What CUDA Out of Memory Error Means
PyTorch asked the GPU for memory, but the GPU could not give enough in one piece. There are two common reasons:
- True VRAM exhaustion: Your model, data, and cache need more memory than the card has.
- Fragmentation: PyTorch keeps freed memory in a cache. The free space is split into small gaps, so a large request fails even though total free memory looks fine.
The error message shows how much memory PyTorch tried to get, how much it already uses, and how much is reserved but unallocated. If that last number is big, the problem is fragmentation. If it is small, the GPU is really full.
Step 1: Check the GPU with nvidia-smi
First, see what is using your GPU memory. The nvidia-smi tool shows how much memory is used and which programs use it. Run these commands on your server:
nvidia-sminvidia-smi --query-gpu=memory.used,memory.total --format=csvnvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv
Old Python scripts, Jupyter notebooks, and model servers usually keep memory in use. Also, memory.used shows the memory used right now, not the highest amount used.
Step 2: Check Memory Use in PyTorch
nvidia-smi shows what the whole GPU is using, but it can't show what PyTorch is doing inside.
To see that, you can add a few lines to your script. They show how much memory your code uses, how much PyTorch holds, and the highest amount used. Call the helper before and after the heavy step:
1import torch2 3def report(label):4 gib = 1024 ** 35 free, total = torch.cuda.mem_get_info()6 print(label,7 f"allocated={torch.cuda.memory_allocated()/gib:.2f} GiB",8 f"reserved={torch.cuda.memory_reserved()/gib:.2f} GiB",9 f"peak={torch.cuda.max_memory_allocated()/gib:.2f} GiB",10 f"free={free/gib:.2f} / {total/gib:.2f} GiB")11 12torch.cuda.reset_peak_memory_stats()13report("before")1415report("after")
allocated is the memory your data is using right now.
reserved is all the memory PyTorch is holding, including unused memory kept for later. It already includes allocated, so do not add them.
peak is the most allocated memory used since the last reset.
A big gap between reserved and allocated may mean fragmentation, but it does not prove it. For more detail, run print(torch.cuda.memory_summary()).
Step 3: Find and Stop Programs Using VRAM
Other programs on your server may be using GPU memory that your job needs. Before you change any code, find those programs and stop the ones you don't need. This is the fastest way to fix CUDA out of memory on a GPU server when another job is the cause.
Use the process IDs from Step 1 and run the commands below:
sudo kill PIDsudo fuser -v /dev/nvidia*
If you run Ollama, you must check which models are loaded and stop the ones you do not use:
ollama psollama stop MODEL_NAME
After a request, Ollama keeps the model in GPU memory for a few minutes. If you are not sure which tool to run on your server, read the Ollama vs vLLM comparison. Then, run nvidia-smi again to check that the memory is free.
Step 4: Lower Batch Size and Context Length
This is the most common way to fix CUDA out of memory on a GPU server. Activation memory grows with batch size, and the KV cache grows with context length.
- Set the batch size to
1 and confirm that it runs.
- Double it until it fails, then go back one step.
- Use gradient accumulation if you need a larger effective batch size.
- For LLMs, cut the maximum context length.
After each change, run the memory check again and compare the numbers. A smaller batch should lower peak by a clear amount. If peak stays the same, the batch size is not the problem.
Step 5: Turn On Mixed Precision
Mixed precision helps fix CUDA out of memory on a GPU server. It does most of the math in 16-bit numbers instead of 32-bit numbers, so it uses less memory and usually runs faster.
On newer GPUs, such as RTX 30-series, A100, and later, use bfloat16. It does not need a gradient scaler:
1with torch.autocast("cuda", dtype=torch.bfloat16):2 loss = model(inputs).loss3loss.backward()
On older cards, use float16 with torch.amp.GradScaler. Autocast keeps the weights in float32, so most of the memory you save comes from activations.
Step 6: Change the Allocator Settings
If reserved is much bigger than allocated, set this before you run your script:
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:Truepython train.py
This setting lets PyTorch grow its memory blocks instead of cutting them into fixed pieces. Newer PyTorch versions read PYTORCH_ALLOC_CONF, and the older name still works.
Also, you can use max_split_size_mb:128. It stops PyTorch from splitting large blocks, but it can make your code slower.
Do not rely on torch.cuda.empty_cache() as your main fix. It only frees memory that PyTorch is holding but not using. It does not free memory that your data is still using.
Step 7: Tune vLLM and Other Model Servers
Model servers use memory in their own way, so the fix is a little different here.
vLLM takes a fixed share of VRAM when it starts, so a full GPU in nvidia-smi is normal. If vLLM fails to start, you must lower the context length at first. Lower the memory share only if another program uses the same GPU:
vllm serve meta-llama/Llama-3.1-8B-Instruct \ --max-model-len 4096 \ --gpu-memory-utilization 0.85
Also, you can use a quantized model, such as 4-bit or 8-bit. For a full vLLM setup with a service file, check the OpenAI-compatible API server guide.
Example: CUDA OOM Before and After Fixing
This example shows how each fix changes GPU memory use. The numbers are only a sample, so your own results will differ. Run the memory check after every change and look for the same kind of drop.
| Change |
Peak allocated |
Reserved |
Result |
| Start (batch 32, fp32) |
22.4 GiB |
23.6 GiB |
OOM on 24 GiB card |
| Batch 8 |
9.8 GiB |
10.5 GiB |
Runs |
| Batch 8 + bfloat16 |
6.1 GiB |
6.9 GiB |
Runs, with space to grow |
When a GPU Upgrade Is the Right Fix for CUDA OOM
Upgrade only after you have tried every fix above. You need more VRAM when:
- The model itself does not fit. A 7B model in 16-bit needs about 14 GB for its weights alone. A 4-bit version needs about 4 to 5 GB, so try that first.
- It still fails with batch size 1 and a short context.
- Peak memory stays close to the total VRAM, even with mixed precision.
- Your app needs a long context or many users at the same time.
In these cases, you need a bigger GPU or more than one GPU. A dedicated GPU server gives you more VRAM without any code changes.
Conclusion
Most times, you can fix CUDA out of memory on a GPU server without new hardware. Read the error, check nvidia-smi, measure inside PyTorch, and then try the fixes one by one. If the model still does not fit at batch size 1, a larger GPU is the answer.