Memory allocators: malloc, arenas, fragmentation, and PyTorch's caching allocator

Who hands out a training job's memory, from Python's pymalloc and glibc's malloc to jemalloc, tcmalloc, mimalloc and PyTorch's CPU and CUDA allocators, and why freed memory stays in the process: measured on a Linux kernel, read in the source. A child of Topic: operating-systems. Data as of October 2026. Reading: 41 min, plus 10 in closed details.

The idea in one screen

An allocator buys memory from the kernel (or the CUDA driver) rarely and in big pieces, and hands it out in small pieces often; what you free stays with the allocator and goes back only when a whole page, arena or segment is empty, so a process's RSS measures what its allocators hold, not what it uses, and free memory in the wrong-shaped pieces is fragmentation.

Fig. 1, step by step: freed memory stops at the allocator

  1. Four allocators between a training job and the hardware. The job makes millions of malloc and free calls, nanoseconds each. pymalloc serves Python objects up to 512 B, glibc's malloc NumPy arrays and C extensions (or jemalloc, tcmalloc), mimalloc inside libc10 the CPU tensors of arm64 and Windows wheels, the caching allocator GPU tensors (sections 7, 3 to 6, 8, 9).
  2. They get memory rarely, in big pieces. The first three from the kernel's 4 KiB pages with brk, mmap and madvise; the caching allocator from the CUDA driver with cudaMalloc or cuMemMap. Each cuts its big pieces into the small blocks the job asks for.
  3. What you free stays with the allocator. Orange: held by the allocator, not live. pymalloc returns a 1 MiB arena only when all of it is dead; glibc returns the heap top, whole free pages and big mmapped blocks; mimalloc keeps freed memory for reuse; the caching allocator returns a segment only when nothing in it is live.
  4. Measured: free 98%, and RSS does not move. measured here 400,000 blocks of 256 bytes, then 98% freed. Live data is 1,562 KiB; glibc still holds 110,524 KiB of RSS. The camera moves onto glibc's heap, drawn to scale.
  5. malloc_trim(0) returns only whole free pages. RSS falls to 29,404 KiB and no further: a page holding even one live block stays (section 5).

You need: pages, page faults, mmap and what RSS counts, from the virtual memory page; that page owns everything below the allocator (THP, overcommit, copy-on-write, the OOM killer). GPU memory budgets in training (activations, optimiser state, checkpointing) are on Making training fast, and the GPU's on-chip memory hierarchy on GPU memory hierarchy; this page is the allocator in between.

Allocator
user-space code that gets big regions from the kernel and cuts them into the blocks malloc (or torch.empty) returns.
Chunk, bin
one piece handed out, with a header saying its size; a bin is a list of free chunks of one size range.
Size class
a fixed size (16, 32, 48 ... bytes) that requests are rounded up to, so blocks of one class can share a page.
Internal, external fragmentation
waste inside handed-out blocks (rounding); free memory in pieces too small or in the wrong place for the next request.
Arena
one independent heap; glibc and pymalloc both use the word, for different things.
RSS
resident set size: the pages of the process actually in RAM, live data or not.
Segment (CUDA)
a region the caching allocator got from cudaMalloc; tensors are blocks cut from it.
LayerGets memory fromUnit it hands outGives memory backSee it with
pymallocmmap, 1 MiB arenas16-byte size classes up to 512 B, in 16 KiB poolsan arena when every object in it is deadsys._debugmallocstats(), tracemalloc
glibc mallocbrk (main heap), mmap (big blocks, thread arenas)chunks: request + 8 bytes, rounded to 16, at least 32the heap's top past 128 KiB (trim threshold); mmapped chunks at once; malloc_trimmalloc_info, malloc_stats, /proc/<pid>/smaps
jemalloc, tcmalloc, mimallocmmapsize classes in per-size runs, slabs, spans or pagesafter a delay or rate (decay, release rate, purge delay)their stats calls and environment options
CUDA caching allocatorcudaMalloc, or cuMemCreate plus cuMemMapblocks: 512-byte multiples in 2 MiB or 20 MiB-plus segmentsonly on OOM retry or torch.cuda.empty_cache()memory_summary(), memory snapshots
kernelphysical memory4 KiB pages (buddy allocator for runs of pages, slab caches for its own objects)munmap, madvise(MADV_DONTNEED)/proc/buddyinfo, /proc/slabinfo, /proc/meminfo

