Pidoku

Memory Fragmentation and Allocators

Module 22 Lesson 22.e 1h 15m Difficulty 4/5

Prerequisites 3.f, 12.l


Before you start: words you need#

WordPlain meaning
AllocatorThe code that hands out pieces of memory when a program asks and takes them back when it is done.
Caching allocatorPyTorch’s GPU allocator. It keeps freed memory for reuse instead of returning it to the driver, because asking the driver is slow.
SegmentA large piece of GPU memory the caching allocator got from the driver; it carves tensors out of it.
Reserved vs allocatedReserved: all memory the allocator holds. Allocated: the part currently used by live tensors.
External fragmentationEnough memory is free in total, but in pieces too small for the request (3.f).
Fixed-size blocksMemory cut into equal pieces; any free piece fits any request for one piece, so external fragmentation cannot happen. This is how PagedAttention stores the KV cache (12.l).
OOMOut of memory: an allocation that could not be satisfied (22.f).

1. What is it?#

You have free GPU memory and you cannot use it:

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB.
GPU 0 has a total capacity of 79.19 GiB of which 3.21 GiB is free.
Of the allocated memory 68.42 GiB is allocated by PyTorch,
and 6.11 GiB is reserved by PyTorch but unallocated.
If reserved but unallocated memory is large try setting
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.

6.11 GiB is held by PyTorch but not used by any tensor, and 3.21 GiB more is free on the device, yet a 2 GiB request fails. The reserved-but-unallocated memory is in pieces, none large enough. That is fragmentation. (The exact wording of the message varies between PyTorch versions; the two numbers are always there.)


2. Why does it exist?#

Because of how PyTorch’s caching allocator has to work:

1. Asking the driver for memory (cudaMalloc) is slow, and freeing it synchronises
   the device. So PyTorch asks for large segments and carves tensors out of them.
2. Freed tensors go back to PyTorch's pool, not to the driver.
3. Segments are split to fit requests.
4. Neighbouring free pieces in one segment are merged;
   pieces in DIFFERENT segments never can be.
5. With request sizes that vary, segments end up like a chessboard of used and free pieces.
Segment (2 GB):  [used 512MB][free 256MB][used 768MB][free 384MB][used 128MB]
                  640 MB free in total, largest piece 384 MB
                  → a 512 MB request cannot be served from this segment

This is the external fragmentation of 3.f, on a GPU. PagedAttention (12.l) removed it from the KV cache, the largest and most dynamic consumer. Activations, workspaces and everything else still go through the general allocator.


3. Simple analogy#

A car park. Cars come and go all day. By evening there are forty empty spaces scattered around, but a coach needs six spaces in a row and there is no run of six anywhere. The car park is 60% full and turning away a coach.

The fixes map one to one:

  • Paint equal bays and let the coach use any six (fixed-size blocks with a lookup table: PagedAttention).
  • Reserve a coach area at opening time (preallocate the KV pool).
  • Let the end bay stretch (expandable_segments).
  • Empty the car park and start again (torch.cuda.empty_cache(): disruptive).

4. Tiny example: free memory that cannot be used#

The program in section 6 runs a simple first-fit allocator over 64 GiB, with 20,000 random allocations and frees of varying sizes, then asks for one 2.5 GiB tensor:

live tensors: 828
first-fit: free 235 units (3.7 GiB) in 139 holes, largest hole 9 units (0.14 GiB)
request 160 units (2.5 GiB): first-fit ok=false, fixed blocks ok=true

3.7 GiB free, spread over 139 holes, the largest only 0.14 GiB: the 2.5 GiB request fails. If the same memory were managed as fixed-size blocks, and the consumer could use non-adjacent blocks through a table, the request would succeed. That trade (accept non-contiguous storage, get rid of external fragmentation) is the core idea of PagedAttention.


5. Technical explanation#

Where fragmentation comes from in inference#

SOURCE                                     SEVERITY
Variable prompt lengths → variable         HIGH: the main one outside the KV cache
  activation sizes in prefill
Variable batch sizes                       MEDIUM
A KV cache that is not paged               FATAL: why paging exists
LoRA adapters loaded and unloaded (18.g)   MEDIUM
Multimodal encoders with varying images    MEDIUM
Long-running processes                     grows slowly over hours

A 200-token prompt and a 20,000-token prompt need activation tensors 100 times apart in size. Engines bound this with a per-step token budget (chunked prefill, 12.k): the largest activation is then set by the budget, not by the longest prompt.

Fix 1: preallocate the KV pool (the big one)#

Engines claim a fixed share of GPU memory at startup and manage the KV cache themselves in fixed-size blocks. In vLLM, --gpu-memory-utilization (default 0.9) sets the share of the GPU the whole engine may use; the KV pool is what remains after weights, activations measured in a profiling run, and CUDA graphs (17.h). The most dynamic consumer is thereby out of the general allocator.

