The exact error and what each part means
Current PyTorch raises torch.OutOfMemoryError with a message built in the CUDA caching allocator. It reads: "CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacity of 79.19 GiB of which 1.12 GiB is free. Of the allocated memory 74.30 GiB is allocated by PyTorch, and 2.85 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." The sizes here are an example; yours will differ.
Every figure in that line is a clue. The requested size tells you how big the failing tensor was. Free memory tells you how much the driver could still hand out. Allocated by PyTorch is memory held by live tensors. Reserved but unallocated is memory the allocator has cached but cannot use for this request, usually because it is split into pieces that are too small.
PyTorch’s CUDA notes define memory_allocated() as memory occupied by tensors and memory_reserved() as the total memory managed by the caching allocator. The gap between the two is the number to watch for fragmentation. The exception class is also exposed as torch.cuda.OutOfMemoryError, so one except clause catches it.
| Part of the message | What it tells you | Where to look next |
|---|---|---|
| Tried to allocate X | Size of the tensor that failed | Batch, sequence length or a large intermediate |
| X is free | Memory the driver could still give | Other processes in nvidia-smi |
| Allocated by PyTorch | Memory held by live tensors | Weights, optimizer state, activations, leaks |
| Reserved but unallocated | Cached memory that does not fit the request | Fragmentation and expandable_segments |
References: PyTorch source: CUDACachingAllocator.cpp · PyTorch CUDA semantics: memory management · PyTorch torch.cuda.OutOfMemoryError
Causes, ranked by how often they occur
The most common cause is plain size: a batch, image resolution or sequence length larger than the GPU can hold. Activation memory grows with batch size and, for attention models, with sequence length, so an error that appears only on long samples points here.
Second is training state. The ZeRO paper counts 16 bytes per parameter for mixed-precision training with Adam: 2 for fp16 weights, 2 for gradients and 12 for fp32 master weights and two optimizer moments. A 7B-parameter model therefore needs about 112 GB before activations, which is why full fine-tuning fails on cards that run inference fine. The LLM VRAM requirements guide works through the arithmetic.
Third are tensors kept alive by accident: summing loss tensors across steps (which keeps each step’s graph), storing outputs in a list, or running evaluation without torch.no_grad(). Fourth is another process holding memory, such as a second notebook kernel or a stale job. Fifth is fragmentation, where free memory exists but not in one block large enough.
References: ZeRO: memory optimizations toward training trillion parameter models · PyTorch CUDA semantics: memory management
Diagnostic commands to run first
Start outside Python. nvidia-smi lists every process using the GPU and its memory. If a process you do not expect holds gigabytes, stop it before you change any code. On a rented machine this is often a leftover kernel from an earlier session.
Inside the job, print torch.cuda.memory_allocated() and torch.cuda.memory_reserved() at a few points in a step: after the model loads, after the forward pass, after backward and after the optimizer step. The CUDA notes recommend memory_stats() and memory_summary() for tuning; memory_summary() prints a readable table of the same counters.
For a full picture, record a memory snapshot. Call torch.cuda.memory._record_memory_history(), run the steps that fail, then call torch.cuda.memory._dump_snapshot("my_snapshot.pickle") and drag the file into the viewer at pytorch.org/memory_viz. PyTorch’s guide notes that out-of-memory errors appear in the snapshot as OOM events, and the timeline shows which allocations were live at that moment and where in your code they came from.
| Command | What it shows |
|---|---|
| nvidia-smi | Every process on the GPU and its memory use |
| torch.cuda.memory_allocated() | Bytes held by live tensors |
| torch.cuda.memory_reserved() | Bytes cached by the allocator |
| torch.cuda.memory_summary() | Readable table of allocator counters |
| torch.cuda.memory._record_memory_history() | Starts recording allocations with stack traces |
| torch.cuda.memory._dump_snapshot(path) | Writes a snapshot for pytorch.org/memory_viz |
References: NVIDIA System Management Interface · PyTorch CUDA semantics: memory management · PyTorch: understanding CUDA memory usage
Fixes for training jobs
Halve the batch size and keep the effective batch with gradient accumulation: run several smaller forward and backward passes, then one optimizer step. Train in bf16 or fp16 with torch.autocast, which runs matrix math in lower precision and shrinks activations. Activation checkpointing with torch.utils.checkpoint discards intermediate activations in the forward pass and recomputes them in backward, trading compute for memory.
Fix accidental retention next. Log loss.item() rather than the loss tensor. Wrap evaluation in torch.no_grad() or torch.inference_mode(). Delete large intermediates you no longer need. If you only need to adapt a model, train adapters instead of all weights: LoRA trains small low-rank matrices and leaves the base frozen, so gradients and optimizer state cover a fraction of the parameters. See LoRA fine-tuning cost.
For models that do not fit on one GPU even with these changes, shard weights, gradients and optimizer state across GPUs with FSDP or ZeRO. That moves the problem from one card to several and is covered in PyTorch FSDP training.
References: PyTorch automatic mixed precision · PyTorch torch.utils.checkpoint · Hugging Face PEFT: LoRA · ZeRO: memory optimizations toward training trillion parameter models
Fragmentation and the allocator settings
When reserved but unallocated memory is large, fragmentation is the likely cause. The allocator setting that helps most is expandable_segments. PyTorch’s CUDA notes describe it as letting the allocator grow one segment as needed instead of creating a segment per allocation, which reduces fragmentation when tensor sizes change often, for example with varying batch sizes or sequence lengths.
Check the variable name. In the current PyTorch 2.15 documentation the setting lives in PYTORCH_ALLOC_CONF, and PYTORCH_CUDA_ALLOC_CONF is kept as an alias for backward compatibility. The error text still prints the older name, and both work. Set it before the process starts: PYTORCH_ALLOC_CONF=expandable_segments:True python train.py.
Two other options exist. max_split_size_mb stops the allocator from splitting blocks above a size and is described as a last resort. garbage_collection_threshold makes the allocator reclaim unused cached blocks once usage passes a fraction of capacity. torch.cuda.empty_cache() does not help here: the notes say it releases cached memory to other applications but does not increase the memory available to PyTorch.
References: PyTorch CUDA semantics: memory management · PyTorch source: CUDACachingAllocator.cpp