The running job meets every layer. In the root's training job (a 256-128-10 MLP on 8 MiB of memory-mapped data, two DataLoader workers), Python objects go through pymalloc, NumPy batches through glibc's malloc, weights and activations through mimalloc inside libc10.so (the 1 GiB reservation the root's Syscall tracer tab found), and its threads get their own glibc arenas (the 64 MiB reservations of section 4). On a GPU the tensors would go through the caching allocator.

Where everything was measured (provenance)

Measured in Docker Desktop's Linux VM (Linux 5.10.104-linuxkit, arm64, 4 KiB pages, 5 CPUs; glibc 2.36, Python 3.11.2, torch 2.14.1+cpu, NumPy 2.4.6; jemalloc 5.3.0, gperftools tcmalloc 2.10, mimalloc 2.0.9 from Debian 12), image kb-os-alloc:1, 2026-10-05; scripts and raw outputs in src/. Each container was capped at 1 or 2 CPUs and 1,500 MiB, on a VM shared with other experiments, so times carry some noise; repeated runs are shown where it matters. The cycle-collector run (section 7) is on an Apple M1 Pro, macOS, 2026-10-24. A trap every C benchmark here avoids: the root page's first strace of malloc sizes showed no calls at all, because gcc -O2 removed the malloc, memset and free as dead code; the buffer must escape (into a global, or a volatile sink) for the calls to happen.

1. Free space from zero: headers, free lists, splitting, coalescing

ch. 17 Free-Space Management

The problem. An allocator owns a region of bytes (the heap) and answers malloc(n) with the address of at least n free bytes and free(p) by taking them back. Requests come in any size and order, and a block can never move once handed out, because the program holds raw pointers into it.

The header and the free list. free(p) passes only the address, so the allocator writes a header just before every block, holding at least the size (OSTEP's example adds a "magic" number to catch corruption; glibc's header is the size and three flag bits in 8 bytes, section 3). Free regions are linked into a free list whose links live inside the free regions themselves: there is nowhere else to put them. A fresh heap is one free chunk.

header: size
the bytes the program uses (the pointer malloc returned points here)

Splitting and coalescing. A request smaller than the chosen chunk splits it: the front goes to the program, the rest stays on the list. A freed chunk next to another free chunk is coalesced with it into one; without that the heap fills with free slivers too small for anything.

Fragmentation, the two kinds. External fragmentation: enough memory is free in total, but in pieces, so a request fails (or the heap grows). Internal fragmentation: a block is larger than asked for (rounding, size classes, headers), and the excess is wasted inside it. The classic survey measures it as the allocator's peak memory against the peak of live data (Wilson et al. 1995); this page uses RSS against live bytes.

Predict: a 100-byte heap, ten requests of 10 bytes (it is now full), then free every other one. 50 bytes are free. Can a request for 15 bytes succeed, with coalescing on?

Fig. 2, step by step: the drill on a 100-byte heap, coalescing on

  1. A fresh heap is one free chunk. 100 bytes at address 1000, no headers (OSTEP's -H 0); the free list holds one entry, [1000, 100].
  2. Ten malloc(10) calls split it. Each takes the front 10 bytes of the free chunk and leaves the rest on the list; after the tenth the heap is full and the free list is empty.
  3. Free every other block. free(ptr[0]), [2], [4], [6], [8]: five 10-byte chunks go back on the list (the arcs: the links live inside the free chunks). No two are neighbours, so there is nothing to coalesce.
  4. malloc(15) fails. 50 bytes are free but the largest piece is 10; the search looked at all 5 entries and returned -1. External fragmentation, and no policy fixes it.
  5. free(ptr[1]) coalesces. Its neighbours on both sides are free, so the three merge into one 30-byte chunk at 1000 and the list shrinks to 4 entries. With coalescing off the list would hold six 10-byte pieces.
  6. malloc(15) now succeeds. Best fit takes the 30-byte chunk, splits it, returns address 1000 and leaves 15 bytes at 1015 on the list.

Which free chunk to pick. Best fit takes the smallest chunk that fits (little waste, a full search, tiny leftovers); worst fit the largest (big leftovers, a full search, fragments badly in practice); first fit the first that fits (fast, but the front of the list fills with small pieces); next fit continues from where the last search stopped. A list sorted by address makes coalescing cheap; sorted by size, first fit becomes best or worst fit.

Q5: without coalescing the free list grows to dozens of slivers and later large requests fail although plenty of bytes are free in total; with it the list stays short. Q1 to Q4 vary policy and order; Q7 is the drill above.

Better than one list: size classes. Most programs allocate a few sizes over and over. A segregated list allocator keeps one list per size class (16, 32, 48, ... bytes), so a request is a pop with no search and objects of one size sit together: every allocator below does this. The kernel's own are the slab allocator (a cache of pre-cut objects per type; Bonwick, USENIX 1994) and, for runs of whole pages, the buddy allocator: blocks of 2k pages that split in halves and merge with their "buddy", cheap to coalesce at the price of internal fragmentation (a 9-page request takes 16).

The kernel's slab caches and buddy lists, read live (recorded outputs)

measured here /proc/slabinfo in a container (excerpt). A task_struct, the kernel's record of one thread, is 3,712 bytes, one per slab page. Dentries (cached path components) are 200 bytes, 20 per page. The nonzero "tunables" columns are printed only by the older SLAB implementation (SLUB, the default in most distribution kernels, prints zeros), so this linuxkit kernel uses SLAB: an inference from the format, not checked against its config.


measured here cat /proc/buddyinfo: the number of free blocks of each order, 0 (4 KiB) to 10 (4 MiB). A huge page (2 MiB, order 9) can be found only while order-9 or order-10 blocks remain, which is why huge pages get harder to find on a long-running, fragmented machine (the virtual memory page owns THP).

Coalescing keeps free space in one piece: the same random operations with it off and on

OSTEP's chapter 17 homework simulator, malloc.py, ported line for line (same seed, same printed answers ). Each lane draws the heap to scale: allocated chunks coloured by pointer, free chunks dashed orange. Predict, then step: with preset Q5 (1,000 random operations), how long does each free list get, and do requests start failing?

All of malloc.py's options
The printed output, as malloc.py -c prints it, up to this step

External fragmentation here is 1 minus (largest free chunk / total free bytes): 0 when all free space is one chunk, near 1 when it is many slivers. "Searched" is how many list elements the search looked at, OSTEP's measure of search cost. Port checked by src/sim/check_freelist.mjs against src/inputs/ostep_malloc.py (ostep-homework vm-freespace).

2. What one request really costs

ch. 14 Interlude: Memory API

In glibc a chunk is the request plus an 8-byte size field, rounded up to a multiple of 16, at least 32 bytes: request2size (malloc.c line 1326, glibc 2.36). Measured with two back-to-back mallocs, whose distance is the chunk size (the chart beside).

C trusts the program completely: a use after free, a double free or an overflow corrupts the allocator's own data, often far from where it happened. In ML work these bugs live in C and C++ extensions, and from Python they surface as a segmentation fault or a malloc(): ... abort with no Python traceback; the root's Debug lab shows how to get a native stack.

The C API, the bugs and the tools (reference)

The calls (malloc(3), posix_memalign(3), malloc_usable_size(3)):

CallDoesWorth knowing
malloc(n)n bytes, contents not initialisedaligned for any type: 16 bytes on 64-bit Linux
calloc(k, n)k × n bytes, zeroedchecks k × n for overflow; fresh pages from mmap are already zero, so glibc skips the memset for them (malloc.c line 3707)
realloc(p, n)resize, maybe movinga large mmapped block can grow with mremap without copying (mremap_chunk, line 3068)
free(p)give backfree(NULL) does nothing; everything else must be a pointer malloc returned, freed once
posix_memalign, aligned_allocn bytes at a chosen alignmentwhat PyTorch's CPU allocator calls on x86-64 Linux, with 64-byte alignment (section 8)
malloc_usable_size(p)how many bytes the block really hasshows the rounding (the chunk-size chart)
  • Leak: memory never freed. Harmless in a short process, fatal in a server or a long training run.
  • Use after free: writing through a pointer after free, into a chunk that may already belong to someone else or whose first bytes now hold the free list's links.
  • Double free: glibc catches the common case and aborts with free(): double free detected in tcache 2.
  • Overflow: writing past the end tramples the next chunk's header; glibc notices later with messages such as malloc(): corrupted top size.

Tools: AddressSanitizer (gcc -fsanitize=address, which puts poisoned red zones around every block and keeps freed memory in quarantine), Valgrind's memcheck, and glibc's own checks.

A chunk is the request plus 8 bytes, rounded up to 16, at least 32

measured here src/exp/sizes.c. Usable is what malloc_usable_size reports; the stride is the chunk size. Formula: chunk = max(32, (request + 8 + 15) rounded down to a multiple of 16); a 1-byte request costs 32 bytes, a 25-byte one 48. Next to a 256-byte request the 8-byte header is 3% overhead; next to a 16-byte one it is half the chunk, which is why allocating millions of tiny objects one by one is expensive in memory as well as time.

3. Inside glibc's malloc: chunks, bins, the heap's top, and two thresholds

ch. 17 (real allocators), beyond OSTEP

glibc's allocator (ptmalloc, descended from Doug Lea's dlmalloc) is what malloc means on Debian, Ubuntu and most Linux machines a training job runs on. Its source is malloc/malloc.c plus arena.c; line numbers below are glibc 2.36, the version in the lab image, and glibc's MallocInternals page is the best tour.

A chunk (struct malloc_chunk, line 1148) starts with the previous chunk's size (used only while that one is free) and its own size, whose three low bits are flags because sizes are multiples of 16: P (PREV_INUSE, line 1366: do not merge with the chunk before me), M (IS_MMAPPED, line 1373: I came from my own mmap), A (NON_MAIN_ARENA, line 1382: I belong to a thread arena, section 4). A free chunk keeps its list links fd and bk in its first user bytes.

prev_size (8)
size | A M P (8)
user data (or, when free: fd, bk, ...)

Fig. 3, step by step: where malloc(n) looks, cheapest first

  1. tcache, per thread. Chunks up to 1,032 B, 7 per size, no lock, last in first out: since glibc 2.26 the fast path for most small requests. A malloc plus free of the same small size, repeated, is a tcache push and pop: 11.1 ns here.
  2. fastbin, per arena. Once a size's tcache list holds 7, the next free of up to 128 B goes to the arena's fastbin: single-linked, popped under the arena lock, not merged with its neighbours until a consolidation.
  3. small bin. Below 1,024 B, one exact size per bin, double-linked: take the first chunk.
  4. unsorted bin. Every other freed chunk lands here first; the next malloc walks it, takes an exact fit on the way and sorts the rest into the small and large bins.
  5. large bin. 1,024 B and up, size ranges sorted by size: best fit within the bin, then split. Before a large request _int_malloc consolidates the fastbins, and it finds bigger bins through a bitmap.
  6. top chunk. The free end of the heap: split off its front when no bin fits. Freeing merges a chunk with free neighbours, and one that touches the top grows the top; tcache and fastbins keep chunks whole for speed.
  7. sysmalloc: ask the kernel. When the top is too small, brk grows the heap; a request at or above the mmap threshold gets its own mmap instead (below). The orange levels are what a free refills; only this last one is a system call.

Simplified order of glibc 2.36 for a request that fits each level's range: the tcache check is in __libc_malloc, the rest in _int_malloc (line 3765). Chunk counts in Fig. 3 are illustrative; sizes and limits are the source's (table below).

The cost of each place, measured. A malloc plus free of the same small size, repeated, is a tcache push and pop (step 1). A thousand mallocs followed by a thousand frees overflow the 7-entry tcache and go through the bins, still cheap for 256 bytes (28.9 ns a pair) but 899.1 ns for 4 KiB. That jump is the trim threshold, below.

Every bin with its size range and source line (reference)
BinHoldsHow it worksSource
tcachechunks up to 1,032 bytes, 7 per sizeper thread, no lock, last in first out: the fast path for most small requests since glibc 2.26TCACHE_MAX_BINS 64, TCACHE_FILL_COUNT 7, lines 309 to 328
fastbinschunks up to 128 bytesper arena, single-linked, not merged with neighbours until a consolidationDEFAULT_MXFAST = 64 × 8 / 4, line 852
unsorted binany freed chunk, firstone list; the next malloc sorts its chunks into the right bins as it walks it, taking an exact fit on the way_int_malloc, line 3765
small binsbelow 1,024 bytes, one size each62 double-linked lists, exact sizeNSMALLBINS 64, MIN_LARGE_SIZE, lines 1571 to 1574
large bins1,024 bytes and up, size rangessorted by size, best fit within the bin; large free chunks also carry fd_nextsize, bk_nextsizeNBINS 128, line 1570
top chunkthe free space at the end of the heapsplit when no bin fits; the heap grows with brk when top is too smallsysmalloc, line 2541

The same program twice: after one free, glibc stops using mmap for 1 MiB

Default (dynamic threshold)

MALLOC_MMAP_THRESHOLD_=131072 (fixed)

measured here strace -e trace=brk,mmap,munmap,write ./threshold (src/exp/threshold.c); the "---" lines are the program's own markers.

Where the bytes come from: brk, mmap, and the dynamic threshold

The main heap grows by moving the "program break" with brk (brk(2)): cheap, but only the top can ever be given back. A request at or above M_MMAP_THRESHOLD gets its own mmap instead, unmapped the moment it is freed. The threshold starts at 128 KiB (DEFAULT_MMAP_THRESHOLD_MIN, line 961) and is dynamic: freeing an mmapped chunk larger than it raises the threshold to that size and the trim threshold to twice that (lines 3366 to 3371), up to 32 MiB on 64-bit (4 * 1024 * 1024 * sizeof(long), line 972), on the guess (mallopt(3)) that the program will allocate that size again and should not pay an mmap, a munmap and fresh page faults each time.

Predict: malloc 1 MiB, touch it, free it, then malloc 1 MiB again and free it. Which system calls does the second malloc make?

The two traces, step by step

  1. Two runs of the same program under strace. Left, glibc's default (a dynamic threshold); right, the threshold pinned at 128 KiB with MALLOC_MMAP_THRESHOLD_=131072. The program makes four calls.
  2. 1st malloc(1 MiB). Above the 128 KiB threshold, so both runs map a fresh region with mmap (the brk calls set up the heap for small allocations).
  3. free. Both runs give the mapping straight back with munmap. In the default run glibc also raises its threshold to about 1 MiB.
  4. 2nd malloc(1 MiB). The default run now serves it from the heap, growing it with brk; the fixed-threshold run maps again.
  5. free. The default run makes no system call: the 1 MiB stays in the heap (the trim threshold is now about 2 MiB). The fixed run unmaps it.
  6. End. Same program, same requests; the default run ends holding 1 MiB more.

Setting any of M_MMAP_THRESHOLD, M_TRIM_THRESHOLD, M_TOP_PAD or M_MMAP_MAX turns the dynamic adjustment off (mallopt(3)).

The trim threshold, and the 899 ns. When the top chunk grows past M_TRIM_THRESHOLD (128 KiB to start, line 919), free shrinks the heap with brk (systrim, line 2971). In the batch benchmark, a thousand 4 KiB blocks freed together merge into a 4 MiB top, glibc trims it, and the next round grows the heap again and takes a page fault on every new page: 899.1 ns a pair. With MALLOC_TRIM_THRESHOLD_=67108864 the heap is kept and the same loop costs 28.4 ns. The price moves elsewhere: the setting also pins the mmap threshold, so 1 MiB blocks now take an mmap and munmap every time (4,723.3 ns a pair, against 2,142.4 by default). Every knob here trades memory held against system calls and page faults.

malloc_trim. malloc_trim(0) (malloc_trim(3)) does more than its name says: it consolidates every arena and then calls madvise(MADV_DONTNEED) on every whole free page inside free chunks anywhere in the heap, not just at the top (mtrim, lines 5035 to 5089). The kernel drops those pages from RSS while the addresses stay valid. Section 5 measures what that recovers, and what it cannot.

The knobs, and how to look inside a running process (reference)

Each tunable can be set three ways: mallopt() in C; an environment variable with a trailing underscore (MALLOC_ARENA_MAX, MALLOC_MMAP_THRESHOLD_, MALLOC_TRIM_THRESHOLD_, MALLOC_TOP_PAD_); or GLIBC_TUNABLES=glibc.malloc.trim_threshold=...:glibc.malloc.arena_max=2 (glibc manual, memory allocation tunables). To look inside: malloc_stats() prints per-arena totals, malloc_info(0, stdout) prints XML with every bin, mallinfo2() returns the totals as a struct (mallinfo(3)). From Python, ctypes.CDLL("libc.so.6").malloc_stats() works in any process; gdb -p <pid> -batch -ex 'call (void)malloc_stats()' works in one you did not write.

4. Arenas: one heap per group of threads

ch. 17, ch. 28 Locks (why a shared heap needs one)

The problem. One heap shared by every thread needs a lock around every malloc and free, and a training process has many threads (PyTorch's intra-op pool, the DataLoader's pin-memory thread, the main thread). glibc's answer is several arenas, each a separate heap with its own lock and bins. A thread sticks to its last arena, moves to a free one when that lock is taken, and creates a new one while there are fewer than the limit (arena_get2, arena.c line 924). The limit is 8 per CPU on 64-bit (NARENAS_FROM_NCORES, malloc.c line 1935): 40 on this 5-CPU VM, 1,024 on a 128-core training host, unless MALLOC_ARENA_MAX says otherwise. Every thread arena reserves a 64 MiB heap (HEAP_MAX_SIZE, arena.c line 31) and commits pages as it grows: the root page's recording of the running job's /proc/PID/maps (its src/read/code/out/maps) shows exactly these, 132 KiB used and 65,404 KiB reserved, appearing three times when the DataLoader started.

The cost is steps 4 and 5 of Fig. 4: freed memory stays in the arena it came from. That is the documented reason behind the common MALLOC_ARENA_MAX=2 advice for multi-threaded servers.

Fig. 4, step by step: eight producers, one consumer, one heap or ten

  1. One heap, one lock. With MALLOC_ARENA_MAX=1 all nine threads of the benchmark (eight producers, one consumer) share the main arena: every malloc and free waits for the same lock.
  2. An arena per thread. By default a thread that finds the lock taken gets an arena of its own, up to 8 per CPU: glibc used 10 here (main, eight producers, the consumer). Each thread arena reserves a 64 MiB heap and commits pages as it grows.
  3. Producers hand buffers to the consumer. Each producer allocates in its own arena, buffers of 64 B to 64 KiB, and passes them on, at most 4,096 in flight: the shape of a data pipeline.
  4. The consumer frees each one into the arena it came from. A chunk freed by another thread goes back to the arena it came from, not the freeing thread's (the A flag of section 3 marks a thread arena's chunk).
  5. Free space is stranded per arena. Memory free in one arena cannot serve a request in another, so with many threads each holding some free memory, the total held grows with the number of arenas: peak RSS 220.8 MiB with ten arenas against 136.4 MiB with one, which took 9.37 s instead of 5.88.

