AI Job Hits CUDA Out of Memory but VRAM Looks Free? PyTorch Caching Allocator Fragmentation, Reserved-vs-Allocated & Expandable Segments Diagnosis Guide

2026-11-22 | GPU Repair | 16 minutes | HK GPU Fix Editorial Team

AI Job Hits CUDA Out of Memory but VRAM Looks Free? PyTorch Caching Allocator Fragmentation, Reserved-vs-Allocated & Expandable Segments Diagnosis Guide

Key takeaway

When PyTorch reports CUDA out of memory while reserved-but-unallocated memory is several gigabytes, the problem is usually a fragmented caching allocator, not a card that is simply too small. This guide explains segments and blocks, how to read the error numbers, and five decisive tests.

What this pattern actually looks like

This guide only applies when three conditions are all true at the same time. If any one of them is missing, the fault belongs to a different diagnosis path.

First, an AI job stops with `torch.OutOfMemoryError: CUDA out of memory`, or a similar CUDA out-of-memory error. The error message itself lists several numbers: how much memory the failed allocation tried to request, the total capacity of the GPU, how much memory is free, how much is "allocated by PyTorch", and how much is "reserved by PyTorch but unallocated".

Second, at the moment of the error, the "reserved by PyTorch but unallocated" figure is large — measured in gigabytes, not close to zero. In other words, PyTorch has already reserved a large amount of VRAM from the driver, but a big part of it is not assigned to any tensor. There is memory, but it is broken up, and no single piece of free space is large enough and continuous enough for the allocation that just failed. The PyTorch error message itself points in this direction: "If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation."

Third, `nvidia-smi` still appears to show free space, or its numbers do not match the error. The used-memory figure shown by `nvidia-smi` includes memory the allocator has reserved but is not using, so it cannot tell you how much genuinely usable continuous space remains. Judging by `nvidia-smi` alone will mislead.

These three conditions need to be kept apart from neighbouring shapes, because the tests are completely different. If the allocated figure is close to total capacity and reserved-but-unallocated is close to zero, that is genuine exhaustion, not fragmentation. If the program cannot find a CUDA device at all, that is a detection problem. If a game reports "Out of Video Memory" while VRAM is not full, that is a game-allocator problem, not a PyTorch-allocator problem. This guide is about the PyTorch allocator having memory that is too fragmented to use.

The mechanism: the caching allocator, segments, and blocks

PyTorch does not call `cudaMalloc` and `cudaFree` directly for every tensor. Those calls are synchronising operations across the whole device, and calling them for every tensor would be far too slow. Instead, PyTorch uses a caching allocator that manages VRAM in two layers.

A segment is a continuous region obtained from CUDA, either through `cudaMalloc` or through a virtual-memory mapping. A block is a sub-region inside a segment that tracks one individual allocation. When a tensor needs memory, the allocator looks for a free block large enough to hold it. If the block is larger than needed, the allocator splits it: the front part becomes the allocation, and the remainder becomes a new free block. When a block is freed, the allocator tries to merge it with its neighbours — but only if those neighbours are also free. Two free blocks with an allocated block between them cannot be merged.

The most important limit is this: blocks in different segments can never be merged. A 16 MiB free block in one segment plus a 16 MiB free block in another segment cannot be combined into a 32 MiB block to satisfy a 32 MiB request, even though the total free space adds up to 32 MiB. The PyTorch documentation describes this failure mode directly: "even though there is 'technically' enough free space to store a requested allocation, the CUDA caching allocator is unable to actually serve the request."

Because the allocator keeps freed blocks for reuse instead of returning them to the driver immediately, `torch.cuda.memory_reserved()` — the total backing memory of the whole pool — is usually larger than `torch.cuda.memory_allocated()` — the bytes genuinely occupied by live tensors. The gap between the two is cached, reusable memory, not a leak. Fragmentation is what happens when the free space inside that gap is cut into pieces that are too small and too scattered to join into one block large enough for the next request.

