Lyceum Magazine cover: the title CUDA out of memory with LLMs: where VRAM goes and how to fix it, a tall purple-topped block rising well above a shorter dashed outline, suggesting memory demand that outgrows the space on the card.
Lyceum Magazine cover: the title CUDA out of memory with LLMs: where VRAM goes and how to fix it, a tall purple-topped block rising well above a shorter dashed outline, suggesting memory demand that outgrows the space on the card.

Why CUDA out of memory happens in LLM jobs

CUDA out of memory happens when PyTorch asks the GPU for a block of memory and the card has no free block that large. The fix depends on which part of the job fills the card, so find that part first.

Why does a fine-tuning job run out of memory when the model itself fits on the GPU? Loading needs room for the weights only. Training also needs room for gradients, optimizer state and saved intermediate results.

VRAM is the GPU's own memory, separate from the server's RAM. PyTorch keeps freed VRAM in a cache for reuse, called the caching allocator. PyTorch's CUDA notes name the calls that separate memory held by tensors, the arrays PyTorch stores data in, from memory the cache reserves.

import torch

# run after one training step
print(f"held by tensors:   {torch.cuda.memory_allocated() / 1e9:.1f} GB")
print(f"reserved by cache: {torch.cuda.memory_reserved() / 1e9:.1f} GB")
print(f"peak since start:  {torch.cuda.max_memory_allocated() / 1e9:.1f} GB")

If the peak is close to the card's size, the job really needs that much, and you have to cut what it needs. If reserved memory is far above held memory, the problem is fragmentation: free memory split into pieces too small to use.

Where GPU memory goes: weights, gradients, optimizer states and activations

A training step first runs the input through the model: the forward step. The backward step then works out how each weight should change. Four blocks of data fill GPU memory meanwhile.

  • Weights are the model's parameters. In 16-bit precision (BF16), each takes 2 bytes.
  • Gradients are the result of the backward step: how far each weight should move. They take another 2 bytes per parameter.
  • Optimizer states are what the optimizer remembers between steps. AdamW, the usual optimizer for LLMs, keeps a 32-bit copy of each weight and two running averages of past gradients: 12 bytes.
  • Activations are the intermediate results of the forward step, saved for the backward step. They grow with sequence length and batch size.

The ZeRO paper from Microsoft Research adds the first three to 16 bytes per parameter. We call this the static memory, because it does not change with batch size or sequence length.

static training memory = parameters × 16 bytes   (2 weights + 2 gradients + 12 optimizer states)

Weights are rarely the problem: Hugging Face puts Llama 3.1 8B at 16 GB to load. Full fine-tuning needs eight times that. Our 70B VRAM breakdown runs the same sums for a larger model.

Worked example: a LoRA job on Llama 3.1 8B that does not fit, then fits

The example follows one hypothetical job from 850 GB down to 30 GB. The job fine-tunes Llama 3.1 8B on one NVIDIA H100, a data-centre GPU with 80 GB of VRAM. Each sequence is 4,096 tokens long, and the job processes eight at once.

The model shape comes from Meta's Llama 3 paper: 32 layers and 32 attention heads per layer. The job uses LoRA (low-rank adaptation), which freezes the model and trains small extra matrices called adapters. With rank 16, each adapter matrix is 16 columns wide, which sets its size. Adapters on every weight matrix of the model add up to 41.9 million parameters.

Calculated example, hypothetical jobWeightsGradients and optimizer statesActivationsTotalFits 80 GB
Full fine-tuning, before any batch16 GB112 GBnot counted128 GBNo
LoRA, standard attention16 GB0.7 GB833 GB850 GBNo
LoRA, FlashAttention16 GB0.7 GB146 GB163 GBNo
LoRA, FlashAttention, gradient checkpointing16 GB0.7 GB13 GB30 GBYes

Full fine-tuning fails before the first batch: 8 billion parameters at 16 bytes is 128 GB. LoRA keeps gradients and optimizer states only for the adapters, so they shrink from 112 GB to 0.7 GB.

We estimated activations with the per-layer formula of Korthikanti and colleagues at NVIDIA. Most of the 833 GB is attention scores. An attention head scores how much each token should weigh every other token, so it holds 4,096 × 4,096 scores per sequence. Korthikanti's formula counts 5 bytes per score: the 2-byte score, a 2-byte normalised copy and a 1-byte mask. Across 32 heads, 32 layers and 8 sequences, that is 687 GB, or 82% of the activations.

FlashAttention computes attention in small tiles inside the GPU's fast on-chip memory. It never writes the full score matrix to VRAM, so memory grows linearly with sequence length. The other saved results of each layer remain: 146 GB, for 163 GB in total.

Gradient checkpointing keeps only each layer's input and recomputes the rest during the backward step. Activations fall from 146 GB to 13 GB, and the job fits with 50 GB to spare.

Horizontal bars of GPU memory for one hypothetical fine-tuning job on Llama 3.1 8B with 4,096-token sequences, 8 at a time, against one 80 GB H100. Full fine-tuning needs 128 GB before any batch. LoRA with standard attention needs 850 GB, with FlashAttention 163 GB, and with gradient checkpointing added 30 GB, the only step under the 80 GB line. Calculated example, not a measurement.
In our calculated Llama 3.1 8B example, only LoRA with FlashAttention and gradient checkpointing fits one 80 GB H100, at 30 GB.

Inference fills memory differently. The model keeps a KV cache (key-value cache), its record of every token read so far. Llama 3.1 8B stores 131,072 bytes per token, so a 128,000-token conversation holds 16.8 GB, as much as the weights. Hugging Face lists 15.62 GB for the same cache, because it counts a gigabyte as 2^30 bytes, not 10^9.