How full each arena is in Fig. 4 is illustrative; the thread and arena counts and the numbers in the steps are measured (the chart beside the next paragraph).

One arena held the least at peak but was the slowest (step 5): the lock became the bottleneck arenas remove. When the work ended glibc held 2.3 MiB, while jemalloc, tcmalloc and mimalloc still held about 125 to 235 MiB, because they return memory on a timer or a rate (section 6). This workload frees everything, so it cannot show arena bloat (long-lived objects mixed with short-lived ones in a long-running server); the lesson is the method: measure peak RSS, steady RSS and time for your own pattern before setting a knob.

Fewer arenas hold less memory and take longer: eight producers, one consumer

measured here src/exp/arenas.c: eight producer threads allocate 2,000,000 buffers of random size (64 B to 64 KiB) and hand them to one consumer thread that frees them, at most 4,096 in flight, the shape of a data pipeline; three runs each on 2 CPUs, medians. Bars are peak RSS. glibc used 10 arenas by default (main, eight producers, the consumer), counted from malloc_stats().

5. Fragmentation, measured

ch. 17

Test 1: free 98% of a heap. 400,000 blocks of 256 bytes (272-byte chunks, 100,000 KiB of data) are allocated and touched; then all but every 64th are freed, leaving 1,562 KiB live, spread evenly over the whole heap.