Fix 2: expandable_segments#

Shell
export PYTORCH_ALLOC_CONF=expandable_segments:True

PYTORCH_ALLOC_CONF is the current name; PYTORCH_CUDA_ALLOC_CONF still works as an alias “for backward compatibility” (PyTorch 2.15 documentation). With this option the allocator uses CUDA’s virtual memory API to create one segment per stream that grows when more memory is needed, instead of many fixed segments. Varying sizes then tile into one long segment instead of leaving slivers between segments. PyTorch still marks it experimental; it is off by default.

Engines with their own memory pools may switch it off inside them. vLLM’s sleep-mode allocator, for example, temporarily disables expandable segments within its pool, because the two are incompatible. Check your engine’s documentation before relying on it.

Fix 3: bucket shapes#

Round activation shapes up to a few sizes (128, 256, 512, … tokens). The allocator then sees a small set of sizes, and a freed block fits the next request of the same bucket. It costs some wasted compute on padding. CUDA graph capture sizes (13.k) do this as a side effect.

Fix 4: other allocator settings#

Shell
PYTORCH_ALLOC_CONF=expandable_segments:True,garbage_collection_threshold:0.8
  • max_split_size_mb:N stops the allocator splitting blocks larger than N MB, which keeps big pieces whole. The PyTorch documentation calls it “a last resort” for workloads that OOM with many inactive split blocks.
  • garbage_collection_threshold:0.8 makes the allocator release old unused blocks once usage passes 80%, instead of waiting for a failure and then freeing everything at once, which stalls latency-sensitive servers.
  • backend:cudaMallocAsync uses CUDA’s own asynchronous allocator instead of PyTorch’s; the two options above then do not apply.

Fix 5: empty_cache(), carefully#

Python
torch.cuda.empty_cache()     # return unused cached segments to the driver

It does release fragmented segments, but it synchronises the device, makes later allocations pay the slow driver path again, and can cause a latency spike. Use it once after loading, or between distinct phases. Never in the request path.

Diagnosing it#

Python
print(torch.cuda.memory_summary())

Read three things:

  • Reserved − allocated. Memory held but unused. Not all of it is “fragmentation”: some is simply cached for reuse. It becomes a problem when it is large and allocations fail.
  • Non-releasable memory. Inactive pieces of split blocks: the most direct fragmentation number.
  • cudaMalloc retries and CUDA OOMs in the header. Retries mean the allocator had to free its cache and try again: any non-zero value means memory pressure.

For detail, record a snapshot and view it:

Python
torch.cuda.memory._record_memory_history(max_entries=100_000)
# ... run the workload ...
torch.cuda.memory._dump_snapshot("snapshot.pickle")
torch.cuda.memory._record_memory_history(enabled=None)   # stop recording
# drag snapshot.pickle onto https://pytorch.org/memory_viz

The viewer shows every allocation’s lifetime and the segments over time; fragmentation is visible as a segment full of thin gaps.


6. Under the hood: the simulation, and why paging fixes it#

Go
// frag.go: why "free" memory can still fail an allocation.
// A first-fit allocator over one contiguous region, fed variable-size
// requests, versus a pool of fixed-size blocks fed the same requests.
package main

import (
	"fmt"
	"math/rand/v2"
	"sort"
)

const total = 4096 // memory in 16 MiB units = 64 GiB

type span struct{ start, size int }

// firstFit keeps a sorted list of free spans.
type firstFit struct{ free []span }

func (a *firstFit) alloc(n int) (int, bool) {
	for i, s := range a.free {
		if s.size >= n {
			a.free[i] = span{s.start + n, s.size - n}
			if a.free[i].size == 0 {
				a.free = append(a.free[:i], a.free[i+1:]...)
			}
			return s.start, true
		}
	}
	return 0, false
}

func (a *firstFit) release(start, n int) {
	a.free = append(a.free, span{start, n})
	sort.Slice(a.free, func(i, j int) bool { return a.free[i].start < a.free[j].start })
	merged := a.free[:1]
	for _, s := range a.free[1:] { // coalesce neighbours
		last := &merged[len(merged)-1]
		if last.start+last.size == s.start {
			last.size += s.size
		} else {
			merged = append(merged, s)
		}
	}
	a.free = merged
}

func (a *firstFit) stats() (free, largest int) {
	for _, s := range a.free {
		free += s.size
		largest = max(largest, s.size)
	}
	return
}

