Every address a program uses is virtual: the hardware translates it page by page through a per-process tree of tables, and the kernel fills that tree lazily, one page at a time, at first touch. Everything else (mmap, copy-on-write, huge pages, swap, the OOM killer) is a way of filling, sharing, enlarging or taking back pages.
/proc/PID/maps (section 1): the code of its .so files, the memory-mapped dataset, /dev/shm, the heap, the stack and anonymous memory that is mostly one 1 GiB allocator reservation. Widths follow the address space each kind takes, on a square-root scale.memory.max counts: anonymous frames, page cache and /dev/shm alike (section 12). Copy-on-write, huge pages and the OOM killer are ways of sharing, enlarging or taking back these frames.You need: what a process and fork are, from sections 2 and 4 of Topic: operating-systems (section 4 is the intuition this page goes under) and Processes and the system-call API. Everything else is defined here.
New terms (each defined again where it is taught):
/proc/PID/maps| Mechanism | What it does | Cost measured here | When it bites in ML | Look with |
|---|---|---|---|---|
| Page tables | map 4 KiB virtual pages to physical frames, 4 levels | 2,052 KiB of tables per GiB touched | rarely; huge resident sets on many processes | grep VmPTE /proc/PID/status |
| TLB | caches translations | miss: 7.6 ns vs hit 1.1 ns (root) | random gathers over big embeddings, hash tables | perf stat -e dTLB-load-misses |
| Page fault | fills a table entry on first touch | about 1 us per 4 KiB page | first epoch, first touch of a huge buffer | /usr/bin/time -v, ps -o min_flt,maj_flt |
| mmap | maps a file's cached pages into memory, no copy | random rows: 13x read amplification | datasets, safetensors, torch.load(mmap=True) | cat /proc/PID/maps |
| Copy-on-write | fork shares pages until written | fork of 1 GiB: 19.8 ms; one copy about 3.3 us | DataLoader workers growing to the parent's size | smaps_rollup Private_Dirty |
| Huge pages | one 2 MiB page instead of 512 | 512x fewer faults; up to 298x more memory | allocators, pinned buffers, bloat in sparse arrays | grep AnonHugePages /proc/meminfo |
| Pinned memory | pages the kernel may not move or swap | default limit here 64 KiB | pin_memory=True, RDMA, containers | ulimit -l, VmLck |
| memory cgroup, OOM | caps a container, kills when it cannot reclaim | killed at the limit, exit 137 | "Killed" with no traceback; /dev/shm counted | memory.events, memory.stat |
Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 4 KiB pages, 5 CPUs, about 10 GB, 1 GiB swap, THP in "madvise" mode, overcommit mode 1, one NUMA node, no GPU), image kb-os-vm:1 (the root's lab image plus safetensors), October 2026. Containers were not privileged. Things that need a GPU, a newer kernel, writable sysctls or real NUMA are taught from primary sources and tagged not run here. Labels: measured ran here; source read from kernel source or documentation (Linux v5.10, the kernel these runs used, file and line). Scripts and raw outputs: src/exp/ and src/raw/ in the repository.
| OSTEP chapter | Sections here |
|---|---|
| 13 The Abstraction: Address Spaces; 14 Memory API | 1 |
| 15 Address Translation; 16 Segmentation; 17 Free-Space Management | 1, 2 (allocators: the sibling page Memory allocators) |
| 18 Paging: Introduction; 20 Paging: Smaller Tables | 2, 8 |
| 19 Paging: Faster Translations (TLBs) | 3, 8 |
| 21 Beyond Physical Memory: Mechanisms; 22 Policies | 4, 6, 11 |
| 23 Complete Virtual Memory Systems (VAX/VMS, Linux) | 4, 5, 7, 8 (this page is chapter 23 extended to Linux 5.10 and to ML) |
Every process gets its own address space: a private range of addresses that the hardware translates to real memory on every access, so processes cannot see each other's data yet can share what is identical (the code of libtorch_cpu.so, the dataset file). On 64-bit Linux the user part is 248 bytes (256 TiB) on arm64 with 4 KiB pages and 247 bytes (128 TiB) on x86-64 with four-level tables (arm64 memory layout; x86-64 memory map). Almost all of it is empty. What exists is a list of mappings (virtual memory areas, VMAs): contiguous ranges with one set of permissions and one source, a file or anonymous zero-filled memory. Threads of one process share one address space; that is all "sharing memory" means for threads.
The 54 anonymous mappings add up to 1.5 GiB mainly because of one 1 GiB reservation by the allocator inside libc10.so (the sibling Memory allocators owns that story). Pages are only spent when touched (section 4).
vm.max_map_count caps the number of VMAs per process (default 65,530 in the kernel docs; Docker Desktop's VM sets 262,144, read here). The job uses about 456. A process that maps thousands of files or shards, or an allocator that splits its arena into many protected pieces, gets ENOMEM from mmap long before memory is short, and the error says nothing about VMAs.cat /proc/PID/maps | wc -l; pmap -x PID | tail -1; cat /proc/sys/vm/max_map_count
source: one struct mm_struct per address space holds pgd, the root of its page-table tree, and the set of VMAs (include/linux/mm_types.h line 388; a red-black tree in 5.10, a maple tree since 6.1); each VMA is a struct vm_area_struct with vm_start, vm_end, flags, an optional vm_file and a table of operations vm_ops that says how to fill a page when it is first touched (line 305). Threads of one process share one mm_struct.
The running job reserves 2 GiB of addresses; most of it is one allocator reservation, not memory
That total is what ps and top report as VSZ (virtual size): address space, not memory (section 13). measured: the root's recording of the main process just after its DataLoader workers were forked.
/proc/PID/mapsOne line per VMA: start-end, permissions (r, w, x, and p private or s shared), file offset, device, inode, path.
Memory is managed in fixed-size pages: 4 KiB here (getconf PAGESIZE prints 4096). A virtual address splits into a virtual page number (high bits) and an offset inside the page (low 12 bits, passed through unchanged). The page table maps each virtual page to a physical page frame, plus permission bits.
Why a tree. One flat table for 236 virtual pages at 8 bytes an entry would be 512 GiB per process. Instead the 36 bits are cut into four 9-bit pieces; each indexes a 4 KiB table of 512 eight-byte entries, which points to the next table. Only the tables on the path to a mapped page exist, so a sparse address space costs almost nothing. The arm64 kernel computes the number of levels as (VA_BITS - 4) / (PAGE_SHIFT - 3) (pgtable-hwdef.h line 26): (48 - 4) / (12 - 3) = 4 levels for 4 KiB pages.
0xffff81fd2000, the first byte of the job's memory-mapped dataset (from the maps lines in section 1), splits into four 9-bit indices (511, 510, 15, 466) and a 12-bit offset (0x0). Each index picks one of 512 entries in a 4 KiB table. The Address translator tab does this for any address, on arm64 with 4, 16 or 64 KiB pages and on x86-64 with four or five levels.0xffff81fd2 in the TLB and misses. The walk starts at TTBR0_EL1, the register holding the physical address of this process's level 0 table (CR3 on x86-64); a process switch reloads it.The indices are computed from the address (arm64, 4 KiB pages); table and frame numbers are illustrative (reading real frame numbers from /proc/PID/pagemap needs privileges).
The bits do work. Accessed is set by hardware on use: page reclaim reads and clears it to find cold pages (section 6). Dirty says a file page must be written back before reuse. Read-only on a writable mapping is how copy-on-write traps the first write (section 7). Not present is how swap and lazy allocation trap the first access (section 4).
VmPTE grew by KiB after touching 1 GiB. That is 0.2% of the memory mapped, per process: 64 workers each touching the same 10 GiB shared dataset carry 64 copies of its tables (1.3 GiB). With huge pages the kernel still sets aside one table per 2 MiB (section 8), so the measured VmPTE did not shrink.A process maps a 64 GiB file but only ever reads 1 MiB of it at one spot. Roughly how much page-table memory does that cost?
grep -E 'VmPTE|VmRSS|VmSize' /proc/PID/status
| x86-64 | arm64 (this VM) | |
|---|---|---|
| Level names, root first | PGD, (P4D with 5 levels), PUD, PMD, PTE | level 0, 1, 2, 3 (Linux reuses the x86 names) |
| Register holding the root | CR3 (one per CPU, reloaded on a process switch) | TTBR0_EL1 for user addresses, TTBR1_EL1 for the kernel half |
| Page sizes | 4 KiB; 2 MiB and 1 GiB as huge pages | granule of 4, 16 or 64 KiB, chosen when the kernel is built; Apple's macOS uses 16 KiB (the M1 host reports bytes, a labelled contrast) |
| Bigger address spaces | 5 levels (LA57): 57-bit, 128 PiB (5-level paging) | 52-bit with 64 KiB pages (LVA) |
| Key entry bits | Present, R/W, U/S, Accessed, Dirty, NX | valid, AP (user, read-only), AF (accessed), nG (not global), DBM (dirty), PXN/UXN (no execute) (lines 135 to 148) |
A four-level walk is four extra memory reads for every load and store, so the CPU keeps recent translations in a translation lookaside buffer (TLB), a small cache from virtual page number to frame and permissions. A hit adds nothing; a miss triggers the hardware walk of section 2 (its reads are themselves cached in the data caches, so a miss costs nanoseconds, not four trips to DRAM). The root page measured it on this machine: one access costs 1.1 ns while the touched pages fit in the TLB and 7.6 ns once they do not, with the knee between 2,048 and 4,096 pages (8 to 16 MiB of TLB reach, entries times page size); with 2 MiB pages the same walk stays at 1.1 ns (Topic: operating-systems, section 4 and the OS simulators tab, which also replays OSTEP's TLB homework). The Address translator tab sizes the reach for any footprint.
After a switch to another process the old translations are wrong, and flushing the whole TLB on every switch would make switches expensive, so entries are tagged with an ASID (arm64: 8 or 16 bits, read from the CPU at boot, arch/arm64/mm/context.c line 42; x86-64 calls it PCID, 12 bits). Kernel mappings are global and shared by all processes; user mappings are "not global" (the nG bit).
When a process changes or removes a mapping (munmap, mprotect, madvise(MADV_DONTNEED), page migration, swapping a page out), every CPU that may have cached the old translation must drop it, or a thread there would keep using a page that is no longer its own. That is a TLB shootdown, and the two architectures do it very differently source:
The kernel sends an inter-processor interrupt to each CPU running the address space and waits for all to flush (arch/x86/mm/tlb.c lines 798 to 825, smp_call_function_many); over 33 pages it flushes everything instead (line 842). Cost grows with the number of CPUs the process has run on.
The kernel issues TLBI VALE1IS ("inner shareable"), which the hardware broadcasts to every CPU, then waits with a barrier (arch/arm64/include/asm/tlbflush.h lines 255 to 272). No interrupt, no other CPU's code runs.
When it bites in ML. A CPU-heavy process with many threads (PyTorch's intra-op pool, a data loader with threads) whose allocator keeps returning memory to the kernel and asking for it again triggers a shootdown each time; on large x86 servers each costs interrupts on every CPU that ran the process. Symptom: high system time with no obvious system calls in your code. Fix: keep memory cached in the allocator instead of returning it (the Memory allocators page covers the knobs), fewer threads, huge pages.
perf stat -e dTLB-load-misses,dTLB-loads -p PID # not available in this VM (no hardware counters)
grep -E 'TLB' /proc/interrupts # x86: "TLB shootdowns" per CPU
On arm64 a shootdown costs the same with 0 or 3 other threads running
mmap and malloc only add a VMA; no frame is allocated and no table entry written (demand paging). The first access finds an invalid (or read-only) entry and the CPU raises a page fault: the kernel looks up the VMA, decides what the page should contain, fills the entry and re-runs the instruction. The program never notices, except in time. A minor fault needs no I/O; a major fault waited for a device (getrusage(2); in 5.10 a fault that had to be retried also counts as major, mm/memory.c lines 4548 to 4557).
Pick a case, then follow one access
TTBR0_EL1. The last entry is none (never touched): the walk stops with a fault.__do_page_fault (line 408) looks the address up among the mappings. VMA: anonymous, private, rw-.handle_pte_fault (mm/memory.c line 4330) chooses the handler from the entry and the VMA.TTBR0_EL1 and finds no entry: the walk stops with a fault.find_vma finds no mapping: the kernel sends SIGSEGV; Python dies with "Segmentation fault". Nothing is filled and nothing is retried.Three details that matter. (1) The zero page: a read of never-written anonymous memory maps one shared, read-only page of zeros (mm/memory.c lines 3496 to 3500): measured, reading 64 MiB took faults and added 0 KiB of RSS; writing it afterwards took the same number of faults again. So "I allocated and read it, but RSS did not grow" is expected. (2) Fault-around: a read fault on a cached file page maps up to 16 neighbouring cached pages at once (fault_around_bytes = 64 KiB, line 3875). The root's warm read of the 2,056-page dataset took exactly 129 minor faults, which is 2,056 / 16 rounded up. (3) MAP_POPULATE (or madvise(MADV_POPULATE_WRITE) since 5.14) pays all faults inside the mmap call: 64 MiB took ms in the call against ms by touching page by page, because one call avoids 16,384 trips into the kernel.
You np.empty(10**9, dtype=np.uint8) and immediately call .sum(). Memory use (RSS) afterwards?
np.empty is a fresh anonymous mapping (glibc serves big requests with mmap). Reading it faults each page onto the shared zero page: 244,141 minor faults, no new frames. The sum is 0. RSS grows only when you write. (With transparent huge pages enabled for the range, a read fault can instead map a huge zero page; same outcome.)When it bites in ML. The first epoch is slower than the rest (major faults on the dataset; the root's Debug lab case "The first epoch is slower than the rest: cold and warm page cache"); the first iteration of a step that allocates a big new buffer pays one fault per 4 KiB (1 GiB = 262,144 faults, about 0.27 s at the 1 us measured here, per process); a latency-sensitive server sees spikes when pages are first touched. Fixes: pre-touch (MAP_POPULATE, a warm-up step), huge pages (section 8), keep buffers alive across steps instead of reallocating.
ps -o pid,min_flt,maj_flt,rss,cmd -p PID; /usr/bin/time -v python train.py # "Major/Minor page faults"
read() copies bytes from the kernel's cache of the file (the page cache, section 6) into your buffer: two copies of the data in memory, a system call per read, and a buffer you must manage. mmap(addr, length, prot, flags, fd, offset) instead adds a VMA whose pages are the page-cache pages of the file (mmap(2)). The first touch of each page faults (section 4) and maps the cached page directly; nothing is copied. Two choices make four kinds of mapping:
read(): a second copy. read() copies those bytes into the process's own buffer: two copies of the data in memory, a system call per read, and anonymous memory that counts against the process.mmap: the mapping is the cache. Instead, the page-table entries of the mapping point at the page-cache pages themselves. Each first touch faults (section 4) and maps the cached page; nothing is copied.MAP_PRIVATE the first write copies that page into anonymous memory for the writer only (copy-on-write, section 7); the file and the other process are untouched.read_ahead_kb, 128 KiB by default): good for a sequential pass, wasted on random rows. madvise(MADV_RANDOM) reads one page per fault. Measured below.| MAP_PRIVATE | MAP_SHARED | |
|---|---|---|
| File | Reads see the file; a write copies that page into private anonymous memory (copy-on-write), the file never changes. Used by: the loader for code and data of every .so; np.memmap(mode="c"). | Reads and writes go to the page cache, other mappers see them at once, writeback puts them in the file (msync to force it). Used by: np.memmap(mode="r+"), databases, the job's dataset (read-only, r--s in its maps). |
| Anonymous | Private zero-filled memory. After fork, copy-on-write. Used by: malloc of large blocks, thread stacks, every allocator's arenas, all your tensors. | Memory shared with children after fork (backed by an invisible shmem file). Used by: multiprocessing shared values. Named shared memory is a file in /dev/shm, which is how DataLoader workers pass batches. |
fault everything in now (section 4).
do not count this toward the commit limit (section 10).
place exactly here, silently replacing whatever was mapped; use MAP_FIXED_NOREPLACE.
back with pre-reserved huge pages (section 8).
20,000 random rows of 1,028 bytes (the job's row format) from a 256 MiB file, warm (in the page cache) and cold (evicted with posix_fadvise(POSIX_FADV_DONTNEED), which any process may do for clean pages). The rows are 19.6 MiB of useful data; "read from storage" is read_bytes in /proc/self/io.
Warm, all three cost 1 to 2 microseconds a row (Python dominates). Cold, a fault on a mapping reads around the faulting page (read_ahead_kb, 128 KiB by default): on this small file that pulled in the whole file (13x the useful bytes) and then served the rest from memory, the fastest here; on a dataset much larger than RAM the same bet reads 32 pages to use one and fills the cache with neighbours you will not touch. madvise(MADV_RANDOM) turns read-around off: one page per fault, 3.4x amplification, one device round trip per row. So a shuffled index over a huge file wants MADV_RANDOM or explicit pread; a sequential pass or a small hot file wants the default (or MADV_SEQUENTIAL, MADV_WILLNEED).
Cold, a plain mapping read the whole file to serve 20,000 rows; MADV_RANDOM read a quarter of it but paid a device trip per row
A 256 MiB state dict (eight 32 MiB float32 tensors) saved with torch.save and with safetensors, loaded cold four ways. "Return" is the time until the call returns; then every tensor is summed once.
torch.load reads every byte into fresh anonymous memory before returning. torch.load(mmap=True), in its own words, maps the file "rather than loading all the storages into memory" (docstring of torch 2.14.1), and safetensors (whose format is "fast (zero-copy)", safetensors docs) returns tensors whose storage is the mapping: the call returns in milliseconds and the bytes arrive as page faults when first used (measured: torch.load returned after 194 ms holding 243 MiB, torch.load(mmap=True) after 4.5 ms holding none). The pages are clean page cache: the kernel can drop and re-read them, and every process mapping the file shares one copy. The first forward pass pays the faults the load call skipped. safe_open plus get_tensor reads only the tensors asked for, which is how one rank of a sharded model loads only its shard.
Eight inference processes on one host each torch.load(path, mmap=True) the same 14 GB checkpoint and run. Free memory drops by about how much for the weights?
free). Each process's RSS still shows up to 14 GB, which is why RSS sums mislead (section 13). The catch: if a process converts or moves the tensors (to another dtype, or to a GPU and then keeps a CPU copy), that copy is private anonymous memory, eight times over.grep -A3 train.bin /proc/PID/smaps # Rss, Pss and Shared_Clean of one mapping
Linux keeps file data that was read or written in otherwise unused RAM, the page cache, because RAM that holds nothing is wasted. free shows it as "buff/cache"; "available" estimates what could be handed to programs if they asked, mostly by dropping clean cache. Writing, flushing and fsync of cached data belong to the sibling Storage and file systems; here the question is how memory is taken back.
Reclaim. Each memory zone has three watermarks of free pages. Below low, the kernel thread kswapd wakes and reclaims in the background until high; below min, an allocating process must reclaim by itself before it gets memory (direct reclaim), which shows up as stalls in that process. In 5.10, low = min + max(min / 4, managed × watermark_scale_factor / 10,000) and high = min + 2 × that (mm/page_alloc.c lines 7874 to 7880). Here min_free_kbytes is KiB and the scale factor is 10, so low and high sit about 11 MiB and 22 MiB above min. Raising watermark_scale_factor starts background reclaim earlier, a common fix for allocation stalls on big-memory hosts.
Which pages go. Linux 5.10 keeps two lists per type (anonymous and file), active and inactive, an approximation of least-recently-used built on the hardware accessed bit (section 2): pages are scanned from the inactive tail, and one referenced since gets another chance. Clean file pages are cheapest to drop (re-read later); dirty ones must be written first; anonymous pages can only go to swap. vm.swappiness (60 here, the default, mm/vmscan.c line 172) weighs anonymous against file reclaim.
Inside a container the same reclaim runs against the cgroup's limit instead of the machine's: reading a 768 MiB file in a 512 MiB container filled the cache up to the limit and recycled it, with thousands of "max" events and no OOM kill (the replay in section 12, scenario "Page cache only").
Linux 6.1 added the multi-generational LRU, which replaces the two lists with several age generations and scans page tables instead of reverse mappings (multigen_lru docs).
free -m; grep -E 'Active|Inactive|Dirty|Writeback' /proc/meminfo; vmstat 1 # si/so swap, bi/bo block I/O
Three watermarks decide who reclaims: kswapd in the background, or the allocating process itself
Free memory on this VM, to scale, summed over zones. min is the measured min_free_kbytes; low and high are derived from the 5.10 formula below.
fork must give the child an exact copy of the parent's memory; copying gigabytes for a DataLoader worker that reads a few batches would take seconds and double memory. So fork copies the page tables, not the pages, and marks every private writable entry read-only in both processes; the first write by either side faults and copies just that page. (The fork API itself is the sibling Processes and the system-call API's.)
do_wp_page sees frame C is shared, wp_page_copy copies it into a new frame C' and the child's entry becomes writable. Measured: ns per page.gc.collect(). Python's collector writes a counter into the header of every tracked object, so every page holding such objects is copied, read or not. Measured on one million lists: 16,817 pages copied; with gc.freeze() in the parent before fork, 30 (below).source: fork's copy_present_pte write-protects each private writable entry in both tables (mm/memory.c lines 878 to 880). A later write faults on a read-only entry of a writable VMA; do_wp_page sees the frame is shared and wp_page_copy (line 2817) copies that one page and gives the writer its own. A page with only one user left is simply made writable again.
What this costs measured. fork + exit + wait grows by about 19 microseconds per resident MiB with 4 KiB pages, and is 30x cheaper at 1 GiB when the memory is in transparent huge pages (one entry per 2 MiB, copy_huge_pmd). Each later write costs a fault and a copy: ns per 4 KiB page. With huge pages the first write does not copy 2 MiB: 5.10 splits the huge entry and falls back to 4 KiB copies (mm/huge_memory.c lines 1315 to 1317); measured, the child's writes took the same 65,538 faults at ns each.
Reading a Python object increments and decrements its reference count, which writes the page it sits on, so a forked worker that only reads a list of a million objects copies the pages holding them (PyTorch's "memory leak" that is not a leak, torch.utils.data docs). The second writer is the cyclic garbage collector: a full collection writes a counter (gc_refs) into the header of every container object it tracks, so a gc.collect() in a worker copies every page of tracked objects even if your code never reads them. Measured: a parent builds one million two-element lists, forks, and the child does one thing:
The fix the Python docs give for exactly this: "call gc.disable() early in the parent process, gc.freeze() right before fork(), and gc.enable() early in child processes" (gc.freeze, Python 3.7+). gc.freeze() moves every tracked object into a permanent generation that collections skip: 30 pages copied instead of 16,817. It does not stop reference-count writes; for data you iterate, store it as NumPy arrays, Arrow tables or one big bytes buffer with offsets (63 pages), not as millions of Python objects.
fork's cost is the table copy: it grows with resident memory, and huge pages cut it 30x
One gc.collect() in the child copied 16,817 pages; gc.freeze() in the parent brought it to 30
Pages the child copied (growth of its Private_Dirty in /proc/self/smaps_rollup), Python 3.11.2, numpy 2.4.6. Reading every list copied about 61 MiB: the pages that hold the list objects themselves (the integers inside were not touched).
An int above 256 is a 28-byte object (sys.getsizeof) stored in a 32-byte block (the most common gap between consecutive ints, 99.8% of pairs), so 128 fit in a 4 KiB page; the list itself is an 8-byte pointer per element, read but not written, so it stays shared; a NumPy int64 array is one object plus 8 bytes per number, and reading the numbers touches no reference count. measured with the root page's src/sim/real/cow.py (Python 3.11.2, numpy 2.4.6, 1,000,000 elements, growth of the child's Private_Dirty): a child that only iterates the list copied 31,520 kB, 7,880 pages, against 7,814 in the model (one page per 128 objects, plus the list's header); len() of the list copied 32 pages; sum() of the NumPy array 67 pages and iterating it 38 (the interpreter's own pages). With 8 DataLoader workers that is 8 private copies; with a dataset of 100 million Python objects the copies alone exceed many machines' memory, and they grow each epoch as workers touch more of it, which is why it looks like a leak. PyTorch's documentation says the same: "the loader worker processes will consume the same amount of CPU memory as the parent process for all Python objects in the parent process which are accessed from the worker processes", and recommends "non-refcounted representations such as Pandas, Numpy or PyArrow objects" (torch.utils.data; issue 13246, opened 2018-10-29).
Your Dataset holds a list of 50 million file paths (Python strings). With 8 fork-started workers, what happens to memory over the first epoch?
paths[i] touches the string's reference count, and any garbage collection in a worker touches every tracked container. Shared pages turn private one 4 KiB page at a time, so each worker's USS climbs as the epoch reads more of the list. Store the paths as one NumPy byte array plus offsets (or Arrow), and gc.freeze() before the DataLoader forks. The root's Debug lab case "Worker memory grows: copy-on-write meets reference counts" measures it per worker.madvise(MADV_DONTFORK) keeps a range out of the child entirely, "useful to prevent copy-on-write semantics from changing the physical location of a page if the parent writes to it after a fork" (DMA buffers, section 9); MADV_WIPEONFORK gives the child zeros instead (madvise(2)). Forking a process that runs threads has its own trap (a lock held by a thread that does not exist in the child): the root's Debug lab case "A worker hangs forever: fork while another thread holds a lock".
grep -E 'Private_Dirty|Shared_Dirty' /proc/WORKER_PID/smaps_rollup
A level-2 entry can point straight at a 2 MiB block instead of a table (with 4 KiB base pages; 1 GiB at level 1). One TLB entry then covers 512 small pages, a walk is one level shorter, and a fault fills 2 MiB at once. Linux offers two ways: transparent huge pages (THP), used automatically for anonymous memory where possible, and hugetlbfs, a pool of huge pages reserved in advance.
VmPTE after touching 1 GiB was KiB either way.Where huge pages do save: fork. The sibling Processes and the system-call API measured os.fork() from a process holding torch and 1 GiB of NumPy at 5.96 ms with NumPy's huge pages (its default) against 22.5 ms with NUMPY_MADVISE_HUGEPAGE=0.
In ML. The root found that this PyTorch wheel's allocator reserves 1 GiB and marks it MADV_HUGEPAGE, so tensor memory gets THP even in madvise mode (Syscall tracer tab of Topic: operating-systems). Big dense tensors and pinned staging buffers are ideal THP users; sparse, long-lived structures on a system in always mode are where bloat appears. Fix for bloat: madvise mode, or MADV_NOHUGEPAGE on the sparse range, or a lower max_ptes_none.
/sys/kernel/mm/transparent_hugepage/enabled is always, madvise (only ranges marked madvise(MADV_HUGEPAGE)) or never; here madvise. defrag says whether a fault may stall to compact memory into a free 2 MiB block; here madvise (stall only for marked ranges). The background thread khugepaged later collapses 512 small pages into a huge one, scanning pages per pass, and with max_ptes_none = it will collapse a range in which 511 of 512 pages were never touched, filling them with zeros (transhuge docs). Watch AnonHugePages in /proc/meminfo or a process's smaps_rollup.
An administrator reserves a pool (vm.nr_hugepages, or per size under /sys/kernel/mm/hugepages/); programs get pages from it with mmap(MAP_HUGETLB) or files in a hugetlbfs mount. Pool pages are never swapped, never split, and never bloat, but are taken from the machine even when unused. This arm64 kernel offers 64 KiB, 2 MiB, 32 MiB and 1 GiB sizes (its cgroup lists hugetlb.64KB, 2MB, 32MB, 1GB; 64 KiB and 32 MiB use arm64's contiguous bit, 16 adjacent entries cached as one); the pool here is empty (HugePages_Total: 0) and filling it needs privileges (hugetlbpage docs).
cat /sys/kernel/mm/transparent_hugepage/{enabled,defrag}; grep -E 'AnonHugePages|HugePages_' /proc/meminfo; grep thp /proc/vmstat
Normally the kernel may move a page (compaction, NUMA migration, THP collapse) or write it to swap, because only the page table knows where it is and the table is updated. A device that copies memory by itself (DMA: a GPU, a network card doing RDMA) holds a physical address and does not consult the page table; if the page moves mid-copy, the device reads someone else's data. Two mechanisms stop that. mlock(addr, len) faults the range in and keeps it resident, never swapped (mlock(2)). Pinning is stronger and kernel-internal: a driver calls pin_user_pages (the FOLL_PIN flavour of get_user_pages, pin_user_pages docs) and the pages may not be moved or freed until it unpins them. Both take memory out of what reclaim can use.
Pinned memory for GPU copies not run here. cudaHostAlloc / cudaMallocHost "Allocates size bytes of host memory that is page-locked and accessible to the device", with the warning that "allocating excessive amounts of pinned memory may degrade system performance, since it reduces the amount of memory available to the system for paging"; cudaHostRegister page-locks an existing range (CUDA runtime API, memory management). Why it matters: "when CUDA sends pageable data from CPU to GPU, it must first create a page-locked copy of that data before making the transfer" (PyTorch pinned memory tutorial), an extra copy through a staging buffer. In PyTorch:
DataLoader(pin_memory=True) runs a thread that copies each batch into pinned memory, so x.to("cuda", non_blocking=True) can be an asynchronous DMA that overlaps compute.t.pin_memory() right before one copy is usually slower than copying directly (it pays the staging copy itself); pin once, reuse.non_blocking=True are asynchronous: modifying the source tensor before the copy finished corrupts the GPU copy.The limit measured. Unprivileged locking is capped by RLIMIT_MEMLOCK, which is 64 KiB in a default Docker container:
That ENOMEM ("Cannot allocate memory") is the error an RDMA library or a pinned-memory allocator reports inside a container whose limit was never raised, and it does not mention the limit. Raise it with docker run --ulimit memlock=-1, LimitMEMLOCK=infinity in a systemd unit, or /etc/security/limits.conf; CAP_IPC_LOCK bypasses it.
Unified (managed) memory: page faults that cross to the GPU. cudaMallocManaged gives one pointer valid on CPU and GPU; its pages live on one side at a time and migrate on a page fault from the other side, the same demand paging as section 4 with a device on the far end. The fault is serviced by NVIDIA's nvidia-uvm kernel module, and on systems with Linux's HMM or hardware coherence (Grace Hopper) the GPU uses the process's own page tables. The sibling Virtualization and the GPU driver stack (section 11, "GPU memory and the driver, from the operating system's side") follows the driver's side; the CUDA programmer's view of pinned, mapped and managed memory, with prefetching, is GPU memory hierarchy (section 8).
ulimit -l; grep VmLck /proc/PID/status; grep -E 'Mlocked|Unevictable' /proc/meminfo
Pageable memory needs a staging copy before the GPU can DMA it; pinned memory is copied directly, and asynchronously
Static before/after diagram of one host-to-GPU copy, from the CUDA and PyTorch documentation quoted below not run here (no GPU in this VM).
Programs reserve far more than they touch (allocator arenas, thread stacks, sparse arrays, a 1 GiB reservation by PyTorch's allocator). Refusing every reservation that exceeds RAM would waste memory; accepting all means some promise may not be kept. The kernel's choice is vm.overcommit_memory source (overcommit-accounting; mm/util.c lines 860 to 876):
| Mode | Rule in 5.10 | Consequence |
|---|---|---|
| 0, heuristic (default) | refuse one request larger than RAM + swap; accept the rest | wild requests fail, everything else succeeds; the OOM killer settles the bill |
| 1, always (this VM) | accept everything | sparse arrays work; the 64 GiB request below succeeded |
| 2, never | total commitments (Committed_AS) may not exceed CommitLimit = RAM × overcommit_ratio% + swap; "In mode 2 the MAP_NORESERVE flag is ignored" | allocations fail with ENOMEM instead of later OOM kills; programs that reserve big address ranges fail to start |
Measured. CommitLimit = 10,189,980 × 50% + 1,048,572 = 6,143,562 KiB against KiB reported (the same, to page rounding; vm_commit_limit, mm/util.c line 805). With MAP_NORESERVE the 64 GiB mapping was not counted at all; malloc(32 GiB) returned a pointer:
Under mode 0 the 64 GiB request would have failed (larger than RAM + swap, 10.7 GiB); under mode 2 so would anything that took commitments past 5.9 GiB. Containers cannot change this setting: it is one value for the whole kernel. When it bites: a cluster that sets mode 2 for safety makes large virtual reservations (CUDA's and allocators' address-space reservations, big np.empty scratch buffers) fail at allocation time; read CommitLimit and Committed_AS before blaming the framework.
cat /proc/sys/vm/overcommit_memory /proc/sys/vm/overcommit_ratio; grep -i commit /proc/meminfo
Allocating is not using: one 64 GiB mapping on a 10 GB machine succeeded and pushed commitments to 11.6 times the commit limit
Measured on this VM (mode 1, ratio 50), KiB from /proc/meminfo.
Anonymous pages have no file to be re-read from, so to reclaim one the kernel writes it to a swap device, replaces the table entry with a not-present entry holding the swap location, and frees the frame. The next access is a major fault: do_swap_page reads it back (handle_pte_fault, mm/memory.c line 4377), reading 2page-cluster = 8 neighbouring swap slots at once (vm.page-cluster = 3 here).
What it costs measured. A process that needs 640 MiB in a container limited to 512 MiB with 512 MiB of swap allowed did not die; it ran with about 260 MiB in swap and every pass over its memory took 4 to 5 seconds, the same pass that takes milliseconds when it fits (the replay in section 12, scenario "Swap allowed"; the root's Debug lab case "Not dead, just slow: the working set spills into swap" has the per-pass numbers). For a training job that is usually worse than being killed: it looks alive, holds its GPUs, and makes no progress.
The signal to watch is pressure, not free memory: with pressure stall information (PSI), /proc/pressure/memory and each cgroup's memory.pressure report the share of time tasks were stalled waiting for memory.
Neither zswap nor zram is built into this kernel. zswap is a compressed cache in front of a swap device: pages being swapped out are compressed into a RAM pool first and written to disk only when the pool is full (zswap docs). zram is a compressed RAM block device used as swap. Both trade CPU for fewer disk reads.
PSI is not enabled in this kernel. Where it is, the files report some and full stall shares over 10, 60 and 300 s (PSI docs). It is the best single "is this job memory-starved" signal; systemd-oomd kills on it (systemd-oomd).
swapon --show; vmstat 1 # si/so columns; grep -E 'pswpin|pswpout' /proc/vmstat
Four real runs at a 512 MiB limit: page cache is given back at the line, anonymous memory and /dev/shm are not
measured: sampled every 25 ms from inside the container; each step replays one stretch of the run between two events, its samples in order; each scenario starts from the same empty container (src/exp/cg_replay.sh, raw src/raw/cg_*.txt). Predict first: "Page cache only" and "Grow until killed" both reach the line; which one dies? Then play "/dev/shm counts" to the end: the shmem area outlives the killed process.
On a shared host each job (container, pod, Slurm step) gets a memory budget. A cgroup v2 memory controller charges every page a process in the group allocates to the group, and reclaims within the group when it reaches its limit. What is charged: "userland memory - page cache and anonymous memory", kernel structures such as dentries and inodes, and TCP socket buffers (cgroup-v2 docs, Memory). Four files carry most of it, in each cgroup's directory (/sys/fs/cgroup/ inside a container): memory.current (bytes charged now, page cache included), memory.max (the hard limit: reclaim, then the OOM killer inside the group; docker --memory, a Kubernetes memory limit), memory.events (counters high, max, oom, oom_kill) and memory.stat (the breakdown: anon, file, shmem, ...).
Four real runs at a 512 MiB limit, one stretch per step
memory.current reaches the 512 MiB line, where the kernel reclaims inside the group (1,196 max events by the end of the write).max events in all, anonymous memory never above 3 MiB.oom_kill 0). Clean page cache is given back at the line.max events, oom 2, oom_kill 1).grow exit code 137 after 480 MiB touched; memory.current falls back to 3 MiB.max events.grow exit code 0: nothing was killed, and nothing was fast./dev/shm. Shared memory, as DataLoader workers use: shmem (counted inside file) rises to 319 MiB, and no process holds it.memory.current is still 324 MiB.The fourth run is the one to remember for data loading: files in /dev/shm are shared memory charged to the cgroup, they survive the process that wrote them, and no process's RSS shows them. DataLoader workers hand batches to the main process through such files; the root's Debug lab case "DataLoader workers run out of /dev/shm" shows the other way it fails (Docker's default 64 MiB /dev/shm), and PyTorch's own README says to raise it "either with --ipc=host or --shm-size" (PyTorch README).
| File | Meaning |
|---|---|
memory.high | "Memory usage throttle limit... Going over the high limit never invokes the OOM killer": the group's tasks are made to reclaim and are put to sleep, up to 2 s per return to user space in 5.10 (MEMCG_MAX_HIGH_DELAY_JIFFIES, mm/memcontrol.c line 2466) (not run on this page: Docker 20.10 has no flag for it and the container cannot write its own cgroup; Containers and isolation ran it from the host, with and without swap) |
memory.low, memory.min | protection: below these the group's memory is reclaimed only reluctantly, or never |
memory.swap.max | swap allowed (docker --memory-swap minus --memory) |
memory.stat | also file includes shmem; file_dirty, sock and more |
memory.oom.group | if 1, "all tasks belonging to the cgroup or to its descendants are killed together or not at all" |
When reclaim fails, oom_badness scores every candidate process (mm/oom_kill.c lines 201 to 238) and the highest score is sent SIGKILL:
/proc/PID/oom_score_adjmemory.max + allowed swap (mem_cgroup_get_max, line 1690)In a 1 GiB container with no swap, process A holds 450 MiB (adj 0) and process B 250 MiB but set its own oom_score_adj to 500. The group hits its limit. Who dies?
CAP_SYS_RESOURCE, which a default container lacks (measured: refused)./proc/PID/oom_score shows (1000 + points × 1000 / totalpages) × 2 / 3, always with the machine's RAM + swap (fs/proc/base.c lines 549 to 566). Four processes in a 1 GiB container, the formula against the kernel's number measured:
Try it with up to three processes in one cgroup.
totalpages = the cgroup's limit plus allowed swap; /proc/PID/oom_score uses the machine's RAM + swap (). Defaults: the measured run above.
Kubernetes sets the adj for you by quality-of-service class: Guaranteed -997, BestEffort 1000, Burstable min(max(2, 1000 - (1000 × memoryRequestBytes) / machineMemoryCapacityBytes), 999) (node-pressure eviction docs). So when the node runs out, a pod with a small request relative to the node is killed first; when a container exceeds its own limit, its cgroup OOM kills inside it regardless. Requests, limits and the rest of cgroups v2 are the sibling Containers and isolation's.
Killed; the exit code is 137 (128 + 9); Kubernetes reports OOMKilled; the kernel log has "Memory cgroup out of memory: Killed process" (dmesg, not readable in an unprivileged container); memory.events counts oom_kill. A Python MemoryError is a different event: an allocation the kernel refused (mode 2, an rlimit, a 32-bit limit), which the root's Debug lab sets side by side.cat /sys/fs/cgroup/memory.{current,max,events}; grep -E '^(anon|file|shmem) ' /sys/fs/cgroup/memory.stat; cat /proc/PID/oom_score{,_adj}
Shared pages (libraries, the page cache of a mapped file, copy-on-write pages after fork) are resident for several processes at once, so adding up per-process numbers counts them several times. Four measures, from /proc/PID/status and /proc/PID/smaps_rollup:
The running job, measured while training (main process and its two fork-started DataLoader workers): the workers' RSS of about 250 MiB each is nearly all Shared_Dirty, the parent's heap and the imported torch, inherited by fork and not yet written. Their USS, what each really adds, is under 9 MiB. Over an epoch, copy-on-write (section 7) turns Shared_Dirty into Private_Dirty, so watch USS per worker, not RSS. Which number a tool reports: ps and top show VSZ and RSS; smem shows PSS and USS; container tools and Kubernetes read the cgroup (memory.current, which also includes page cache), a fifth answer.
for p in $(pgrep -f train.py); do grep -E '^(Rss|Pss|Private)' /proc/$p/smaps_rollup; done; smem -P train.py
Three processes show 815 MiB of RSS but own 104 MiB: the workers' RSS is almost all inherited Shared_Dirty
Each recipe applies a section above; what is new here is the sizing and the alerting.
One or a few large files (a NumPy array, Arrow, a packed binary with an index), np.memmap-ed as the running job does: workers share one page-cache copy and pay only faults. Shuffled access to a dataset larger than RAM wants MADV_RANDOM or pread (section 5); replace mapped files by write and rename (SIGBUS).
Metadata in NumPy or Arrow, gc.freeze() before the iterator forks, USS per worker on the dashboard (sections 7, 13). Spawn or forkserver avoid the sharing at the cost of start-up: the root measured 0.021 s fork against 0.836 s spawn to the first batch.
Give the container --shm-size (or --ipc=host) of at least workers × prefetch factor × batch bytes, and remember it is charged to the memory limit and survives a killed process (section 12).
Log memory.max, memory.events and memory.stat from inside the job; exit code 137 with oom_kill incremented is the cgroup, not your code. Leave headroom for page cache and /dev/shm. If swap is allowed, alert on memory.swap.current: a swapping training job is a stalled one.
A server with two CPU sockets has memory attached to each; a CPU reaches its own node's memory faster than the other's (non-uniform memory access). This lab has one node (numactl --hardware reports none). The policies, from set_mempolicy(2) and mbind(2):
| Policy | Where pages go | Use |
|---|---|---|
| MPOL_DEFAULT (local) | the node of the CPU that first touches the page ("first touch") | the default; why the thread that initialises a buffer decides where it lives |
| MPOL_BIND | only the given nodes | numactl --membind; strict, can OOM while another node is free |
| MPOL_PREFERRED | the given node if possible | soft placement |
| MPOL_INTERLEAVE | round-robin over nodes, page by page | big shared tables read from all sockets |
Automatic NUMA balancing (kernel.numa_balancing) periodically makes pages inaccessible so the next access faults (do_numa_page, the pte_protnone branch in handle_pte_fault, line 4380), notes which node touched it, and migrates pages or tasks to match; each migration is a TLB shootdown (section 3) (sysctl kernel docs, numa_balancing). Cgroups restrict nodes with cpuset.mems.
In ML. Each GPU hangs off one socket's PCIe; nvidia-smi topo -m prints each GPU's CPU and NUMA affinity. A data loader and pinned buffers on the other socket send every batch across the inter-socket link. Launch per-GPU processes with matching numactl --cpunodebind=N --membind=N (or the launcher's affinity options). Hardware detail lives in Topic: hardware (memory tiers in Memory technology); CPU pinning in Scheduling and CPU time.
numactl --hardware; numastat -p PID; cat /proc/PID/numa_maps | head
gc.collect(), 30 after gc.freeze().CAP_SYS_RESOURCE), and if you could, the kernel would kill something else, perhaps the data loader or the node agent. Size the limit instead.mmap: a new VMA, no frames. The first store to each page misses the TLB; the hardware walk finds no valid entry; the CPU raises a fault; the kernel finds the VMA (writable, anonymous), allocates any missing table levels, takes a zeroed frame, writes the entry and resumes the store (do_anonymous_page). 262,144 such faults, about 1 us each here. With THP for the range, 512 faults of 2 MiB each. RSS grows as pages are touched, not at malloc.memory.current minus reclaimable cache for the pod as a whole.memory.events (oom_kill), Kubernetes' OOMKilled reason, or the kernel log. Then find what grew: memory.stat anon vs file vs shmem (DataLoader shared memory counts), worker USS (copy-on-write), pinned memory. Fix the growth or raise the limit; do not rely on swap.Type any virtual address, or pick one of the running job's real addresses (from its /proc/PID/maps, recorded by the root page), and see how the hardware cuts it into page-table indices on five real configurations. Then size the tables and the TLB reach for a given amount of memory. The geometry follows the kernel's own formulas (arm64: (VA_BITS - 4) / (PAGE_SHIFT - 3) levels; x86-64: 4 or 5 levels), quoted in the Reading tab's section 2.
0x900000000000 on x86-64 with 4 levels: it is above 247, so it is not canonical and the CPU faults before walking anything, while on arm64 the same number is an ordinary user address.Links checked on 5 October 2026. Times are estimates for the part worth reading. Suggested order: this page's Reading tab with OSTEP chapters 18 to 23 beside it; the root's OS simulators for the homework; then Gorman's book or the kernel docs for whichever mechanism you are debugging.
Cut any address into page-table indices on five real configurations; size page tables and TLB reach for a footprint.After sections 2 and 3. (The four cgroup replays and the OOM formula, once a tab here, are now in section 12.)
Section 4 is the intuition for this page; the running job is followed through the whole OS.
On the root page: the TLB on an array walk (row against column major) and page replacement policies, checked against OSTEP's homework (translating an address and copy-on-write are this page's sections 2 and 7).
On the root page, the memory cases: "Worker memory grows: copy-on-write meets reference counts", "Killed with exit code 137: the cgroup OOM killer", "Which process the OOM killer picks: oom_score and oom_score_adj", "Not dead, just slow: the working set spills into swap", "DataLoader workers run out of /dev/shm", "The first epoch is slower than the rest: cold and warm page cache".
On the root page: the job's mmap calls, including the 1 GiB MADV_HUGEPAGE reservation and who makes it.
fork, exec and the start methods whose memory this page explains.
Context switches measured (a thread switch was no cheaper than a process switch there), CPU pinning and NUMA scheduling.
What sits between your tensors and the pages on this page: brk and mmap, glibc arenas, mimalloc, PyTorch's CUDA caching allocator.
Threads sharing one address space; futexes live in shared pages.
The page cache from the writing side: writeback, fsync, readahead, checkpoints.
cgroups v2 in full, PSI, Kubernetes requests and limits.
Nested page tables, the IOMMU, GPU memory and unified memory from the OS side.
Caches, atomics and mmap (section 4) from C++. 33 min, plus 21
llama.cpp loading weights with mmap, then a surprise copy. 33 min, plus 36
Reference counting and the garbage collector that section 7 measured, from the language side. 19 min, plus 6
DataLoader, pinned memory and loading checkpoints in context.
Where host memory, pinned buffers and OOM kills meet real clusters.
Caches, TLBs, memory channels and NUMA from the hardware side.
DRAM, HBM and the memory tiers underneath the frames on this page.
Section 8: pinned, mapped and managed memory from the CUDA programmer's side, with prefetching.
ch. 13 Address spaces, ch. 19 TLBs, ch. 20 Smaller tables, ch. 22 Policies, ch. 23 Complete VM systems.The chapter map is in a closed block at the top of the Reading tab.
The classic walk through Linux's VM code. Written for 2.4/2.6, so names changed, but page tables, the page cache, reclaim and swap are explained as nowhere else.
Caches and the TLB from the hardware up, with measurements; section 4 is virtual memory.
How to observe everything on this page in production: tools, methodology, pitfalls.
The kernel's own overview: pages, huge pages, zones, nodes, page cache, reclaim, compaction, OOM.
Every memory.* file, what is charged, and the usage guidelines for memory.high against memory.max.
All THP knobs and counters; how to reserve and use hugetlbfs.
The three modes and what each kind of mapping costs in commit charge.
Every field of status, smaps, meminfo and oom_score_adj.
Why each mechanism was added, by the people reviewing it.
RSS, PSS and shared memory, gently; section 13 measured the same on the job.
Pinned memory and asynchronous copies, measured on GPUs (this page could not run them).
Measurements: Docker Desktop's Linux VM on an Apple M1 laptop, Linux 5.10.104-linuxkit, October 2026. Kernel source excerpts: Linux v5.10, stored with line numbers in this page's src/inputs/kernel_v5.10_extract.txt.