Fig. 5, step by step: four gaps of glibc's heap, 17 pages, to scale

  1. Allocate and touch 400,000 blocks. 272-byte chunks packed end to end across 4 KiB pages; RSS 110,524 KiB. Fig. 5 shows a window of four gaps (17 pages) of a heap of about 27,600 (110,524 KiB / 4 KiB).
  2. Free all but every 64th. Each freed chunk merges with its free neighbours (except the 7 the tcache keeps), so every gap becomes one free chunk of 63 × 272 = 17,136 bytes, with a survivor every 17,408 bytes. 1,562 KiB live; RSS does not move: the freed pages stay mapped and resident.
  3. malloc_trim(0) drops the whole free pages. madvise(MADV_DONTNEED) on every page that lies entirely inside a free chunk; the partly used page at each end of a gap, holding a survivor, stays. RSS falls to 29,404 KiB.
  4. Free the rest. Every chunk merges into the top, which glibc trims at once: 4,436 KiB. The other three allocators keep about 105 to 110 MiB until they are told to purge (the table beside the next paragraph).

Page and chunk positions in Fig. 5 follow from the sizes (272-byte chunks laid end to end from the heap's start); the RSS figures are measured.

(1) Every allocator keeps about 105 to 110 MiB resident for 1.6 MB of live data. (2) malloc_trim(0) returns glibc's whole free pages, down to 29,404 KiB, and no further: the 6,250 survivors sit one every 17,408 bytes (64 × 272), so every gap keeps a partly used page at each end, about 24 MiB of pinned pages (29,404 minus the 4,436 KiB held once everything is freed). jemalloc keeps all 107 MiB even with purging on, because each of its 256-byte slabs still holds one survivor: purging returns only pages with nothing live on them. (3) With everything freed, glibc is back near its start at once (4,436 KiB: the top was trimmed); the others keep about 105 to 110 MiB by default and give it back only when told to: jemalloc with its background purging thread (9,624 KiB 3 s later), mimalloc with MIMALLOC_PAGE_RESET=1 (4,828 KiB); this tcmalloc kept everything even with TCMALLOC_RELEASE_RATE=10 in the 3 s window.

Predict: a process allocated 2 GB of small objects, then freed all but 1% of them, scattered. RSS stays near 2 GB. Will malloc_trim(0) bring it near 20 MB?

One live chunk pins a page: RSS after freeing 98%, after malloc_trim, and after freeing everything

measured here src/exp/frag.c, 1 CPU. Columns: RSS after the frees, after malloc_trim(0) (glibc only; the others do not provide it), and 3 s after freeing the rest. Live data after the frees: 1,562 KiB; start of each run: 756 to 5,572 KiB. The "purging" rows: jemalloc with MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0, tcmalloc with TCMALLOC_RELEASE_RATE=10, mimalloc with MIMALLOC_PAGE_RESET=1 MIMALLOC_RESET_DELAY=0 (option names of these versions).

Test 2: long-run growth in a data loader. Four threads "decode" 120,000 samples into NumPy arrays of 64 KiB to 8 MiB (log-uniform, fixed seed); a prefetch window keeps the last 8 arrays; and for every sample the loader also keeps a 600-byte record forever (metadata, a cache entry, a log line), so live memory grows by a known 600 bytes a sample, 68.7 MiB in total. The question is how much RSS each allocator holds on top of that.

glibc's default ends at about 211.1 MiB against 68.7 MiB live: the dynamic threshold soon moves the arrays onto the heap (section 3), and the small records made right after each array land between them and pin it. Pinning the threshold (MALLOC_MMAP_THRESHOLD_=131072) keeps every array in its own mmap and holds the least, 106.5 MiB, but every array then costs an mmap, a munmap and a page fault per page: 42.83 s against 10.43 s. jemalloc holds less than glibc here (148.4 MiB); tcmalloc and mimalloc hold more but finish fastest.

No allocator setting wins both memory and time on the same data-loader workload

measured here src/exp/loader_growth.py, 4 threads on 2 CPUs, 3 runs per configuration (the curve is run 1; the end figures are medians). RSS is sampled every 250 samples; the dashed line is live data (window plus kept records).

6. jemalloc, tcmalloc, mimalloc: the same job, other designs

ch. 17 (segregated lists), beyond OSTEP

All three replace glibc's one heap with bins by size classes in their own runs of pages: every object of a class lives in memory that holds only that class, so finding a free object is a pop from a short list and fragmentation is bounded per class. They differ in how threads are kept apart and in when memory goes back to the kernel.

jemalloctcmallocmimalloc
Small objectssize classes in slabs; a per-thread cache (tcache) in frontsize classes in spans; a per-thread cache (gperftools) or a per-CPU cache using restartable sequences (newer tcmalloc) in front of central free listssize classes in 64 KiB "pages"; each page has its own free lists ("free list sharding"): one for the owning thread, one for frees from other threads
Threadsseveral arenas, 4 per CPU by default, threads spread over themcaches per thread or per CPU, shared central lists and page heapa heap per thread; cross-thread frees go onto the page's thread-free list with one atomic operation
Gives memory back"decay": dirty pages purged over dirty_decay_ms (10 s default), only on allocator activity unless background_thread:truegradually, at TCMALLOC_RELEASE_RATE (default 1); MallocExtension::ReleaseFreeMemory() forces itafter a delay (option names differ by version)
Sourcesjemalloc(3)gperftools tcmalloc, tcmalloc designmimalloc tech report, repository

Origins: jemalloc, Jason Evans for FreeBSD's libc (2005), then Meta; tcmalloc, Google (the gperftools version measured here, and a newer one in Google's tcmalloc repository); mimalloc, Microsoft Research, Leijen, Zorn and de Moura (2019).