func main() {
	rng := rand.New(rand.NewPCG(1, 2))
	ff := &firstFit{free: []span{{0, total}}}
	type live struct{ start, size int }
	var held []live
	pagedFree := total // fixed-size blocks: only the count matters

	for step := 0; step < 20000; step++ {
		if len(held) > 0 && rng.IntN(3) == 0 { // free a random live tensor (1 in 3 steps)
			i := rng.IntN(len(held))
			ff.release(held[i].start, held[i].size)
			pagedFree += held[i].size
			held[i] = held[len(held)-1]
			held = held[:len(held)-1]
			continue
		}
		n := 1 + int(rng.ExpFloat64()*12) // mostly small, sometimes large
		if n > pagedFree {
			continue
		}
		if s, ok := ff.alloc(n); ok {
			held = append(held, live{s, n})
			pagedFree -= n
		}
	}
	free, largest := ff.stats()
	fmt.Printf("live tensors: %d\n", len(held))
	fmt.Printf("first-fit: free %d units (%.1f GiB) in %d holes, largest hole %d units (%.2f GiB)\n",
		free, float64(free)/64, len(ff.free), largest, float64(largest)/64)
	big := 160 // a 2.5 GiB activation for one long prefill
	_, ok := ff.alloc(big)
	fmt.Printf("request %d units (%.1f GiB): first-fit ok=%v, fixed blocks ok=%v\n",
		big, float64(big)/64, ok, big <= pagedFree)
}

The output is in section 4. What the comparison shows:

GENERAL ALLOCATOR                       FIXED-SIZE BLOCKS (PAGED KV CACHE)
variable-size requests                  every request is a whole number of blocks
external fragmentation possible         impossible: all free blocks are interchangeable
needs contiguous memory                 a block table maps logical to physical blocks
can fail with plenty free               succeeds while enough blocks are free

The price of paging is the indirection: the attention kernel must follow the block table. That is cheap for the KV cache, which is read in chunks anyway. It is not possible for an ordinary tensor a GEMM reads as one contiguous array, which is why activations still need expandable_segments, bucketing and a bounded token budget.


7. Performance implications#

  • Allocator misses cost time. When the cache cannot satisfy a request, the allocator frees cached blocks and calls the driver, which synchronises the device: a visible stall in the timeline (22.h).
  • expandable_segments has a small cost when a segment grows (mapping more physical memory) and usually a large benefit for variable shapes.
  • Headroom is throughput. Every gigabyte lost to fragmentation is a gigabyte not available to the KV pool, which means a smaller maximum batch (12.f).
  • CUDA graphs fix addresses (5.f). Graph memory pools are kept for the life of the graphs, which is another reason engines capture a bounded list of sizes.

8. Production implications#

  • Set expandable_segments:True for variable-shape PyTorch workloads, unless your engine says otherwise.
  • Check the KV pool is preallocated and the memory share is set with headroom.
  • Monitor reserved − allocated, non-releasable memory and allocator retries over time. Growth over a long-running process is a real failure mode (22.f, type 4).
  • Never call empty_cache() in the request path.
  • Bound the largest activation: cap input length and set a per-step token budget.
  • Test with the longest prompt you accept before raising the memory share.
  • Restart on a schedule if fragmentation builds up and cannot be fixed otherwise. Inelegant but effective; drain traffic first (20.h).

9. Common mistakes#

  1. Reading nvidia-smi memory as tensor memory. It shows what the allocator has reserved, plus the CUDA context and other libraries.
  2. Raising --gpu-memory-utilization to 0.97 and then OOMing on an activation spike.
  3. empty_cache() in the hot loop. It synchronises and slows everything.
  4. Treating all of reserved − allocated as fragmentation. Much of it is a healthy cache.
  5. Assuming OOM means “not enough memory”. Read memory_summary(); it is often fragmentation.
  6. Ignoring slow growth. A process that OOMs after six hours has an accumulation problem.

10. Hands-on exercise#

  1. Run frag.go. Change the free probability from 1 in 3 to 1 in 2. Why does fragmentation almost vanish? What does that say about fragmentation and occupancy?
  2. Change the size distribution to only three sizes (bucketing: 4, 16, 64 units). How large is the largest hole now?
  3. Reproduce it on a GPU. Allocate many tensors of random sizes, free every other one, then request one large tensor. Print memory_summary() and find the non-releasable memory.
  4. Fix it. Re-run with PYTORCH_ALLOC_CONF=expandable_segments:True. Does the OOM go away?
  5. Visualise. Record a memory snapshot of a real inference workload with varying prompt lengths and open it in the memory viewer. Where are the gaps?

11. Interview questions#

  1. Why does PyTorch cache GPU memory instead of returning it to the driver?
  2. What is “reserved but unallocated” memory, and when is it a problem?
  3. What does expandable_segments change, and why does it reduce fragmentation?
  4. Why do fixed-size blocks remove external fragmentation, and what do they cost?
  5. When should you call empty_cache(), and when not?
  6. The OOM message says 6 GiB is reserved but unallocated. Diagnose it.
  7. A server OOMs after six hours but never at startup. What is happening?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in