You start training or loading a model, and seconds later PyTorch stops with torch.OutOfMemoryError: CUDA out of memory. The GPU has a fixed amount of memory, and something in your run asked for more than was free at that moment.
This guide shows how to read the error, measure what is really using memory, and apply fixes in order of effort: smaller batches, mixed precision, gradient checkpointing, and allocator settings. Commands assume Linux with an NVIDIA GPU and a CUDA-enabled PyTorch build.
Quick fix: Halve the batch size, wrap inference in
torch.inference_mode(), and use mixed precision (torch.autocast). Checknvidia-smifor other processes holding memory before changing code.
What does the CUDA out of memory error tell you?
A typical message looks like this:
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.50 GiB.
GPU 0 has a total capacity of 23.65 GiB of which 812.00 MiB is free.
Including non-PyTorch memory, this process has 22.10 GiB memory in use.
Of the allocated memory 20.31 GiB is allocated by PyTorch, and 1.42 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.
Read it in parts. Tried to allocate is the single request that failed. Allocated by PyTorch is memory held by live tensors. Reserved but unallocated is cached by PyTorch’s allocator; a large value hints at fragmentation. Older PyTorch versions raise RuntimeError with similar text.
Step 1: Is another process using the GPU?
- Check current usage:
nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csvYou should see each GPU’s used and total memory, plus a list of processes. A forgotten Jupyter kernel or an Ollama server holding a model is a common culprit.
- Stop the stray process, then rerun:
kill <PID> # only for processes you own and recognizeYou should see that PID disappear from the
nvidia-smiprocess list.
Warning: On shared machines, never kill processes you do not own. Ask the owner or use a different GPU via
CUDA_VISIBLE_DEVICES=1.
Step 2: Measure memory from inside PyTorch
PyTorch exposes allocator statistics. Print them around the step that fails:
import torch
def report(tag: str) -> None:
alloc = torch.cuda.memory_allocated() / 2**30
reserved = torch.cuda.memory_reserved() / 2**30
peak = torch.cuda.max_memory_allocated() / 2**30
print(f"{tag}: allocated={alloc:.2f} GiB reserved={reserved:.2f} GiB peak={peak:.2f} GiB")
torch.cuda.reset_peak_memory_stats()
report("start")
# ... model load, forward, backward ...
report("after step")
Typical output from a training loop:
start: allocated=0.00 GiB reserved=0.00 GiB peak=0.00 GiB
after step: allocated=6.84 GiB reserved=9.02 GiB peak=14.37 GiB
The peak value matters most, because the failure happens at the high-water mark, usually during the backward pass. For a full breakdown, print(torch.cuda.memory_summary()) prints a detailed table.
Step 3: Reduce batch size or sequence length
Activation memory scales roughly with batch size and, for transformers, with sequence length (attention can scale worse). Halving either is the fastest test.
- Lower the batch size and keep the effective batch with gradient accumulation:
accum_steps = 4 optimizer.zero_grad(set_to_none=True) for i, (x, y) in enumerate(loader): # loader batch_size reduced 4x loss = loss_fn(model(x.cuda()), y.cuda()) / accum_steps loss.backward() if (i + 1) % accum_steps == 0: optimizer.step() optimizer.zero_grad(set_to_none=True)You should see the peak value from Step 2 drop roughly in proportion to the batch reduction.
Step 4: Use mixed precision
Running most operations in bfloat16 or float16 roughly halves activation memory and often speeds up modern GPUs. bfloat16 needs Ampere-class or newer hardware; float16 needs a gradient scaler.
use_bf16 = torch.cuda.is_bf16_supported()
dtype = torch.bfloat16 if use_bf16 else torch.float16
scaler = torch.amp.GradScaler("cuda", enabled=not use_bf16)
with torch.autocast(device_type="cuda", dtype=dtype):
loss = loss_fn(model(x), y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
You should see a lower peak and no change in loss behavior beyond small numerical noise. If loss becomes nan with float16, try bfloat16 or check the scaler.
Step 5: Inference mode and no stored graphs
During evaluation, autograd still records operations unless told otherwise. Wrap inference in torch.inference_mode() and avoid accumulating tensors that keep graphs alive.
model.eval()
with torch.inference_mode():
logits = model(x)
# Bad: keeps the whole graph for every step
# history.append(loss)
# Good: store a Python float
history.append(loss.item())
You should see memory stay flat across evaluation batches instead of climbing.
Step 6: Gradient checkpointing for large models
Checkpointing discards some activations in the forward pass and recomputes them during backward. It trades extra compute for lower memory. Hugging Face models usually expose model.gradient_checkpointing_enable(); plain PyTorch code uses torch.utils.checkpoint.
from torch.utils.checkpoint import checkpoint
def forward(self, x):
for block in self.blocks:
x = checkpoint(block, x, use_reentrant=False)
return self.head(x)
Expect slower steps (often noticeably slower) in exchange for a much lower peak.
Step 7: Fragmentation and PYTORCH_CUDA_ALLOC_CONF
If the error reports a large reserved but unallocated amount, memory may be fragmented. Recent PyTorch versions support expandable segments:
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
python train.py
Supported options vary between releases, so check the CUDA semantics page for your version.
Note:
torch.cuda.empty_cache()returns cached blocks to the driver so other processes can use them. It does not free memory held by live tensors and rarely fixes an OOM inside the same process.
How do you load a large model with less GPU memory?
For inference with Hugging Face Transformers, load weights directly in half precision instead of float32. Float32 weights need about 4 bytes per parameter; bfloat16 needs about 2, before activations and the KV cache are counted.
import torch
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
"your-org/your-model",
torch_dtype=torch.bfloat16,
device_map="auto", # requires the accelerate package
)
print(model.get_memory_footprint() / 2**30, "GiB")
You should see a footprint close to half of the float32 figure. With device_map="auto", layers that do not fit on the GPU may be placed on the CPU, which avoids the OOM but runs much slower. Generation length matters too: long outputs grow the KV cache, so cap max_new_tokens while debugging.
Symptom-cause-fix table
| Symptom | Likely cause | Fix |
|---|---|---|
| OOM on the first batch | Model + batch too large | Smaller batch, mixed precision, quantized or smaller model |
| OOM after many steps | Tensors kept alive (lists of losses, logits) | Store .item(), detach, use inference mode |
| OOM only during evaluation | Autograd enabled or bigger eval batch | torch.inference_mode(), separate eval batch size |
| Large reserved-but-unallocated | Fragmentation | expandable_segments:True |
| Free memory low before your run | Another process | Check nvidia-smi, choose another GPU |
FAQ
Why does nvidia-smi show more memory than memory_allocated()?
nvidia-smi includes the CUDA context, PyTorch’s cached-but-free blocks, and other libraries such as cuDNN workspaces. memory_allocated() counts only live tensors.
Can I run a model larger than my GPU memory?
For inference, quantization, CPU offload (for example Accelerate’s device_map="auto"), or a serving engine can help. See our vLLM vs Ollama comparison for serving options.
Does setting the batch size to 1 always fix it?
No. If the weights plus optimizer state alone exceed GPU memory, batch size does not help. Adam keeps extra state per parameter, so consider a smaller model, lower-precision weights, or a memory-efficient optimizer.
Why is torch.cuda.is_available() False instead?
That is a different problem: PyTorch cannot see the GPU at all. Check the driver and whether you installed a CPU-only wheel.
Conclusion
Treat a CUDA OOM as a measurement problem first. Check other processes, record the peak, then apply the cheapest fix that brings the peak under the limit. Batch size, mixed precision, and inference mode solve most cases; checkpointing and allocator tuning handle the rest.
Related guides
- Hugging Face Transformers Python Tutorial: Run a Small Model Locally
- PyTorch to ONNX Runtime: Export and Inference Workflow
- vLLM vs Ollama: Local Development or High-Throughput Serving?


Leave a Reply