Switching needs no code change. malloc is resolved by the dynamic linker, so preloading another library replaces it for the whole process: LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 python train.py (the path differs per distribution and architecture; here it is under aarch64-linux-gnu). PyTorch's performance tuning guide recommends exactly this for CPU workloads ("Jemalloc or TCMalloc can get better performance by reusing memory as much as possible"). Check it took: grep -c jemalloc /proc/<pid>/maps is nonzero. DataLoader workers inherit the environment. Three caveats: memory allocated by one allocator must be freed by the same one (preloading guarantees that; a later dlopen does not); a library with its own allocator built in is unaffected (section 8: this wheel's tensors); and a missing library path does nothing but print a loader warning.

Read across a row: glibc's cliff is the 4 KiB batch (the trim churn of section 3); jemalloc's and mimalloc's are the large sizes, which they hand to the kernel with their own mappings (mimalloc's 1 MiB pair costs 789.3 ns); tcmalloc's fast path is the quickest at every small size (5.4 ns).

Each allocator has a size where it falls off a cliff: nanoseconds per malloc and free

measured here src/exp/bench.c, one thread, best of 5 runs. "Pairs": malloc, touch one byte, free, repeated, the allocator's fast path. "Batch": 1,000 mallocs then 1,000 frees. Two-thread figures are in src/raw/bench.txt. Microbenchmarks flatter the fast paths; real code mixes sizes and threads.

The running job under four allocators, 40 steps with two DataLoader workers, three runs each:

The differences are a few MiB and within the run-to-run spread of time, the honest result for this job: most of its memory is the libraries and the tensors, and on this arm64 wheel tensors do not go through malloc at all (section 8). Allocator choice matters for processes that allocate and free a lot of native memory from many threads for a long time: data loading with decoding, tokenization services, inference servers, and CPU training on x86-64, where tensors do use malloc.

The running job under four allocators: a few MiB apart, within the noise

measured here src/exp/job_alloc.sh and job_wrap.py: peak and final RSS of the main process from /proc/self/status, wall time from start to exit (including import torch).

7. Python's own layer: pymalloc, reference counts, and memory that does not come back

ch. 17 (segregated lists, again)

Why Python has its own allocator. A Python program creates and destroys small objects constantly: every integer result, every tuple, every frame. CPython routes requests of 512 bytes or less to pymalloc: "a pymalloc allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses memory mappings called arenas with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms" (Python 3.11 memory management). Larger requests go to malloc.

On top of that, several types keep free lists of recently freed objects for instant reuse, and small integers from -5 to 256 are preallocated once. Measured: 2,000,000 one-element tuples of fresh ints (about 160 MB of objects), then keep every 1,000th and drop the rest, then drop those too.


measured here src/exp/pymalloc_demo.py, run as is and with PYTHONMALLOC=malloc (which sends every object to glibc). Arena counts from sys._debugmallocstats().

With 2,000 survivors (0.1% of the objects) pymalloc still held all 158 arenas, 163.1 MiB: the Python version of section 5's pinned pages. This is why a long-running Python process rarely shrinks after del of a big structure if anything from it survives (a cached element, a reference in a log, an exception traceback). When everything died, pymalloc gave its arenas back at once (12.3 MiB), while glibc kept 222.3 MiB until malloc_trim(0) (9.3 MiB): its freed chunks sat below a live chunk near the top of the heap, which blocks trimming.

One live object keeps its pool, and its pool keeps the whole 1 MiB arena

Three levels (Objects/obmalloc.c at v3.11.2): arenas of 1 MiB got with mmap (ARENA_BITS 20, line 958; _PyObject_ArenaMmap, line 149), cut into 64 pools of 16 KiB (POOL_BITS 14, line 973), each pool serving one size class in steps of 16 bytes (ALIGNMENT 16, line 879) up to 512 (SMALL_REQUEST_THRESHOLD, line 904). A 1-element tuple (48 bytes) and an int (28 bytes, class 32) come from different pools. An arena goes back to the kernel only when every object in all 64 pools is dead. Pool contents drawn illustrative; the sizes are the source's.

When an object is freed: reference counts at once, cycles later

CPython frees an object the moment its reference count reaches zero: the block goes straight back to its pymalloc pool (or to malloc). Objects that refer to each other in a cycle never reach zero, so a separate cycle collector finds them; it runs when allocations minus deallocations of tracked objects pass a threshold (gc.set_threshold, gc module). Until it runs, everything a cycle holds stays allocated: payloads, NumPy buffers, CPU or GPU tensors.

The same 2,000 records: freed at once without a cycle, held until the collector runs with one

measured on Apple M1 Pro, macOS, Python 3.11.9 src/exp/gc_cycles.py: each record owns a 10,000-byte payload; bars are the most memory tracemalloc saw still allocated after a record was dropped. No cycle: 0.2 KiB. In two-object cycles with the collector on (default threshold 700, 10, 10): up to 6.7 MiB waits for a collection. With gc.disable(): 38.5 MiB (2,000 × 2 × 10,000 bytes = 38.1 MiB of payloads, plus the objects) until gc.collect() found 4,000 objects and freed them. Python 3.14.8 reports a threshold of 2000, 10, 10 and held up to 19.2 MiB in the same cycle run: what waits for the collector depends on the version.