`expandable_segments` is a switch aimed at this problem. When it is switched on, the allocator uses expandable segments instead of fixed-size segments, and no longer calls `cudaMalloc` for a new fixed-size segment each time. This greatly reduces fragmentation. NVIDIA's Megatron Bridge documentation describes the effect as one that "dramatically reduces fragmentation and often eliminates borderline OOM without any model or parallelism changes". But it must be stated clearly: the switch has to be set before the process starts, because the allocator reads the environment variable once, when it is initialised. Changing it halfway through a run has no effect.

There is also a naming point that causes confusion. The older environment variable name is `PYTORCH_CUDA_ALLOC_CONF`, and it is the name that appears in the PyTorch error message itself. The current main name in newer versions is `PYTORCH_ALLOC_CONF`, with the older name kept as a backwards-compatible alias. Both names should be used as appropriate: the older name is what the error message shows, and the newer name is the current main name. Neither one should be presented as the only correct name.

Two further cautions come from the sources. First, `expandable_segments` is not a cure for every kind of fragmentation: the PyTorch documentation notes that some fragmentation can be fixed with expandable segments (in particular some cases related to CUDA graphs) and some cannot. Second, there is no universal table of "normal" reserved-to-allocated ratios. The ratio depends on the model, the batch size, and the sequence length, so the standard is always the reader's own comparison — a fresh process, before and after the switch, before and after shrinking the batch — not a published number.

The four suspect layers

A CUDA out-of-memory error with free-looking VRAM has four possible layers. Only the first is the subject of this guide.

Layer 1: Allocator fragmentation — memory exists but no large continuous block (the subject of this guide)

The error message shows a large reserved-but-unallocated figure. A fresh process runs fine, and the error only appears after the job has run for a while or after tensors have been loaded and freed several times. Switching on `expandable_segments` makes the problem disappear or pushes the failure point later. The evidence is the first three tests below pointing at the same layer together.

Layer 2: Genuine capacity exhaustion — the tensors genuinely do not fit

The model weights, KV cache, activations, and fixed overhead together are genuinely larger than the VRAM. The evidence is an allocated figure close to total capacity with reserved-but-unallocated close to zero, and the job only runs after the batch is shrunk, the model is quantised, or a smaller model is used. This layer must be separated out, or a card that is simply too small will be misdiagnosed as fragmented.

Layer 3: Accumulated occupancy — other processes or leftover programs are eating VRAM

An old Python process has not exited, another program is occupying VRAM, or tensors keep accumulating inside the same program — the classic leak case is `total_loss += loss`, which keeps every step's autograd graph alive. The evidence is that a fresh process fails too, or that `nvidia-smi` shows other processes occupying memory. The separation is made by the fresh-process test below.

Layer 4: Framework or driver — CUDA is not found, or the versions do not match

The framework reports "No CUDA device found", or the CUDA version supplied by the driver is not new enough. This layer differs from the subject of this guide because it is a detection failure, not an allocation failure. The error message itself separates them: "Tried to allocate" means the allocation layer, while "No CUDA device" means the detection layer.

Five decisive tests

Each of these tests answers a different question. None of them appears in the neighbouring guides.

T1: Error-message number comparison — allocated versus reserved-but-unallocated

Do not stop at the words "CUDA out of memory". Read the error message number by number: how much the failed allocation tried to request ("Tried to allocate"), the total capacity, how much is free, how much is "allocated by PyTorch", and how much is "reserved by PyTorch but unallocated". The decision rule is: allocated close to capacity means genuine exhaustion (Layer 2); reserved-but-unallocated large, in gigabytes, means fragmentation (Layer 1). This judgement relies on the error message itself, not on `nvidia-smi`.

T2: Fresh-process comparison — the same settings, a fresh process, runs fine

Run the same model, the same batch, and the same settings in a brand-new Python process. If it runs, the problem follows the accumulated state inside the process — fragmentation or accumulated occupancy, Layers 1 or 3. If a fresh process fails in the same way, the problem follows the settings — genuine exhaustion, Layer 2. Add one more step: inside the fresh process, load and free tensors several times and watch whether it changes from running fine to failing. Changing from working to failing after repeated load and free cycles is characteristic of accumulating fragmentation.

T3: expandable_segments switch comparison — does the failure point move?

