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
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.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.
malloc (or torch.empty) returns.cudaMalloc; tensors are blocks cut from it.| Layer | Gets memory from | Unit it hands out | Gives memory back | See it with |
|---|---|---|---|---|
| pymalloc | mmap, 1 MiB arenas | 16-byte size classes up to 512 B, in 16 KiB pools | an arena when every object in it is dead | sys._debugmallocstats(), tracemalloc |
| glibc malloc | brk (main heap), mmap (big blocks, thread arenas) | chunks: request + 8 bytes, rounded to 16, at least 32 | the heap's top past 128 KiB (trim threshold); mmapped chunks at once; malloc_trim | malloc_info, malloc_stats, /proc/<pid>/smaps |
| jemalloc, tcmalloc, mimalloc | mmap | size classes in per-size runs, slabs, spans or pages | after a delay or rate (decay, release rate, purge delay) | their stats calls and environment options |
| CUDA caching allocator | cudaMalloc, or cuMemCreate plus cuMemMap | blocks: 512-byte multiples in 2 MiB or 20 MiB-plus segments | only on OOM retry or torch.cuda.empty_cache() | memory_summary(), memory snapshots |
| kernel | physical memory | 4 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.
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.
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.
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.
Fig. 2, step by step: the drill on a 100-byte heap, coalescing on
-H 0); the free list holds one entry, [1000, 100].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.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.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.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.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).
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).
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?
malloc.py -c prints it, up to this stepExternal 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).
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 calls (malloc(3), posix_memalign(3), malloc_usable_size(3)):
| Call | Does | Worth knowing |
|---|---|---|
malloc(n) | n bytes, contents not initialised | aligned for any type: 16 bytes on 64-bit Linux |
calloc(k, n) | k × n bytes, zeroed | checks 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 moving | a large mmapped block can grow with mremap without copying (mremap_chunk, line 3068) |
free(p) | give back | free(NULL) does nothing; everything else must be a pointer malloc returned, freed once |
posix_memalign, aligned_alloc | n bytes at a chosen alignment | what 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 has | shows the rounding (the chunk-size chart) |
free, into a chunk that may already belong to someone else or whose first bytes now hold the free list's links.free(): double free detected in tcache 2.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.
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.
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.
Fig. 3, step by step: where malloc(n) looks, cheapest first
_int_malloc consolidates the fastbins, and it finds bigger bins through a bitmap.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.
| Bin | Holds | How it works | Source |
|---|---|---|---|
| tcache | chunks up to 1,032 bytes, 7 per size | per thread, no lock, last in first out: the fast path for most small requests since glibc 2.26 | TCACHE_MAX_BINS 64, TCACHE_FILL_COUNT 7, lines 309 to 328 |
| fastbins | chunks up to 128 bytes | per arena, single-linked, not merged with neighbours until a consolidation | DEFAULT_MXFAST = 64 × 8 / 4, line 852 |
| unsorted bin | any freed chunk, first | one 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 bins | below 1,024 bytes, one size each | 62 double-linked lists, exact size | NSMALLBINS 64, MIN_LARGE_SIZE, lines 1571 to 1574 |
| large bins | 1,024 bytes and up, size ranges | sorted by size, best fit within the bin; large free chunks also carry fd_nextsize, bk_nextsize | NBINS 128, line 1570 |
| top chunk | the free space at the end of the heap | split when no bin fits; the heap grows with brk when top is too small | sysmalloc, line 2541 |
measured here strace -e trace=brk,mmap,munmap,write ./threshold (src/exp/threshold.c); the "---" lines are the program's own markers.
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.
brk), and freeing it gives nothing back: the trim threshold is now about 2 MiB. Step through both traces beside, the default and with the threshold pinned.The two traces, step by step
MALLOC_MMAP_THRESHOLD_=131072. The program makes four calls.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).free. Both runs give the mapping straight back with munmap. In the default run glibc also raises its threshold to about 1 MiB.malloc(1 MiB). The default run now serves it from the heap, growing it with brk; the fixed-threshold run maps again.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.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.
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.
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
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.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.
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().
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
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.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.
malloc_trim(0) bring it near 20 MB?mtrim calls MADV_DONTNEED inside free chunks, not only at the top), but a page holding even one live chunk stays. With 1% of objects alive and spread out, many pages still hold one: here 1.5% live left RSS at 27% of its peak after the trim. The real fix is to not interleave long-lived and short-lived objects in the same memory (separate arenas or pools, or allocate the long-lived ones first), or to restart worker processes periodically.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.
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).
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.
| jemalloc | tcmalloc | mimalloc | |
|---|---|---|---|
| Small objects | size classes in slabs; a per-thread cache (tcache) in front | size classes in spans; a per-thread cache (gperftools) or a per-CPU cache using restartable sequences (newer tcmalloc) in front of central free lists | size 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 |
| Threads | several arenas, 4 per CPU by default, threads spread over them | caches per thread or per CPU, shared central lists and page heap | a 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:true | gradually, at TCMALLOC_RELEASE_RATE (default 1); MallocExtension::ReleaseFreeMemory() forces it | after a delay (option names differ by version) |
| Sources | jemalloc(3) | gperftools tcmalloc, tcmalloc design | mimalloc 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).
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.
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).
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.
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.
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.
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.
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).
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 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.
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.
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.get_pool, lines 3640 to 3667).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).get_free_block, lines 3705 to 3762).should_split, lines 3675 to 3693).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.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)
cudaMalloc; with expandable segments the allocator maps 900 MiB of pages into one reserved range instead.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.cudaFree calls) and asks for a new 270 MiB one.OutOfMemoryError.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.
| PYTORCH_ALLOC_CONF option | Does | Use when |
|---|---|---|
expandable_segments:True | one 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:N | blocks of N MiB or more are never split, and are released first on OOM | the older fix for big fragmenting tensors; helps when large and medium requests mix |
roundup_power2_divisions:N | rounds large sizes to N steps per power of two | many slightly different sizes |
garbage_collection_threshold:0.8 | with a memory fraction set, frees old cached blocks once usage passes the fraction, before an OOM | avoiding the full release at OOM time |
large_segment_size_mb, max_non_split_rounding_mb | the 20 MiB segment size, and how much bigger an unsplit block may be than the request | rarely |
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.
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.
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.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.Find which layer first. Each layer has its own tool; the gap between two of them says where the memory is.
| Look at | If it says | Then it is | Fix |
|---|---|---|---|
tracemalloc snapshots, compared over steps | one Python line's total grows | a 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 total | RSS grows, tracemalloc flat | native memory: a C library, or allocator overhead | next two rows |
heaptrack on the process | a native call stack whose allocations are never freed, or millions of temporary ones | a native leak or allocation churn in an extension | fix the code at that stack |
malloc_stats() or malloc_info() in the process (ctypes or gdb) | large "system bytes" with small "in use", many arenas | glibc 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_Dirty | workers' private memory grows over the first epoch | copy-on-write of a Python-object dataset, not the allocator | NumPy or Arrow storage (virtual memory page) |
torch.cuda.memory_stats() | reserved far above allocated, OOM with memory free | caching-allocator fragmentation (section 9) | expandable_segments:True, then max_split_size_mb |
the container's memory.current against your processes' RSS | the cgroup's total far above RSS | page cache or /dev/shm counted against the limit | the 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.
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.
malloc_trim releases whole free pages anywhere; others return memory after a delay.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).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.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).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.| Chapter | On this page | Beyond the chapter here |
|---|---|---|
| 13 Address Spaces | the heap as a region of the address space (section 1) | brk and mmap traced (section 3) |
| 14 Interlude: Memory API | malloc, free, calloc, realloc, common errors (section 2) | chunk sizes measured; glibc's error messages |
| 17 Free-Space Management | headers, 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 Swapping | why memory an allocator keeps still costs (RSS and limits) | the virtual memory page |
| 26 to 28 Concurrency and locks | why arenas and thread caches exist (section 4) | the concurrency page |
Links checked on 5 October 2026 (the heaptrack, gc and memory-visualiser links on 24 October 2026). Times are estimates for the part worth reading. Suggested order: this page's Reading tab with OSTEP chapters 14 and 17 and their homework (the simulator in section 1); then glibc's MallocInternals page; then Zach DeVito's guide before your next CUDA OOM.
The running training job followed through the whole OS. Its section 5 is the short version of this page; its Syscall tracer shows the 1 GiB reservation; its Debug lab has the CUDA OOM, OOM-kill and copy-on-write cases.
System calls (what brk and mmap cost), fork and the DataLoader's workers.
The context switch measured, CFS read live from /proc, EEVDF as a simulator, affinity, NUMA and cgroup CPU quotas and throttling.
The layer under this one: pages, faults, mmap, THP, overcommit, pinned memory, RSS and PSS, memory cgroups and the OOM killer.
Why arenas and thread caches exist: locks, contention, atomics.
Devices and the block layer, the VFS, readahead and writeback measured, fsync and atomic replace, journaling, and checkpoints that survive a crash.
Namespaces and cgroups v2 built by hand, PID 1 and docker stop, memory.max against memory.high, seccomp, rootless, gVisor and Firecracker.
VM exits measured, nested paging, why cross-CPU wake-ups are slow here, virtio, the IOMMU, MIG, and one CUDA call down to the driver.
PyTorch beyond the allocator: compilation, CUDA graphs, profiling.
GPU memory budgets in training: activations, optimiser state, checkpointing and the compile memory budget as levers. This page is the allocator under them.
HBM, shared memory, registers and coalescing: the memory inside the GPU, below the caching allocator.
new and delete, RAII, caches and memory layout from the language side.
The object model behind pymalloc; reference counting and the collector from the language side (their memory behaviour is section 7 here).
Ownership as compile-time memory management, with a real run where the allocator hands a new buffer the block just freed.
Where GPU memory goes at scale: sharding, activation checkpointing, the memory budget per GPU.
The foundations of section 1 and 2, with the homework the Free-list lab runs.
The glibc maintainers' own tour of chunks, bins, arenas and tcache, with diagrams.
The source every glibc number on this page cites.
Segments, blocks, streams and the reasons for each rule, by one of its authors.
Memory snapshots and the visualizer; every PYTORCH_ALLOC_CONF option.
The Note [Expandable Segments] and the malloc retry chain are worth reading in full.
The classic survey: policies against mechanisms, and why real programs fragment less than random tests suggest.
Object caches for the kernel; the idea behind every size-class allocator since.
The design of the allocator inside PyTorch's arm64 and Windows wheels.
The options (decay, background threads, arenas) and the per-CPU cache design.
pymalloc, PYTHONMALLOC, the debug hooks and the snapshot API.
Native allocation tracing with stack traces; the collector's thresholds and the gc.freeze recipe for forking servers.
Its CPU section recommends jemalloc or tcmalloc through LD_PRELOAD.