In ML work. Python objects matter most in DataLoader workers: a dataset held as millions of Python objects (lists of strings, dicts of ints) is touched by reference counting on every access, which copies the shared pages after fork into every worker. A forked worker that only iterates 1M Python ints copied 7,880 pages, against 38 to 67 for a NumPy array of the same data; the virtual memory page owns copy-on-write and shows that run in its section 7. Keep large datasets in NumPy arrays, Arrow buffers or memory-mapped files, not in Python objects. The gc.freeze recipe (gc.disable() early in the parent, gc.freeze() right before fork(), gc.enable() in the child) stops the collector from touching the parent's objects, "avoiding unnecessary copy-on-write in child processes", but reference counting still writes. And break cycles that hold tensors (a stored exception with its traceback, an object that keeps a closure over itself), or that memory waits for the collector.

8. NumPy and PyTorch on the CPU: who calls whom

NumPy allocates array data with malloc, plus two tricks (numpy/_core/src/multiarray/alloc.c at v2.4.6): a small cache of freed buffers under 1,024 bytes, 7 per size (NBUCKETS and NCACHE, lines 45 to 47), and, for arrays of 4 MiB or more on Linux, madvise(MADV_HUGEPAGE) on the data (indicate_hugepages, lines 99 to 112), so with THP in "madvise" mode large arrays may get 2 MiB pages.

PyTorch's CPU tensors go through c10::alloc_cpu (c10/core/impl/alloc_cpu.cpp at v2.14.1), and which allocator that is depends on the build: mi_malloc_aligned when PyTorch is built with mimalloc (lines 111 to 117), which its CMakeLists turns on "on Windows and AArch64" Linux (lines 451 to 468 of CMakeLists.txt); otherwise posix_memalign from glibc (line 126) with 64-byte alignment, "enough for computation up to AVX512" (c10/core/alignment.h, line 15). On Linux, THP_MEM_ALLOC_ENABLE=1 makes buffers of 2 MiB or more page-aligned and madvised for huge pages (lines 58 to 70 and 136 to 147). So the same Python code allocates tensors with glibc on an x86-64 Linux box and with mimalloc on a Graviton or Grace host, and LD_PRELOAD=libjemalloc.so changes tensor allocation only on the first.

The root's 1 GiB reservation, explained. Traced here, the first CPU tensor in a process makes mimalloc reserve 1 GiB of address space and mark it for huge pages (the highlighted mmap and madvise lines of the trace).

The trace: a torch tensor and a NumPy array of 64 MiB, made and deleted (recorded output)

measured here strace -s 200 -e trace=mmap,munmap,madvise,brk,write python src/exp/torch_cpu.py; each marker prints RSS before the action; thread-stack mmaps from the first multi-threaded fill are cut. The root's gdb stack (its src/trace/raw/hugepage_stack.txt) shows the caller is mimalloc inside libc10.so.

The reservation costs nothing until touched (overcommit; the virtual memory page). A 64 MiB tensor then made no system call at all: it was carved from the reservation and its pages faulted in on first touch (RSS 228.1 to 294.1 MiB), and after del RSS stayed at 294.1 MiB to the end: mimalloc keeps freed memory for reuse. NumPy's 64 MiB array, by contrast, took its own mmap (above glibc's threshold), got its huge-page hint, and went back with munmap on del.

The same in mimalloc's source (provenance)

The vendored mimalloc (commit 30ac9d5, version 2.4.1) reserves arenas "N KiB at a time (=1GiB)" (MI_DEFAULT_ARENA_RESERVE, src/options.c lines 69 to 75 and 152), with MAP_NORESERVE, and calls madvise(MADV_HUGEPAGE) on it (src/prim/unix/prim.c lines 391 to 400).

Pinned host memory from source; not run here. pin_memory() and DataLoader(pin_memory=True) allocate page-locked host memory through PyTorch's CachingHostAllocator, which calls cudaHostAlloc (CachingHostAllocator.cpp line 77 at v2.14.1), caches freed blocks like its GPU counterpart, and rounds each request up to the next power of two "to improve reuse" (CachingHostAllocator.h lines 339 to 347; no upper limit on the rounding by default, pinned_max_round_threshold in AllocatorConfig.h line 360). A 600 MB pinned buffer therefore takes 1 GiB of locked RAM, which the kernel can never swap or reclaim. Why pinning exists and what it costs the kernel belongs to the virtual memory page.

9. PyTorch's CUDA caching allocator, and "out of memory" with memory free

ch. 17 again, one level up

from source and docs; not run here: no GPU Line numbers are c10/cuda/CUDACachingAllocator.cpp at v2.14.1 unless named; constants are in c10/core/AllocatorConfig.h. Zach DeVito's guide to the caching allocator is the best walkthrough by one of its authors.

The problem. Asking the CUDA driver for memory is slow, and caching "allows fast memory deallocation without device synchronizations" (CUDA semantics, memory management), so PyTorch keeps every freed block of a training step and reuses it: glibc's bins again. The visible consequence, in the docs' words: "the unused memory managed by the allocator will still show as if used in nvidia-smi".

The rules (the comment at the top of the file, lines 93 to 122, and the code): every request is rounded up to a multiple of 512 bytes; requests up to 1 MiB come from 2 MiB segments (the small pool), requests of 1 to 10 MiB from 20 MiB segments, larger ones from a segment of their own size rounded to 2 MiB; a request takes the best fit among cached free blocks and splits it; freeing never calls the driver, the block returns to its pool and merges with free neighbours in its segment; and when cudaMalloc fails, the allocator releases cached segments that hold nothing live and retries, then raises. A segment with even one live block cannot be returned.

Each rule with its source lines (reference)
  • Rounding. Every request is rounded up to a multiple of 512 bytes (round_size, lines 3060 to 3072; kMinBlockSize 512). With roundup_power2_divisions:N large requests are instead rounded to one of N steps between powers of two (lines 3036 to 3058), which makes sizes repeat and blocks reusable.
  • Two pools. Requests up to 1 MiB (kSmallSize) go to the small pool, packed into 2 MiB segments (kSmallBuffer); larger ones to the large pool (get_pool, lines 3640 to 3667).
  • Segment size. When nothing cached fits, a new segment comes from cudaMalloc: 2 MiB for small requests, 20 MiB for requests from 1 to 10 MiB (so several share one), and the request rounded up to 2 MiB above that (get_allocation_size, lines 3695 to 3703).
  • Best fit. A pool's free blocks are sorted by stream, size, segment age and address; a request takes the smallest one that fits (get_free_block, lines 3705 to 3762).
  • Splitting. If the chosen block is bigger, the front is handed out and the rest stays cached, in the small pool if at least 512 bytes remain, in the large pool only if more than 1 MiB remains (should_split, lines 3675 to 3693).
  • Freeing never calls the driver: the block goes back to its pool and merges with free neighbours in the same segment (free_block and try_merge_blocks, lines 3502 to 3612). A block is tied to the stream it was allocated on; using it on another stream needs tensor.record_stream(s), or it may be reused too early.
  • Out of memory: the retry chain. If cudaMalloc fails, the allocator frees cached blocks and tries again: first just enough oversize blocks (only when max_split_size_mb is set), then every cached segment that is not split, then raises (malloc, lines 1720 to 1792). A segment with even one live block cannot be returned.

The failure. Segments are sized by the first requests that needed them. When later requests are a little bigger (batch 9 after batch 8, a longer sequence), they do not fit the free holes, new segments are made, and the slivers left in old segments are stranded beside something live, until cudaMalloc fails with hundreds of megabytes free in total. The message says so (lines 1927 to 1953):

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate <segment size>. GPU 0 has a total capacity of <total> of which <free> is free. ... Of the allocated memory <a> is allocated by PyTorch, and <r> 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.