CUDA out of memory: symptom, check, fix
Use this table as a first pass. Change one setting at a time and rerun the same step so you know which change worked.
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
| Fails on the first step | Batch or model too large | memory_allocated after model load | Smaller batch, bf16, checkpointing |
| Fails only on long samples | Sequence length spikes activations | Log sequence length at failure | Cap length, bucket by length |
| Fails at the optimizer step | Optimizer state | Allocated jumps after step() | LoRA, 8-bit optimizer, FSDP |
| Memory climbs every step | Tensors kept alive | Snapshot timeline grows | loss.item(), no_grad in eval |
| Little free memory at startup | Another process | nvidia-smi process list | Stop the stale process |
| Large reserved but unallocated | Fragmentation | reserved minus allocated | expandable_segments:True |
References: NVIDIA System Management Interface · PyTorch CUDA semantics: memory management · PyTorch: understanding CUDA memory usage · PyTorch torch.utils.checkpoint
Prevent the error before a long run
Run the largest batch and the longest sequence first, not a random sample. Many jobs pass a short test and fail hours later on one long document. Sorting a few batches by length and running them in a warm-up catches this in minutes.
Log memory_allocated, memory_reserved and the peak counter every N steps. Save checkpoints often enough that a failure costs little; GPU training checkpoints covers the schedule. Leave headroom of a few gigabytes rather than tuning to the last megabyte, because allocator behaviour and library versions change.
References: PyTorch CUDA semantics: memory management
When the answer is a bigger GPU
Sometimes the model simply does not fit. If weights plus optimizer state exceed the card before any activations, no setting will help. Estimate the need with the VRAM calculator and compare it with the card. NVIDIA lists 80 GB on the H100 and A100 80GB, 48 GB on the L40S and 141 GB on the H200.
A bigger GPU also makes sense when the workarounds cost too much time. Activation checkpointing adds recompute, and gradient accumulation adds steps. If a job on a 24 GB card needs both plus a tiny batch, an 80 GB card such as the H100 may finish sooner overall. For memory-bound work, the H200 adds capacity on the same architecture.
| GPU | Memory (NVIDIA spec) |
|---|---|
| L40S | 48 GB |
| A100 80GB | 80 GB |
| H100 SXM | 80 GB |
| H200 SXM | 141 GB |
References: NVIDIA H100 specifications · NVIDIA A100 specifications · NVIDIA L40S specifications · NVIDIA H200 specifications
Checklist and next step
Read the error’s four numbers. Check nvidia-smi for other processes. Print allocated and reserved memory around each phase of a step. Lower the batch, use bf16, add checkpointing and accumulation. Remove retained tensors. Set expandable_segments if reserved memory is large. Record a snapshot if the cause is still unclear.
If the model needs more memory than the card has, size the GPU to the job. NeuraMesh rents cloud GPUs by the hour: choose a GPU, plan, GPU count, hours and region on rent GPUs and you receive a confirmed quotation, typically within one business day, with nothing charged until you approve it.
NeuraMesh prices for these GPUs
| GPU | Memory | Data center | Value |
|---|---|---|---|
| RTX 4090 | 24 GB | $0.46 | $0.40 |
| L40S | 48 GB | $1.26 | $0.54 |
| A100 | 80 GB | $1.56 | $0.98 |
| H100 | 80 GB | $2.88 | $2.00 |
Every order is confirmed in a quotation before you pay. See all GPU prices.
Questions readers ask
How do I fix CUDA out of memory in PyTorch?
Lower the batch size, train in bf16 with autocast, add activation checkpointing and gradient accumulation, and make sure evaluation runs under torch.no_grad(). Check nvidia-smi for other processes. If reserved but unallocated memory is large, set PYTORCH_ALLOC_CONF=expandable_segments:True before starting the job.
Does torch.cuda.empty_cache() fix out-of-memory errors?
Rarely. PyTorch’s documentation says it releases unused cached memory so other applications can use it, but it does not increase the memory available to PyTorch, because memory held by live tensors is not freed.
Is it PYTORCH_ALLOC_CONF or PYTORCH_CUDA_ALLOC_CONF?
The current PyTorch documentation names PYTORCH_ALLOC_CONF and keeps PYTORCH_CUDA_ALLOC_CONF as an alias for backward compatibility. The out-of-memory message still prints the older name. Either works for expandable_segments:True.
Why does memory grow every training step?
Something keeps tensors alive. Common culprits are adding the loss tensor to a running total, storing model outputs in a list, or running validation with gradients enabled. A memory snapshot viewed at pytorch.org/memory_viz shows which allocations keep growing and the line that created them.
How much GPU memory does fine-tuning need?
For full fine-tuning with Adam in mixed precision, the ZeRO paper counts about 16 bytes per parameter before activations, so a 7B model needs roughly 112 GB. LoRA and QLoRA cut this sharply because only small adapter weights carry gradients and optimizer state.
Sources and editorial notes
- PyTorch source: CUDACachingAllocator.cpp
- PyTorch CUDA semantics: memory management
- PyTorch torch.cuda.OutOfMemoryError
- ZeRO: memory optimizations toward training trillion parameter models
- NVIDIA System Management Interface
- PyTorch: understanding CUDA memory usage
- PyTorch automatic mixed precision
- PyTorch torch.utils.checkpoint
- Hugging Face PEFT: LoRA
- NVIDIA H100 specifications
- NVIDIA A100 specifications
- NVIDIA L40S specifications
- NVIDIA H200 specifications
Primary documentation reviewed November 24, 2026. Provider descriptions reflect published documentation. Recommendations are our analysis; worked figures are illustrative unless explicitly stated otherwise. No independent provider benchmark or uptime ranking is claimed.
Need this GPU? Rent it from NeuraMesh: choose a GPU and plan, get a confirmed quotation, and pay only when you approve. See pricing.