The activation formula was derived for an older model design, so these are estimates, not measurements. They leave out PyTorch's own overhead and fragmentation, so keep headroom on the card.

How to fix CUDA out of memory, in order

Fix CUDA out of memory by shrinking the block your measurement points to, cheapest change first.

Diagram pairing each block of GPU memory with the fix that shrinks it, with sizes from the Llama 3.1 8B example. Attention scores, 687 GB, are removed by FlashAttention at no extra compute. Other activations, 146 GB, shrink with a smaller micro-batch or gradient checkpointing, which costs 30 to 40% more training time. Gradients and optimizer states, 112 GB with full fine-tuning, shrink with LoRA adapters and then sharding. Weights, 16 GB, shrink with 4-bit QLoRA and then ZeRO-3 or FSDP sharding.
Each fix shrinks one block of GPU memory; the sizes are from our calculated Llama 3.1 8B example, not measurements.
  1. Turn on FlashAttention. It removes the stored attention scores at no extra compute. In Hugging Face Transformers, set `attn_implementation` when you load the model.
  2. Lower the micro-batch, the number of sequences per forward step, and raise gradient accumulation. Gradient accumulation adds up gradients over several small batches before each weight update. Activations shrink with the micro-batch, while each update still sees the same number of sequences.
  3. Turn on gradient checkpointing. NVIDIA's team measured 30 to 40% more training time when every layer is recomputed. Our gradient checkpointing guide covers cheaper variants.
  4. Train adapters instead of all weights. QLoRA also stores the frozen model in 4 bits. Its authors fine-tuned a 65B model on a single 48 GB GPU. They found adapters were needed on every weight matrix to match full fine-tuning.
  5. Fix fragmentation. When reserved memory far exceeds held memory, set the allocator option `expandable_segments`, which lets PyTorch grow its memory blocks instead of adding new ones. PyTorch documents it for jobs whose allocation sizes keep changing, such as a changing batch size.
  6. Offload to CPU memory last. Microsoft's DeepSpeed training library can move optimizer and gradient states to the server's RAM. That frees VRAM, but the data then travels back to the GPU on every step.

Steps 1 to 3 are settings in a Hugging Face training script, shown here with the example job's values.

from transformers import AutoModelForCausalLM, TrainingArguments

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B",
    torch_dtype="bfloat16",
    attn_implementation="flash_attention_2",
)
args = TrainingArguments(
    output_dir="out",
    per_device_train_batch_size=8,  # step 2 not needed: checkpointing alone fits
    gradient_accumulation_steps=1,
    gradient_checkpointing=True,
    bf16=True,
)

Step 5 is an environment variable, set before the script starts.

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

When to shard with ZeRO-3 or FSDP, or move to a bigger GPU

Shard the model across GPUs with ZeRO stage 3 or FSDP when the static memory alone still exceeds one card after adapters and 4-bit weights. Sharding splits each block across GPUs, so every card holds a slice. DeepSpeed's ZeRO stage 1 splits optimizer states, stage 2 adds gradients and stage 3 adds the weights. PyTorch's FSDP (Fully Sharded Data Parallel) does the same and cites ZeRO stage 3 as its model. Our ZeRO-3 vs FSDP comparison weighs the two.

Lyceum is a sovereign European AI inference provider for open-source models, and our GPUs run in European data centres. On our inference API, we don't keep your prompts or outputs, and we never use them for training. Our GPU virtual machines are billed per second with root access, for teams that train their own models. Each launches with 1, 2, 4 or 8 GPUs, and our machine types list the VRAM per card.

GPU on our VMsVRAM per GPUVRAM with 8 GPUs
H10080 GB640 GB
H200141 GB1,128 GB
B200192 GB1,536 GB
B300288 GB2,304 GB

A bigger card beats sharding when the activations of a single sequence break the budget. Sharding splits the static memory and spreads sequences across GPUs, but one sequence always stays on one card. Jobs across several servers need fast links between them. Our clusters use 400 Gb/s InfiniBand, a high-speed server network, with capacity reserved per contract.

Inference runs out of memory through the KV cache instead. Our guide to OOM in vLLM, a widely used serving engine, covers its settings.

How to predict memory before you launch

Predict memory before you launch with Pythia, our command-line tool that runs your PyTorch script and estimates what it needs. It predicts training and inference memory, counting weights, gradients, optimizer states and activations. It also estimates runtime on T4, A100 and H100 GPUs and recommends one.

lyceum gpu-selection run train.py -- --epochs 1

Pythia covers one model on one GPU and skips the temporary tensors inside each operation, so keep headroom. For a model you only serve, the sizing tool on our compute page shows the memory a Hugging Face model needs and which GPU fits.

We recommend staying on one GPU whenever the prediction fits after steps 1 to 4. With ZeRO-3, each GPU fetches the weight slices it lacks from the others on every pass, and that waiting slows each step. If the prediction does not fit, shard or move to a larger card. Run Pythia on your training script first, then launch a VM with the GPU it names.

Sources

  1. docs.pytorch.org
  2. Rajbhandari et al.: ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (2019)
  3. Hugging Face: Llama 3.1 - 405B, 70B & 8B with multilinguality and long context (July 2024)
  4. arxiv.org
  5. arxiv.org
  6. FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (July 2024)
  7. huggingface.co
  8. Dettmers et al.: QLoRA: Efficient Finetuning of Quantized LLMs (May 2023)
  9. DeepSpeed: Zero Redundancy Optimizer tutorial
  10. docs.pytorch.org