"Tried to allocate" reports the segment size the allocator asked the driver for (alloc_size), so a 3 MiB tensor can fail as "Tried to allocate 20.00 MiB". "Reserved but unallocated" is the fragmentation: cached memory no request fit.

The fix: expandable segments. The file's Note [Expandable Segments] (lines 311 to 401) tells the batch-size story and the cure: "Instead of making one segment per allocation, it tries to make one segment (per stream) that grows as necessary". It reserves a range of GPU virtual addresses as large as the device memory (cuMemAddressReserve) and maps physical memory into it in pages, 2 MiB for the small pool and 20 MiB for the large one, with cuMemCreate and cuMemMap, so new memory lands right after the old and free space at the end of the segment joins with what is mapped next: virtual memory (the virtual memory page), applied by a user-space allocator to the GPU. The limits the note lists: slightly slower first allocations, and no CUDA IPC of such memory (sharing GPU tensors between processes).

Fig. 6, step by step: the batch-size story on a 2,560 MiB device, default (front) and expandable segments (back)

  1. The weights: one segment. A 900 MiB request is above 10 MiB, so the default gets a segment of its own size from cudaMalloc; with expandable segments the allocator maps 900 MiB of pages into one reserved range instead.
  2. Batch 8: segments sized by the first requests. The first activation (96 MiB, kept) and temporary (240 MiB, freed at once) each get a new segment from cudaMalloc. The freed temporary stays in its segment as a cached block (orange): no cudaFree, and the next activation is cut from it with no driver call.
  3. Batch 8 ends: everything but the weights is cached. The activations are freed in reverse order; reserved stays at 2,436 MiB while 900 MiB is allocated. The cache is warm for a repeat of the same sizes.
  4. Batch 9: a little bigger, and the cache no longer fits. The first 108 MiB activation is cut from an old 240 MiB block, leaving a 132 MiB sliver; the 270 MiB temporary fits in no cached block and the device is full, so the allocator releases every fully free segment (six cudaFree calls) and asks for a new 270 MiB one.
  5. Batch 10: out of memory with memory free. 120 MiB activations and 300 MiB temporaries: each new 300 MiB segment ends up holding two activations and a 60 MiB sliver. At request 104 a 300 MiB temporary fits in no free block (the largest is 180 MiB) and nothing more can be released: 2,340 MiB reserved, 1,860 MiB allocated, 480 MiB reserved but unallocated. OutOfMemoryError.
  6. Expandable segments finish. Same requests: one segment per pool grows by mapping pages after the old ones, so free space at its end joins what is mapped next. All 201 requests run; reserved peaks at 2,420 MiB of 2,560.

Driven by the page's model of the allocator (the lab beside the next paragraph; checked against src/sim/cache_ref.py); the request sizes are illustrative, the rules are the source's.

Every knob, and what to look at

PYTORCH_ALLOC_CONF optionDoesUse when
expandable_segments:Trueone growing segment per stream and pool, mapped in pages"reserved but unallocated" is large; varying batch or sequence sizes. The first thing to try
max_split_size_mb:Nblocks of N MiB or more are never split, and are released first on OOMthe older fix for big fragmenting tensors; helps when large and medium requests mix
roundup_power2_divisions:Nrounds large sizes to N steps per power of twomany slightly different sizes
garbage_collection_threshold:0.8with a memory fraction set, frees old cached blocks once usage passes the fraction, before an OOMavoiding the full release at OOM time
large_segment_size_mb, max_non_split_rounding_mbthe 20 MiB segment size, and how much bigger an unsplit block may be than the requestrarely

Option names from c10/core/AllocatorConfig.cpp lines 17 to 24; PYTORCH_ALLOC_CONF is the current variable and PYTORCH_CUDA_ALLOC_CONF is still read (lines 46 to 52). Descriptions follow the CUDA notes.

What to look at. torch.cuda.memory_allocated() (live tensors) against torch.cuda.memory_reserved() (what the cache holds); torch.cuda.memory_stats()["inactive_split_bytes.all.current"], the free space stranded in split segments, the fragmentation number; torch.cuda.memory_summary() for all of it in a table. nvidia-smi shows what the cache reserved plus the CUDA context, never what the model needs. torch.cuda.empty_cache() returns cached, unused segments to the driver: useful when another process needs the GPU, useless against fragmentation, and slower afterwards because the cache must refill.

The same requests, two configurations: the default runs out of memory with hundreds of MiB reserved but unallocated; expandable segments finish

A model of the allocator's rules at v2.14.1 (src/sim/cache_ref.py, every rule with its line numbers), ported to this page and checked against it step by step (). Each bar is the device memory to scale: segments side by side (what cudaMalloc returned, or the mapped pages of an expandable segment), live tensors filled, cached free blocks hatched. It starts on a toy training loop whose batch goes 8, 9, 10, 8, 10 on a 2,560 MiB device (peak of live tensors 2,400 MiB). Predict which lane fails first, then step or jump to the first OOM; then set the right lane to max_split_size_mb:200, the older fix, and watch it return whole segments to the driver (cudaFree) to make room.

What the model leaves out

