PyTorch CUDA Out of Memory: Allocation Checks and Fixes
Diagnose PyTorch CUDA out of memory (Tried to allocate) errors. Compare total capacity, allocated tensors, reserved cache fragmentation and GPU processes.
A PyTorch CUDA out of memory fix starts by reading the four numbers in the Tried to allocate exception: requested allocation size, physical total capacity, memory already allocated by active tensors and memory reserved in total by the PyTorch caching allocator. Use those values to separate a fragmented reserved pool (set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True), genuine tensor capacity exhaustion (reduce activation or model footprint) and co-located GPU processes in nvidia-smi.
- Root cause
- Caching allocator fragmentation: reserved in total by PyTorch minus already allocated leaves substantial unused cache, or unallocated device memory exists, but no single contiguous segment fits the Tried to allocate X GiB request. Genuine tensor capacity exhaustion: already allocated is near total capacity because model weights, optimizer states, gradients, batch activations or retained computation graphs exceed physical VRAM. Co-located GPU processes: external workloads, leaked distributed ranks or a co-resident serving process in nvidia-smi occupy device memory outside the failing PyTorch process.
- Recommended fix
- Read the four memory numbers in the exception message first to compare the requested allocation size, total GPU capacity, active allocated tensors and total memory reserved by the PyTorch caching allocator before changing environment variables or model hyperparameters.
- How Denpex helps
- Denpex investigates PyTorch CUDA Out of Memory: Allocation Checks and Fixes using the evidence you provide or your connected workload collects. Earlier rank, host or application evidence is needed to distinguish an initiating failure from a downstream report.
What this failure is
PyTorch raises torch.OutOfMemoryError (or RuntimeError: CUDA out of memory. Tried to allocate ...) when neither the CUDACachingAllocator free pool nor the underlying CUDA driver can provide a contiguous device memory block large enough for a requested tensor or kernel workspace.
Is this what broke your run? Paste your log.
You're reading about PyTorch CUDA Out of Memory: Allocation Checks and Fixes. Paste your own traceback and relevant evidence for an investigation of your workload, with a next action or a specific missing fact. A reference entry does not establish your cause. No account or card for the free diagnosis. Review data handling before submitting sensitive logs.
Before uploading, review cloud data handling and local options.
Upload your log file. Large files are processed in your browser. Only selected evidence is submitted when you run diagnosis.
Why it happens (the mechanism)
Every PyTorch CUDA out-of-memory message reports four critical measurements: Tried to allocate X GiB (the size of the requested tensor or workspace), Y GiB total capacity (physical VRAM on the device), Z GiB already allocated (memory actively held by live PyTorch tensors) and W GiB reserved in total by PyTorch (VRAM claimed from the CUDA driver by the PyTorch caching allocator). Allocations fail across three distinct paths: (1) fragmentation, where reserved minus allocated (or remaining unallocated VRAM) exceeds X GiB but is split into non-contiguous blocks too small for the request; (2) genuine capacity exhaustion, where Z GiB already allocated plus X GiB approaches or exceeds Y GiB total capacity because model parameters, gradients, optimizer states or forward activations do not fit; or (3) co-located processes, where external processes visible in nvidia-smi consume physical VRAM outside PyTorch accounting.
What you'll observe
- A CUDA tensor allocation or kernel workspace request fails with torch.OutOfMemoryError even when total device capacity or reserved PyTorch cache appears to have remaining space.
Common symptoms and what they mean
Check possible explanations against the incident evidence. A matching symptom alone does not establish its cause.
| Symptom | Possible explanation |
|---|---|
| torch.OutOfMemoryError: CUDA out of memory. Tried to allocate ... | Caching allocator fragmentation: reserved in total by PyTorch minus already allocated leaves substantial unused cache, or unallocated device memory exists, but no single contiguous segment fits the Tried to allocate X GiB request. |
| RuntimeError: CUDA out of memory. Tried to allocate X GiB (GPU 0; Y GiB total capacity; Z GiB already allocated; W GiB free; V GiB reserved in total by PyTorch) | Genuine tensor capacity exhaustion: already allocated is near total capacity because model weights, optimizer states, gradients, batch activations or retained computation graphs exceed physical VRAM. |
Which systems are affected
- PyTorch single-GPU and distributed CUDA training and inference workloads
How to confirm this is the problem
Use this checklist to test the hypothesis against a small reproduction. No single line proves the root cause, so preserve the preceding events and compare one variable at a time.
- ✓Read the four numbers in the exception line first: Tried to allocate X GiB, Y GiB total capacity, Z GiB already allocated and W GiB reserved in total by PyTorch.
- ✓Calculate reserved minus allocated (W minus Z) and compare it with X GiB to determine whether unused blocks are sitting fragmented inside the PyTorch caching allocator.
- ✓Run nvidia-smi or inspect torch.cuda.mem_get_info() to verify whether another OS process or orphaned rank already holds VRAM on the target GPU.
- ✓Call torch.cuda.memory_summary() at the failing boundary and note whether the failure occurs during model load, the first forward/backward pass, the first optimizer.step() allocation or gradually across steps.
Root cause
- Caching allocator fragmentation: reserved in total by PyTorch minus already allocated leaves substantial unused cache, or unallocated device memory exists, but no single contiguous segment fits the Tried to allocate X GiB request.
- Genuine tensor capacity exhaustion: already allocated is near total capacity because model weights, optimizer states, gradients, batch activations or retained computation graphs exceed physical VRAM.
- Co-located GPU processes: external workloads, leaked distributed ranks or a co-resident serving process in nvidia-smi occupy device memory outside the failing PyTorch process.
The fix and how to prevent it
How to fix it
- Read the four memory numbers in the exception message first to compare the requested allocation size, total GPU capacity, active allocated tensors and total memory reserved by the PyTorch caching allocator before changing environment variables or model hyperparameters.
- Branch 1 (Fragmentation, where reserved minus allocated is large or free pool exists without a contiguous block): configure allocator expandable segments to let the caching allocator expand existing memory segments instead of relying on the legacy max split size heuristic from earlier PyTorch releases.
- Branch 2 (Genuine capacity exhaustion, where allocated is close to total capacity): reduce peak tensor residency with activation checkpointing (torch.utils.checkpoint), a smaller micro-batch size paired with gradient accumulation, bfloat16 mixed precision (torch.autocast) or distributed sharding via FSDP or DeepSpeed ZeRO.
- Branch 3 (Co-located processes, where nvidia-smi shows an external process consuming VRAM): terminate orphaned worker ranks or move the job to an isolated GPU via CUDA_VISIBLE_DEVICES before retuning PyTorch.
- If memory climbs across steps rather than failing on step one, check for tensors stored in Python lists with an attached autograd graph and detach or convert metrics with .detach() or .item().
How to prevent it
- Log torch.cuda.max_memory_allocated() and torch.cuda.max_memory_reserved() during a short warmup run to verify headroom before launching full jobs.
- Verify clean GPU residency in preflight checks so stray processes do not shrink available VRAM.
Save this diagnosis and catch the next crash automatically
All root cause, fix, and prevention steps above are free to read. Create a free account with any email or GitHub to keep your saved diagnosis history across the encyclopedia and run cloud checks, or use a work email below for the 30-day Team evaluation. No card required.
Or start a 30-day free Team trial (work email)
Verified work email unlocks all 14 fleet diagnostic tools, Slack alerts, and team history for 30 days. No card and no automatic charge.
Diagnose your own log automatically
The root cause and fix steps above stay free. Create a free account to analyze full job logs, attribute the first failed rank, and keep saved incident history.
Sign up free. Analyze your cluster logsNo credit card. Daily allowance follows verified trust tier. Instant access.
Why the recommended fix works
Matching the fix to the four numbers in the exception resolves either non-contiguous allocator fragmentation, true model-plus-activation footprint limits or external VRAM contention without unnecessary throughput loss.
Code examples
# Synthetic debugging script. Run inside your failing environment to inspect allocator state.
import torch
if torch.cuda.is_available():
free_bytes, total_bytes = torch.cuda.mem_get_info()
allocated_bytes = torch.cuda.memory_allocated()
reserved_bytes = torch.cuda.memory_reserved()
print(f"Driver free: {free_bytes / (1024 ** 3):.2f} GiB / Total capacity: {total_bytes / (1024 ** 3):.2f} GiB")
print(f"PyTorch allocated: {allocated_bytes / (1024 ** 3):.2f} GiB / Reserved: {reserved_bytes / (1024 ** 3):.2f} GiB")
print(f"Unallocated reserved cache: {(reserved_bytes - allocated_bytes) / (1024 ** 3):.2f} GiB")
print(torch.cuda.memory_summary(abbreviated=True))This snippet illustrates the entry-specific check. Verify the installed versions, permissions, target and workload context before using it. A command or API example is not proof of recovery.
Diagnostic note
“This entry is grounded in the official PyTorch CUDA memory management documentation and provides a synthetic diagnostic snippet, not a captured customer incident or hardware benchmark claim.”
Diagnose this failure in VS Code
Select the traceback or open the failed terminal, then run Denpex locally to inspect matched failure patterns, supporting evidence and next checks without uploading the log. Verify recommendations against your workload before changing production.
Install the free VS Code extensionPyTorch GPU errors in context
PyTorch training errors commonly originate at tensor device placement, DataLoader /dev/shm IPC, or checkpoint state restoration.
Compare related pytorch gpu errorsRelated failures to investigate next
Frequently asked questions
Questions engineers and on-call staff commonly ask about this failure.
What do the four numbers in CUDA out of memory Tried to allocate mean?
Why use PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True instead of max_split_size_mb?
Does torch.cuda.empty_cache() fix a PyTorch CUDA out of memory error?
Don't just read the fix, diagnose your run
The encyclopedia explains documented failure patterns. Denpex investigates your logs, configuration and stack, shows the supporting evidence, and asks for missing details when needed.