CUDA error: out of memory

cudaErrorMemoryAllocationerror 2

In PyTorch the same failure appears as torch.OutOfMemoryError: CUDA out of memory. Tried to allocate ….

Common causes

The request is larger than the GPU

A T4 has about 14.5 GiB in total, and a shared machine can give one program less. Check the size you compute: a byte count built with int arithmetic can overflow into a huge number, and passing an element count where bytes are expected is off by a factor of 4 or 8.

Memory leaks in a loop

A cudaMalloc inside a loop without the matching cudaFree grows until it fails. In PyTorch, appending a loss tensor to a list (instead of loss.item()) keeps every iteration's graph alive.

Another process holds the memory

Run nvidia-smi to see other processes. A crashed notebook or a second training job can keep gigabytes reserved.

PyTorch training needs more memory than the model size suggests

Activations, gradients and optimizer state add up to several times the weights. Batch size, sequence length and running inference without torch.no_grad() are the usual levers. The caching allocator can also fragment memory, which is what PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True addresses.

Reproduce it

Press Run to execute this on a real NVIDIA GPU in the playground.

Repro: ask for more than the GPU has
main.cu
123456789101112131415161718
#include <cstdio>
#include <cuda_runtime.h>

int main() {
    size_t freeB, totalB;
    cudaMemGetInfo(&freeB, &totalB);
    printf("free %.2f GiB of %.2f GiB\n", freeB / 1073741824.0, totalB / 1073741824.0);

    float *d;
    cudaError_t err = cudaMalloc(&d, 20ull << 30);   // 20 GiB
    printf("cudaMalloc 20 GiB: %s (%s)\n", cudaGetErrorString(err), cudaGetErrorName(err));

    // Not sticky, but still recorded: read it once so a later check does not misreport it.
    printf("cudaGetLastError: %s\n", cudaGetErrorString(cudaGetLastError()));
    err = cudaMalloc(&d, 1 << 20);                   // 1 MiB works fine
    printf("cudaMalloc 1 MiB: %s\n", cudaGetErrorString(err));
    return 0;
}
Output on an NVIDIA T4
free 14.47 GiB of 14.57 GiB
cudaMalloc 20 GiB: out of memory (cudaErrorMemoryAllocation)
cudaGetLastError: out of memory
cudaMalloc 1 MiB: no error

Fix

Fixed: process the data in chunks that fit
main.cu
1234567891011121314151617181920212223242526272829303132333435
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

#define CUDA_CHECK(call)                                                  \
    do {                                                                  \
        cudaError_t err_ = (call);                                        \
        if (err_ != cudaSuccess) {                                        \
            fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__,       \
                    cudaGetErrorString(err_), cudaGetErrorName(err_));    \
            exit(1);                                                      \
        }                                                                 \
    } while (0)

int main() {
    const size_t total = 20ull << 30;          // 20 GiB of work
    size_t freeB, totalB;
    CUDA_CHECK(cudaMemGetInfo(&freeB, &totalB));
    size_t chunk = 1ull << 30;                 // 1 GiB at a time
    if (chunk > freeB / 2) chunk = freeB / 2;  // never more than half of what is free

    float *d;
    CUDA_CHECK(cudaMalloc(&d, chunk));
    int passes = 0;
    for (size_t done = 0; done < total; done += chunk) {
        size_t bytes = total - done < chunk ? total - done : chunk;
        CUDA_CHECK(cudaMemset(d, 0, bytes));   // stand-in for real work on this chunk
        passes++;
    }
    CUDA_CHECK(cudaDeviceSynchronize());
    printf("processed %.0f GiB in %d chunks of %.2f GiB\n",
           total / 1073741824.0, passes, chunk / 1073741824.0);
    CUDA_CHECK(cudaFree(d));
    return 0;
}
Output on an NVIDIA T4
processed 20 GiB in 20 chunks of 1.00 GiB

In PyTorch

PyTorch's message also says how much memory PyTorch itself has allocated and reserved. If reserved is much larger than allocated, memory is fragmented: try PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True. Otherwise reduce the batch size, wrap inference in torch.no_grad(), use torch.autocast for half precision, or free tensors with del x followed by torch.cuda.empty_cache().

PyTorch repro
main.py
1234567891011
import torch

free, total = torch.cuda.mem_get_info()
print(f"free {free / 2**30:.2f} GiB of {total / 2**30:.2f} GiB")
try:
    x = torch.empty(20 * 2**30 // 4, device="cuda")  # 20 GiB of float32
except torch.OutOfMemoryError as e:
    print("OutOfMemoryError:", str(e).split(". GPU")[0])

y = torch.ones(1024, device="cuda")
print("still usable:", y.sum().item())
Output on an NVIDIA T4
free 14.47 GiB of 14.57 GiB
OutOfMemoryError: CUDA out of memory. Tried to allocate 20.00 GiB
still usable: 1024.0

Debugging checklist

  1. Print what is free right before the failing allocation: cudaMemGetInfo(&free, &total) in C++, torch.cuda.mem_get_info() in PyTorch.
  2. Print the size you are asking for, in bytes. Most "impossible" out-of-memory errors are a size calculation bug.
  3. Run nvidia-smi to check for other processes using the GPU.
  4. In PyTorch, torch.cuda.memory_summary() breaks usage down by allocated, reserved and freed blocks.

FAQ

Do I need to restart after a CUDA out of memory error?

No. Unlike an illegal memory access, out of memory does not corrupt the CUDA context. Our repro allocates 1 MiB successfully right after the 20 GiB request fails. In C++, call cudaGetLastError() once to clear the recorded error.

Why does PyTorch run out of memory when nvidia-smi shows memory free?

nvidia-smi and PyTorch measure different things. PyTorch's caching allocator keeps freed blocks reserved for reuse, and a large tensor needs one contiguous block. The out-of-memory message lists reserved-but-unallocated memory; if that is large, enable expandable_segments.

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

Only when memory is held by tensors you have already deleted. It returns cached blocks to the driver, so other processes can use them. It cannot free tensors that are still referenced.