One device and one stream (no cross-stream reuse, CUDA events or record_stream), no CUDA graph pools, no garbage_collection_threshold; cudaMalloc succeeds exactly when reserved plus the request fits the capacity (the driver's own 2 MiB granularity is ignored); an expandable segment reserves address space equal to the capacity rounded up to its page (2 MiB small pool, 20 MiB large pool), and releasing it unmaps the whole pages inside free blocks. Scenario sizes and capacities are illustrative; the rules are the source's.

Two more interactions. Every process has its own cache: two processes on one GPU (a trainer and an evaluator) each hold reserved memory the other cannot use. And CUDA graphs capture fixed addresses, so captured work allocates from a private pool kept until the graph is destroyed (the Note at lines 126 to 156).

PyTorch memory visualiser, Allocator State History view: a list of alloc and free events on the left; on the right one bar per segment, coloured where tensors are live and white where cached blocks are free
A real snapshot in pytorch.org/memory_viz's Allocator State History: each row is one segment, coloured blocks are live tensors and white space inside a row is cached free memory, the "reserved but unallocated" of the OOM message. Rows with white gaps between coloured blocks are the stranded slivers Fig. 6 and the lab draw.Image: PyTorch documentation, Understanding CUDA memory usage (docs/source/_static/img/torch_cuda_memory/allocator_state_history.png, top cropped), PyTorch contributors, BSD-3-Clause licence.

10. Diagnosing memory that grows, and choosing an allocator

Find which layer first. Each layer has its own tool; the gap between two of them says where the memory is.

Look atIf it saysThen it isFix
tracemalloc snapshots, compared over stepsone Python line's total growsa real leak in Python objects (a list of losses kept as tensors with their graphs, a cache with no bound)keep loss.item(), bound the cache
RSS against tracemalloc's totalRSS grows, tracemalloc flatnative memory: a C library, or allocator overheadnext two rows
heaptrack on the processa native call stack whose allocations are never freed, or millions of temporary onesa native leak or allocation churn in an extensionfix the code at that stack
malloc_stats() or malloc_info() in the process (ctypes or gdb)large "system bytes" with small "in use", many arenasglibc holding freed memory (sections 4, 5)malloc_trim(0) as a test, then MALLOC_ARENA_MAX=2, a pinned mmap threshold, or jemalloc with background_thread:true; measure each
/proc/<pid>/smaps_rollup of each DataLoader worker: Pss, Private_Dirtyworkers' private memory grows over the first epochcopy-on-write of a Python-object dataset, not the allocatorNumPy or Arrow storage (virtual memory page)
torch.cuda.memory_stats()reserved far above allocated, OOM with memory freecaching-allocator fragmentation (section 9)expandable_segments:True, then max_split_size_mb
the container's memory.current against your processes' RSSthe cgroup's total far above RSSpage cache or /dev/shm counted against the limitthe root's Debug lab cases

tracemalloc records the Python line that allocated every live block: tracemalloc.start(25), then take_snapshot().statistics("lineno")[:10], or snapshot2.compare_to(snapshot1, "lineno") between two points of a training loop (tracemalloc). It sees Python's allocators and NumPy array data (NumPy reports it), not memory allocated inside other C libraries. heaptrack covers that side: it "traces all memory allocations and annotates these events with stack traces" for any Linux process, through malloc, either from the start (heaptrack python train.py) or attached to a running one (heaptrack --pid <pid>), and its analysis lists leaks, allocation hotspots and temporary allocations (KDE heaptrack; not run here). It does not see tensors on an arm64 PyTorch wheel (mimalloc inside libc10, section 8) or GPU memory.

On the GPU, record a snapshot. torch.cuda.memory._record_memory_history(max_entries=100000), run a few steps, torch.cuda.memory._dump_snapshot("snap.pickle"), and drop the file on pytorch.org/memory_viz, which draws every segment and block over time with the Python stack that allocated it (Understanding CUDA memory usage). The visualiser runs locally in the browser and does not upload the snapshot.

PyTorch memory visualiser, Active Memory Timeline: stacked coloured bands of live tensors rising step by step to about 3 GB and then falling
The Active Memory Timeline of a real snapshot: every band is one live tensor, stacked over time. Tensors pile up to about 3 GB and are then freed in reverse order, the shape of a forward pass followed by a backward pass (the cropped stack trace points into a torchvision ResNet's forward); a band that never ends is the leak to click on, and hovering a band shows the stack that allocated it.Image: PyTorch documentation, Understanding CUDA memory usage (docs/source/_static/img/torch_cuda_memory/active_memory_timeline.png, stack-trace panel cropped), PyTorch contributors, BSD-3-Clause licence.

Choosing an allocator for a training host. Start with the defaults, find out whether allocation is a problem at all (the running job did not care, section 6), and change one thing at a time with peak RSS, steady RSS and step time recorded. Then: jemalloc is the common choice for long-running multi-threaded data and serving processes whose RSS drifts (enable its background thread, or it may never give memory back); tcmalloc for the fastest small-object paths; glibc with MALLOC_ARENA_MAX=2 when you cannot ship a library. On x86-64 CPU training, PyTorch's tuning guide suggests jemalloc or tcmalloc via LD_PRELOAD; on arm64 the tensors already use mimalloc. A container's memory limit counts RSS: memory an allocator keeps "for reuse" is memory the OOM killer counts.

Depth

Interview rehearsal (optional)
Why doesn't free() return memory to the operating system?
The kernel works in pages and only gives memory back by unmapping or advising whole pages. A freed chunk is usually a small piece of a page that also holds live chunks, or sits below other live chunks in the heap, which can only shrink from its top. Allocators keep freed memory to serve the next request without a system call. glibc returns big blocks (above the mmap threshold) at once, trims the top of the heap past the trim threshold, and malloc_trim releases whole free pages anywhere; others return memory after a delay.
Internal against external fragmentation, with an example of each.
Internal: waste inside handed-out blocks, such as glibc's 32-byte chunk for a 1-byte request, a buddy allocator giving 16 pages for 9, PyTorch rounding to 512 bytes or a pinned buffer to a power of two. External: free memory in pieces too small for the request, such as ten 10-byte blocks with every other one freed (50 free, none fits 15), or GPU segments with free slivers no new tensor fits. Compaction fixes external fragmentation only where blocks can move (garbage-collected runtimes); C allocators and PyTorch's cannot move them, so they prevent it with size classes, splitting rules and, on the GPU, virtual memory (expandable segments).
What does the CUDA OOM message's "reserved but unallocated" mean, and what do you do?
Memory the caching allocator holds in segments but no live tensor uses: after it already released every fully free segment, what remains is free space inside segments that still contain live blocks, so it is fragmentation. Try PYTORCH_ALLOC_CONF=expandable_segments:True; check with a memory snapshot which allocations straddle; make sizes regular (pad or bucket sequence lengths, fixed batch sizes, roundup_power2_divisions); then reduce the peak (activation checkpointing, smaller micro-batches).
How does glibc decide between brk and mmap for a request, and why is the threshold dynamic?
Requests at or above M_MMAP_THRESHOLD (128 KiB to start) get their own mmap; smaller ones come from the heap. Freeing an mmapped chunk raises the threshold to that size (up to 32 MiB on 64-bit) and the trim threshold to twice it, on the guess that the program will allocate that size again and should not pay mmap, munmap and page faults every time. The cost is that later big blocks live in the heap and can stay resident; setting the threshold explicitly turns the adjustment off.
Why do multi-threaded programs on glibc sometimes use far more memory than single-threaded ones?
glibc creates up to 8 arenas per CPU, each with its own free chunks; memory freed in one arena cannot serve requests in another, and a chunk freed by another thread returns to its own arena. Free memory spread over many arenas adds up. MALLOC_ARENA_MAX caps it at the cost of lock contention; jemalloc and mimalloc handle cross-thread frees differently (mimalloc with a per-page thread-free list).
A Python service's memory never goes down after a large request. Why, and how do you confirm?
Likely pymalloc arenas pinned by a few surviving objects, or glibc chunks below a live chunk at the heap's top. Confirm: tracemalloc's current total is low while RSS is high; sys._debugmallocstats() shows many arenas with few used pools; malloc_trim(0) from ctypes drops RSS if it is glibc. Fixes: avoid keeping references to per-request objects, move bulk data to arrays, or recycle worker processes.
OSTEP chapter map for this page
ChapterOn this pageBeyond the chapter here
13 Address Spacesthe heap as a region of the address space (section 1)brk and mmap traced (section 3)
14 Interlude: Memory APImalloc, free, calloc, realloc, common errors (section 2)chunk sizes measured; glibc's error messages
17 Free-Space Managementheaders, free lists, splitting, coalescing, policies, segregated lists, slab, buddy (section 1, with the homework simulator)glibc's bins, arenas, thresholds (3, 4); fragmentation measured (5); jemalloc, tcmalloc, mimalloc (6); pymalloc (7); the CUDA caching allocator (9)
21 and 22 Swappingwhy memory an allocator keeps still costs (RSS and limits)the virtual memory page
26 to 28 Concurrency and lockswhy arenas and thread caches exist (section 4)the concurrency page

OSTEP: ch. 14 Memory API, ch. 17 Free-Space Management.