Skip to content
VLASIFY™
TroubleshootingHPC, GPU & Linux

CUDA out of memory: diagnose and fix GPU memory errors

Updated · Scientifically reviewed by Dinkar Mishra, PhD on

Short answer

The GPU ran out of device memory for the next allocation. First check with nvidia-smi that no other process holds memory. Then reduce what your job needs: smaller batch or domain per GPU, mixed precision (FP16/BF16), activation checkpointing, freeing unused tensors, or more GPUs through data or domain decomposition. torch.cuda.empty_cache() does not free memory still referenced by tensors.

Who this is for

Researchers training neural networks or running GPU-accelerated simulations (PIC, CFD, molecular dynamics) who hit GPU memory limits.

Software

CUDA 11.x–12.xPyTorch ≥ 2.0 (for the PyTorch examples)

Symptoms

PyTorch:

torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB.
GPU 0 has a total capacity of 39.39 GiB of which 1.21 GiB is free.

CUDA C/C++ and simulation codes report cudaErrorMemoryAllocation, out of memory from cudaMalloc, or an allocator error from their memory framework (for example AMReX arenas in WarpX).

Diagnosis

1. Is someone else using the GPU?

nvidia-smi --query-gpu=index,name,memory.used,memory.total --format=csv
nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv

If memory is used before your job starts, find and end the owning process. On a cluster, request the GPU through Slurm (--gpus=1) so you get exclusive access.

2. How much does your program need, and when? In PyTorch, print peak usage around the suspect step:

import torch

torch.cuda.reset_peak_memory_stats()
# ... run one training or simulation step here ...
print(f"allocated now: {torch.cuda.memory_allocated() / 2**30:.2f} GiB")
print(f"peak:          {torch.cuda.max_memory_allocated() / 2**30:.2f} GiB")
print(torch.cuda.memory_summary(abbreviated=True))

Memory that grows every iteration is a leak, usually from keeping tensors (or their computation graph) in a Python list. Memory that is high from the first step means the problem simply does not fit.

3. Estimate the requirement. For neural networks, weights + gradients + optimizer states take about 16 bytes per parameter with FP32 Adam, plus activations, which scale with batch size. For grid or particle codes, memory scales with cells × variables × bytes, plus particles × attributes × bytes. Both estimates are in our GPU memory calculator.

Fixes

Start at the top; the first fixes are the cheapest.

  1. Stop leaks. Log loss.item(), not loss. Wrap evaluation in with torch.no_grad():. Delete large intermediates you no longer need.

  2. Reduce work per GPU. Lower the batch size, and use gradient accumulation if you need the same effective batch. For simulations, give each GPU a smaller subdomain (more MPI ranks or GPUs) or reduce particles per cell where convergence tests allow.

  3. Use mixed precision. BF16/FP16 autocast roughly halves activation memory on modern GPUs:

    with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
        out = model(batch)
        loss = loss_fn(out, target)
  4. Activation checkpointing. Recompute activations in the backward pass instead of storing them (torch.utils.checkpoint). This trades roughly 20–30% more compute for much less memory in deep networks.

  5. Reduce fragmentation. Configure the PyTorch CUDA allocator (see the “CUDA semantics” notes for the expandable-segments option in your version), and avoid tensor shapes that change every step.

  6. Scale out. Data parallelism (DDP) does not reduce per-GPU memory for the model itself. Sharded approaches (FSDP, ZeRO) or model parallelism do. For PIC and CFD codes, domain decomposition across more GPUs is the standard route.

When to get help

If your simulation code runs out of memory only at large scale, the cause may be load imbalance (one GPU owns most of the particles), diagnostics that gather full fields onto one rank, or allocator settings. These need code-specific profiling, which we do as part of our HPC and GPU services.

Assumptions and limitations

  • The PyTorch functions shown exist in PyTorch 2.x. Allocator configuration options change between releases, so check the documentation for your installed version.
  • Figures such as “16 bytes per parameter” assume FP32 Adam without sharding. Activation memory depends heavily on architecture and sequence or grid size, and is not included.
  • Unified/managed memory can avoid hard errors by paging to host memory, but usually at a large performance cost.

Frequently asked questions

nvidia-smi shows memory in use but my script has ended. What is holding it?+

Usually another process: a Jupyter kernel that is still alive, a zombie worker from a DataLoader, or another user's job on a shared GPU. nvidia-smi lists processes by PID. End your own idle kernels; on shared systems ask the administrator.

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

Rarely. It returns cached but unused blocks to the driver so other processes can use them, but it cannot free memory still referenced by live tensors. Delete references (del x), avoid keeping graph history (use .item() or .detach() for logged values), and run validation under torch.no_grad().

Why do I get out-of-memory errors even though free memory looks sufficient?+

Fragmentation: the allocator may need one large contiguous block that is not available even if the total free memory is enough. Recent PyTorch versions offer an expandable-segments option in the CUDA allocator configuration to reduce this. See the CUDA semantics notes for your version.

How much GPU memory does my model need?+

For training with Adam in FP32, weights, gradients and optimizer states need about 16 bytes per parameter, before activations. Our GPU memory calculator estimates this, and the activation memory depends on batch size and architecture.

References

  1. CUDA semantics: memory management · PyTorch documentation
  2. PyTorch FAQ: my model reports “cuda runtime error(2): out of memory” · PyTorch documentation
  3. nvidia-smi documentation · NVIDIA
  4. torch.utils.checkpoint (activation checkpointing) · PyTorch documentation

Still stuck?

Send us the error output and your job script. A computational scientist will diagnose it, usually within a day.

Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.

Spotted an error or an outdated command? Tell us. We correct verified issues promptly.

Related guides

How Vlasify can help

Get a Quote