CUDA Out of Memory: Fixes for PyTorch, Ollama, llama.cpp
“CUDA out of memory” means your graphics card ran out of VRAM for what you asked it to load; here are the fixes for each AI tool.
The short version: make the job smaller before anything else. Use a smaller model or quantization, or a shorter context. In Ollama, lower the context with OLLAMA_CONTEXT_LENGTH or num_ctx. In llama.cpp, lower -ngl and -c. In PyTorch, lower the batch size, run inference inside torch.inference_mode(), and if the error says a lot is “reserved but unallocated”, set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True. Check nvidia-smi for other programs holding the GPU, and size models with our VRAM calculator before you load them.
The surprise: torch.cuda.empty_cache(), the line everyone pastes first, can’t give PyTorch a single extra megabyte. It only releases PyTorch’s unused cache to other programs on the same GPU.
Jake’s new 8 GB graphics card ran the photo-quote model fine for a week. Then he raised the context so it could read a whole repair history, and every request ended in a wall of red text: CUDA out of memory. Tried to allocate…
Jake: "Is the new card broken already?"
Ethan: "No, it’s full. You asked it to hold a longer conversation than fits next to the model. Shrink one of the two and it works again."
What the CUDA out of memory error actually tells you
PyTorch’s message is more useful than it looks. It is built from these parts:
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB.
GPU 0 has a total capacity of 7.75 GiB of which 1.10 GiB is free.
... Of the allocated memory 5.20 GiB is allocated by PyTorch,
and 1.30 GiB is reserved by PyTorch but unallocated.
If reserved but unallocated memory is large try setting
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.
| Part | What it tells you |
|---|---|
| Tried to allocate | The size of the one request that failed |
| total capacity / free | Your card’s VRAM and what was left at that moment |
| allocated by PyTorch | Memory your tensors really use |
| reserved but unallocated | Cached memory PyTorch holds but can’t use for this request; large values mean fragmentation |
The example numbers are illustrative; yours will differ. Ollama and llama.cpp print their own wording, but the cause is the same: something didn’t fit.
First check: what is using the GPU?
Run nvidia-smi. It lists every process holding GPU memory: a second Python session, a game, a browser with hardware acceleration, another AI app. Closing those is the cheapest fix there is.
One trap, from the PyTorch CUDA notes: PyTorch keeps freed memory in its own cache so later allocations are fast, and nvidia-smi shows that cache as used. Inside your script, these tell the real story:
import torch
print(torch.cuda.memory_allocated() / 2**30, "GiB used by tensors")
print(torch.cuda.memory_reserved() / 2**30, "GiB held by the cache")
print(torch.cuda.memory_summary()) # full breakdown
Fix CUDA out of memory in Ollama
Ollama loads the model plus memory for the conversation (the context). By default the context window is 4096 tokens; raising it is the most common way people run out. Three fixes, cheapest first:
- Lower the context: start Ollama with
OLLAMA_CONTEXT_LENGTH=4096 ollama serve, or send"options": {"num_ctx": 4096}in an API request, or type/set parameter num_ctx 4096in a chat. - Pull a smaller size or quantization of the same model (our Ollama models list shows the sizes).
- Run
ollama psto see how much of the model is on the GPU; a CPU/GPU split means it barely fits and will be slow.
Shrink the conversation memory itself
The context lives in a key/value (K/V) cache, stored at 16-bit by default. The 8-bit type q8_0 (see the Ollama FAQ) uses about half the memory of the default with a very small loss in precision, and q4_0 about a quarter with a more noticeable loss. It needs Flash Attention, which turns on automatically when your card supports it:
OLLAMA_FLASH_ATTENTION=1 OLLAMA_KV_CACHE_TYPE=q8_0 ollama serve
It is a global setting: every model then runs with that cache type. Two more server settings matter on a small card. OLLAMA_NUM_PARALLEL sets how many requests each model handles at once, and more parallel requests need more memory. ollama stop MODEL unloads a model straight away instead of waiting for it to time out.
Jake: "Ollama stays fast after I close the chat. Is that the problem?"
Ethan: "It keeps the model loaded for a while so the next answer is quick. If the photo-tagging tool needs the card next, stop the chat model first."
If Ollama ignores your graphics card entirely, that’s a different problem: see Ollama not using GPU.
Fix CUDA out of memory in llama.cpp
The llama.cpp server options give you direct control over what goes on the GPU:
| Option | What it does | Use it when |
|---|---|---|
-ngl N | Number of layers stored in VRAM (default auto) | Lower it to keep some layers on the CPU |
-c N | Context size (default: from the model) | Long contexts eat VRAM; set what you need |
-ctk q8_0 -ctv q8_0 | Store the KV cache at 8-bit instead of f16 | Long contexts on a small card |
--n-cpu-moe N | Keep expert weights of the first N layers on the CPU | Mixture-of-experts models |
llama-server -m model.gguf -c 8192 -ctk q8_0 -ctv q8_0
Notice what’s missing: -ngl. Current llama.cpp has a --fit option, on by default, that adjusts the settings you didn’t set so the model fits in device memory. Older guides tell you to add -ngl 99 (“put everything on the GPU”). Setting it yourself takes that choice away from --fit, and on a small card that is exactly how you get the error. Leave it unset first, and use -fitt if you want to keep a margin of free memory on each card.
When it still fails, the log tells you how big the allocation was and on which device (CUDA0 is the first card). Compare that number with the free memory nvidia-smi shows: if the buffer alone is bigger than the card, no setting other than a smaller model, context or quantization will help.
Fix CUDA out of memory in PyTorch
Inference
model.eval()
with torch.inference_mode(): # no gradients kept: much less memory
out = model(batch.to("cuda"))
Also lower the batch size, and load the model in half precision (torch.float16 or torch.bfloat16) if it supports it.
Training
- Halve the batch size until it fits; use gradient accumulation to keep the same effective batch.
- Train in mixed precision with
torch.autocast. - Use gradient checkpointing to trade extra compute for less memory.
- Don’t keep loss tensors in a list during training: store
loss.item(), or the whole graph stays in memory.
Fragmentation: “reserved but unallocated” is large
When sizes keep changing, memory gets cut into pieces too small to reuse. PyTorch’s allocator setting expandable_segments (experimental, off by default) lets allocations grow instead. Set it before Python starts:
# Linux / macOS
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
# Windows (PowerShell)
$env:PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
The older max_split_size_mb option is, in PyTorch’s own words, a last resort for jobs that abort with lots of inactive split blocks.
Jake: "So the new card can do the long repair histories after all?"
Ethan: "With the context set to what you really need and the cache at 8-bit, yes. The rest of the history goes into a summary first."
Fix CUDA out of memory in ComfyUI
ComfyUI’s VRAM options changed recently, and most guides haven’t caught up:
| Flag | What it does |
|---|---|
--lowvram | Does nothing when dynamic VRAM is enabled; otherwise runs the text encoders on the CPU |
--novram | For when low-VRAM mode isn’t enough |
--reserve-vram N | Keeps N GB free for other programs |
--cpu | Runs everything on the CPU (slow, but it works) |
Smaller model files (fp8 or GGUF versions of image models) usually help more than any flag. Image and video jobs also grow with resolution, frame count and batch size, so drop those before you swap models: a 1024×1024 image needs far more working memory than 768×768, and a batch of four needs roughly four times the decode memory of one. If you use the GPU for your desktop too, --reserve-vram 1 leaves about a gigabyte free so the screen doesn’t freeze while a job runs.
Fix CUDA out of memory in Hugging Face Diffusers and Transformers
For image models in Python, the Diffusers memory guide lists switches that cut peak memory without changing the model:
import torch
from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.float16)
pipeline.enable_model_cpu_offload() # keeps only the active part on the GPU
pipeline.vae.enable_tiling() # decodes big images tile by tile
pipeline.vae.enable_slicing() # decodes a batch one image at a time
Don’t also call pipeline.to("cuda"): CPU offload moves each part onto the GPU when it’s needed. enable_sequential_cpu_offload() saves even more memory, but the guide warns it is extremely slow.
For language models, Accelerate’s device_map="auto" fills the GPU first and puts the rest in system RAM. max_memory caps each device so the card keeps some headroom:
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="auto",
max_memory={0: "6GiB", "cpu": "24GiB"})
Two graphics cards and still out of memory
A second card doesn’t pool its memory with the first. Each card holds its own share of the model, so a split can fail on one card while the other has room, especially when the cards have different sizes. The fixes:
- Use one card: the Ollama GPU guide says
CUDA_VISIBLE_DEVICESlimits it to the cards you list; numeric IDs can change order, so the UUIDs fromnvidia-smi -Lare more reliable. - Set the split yourself in llama.cpp:
-ts 3,1puts three quarters of the model on the first card and one quarter on the second;-devpicks which devices to use. - Cap each card in Python:
max_memoryabove takes one entry per GPU.
Jake: "Would a second card from the shelf fix it?"
Ethan: "Only if the model can be split between them. The cache for the conversation still has to live somewhere, so we size the job first."
What torch.cuda.empty_cache() really does
It releases PyTorch’s unused cached memory so other GPU programs can use it. The PyTorch documentation is explicit that memory occupied by tensors is not freed, so it cannot increase the memory available to PyTorch itself. Use it when two programs share one GPU; don’t expect it to fix an out-of-memory error in the same script.
What does free memory inside your own script is dropping the last reference to a tensor or model. Once nothing points to it, PyTorch can reuse that memory for the next allocation; empty_cache() afterwards only matters if another program needs it:
del model, outputs # drop every reference, including in lists and dicts
import gc; gc.collect() # clear Python objects that still point at them
torch.cuda.empty_cache() # optional: hand the cache back to other programs
In a notebook, the last output cell can keep a tensor alive too. If memory never comes back, restarting the kernel is the honest fix.
How much VRAM do you need?
A model needs roughly its file size in VRAM, plus memory for the context. An 8B model at 4-bit is about a 5 GB download, so a 6-8 GB card runs it with a modest context; a 70B model at 4-bit is over 40 GB and needs a big card or a CPU split. Our LLM VRAM calculator gives the exact number for your card, model, quantization and context length before you download anything.
Jake’s checklist
- Run
nvidia-smiand close anything else on the GPU. - Shrink the context to what the job needs (Ollama
num_ctx, llama.cpp-c). - Pick a smaller quantization or model size; check it in the VRAM calculator.
- In PyTorch, lower the batch and use
inference_modefor inference. - Only if “reserved but unallocated” is large:
expandable_segments:True.
Jake: "So it was never the card."
Ethan: "Never. It was the size of the job. Now you can read the error and know which of the five steps to take."
Official references for this guide
- PyTorch CUDA semantics: memory management: the caching allocator,
memory_allocated,empty_cache,expandable_segmentsandmax_split_size_mb. - Ollama FAQ: context length, K/V cache quantization, Flash Attention and parallel requests; Ollama GPU guide for
CUDA_VISIBLE_DEVICES. - llama.cpp server options:
-ngl,-c,-ctk/-ctv,--fit,-tsand--n-cpu-moe. - ComfyUI launch options, and the Diffusers memory guide and Accelerate big-model guide for Python.
Frequently asked questions
What does "CUDA out of memory" mean?
Your program asked the graphics card for more memory than it had free. The model, its working data (the context or batch) and anything else on the GPU didn't fit in its VRAM. It is not a hardware fault.
How do I fix CUDA out of memory?
Use less VRAM: pick a smaller model or a smaller quantization, shorten the context, lower the batch size, or move part of the model to the CPU. Close other programs using the GPU first; nvidia-smi shows them.
Does torch.cuda.empty_cache() fix CUDA out of memory?
Usually not. It releases memory PyTorch has cached but isn't using, so other programs can use it, but it can't give PyTorch itself more memory. It helps only when another program on the same GPU needs the space.
Why do I get CUDA out of memory when nvidia-smi shows free memory?
Either the request was larger than the free space, or the free memory is split into pieces too small to use (fragmentation). If the error says a large amount is "reserved by PyTorch but unallocated", set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True.
Why does nvidia-smi show memory used after my PyTorch code finishes?
PyTorch keeps freed memory in its own cache to make later allocations fast, and nvidia-smi counts that cache as used. torch.cuda.memory_allocated shows what tensors really use; memory_reserved shows the cache.
What is PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True?
A PyTorch memory-allocator setting that lets allocations grow instead of creating new fixed blocks, which reduces fragmentation when sizes keep changing, such as a changing batch size. It is experimental and off by default; set it as an environment variable before Python starts.
How do I fix CUDA out of memory in Ollama?
Lower the context size (OLLAMA_CONTEXT_LENGTH, or num_ctx per request; the default is 4096 tokens), pull a smaller size or quantization of the model, and run ollama ps to see how much of the model sits on the GPU.
How do I fix CUDA out of memory in llama.cpp?
Lower -ngl so fewer layers go to the GPU, shrink the context with -c, and store the KV cache at lower precision with -ctk q8_0 -ctv q8_0. For mixture-of-experts models, --n-cpu-moe keeps expert weights on the CPU.
How do I fix CUDA out of memory in ComfyUI?
Try --novram when VRAM is tight, or --cpu as a slow last resort, and use smaller model files. On current ComfyUI with dynamic VRAM, --lowvram does nothing; without it, --lowvram moves the text encoders to the CPU.
Does reducing batch size fix CUDA out of memory?
Yes, for training and batched inference, memory grows with the batch. Halve it until the error stops; use gradient accumulation to keep the same effective batch size while training.
Can I use system RAM when VRAM runs out?
Yes, by putting part of the model on the CPU: llama.cpp's -ngl, Ollama's automatic split, or ComfyUI's low-VRAM modes. It works but runs much slower than all-GPU.
How much VRAM do I need to run a 7B or 8B model?
Roughly the model file size plus room for the context: an 8B model at 4-bit is about a 5 GB download, so a 6-8 GB card runs it with a modest context. Our LLM VRAM calculator gives the exact figure for your card and context length.
Why does CUDA out of memory happen only after a few minutes?
Memory use grew over time: a conversation or context getting longer, a memory leak such as storing tensors with their gradients in a list, or fragmentation from changing sizes. Check torch.cuda.memory_allocated over time to see which.
What does "cudaMalloc failed: out of memory" mean in Ollama?
Ollama's model runner couldn't get GPU memory while loading the model, its context cache or its working buffers. Lower the context, pick a smaller quantization, close other programs on the GPU, and update Ollama, since some releases misjudged how much would fit.
What does "unable to allocate CUDA0 buffer" mean?
CUDA0 is your first graphics card, and it couldn't hold a block of memory the model asked for. Compare the size in the log with the free memory nvidia-smi shows; if the block is bigger than the card, use a smaller model, context or quantization.
Why do I get CUDA out of memory with two GPUs?
Each card holds its own share of the model, so one card can fill up while the other has room, especially with cards of different sizes. Limit the job to one card with CUDA_VISIBLE_DEVICES, or set the split yourself with llama.cpp's -ts option.
How do I fix CUDA out of memory in Stable Diffusion with Diffusers?
Load the pipeline in float16, call enable_model_cpu_offload() instead of moving the whole pipeline to the GPU, and turn on vae.enable_tiling() for large images. Lower the resolution or batch size if it still fails.
Does Flash Attention reduce VRAM use in Ollama?
It allows the context cache to be stored at lower precision. With OLLAMA_KV_CACHE_TYPE=q8_0, the cache uses about half the memory of the default, with a very small loss in precision.
Is CUDA out of memory bad for my GPU?
No. It is a normal error your program reports when a memory request fails; nothing is damaged, and the GPU is fine once the program stops.
Revision note. Written November 27, 2026, for current PyTorch, Ollama, llama.cpp and ComfyUI releases. “Cut your coat according to your cloth”: size the job to the card, not the other way round.