Skip to content

Operator task guide

How to fix CUDA out of memory (Tried to allocate) and PyTorch memory leaks

Every PyTorch CUDA out of memory message gives four numbers: Tried to allocate X, total GPU capacity, already allocated by PyTorch, and total reserved by the caching allocator. Subtract allocated from reserved first: a large gap means allocator fragmentation, which PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True often fixes without shrinking batch size.

If allocated memory grows monotonically step after step until OOM, you have a PyTorch reference leak (commonly storing loss tensors with .grad_fn history in a list instead of loss.item()). If step 1 fits barely or blows up on long sequences, reduce peak activations with gradient checkpointing, bfloat16, or FSDP/ZeRO.

Reviewed . Reference guidance is not a diagnosis of your workload.

Step-by-step method

  1. 1

    Read the four capacity numbers in the OutOfMemoryError message

    Before changing batch size or buying larger GPUs, check how much memory is reserved-but-unallocated vs actively allocated vs held by another PID in nvidia-smi.

    nvidia-smi
    # Check if fragmentation is high: (reserved - allocated) >> tried_to_allocate
    export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
  2. 2

    Detect whether memory leaks over steps or peaks immediately

    Log torch.cuda.memory_allocated() and memory_reserved() across 20 training steps. Monotonic growth points to retained autograd graphs, cached activations, or unfreed evaluation tensors.

    python3 -c "import torch; print(torch.cuda.memory_summary())"
  3. 3

    Capture a CUDA memory snapshot to pinpoint the leaking tensor

    In PyTorch 2.x, record memory allocation history and inspect which Python stack line created persistent unfreed allocations.

    # Add around suspect training loop:
    # torch.cuda.memory._record_memory_history(max_entries=100000)
    # torch.cuda.memory._dump_snapshot("mem_snapshot.pickle")
  4. 4

    Apply the matching capacity fix for training or Unsloth fine-tuning

    For genuine capacity OOM during fine-tuning (including Unsloth/TRL QLoRA), enable gradient checkpointing, cap max_seq_length, lower per_device_train_batch_size while raising gradient_accumulation_steps, and use paged/8-bit optimizers.

CUDA OOM diagnostic branches

Signals, meanings and actions for how to fix cuda out of memory (tried to allocate) and pytorch memory leaks.
SignalWhat it meansNext action
Reserved minus allocated is larger than Tried to allocateCaching allocator fragmentation.Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True and avoid frequent shape changes.
Other PIDs occupy VRAM in nvidia-smiCo-resident or zombie worker process holds GPU memory.Terminate stale processes and verify clean GPU state before launch.
memory_allocated() climbs every step until crashAutograd graph or tensor list leak (missing .item() / .detach() / no_grad()).Record memory snapshot and strip .grad_fn from logged metrics.
Allocated hits ~95%+ of total capacity on step 1 or long promptTrue model + activation + optimizer footprint exceeds VRAM.Enable activation/gradient checkpointing, lower microbatch, or shard via FSDP2/ZeRO.

Evidence checklist

  • Complete torch.OutOfMemoryError line with all four MiB/GiB values
  • nvidia-smi process table showing any competing VRAM consumers
  • Per-step memory_allocated() trend over steps 1 to 20
  • Batch size, sequence length, dtype, and optimizer choice
  • Whether PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True was active

Common mistakes

Sprinkling torch.cuda.empty_cache() inside every step

Calling empty_cache() forces synchronization and hurts speed without reducing peak tensor allocation.

Saving loss instead of loss.item() into metric lists

Retaining a scalar tensor keeps the entire backward computation graph alive in GPU memory.

Running validation without torch.inference_mode() or torch.no_grad()

Validation forward passes build massive activation graphs if grad tracking stays enabled.

Frequently asked questions

Why do I get CUDA out of memory when nvidia-smi shows free memory?

Either PyTorch caching allocator fragmentation prevents allocating one contiguous block from its reserved pool (fix with PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True), or a single large activation/logit tensor spike exceeded remaining headroom.

How do I fix CUDA out of memory in Unsloth or QLoRA fine-tuning?

Verify no background GPU process is running, enable use_gradient_checkpointing="unsloth", cap max_seq_length to your actual dataset tail, and trade per_device_train_batch_size for gradient_accumulation_steps.

What is the fastest way to find a PyTorch CUDA memory leak?

Log torch.cuda.memory_allocated() each step. If it rises steadily, capture torch.cuda.memory._dump_snapshot() and check for tensors stored without .detach() or .item(), or missing torch.no_grad() during eval.

Does expandable_segments:True slow down training?

In modern PyTorch 2.x on Linux, expandable_segments has minimal overhead while eliminating many fragmentation-driven OOMs on variable sequence lengths.

Live diagnosis, no signup

Upload your GPU log. Find what happened first.

Get the likely cause, supporting evidence, and next safe steps with the same cloud reasoning used by paid plans. A crash the engine recognizes is answered in seconds, then checked by an independent AI review that updates this page when it finishes. A crash it does not recognize waits for the AI's own answer, which can take a few minutes. No account, card, or installation. Logs are masked at Denpex API ingress and are not saved to account history.

Before uploading, review cloud data handling and local options.

training_logs.txt
No log to hand? Try one:

Upload your log file. Large files are processed in your browser. Only selected evidence is submitted when you run diagnosis.

3 free cloud diagnoses per day

Try Denpex for 30 days. FREE.

No credit card. No automatic subscription. See whether Denpex helps with an incident you already understand.

Start your free 30-day Team evaluation

Up to 50 diagnoses a day for 30 days. Verify your work email to activate an eligible company evaluation, then replay a resolved incident and compare the evidence and next steps with your team's confirmed cause.

Use your company email, for example alex@yourcompany.com.

Who qualifies?

Company email domains activate the free 30-day Team evaluation (up to 50 diagnoses a day) after an email and domain check, whatever mail provider you use. If we cannot verify your domain automatically, support reviews it: write to support@denpex.com. Free local diagnosis in the editor extension needs no account.

Using a personal email (Gmail, Outlook, Naver, QQ) or solo cluster? Create a free $0 account (no work email required) to save 7-day history and unlock AI fallback, or send a cluster crash log for a live walkthrough.

Apply the method to your incident

Use the three free diagnoses to review your error and relevant evidence. Keep reference guidance separate from the cause and recovery status of your own workload.

Diagnose your incident