Set `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` (or the newer main name `PYTORCH_ALLOC_CONF`, as explained in the mechanism section) before the process starts, then run the same settings again. If the error disappears, or the failure point is clearly delayed, the fragmentation layer is supported. If it still fails at the same point, that does not rule out fragmentation — expandable segments fix some kinds of fragmentation and not others. Go back to T1, T4 and T5 before concluding genuine exhaustion. Remember: the switch must be set before the process starts, because the allocator reads it once at initialisation. Changing the environment variable mid-run will not take effect, and the process must be restarted.

T4: Peak allocated versus peak reserved comparison, plus the empty_cache test

Measure the peaks around one complete training step: call `torch.cuda.reset_peak_memory_stats()`, run one step, then print `max_memory_allocated()` and `max_memory_reserved()`, and use `torch.cuda.memory_summary(abbreviated=True)` to inspect the allocator state. Peak reserved clearly larger than peak allocated is the fingerprint of fragmentation. Then call `torch.cuda.empty_cache()` and retry: if the retry succeeds, cached-block fragmentation is confirmed; if it still fails, the problem is genuine exhaustion, a leak, or segment-level fragmentation — read it together with the peak numbers, not as a conclusion on its own. Note the limit of this test: `empty_cache()` can only confirm fragmentation at the cached-block level, not at the segment level, so a single successful retry must be read together with the peak numbers, not taken as a conclusion on its own.

T5: Batch and model shrink comparison — does shrinking change whether it fails?

Shrink the micro-batch to 1 (compensating with gradient accumulation) or drop the model down one quantisation level (for example Q8 to Q4), then run again. If the smaller setting runs, the problem sits at the boundary between allocation size and capacity — fragmentation or genuine exhaustion, which T1 then separates. If it still fails at the smallest setting, the problem is not an allocation problem: check the detection layer or look for other processes occupying memory (the other side of T2).

Seven-step diagnosis flow

  1. Define the shape. Confirm the error is `CUDA out of memory` with "Tried to allocate" — not "No CUDA device found", which belongs to the detection path.
  2. Read the numbers. Read the error message number by number: allocated versus reserved-but-unallocated (T1).
  3. Check other processes. Use `nvidia-smi` to see whether another process is occupying VRAM, and use `ps` to look for leftover Python processes.
  4. Run the fresh-process comparison. Same settings, a fresh process, once (T2).
  5. Measure peaks and try empty_cache. Measure one complete step's peak allocated and reserved figures, then call `empty_cache()` and retry (T4).
  6. Try the expandable_segments switch. Set it before the process starts and run again (T3).
  7. Shrink the batch or the model. Shrink the batch or drop a quantisation level and see whether it still fails (T5). If it still fails at the smallest setting, check the detection layer or the framework and driver versions.

What this is not: boundary cases

SituationWhich path applies insteadWhy it is not this guide
Allocated close to total capacity, reserved-but-unallocated close to zeroGenuine VRAM-exhaustion guidesThe memory is genuinely used up, not fragmented
The framework reports that no CUDA device can be foundCUDA-detection guideA detection-layer problem, not an allocation-layer problem
A game reports "Out of Video Memory" while VRAM is not fullGame-allocator guideA game or engine allocator, not the PyTorch allocator
Rendering or creative workloads hit a TDR reset or a long-kernel timeoutTDR and long-kernel guidesA timeout layer, not an allocation layer
High VRAM usage but only slowness or late texturesVRAM-exhaustion and bandwidth guidesA performance problem, not an allocation failure
The model cannot fit at all, or the question is which card to buyLocal-AI VRAM planning guidePlanning, not fault diagnosis

Five common misconceptions

  1. "nvidia-smi says there is still space, so there must be enough space." Wrong. The used figure shown by `nvidia-smi` includes memory the allocator has reserved but is not using, and it cannot show whether one large enough continuous block exists. Read the error message's own numbers instead.
  2. "Reserved larger than allocated means there is a leak." Wrong. The gap between the two is normally cached, reusable memory, not a leak. A leak is shown by allocated memory rising steadily over time, not by reserved being large.
  3. "Adding another card or a bigger card will fix the out-of-memory error." Wrong when the cause is fragmentation. The problem is not total capacity but continuous space; a bigger card only pushes the threshold higher, and with the same allocation pattern the memory will fragment again sooner or later. Run T1 and T3 first instead of changing hardware.
  4. "I can switch on expandable_segments while the program is running." Wrong. The switch must be set before the process starts, because the allocator reads it once at initialisation. Changing the environment variable mid-run has no effect; the process must be restarted.
  5. "empty_cache can be used as a routine fix." Wrong. `empty_cache()` only frees cached blocks, which helps confirm whether the problem is fragmentation. It does not change the allocation pattern and will not stop the next run from fragmenting again. The real fix is `expandable_segments` or a change to the allocation pattern, not clearing the cache every time the job fails.

