Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

AI Model Out of Accelerator Memory? Check These

· 6 min read · Home Tech

In this article
  1. Background: Why Accelerator Memory Is a Hard Limit
  2. First Checks: What to Look at Immediately
  3. How to Diagnose the Exact Cause
  4. Techniques to Reduce Memory Usage
  5. Common Problems and Misconceptions
  6. Alternatives to Fitting in Memory
  7. Frequently Asked Questions

When an AI model runs out of accelerator memory (VRAM on a GPU or HBM on a TPU), the immediate fix is to reduce the memory footprint by shrinking batch size, lowering input resolution, or switching to a smaller model — but the correct long-term answer depends on whether the problem is model size, activations, optimizer state, or fragmentation. This article explains what to check, in order, so you can diagnose the real cause and apply the right fix without guessing.

Background: Why Accelerator Memory Is a Hard Limit

Accelerators (GPUs, TPUs, and other AI chips) have a fixed amount of on-board memory that is physically separate from the host CPU's RAM. Unlike CPU RAM, you cannot easily add more after purchase, and swapping to host memory is either impossible or painfully slow. For deep learning, the memory holds:

  • Model weights — the parameters of the neural network.
  • Activations — intermediate outputs from each layer, needed for backpropagation.
  • Gradients — computed during the backward pass.
  • Optimizer states — e.g., momentum and variance buffers for Adam.
  • Framework overhead — CUDA context, cuDNN workspaces, and temporary tensors.

The total must fit within the accelerator's memory limit (e.g., 16 GB on an NVIDIA V100, 80 GB on an A100, or 64 GB on a TPU v4). When it doesn't, you get an out-of-memory (OOM) error, often a cryptic message like CUDA out of memory or ResourceExhaustedError.

First Checks: What to Look at Immediately

Before diving into advanced techniques, verify the basics. These are the most common causes and the fastest to rule out:

  1. Batch size — Reduce it by half and retry. If it fits, you're memory-bound on activations.
  2. Input size — Lower image resolution, sequence length, or embedding dimensions. Halving resolution cuts activation memory by roughly 4x.
  3. Model size — Try a smaller variant (e.g., BERT-base instead of BERT-large).
  4. Other processes — Check if another job is using the accelerator. Run nvidia-smi (on NVIDIA) or rocm-smi (on AMD) to see memory usage per process.
  5. Framework caching — PyTorch and TensorFlow cache memory by default; the OOM may be due to fragmentation, not true capacity. Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (PyTorch 2.x) or use tf.config.experimental.set_memory_growth to see if it helps.

How to Diagnose the Exact Cause

If simple fixes don't work, you need to measure what's consuming memory. Use the profiler built into your framework:

  • PyTorch: torch.profiler with profile_memory=True shows memory usage per tensor and operation.
  • TensorFlow: tf.profiler or tf.keras.callbacks can log memory.
  • NVIDIA: nsys (NVIDIA Nsight Systems) and ncu (Nsight Compute) give detailed memory traces.

Look for the peak memory allocation. If the peak is during the forward pass, activations dominate. If it's during the backward pass, gradients and optimizer states are the issue. If memory usage grows slowly over steps, you likely have a memory leak (e.g., storing tensors in a Python list).

Techniques to Reduce Memory Usage

Once you know the cause, apply the appropriate technique. These are the most effective, in rough order of ease:

  • Gradient accumulation — Simulate a larger batch size by accumulating gradients over several smaller batches. This reduces activation memory without changing the effective batch size.
  • Mixed precision (FP16/BF16) — Using 16-bit floats halves memory for weights, activations, and gradients. Most modern accelerators support this natively, and frameworks like PyTorch's torch.cuda.amp make it easy.
  • Activation checkpointing (gradient checkpointing) — Don't store all activations; recompute them during the backward pass. This trades compute for memory, often reducing activation memory by 5-10x.
  • Memory-efficient optimizers — Adam stores two extra tensors per parameter. Use AdamW with foreach or switch to Adafactor or 8-bit optimizers (e.g., bitsandbytes) to reduce optimizer state.
  • Model parallelism — Split the model across multiple accelerators. This includes pipeline parallelism (layers on different devices) and tensor parallelism (splitting each layer).
  • Offloading — Move optimizer states or even some parameters to CPU RAM. Libraries like DeepSpeed's ZeRO-Offload do this automatically.

Common Problems and Misconceptions

Many developers assume OOM means the model is too big, but often it's a fixable configuration issue. Here are common pitfalls:

  • PyTorch's memory cache — PyTorch caches freed memory to avoid repeated allocations. This can cause OOM even when the total live memory is under the limit. Use torch.cuda.empty_cache() only if you know what you're doing; it doesn't free memory back to the OS, just to the cache.
  • Batch size is not the only factor — Sequence length in transformers scales activation memory linearly, but attention memory scales quadratically with sequence length.
  • Data type matters — Using FP32 instead of FP16 doubles memory. Check your model's dtype.
  • Fragmentation — Many small allocations can fragment memory, making large contiguous blocks unavailable. Using a larger batch size or enabling expandable segments can help.
  • Not all OOMs are memory — Sometimes the error is due to a driver issue or a process that isn't releasing memory. Restart the kernel or check for zombie processes.

Alternatives to Fitting in Memory

If you've exhausted the above and still can't fit the model, consider these alternatives:

  • Use a smaller model — DistilBERT instead of BERT, or a smaller vision transformer.
  • Quantization — Post-training quantization to INT8 reduces memory by 4x. Use libraries like TensorRT or ONNX Runtime.
  • Cloud or distributed training — Rent a larger accelerator (e.g., 80 GB A100) or use multi-node training.
  • Model pruning — Remove less important weights before training.

Frequently Asked Questions

Why does PyTorch say “CUDA out of memory” even though I have free memory?

PyTorch caches memory allocations to speed up repeated operations. The cache may hold memory that isn't actively used, so the OOM error can occur even when the total live tensors are under the limit. The error message usually shows the total memory and the cached memory. Try reducing batch size or setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to reduce fragmentation.

Is it better to reduce batch size or sequence length first?

It depends on your model. For transformers, sequence length affects memory quadratically due to attention, so reducing sequence length is often more effective. For CNNs, batch size and input resolution both matter linearly, but resolution affects all layers, so reducing it first may be better. Use the profiler to see which dominates.

What is gradient accumulation and does it affect training?

Gradient accumulation means you run several forward/backward passes with small batches, summing the gradients, then update the optimizer once. This mimics a larger batch size without using more memory. The effective batch size is the sum of the small batches. It can affect training dynamics (e.g., batch normalization statistics), but for most models it's a drop-in replacement.

Can I use CPU RAM to help?

Yes, with offloading. Frameworks like DeepSpeed allow you to offload optimizer states and even parameters to CPU RAM. This is slower but allows training models larger than the accelerator's memory. It's a good last resort if you can't get a bigger accelerator.

Why does my model use more memory during training than inference?

During training, you need to store activations for the backward pass, plus gradients and optimizer states. Inference only needs the forward pass and no gradients. That's why training typically uses 3-10x more memory than inference for the same model.

What's the difference between OOM and a memory leak?

An OOM error means the memory limit is reached at a specific point. A memory leak means memory usage grows indefinitely over time, eventually causing OOM. Leaks are often caused by storing tensors in Python lists or not detaching tensors from the computation graph. Use a profiler to see if memory usage increases per step.