What to do next, and what not to do

If the five tests point to allocator fragmentation, the first step is T3: set `expandable_segments` before the process starts and re-run the same job. If the job then runs, the diagnosis is confirmed and the switch can stay in the launch setup. If the job still fails at the same point, go back to T1 and T5: check whether the allocated figure is really close to capacity, and whether a smaller batch or a lower quantisation level changes anything. Those two answers separate fragmentation from genuine exhaustion, and they decide whether the next step is a settings change or a different card.

Do not treat `empty_cache()` as a fix and call it before every run. It is a diagnostic probe, not a repair, and relying on it hides the allocation pattern that is causing the problem. Do not copy a PyTorch allocator switch into a different framework: vLLM, llama.cpp, and Ollama each have their own allocators and KV-cache management, and the PyTorch switch cannot simply be applied to them. Each framework's out-of-memory error has to be investigated with its own tools.

If the diagnosis points to the hardware rather than the allocator — for example, the card itself is failing under load — the practical step is a workshop inspection. Repair pricing on this site follows the published three-tier fee structure of HK$400–2,800, with the final quote after inspection. No fee can be fixed before the inspection determines what is actually at fault.

HK GPU Fix is located at Dali Plaza, Room 1209, Shek Mun. The phone number is 2186 8010 and WhatsApp is 6558 6806. There is no Mong Kok shop and no on-site service; inspection and repair are carried out at the workshop.

FAQ

Q1: The error says CUDA out of memory, but nvidia-smi shows free VRAM. Which number should I trust?

Trust the error message, not `nvidia-smi`. The error message lists how much is allocated by PyTorch and how much is reserved but unallocated. `nvidia-smi` counts reserved memory as used, so it cannot tell you whether a single large continuous block is available. Read the error numbers with T1.

Q2: Reserved memory is much larger than allocated memory. Is that a memory leak?

Not necessarily. The gap between reserved and allocated is normally cached, reusable memory — blocks the allocator kept for the next allocation instead of returning them to the driver. A leak is shown by allocated memory rising steadily over time, for example when a training loop keeps every step's autograd graph alive. Check whether allocated keeps climbing; do not judge by the size of reserved alone.

Q3: I set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True while the job was running and nothing changed. Why?

Because the allocator reads the setting once, when it is initialised at process start. Changing the environment variable mid-run has no effect. Set it before the process starts and restart the process, then re-run the same job.

Q4: Which environment variable name should I use — PYTORCH_CUDA_ALLOC_CONF or PYTORCH_ALLOC_CONF?

Both names refer to the same setting. `PYTORCH_CUDA_ALLOC_CONF` is the older name, and it is the name that appears in the PyTorch error message itself. `PYTORCH_ALLOC_CONF` is the current main name in newer versions, with the older name kept as a backwards-compatible alias. Use the name that matches the version in use, and do not treat either one as the only correct name.

Q5: empty_cache made the job run once. Can I just call it before every run?

No. `empty_cache()` only frees cached blocks, so a successful retry confirms cached-block fragmentation but does not change the allocation pattern. The job will fragment again. The lasting fix is `expandable_segments`, set before the process starts, or a change to the batch size or quantisation level.

Q6: The job still fails at the same point with expandable_segments switched on. Does that mean it is not fragmentation?

Not necessarily. Expandable segments fix some kinds of fragmentation and not others, and a job can also fail because the tensors genuinely do not fit. Go back to T1 and T5: check the allocated-versus-reserved numbers in the error message, and try a smaller batch or a lower quantisation level. If the allocated figure is close to capacity, the problem is genuine exhaustion.

Related articles

Related services

If you need VRAM upgrade / repair, see these service pages: