Virtual memory: paging, the TLB, mmap, copy-on-write, huge pages, the OOM killer

How every address a training job uses becomes real memory, what each step costs, and what happens when memory runs out, measured on a Linux 5.10 kernel. A child page of Topic: operating-systems. Data as of October 2026. Reading: 39 min, plus 13 in closed details.

The idea

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.

  1. One process, one address space. The running job's main process as the root recorded it in /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.
  2. Every access is translated. Every load and store goes through the TLB and, on a miss, the page tables (sections 2 and 3) before it reaches a physical frame.
  3. Frames come from three places. Written anonymous memory (heap, tensors) gets its own zeroed frames (section 4); file mappings are the page cache's frames, shared by every process that maps the file (sections 5 and 6); anonymous memory that was only read maps the one shared zero page. The untouched reservation maps nothing.
  4. Below memory: files and swap. Clean page-cache frames can be dropped and read again from their file; anonymous frames have no file, so reclaim can only write them to swap (sections 6 and 11).
  5. The container's budget. The dashed box is what the container's 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):

address space: a process's private range of virtual addresses
VMA: one mapping, a line of /proc/PID/maps
page / frame: the 4 KiB unit of virtual / physical memory
page table: the per-process tree from virtual pages to frames
TLB: the CPU's cache of translations; reach = entries x page size
ASID / PCID: a tag that lets TLB entries of many processes coexist
TLB shootdown: invalidating a translation on all CPUs
page fault, minor / major: the trap on a page with no valid entry; served from memory / after waiting for a device
page cache: file data kept in RAM
watermarks, direct reclaim: when the kernel frees memory, and who pays
THP / hugetlbfs: automatic / reserved huge pages
DMA, pinning: device copies, and pages that may not move
swap: disk space for anonymous pages
VSZ, RSS, PSS, USS: four answers to "how much memory" (section 13)
In one screen: what each mechanism costs here, when it bites, how to look at it
MechanismWhat it doesCost measured hereWhen it bites in MLLook with
Page tablesmap 4 KiB virtual pages to physical frames, 4 levels2,052 KiB of tables per GiB touchedrarely; huge resident sets on many processesgrep VmPTE /proc/PID/status
TLBcaches translationsmiss: 7.6 ns vs hit 1.1 ns (root)random gathers over big embeddings, hash tablesperf stat -e dTLB-load-misses
Page faultfills a table entry on first touchabout 1 us per 4 KiB pagefirst epoch, first touch of a huge buffer/usr/bin/time -v, ps -o min_flt,maj_flt
mmapmaps a file's cached pages into memory, no copyrandom rows: 13x read amplificationdatasets, safetensors, torch.load(mmap=True)cat /proc/PID/maps
Copy-on-writefork shares pages until writtenfork of 1 GiB: 19.8 ms; one copy about 3.3 usDataLoader workers growing to the parent's sizesmaps_rollup Private_Dirty
Huge pagesone 2 MiB page instead of 512512x fewer faults; up to 298x more memoryallocators, pinned buffers, bloat in sparse arraysgrep AnonHugePages /proc/meminfo
Pinned memorypages the kernel may not move or swapdefault limit here 64 KiBpin_memory=True, RDMA, containersulimit -l, VmLck
memory cgroup, OOMcaps a container, kills when it cannot reclaimkilled at the limit, exit 137"Killed" with no traceback; /dev/shm countedmemory.events, memory.stat
How this page was measured, and the OSTEP chapter map

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 map for this page (free online)
OSTEP chapterSections here
13 The Abstraction: Address Spaces; 14 Memory API1
15 Address Translation; 16 Segmentation; 17 Free-Space Management1, 2 (allocators: the sibling page Memory allocators)
18 Paging: Introduction; 20 Paging: Smaller Tables2, 8
19 Paging: Faster Translations (TLBs)3, 8
21 Beyond Physical Memory: Mechanisms; 22 Policies4, 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)

1. The address space: what one process sees

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).

A limit you can hit
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

In the kernel: mm_struct and vm_area_struct

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.

Selected lines of the real /proc/PID/maps

One line per VMA: start-end, permissions (r, w, x, and p private or s shared), file offset, device, inode, path.

2. Page tables: the tree that translates every address

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.

  1. The address. 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.
  2. TLB miss. The CPU looks for virtual page 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.
  3. Level 0. Memory read 1: entry 511 of the level 0 table holds the frame of a level 1 table. Each level 0 entry covers 512 GiB of addresses.
  4. Level 1. Memory read 2: entry 510 of the level 1 table points at a level 2 table. A level 1 entry covers 1 GiB; a 1 GiB huge page would end the walk here.
  5. Level 2. Memory read 3: entry 15 points at a level 3 table. A level 2 entry covers 2 MiB; a 2 MiB huge page (section 8) ends the walk here, one level shorter.
  6. Level 3. Memory read 4: entry 466 holds the frame number of the data page and its permission bits. Physical address = frame x 4096 + offset.
  7. TLB fill. The translation is cached in the TLB: every later access to this 4 KiB page skips all four reads. The root measured 1.1 ns per access while the pages fit in the TLB and 7.6 ns once they do not.

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).

What the tables cost measured
One last-level table (4 KiB) maps 512 pages = 2 MiB, so touching 1 GiB needs 512 tables = 2,048 KiB, plus a few upper-level tables. Measured: 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 against arm64: level names, root registers, page sizes, entry bits
x86-64arm64 (this VM)
Level names, root firstPGD, (P4D with 5 levels), PUD, PMD, PTElevel 0, 1, 2, 3 (Linux reuses the x86 names)
Register holding the rootCR3 (one per CPU, reloaded on a process switch)TTBR0_EL1 for user addresses, TTBR1_EL1 for the kernel half
Page sizes4 KiB; 2 MiB and 1 GiB as huge pagesgranule 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 spaces5 levels (LA57): 57-bit, 128 PiB (5-level paging)52-bit with 64 KiB pages (LVA)
Key entry bitsPresent, R/W, U/S, Accessed, Dirty, NXvalid, AP (user, read-only), AF (accessed), nG (not global), DBM (dirty), PXN/UXN (no execute) (lines 135 to 148)

3. The TLB: why translation is usually free, and when it is not

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.

Address-space identifiers: why a process switch does not flush the TLB

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).

TLB shootdowns: the cost of changing a mapping

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:

x86-64: interrupt the other CPUs

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.

arm64: one broadcast instruction

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

4. Page faults: memory is filled in on first touch

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

  1. TLB lookup. The CPU issues the store. The TLB has no translation for this page.
  2. Hardware walk. The MMU walks the tables from TTBR0_EL1. The last entry is none (never touched): the walk stops with a fault.
  3. Exception. The CPU enters the kernel (a data abort). The fault-status code says translation fault (no entry) or permission fault (read-only entry): do_translation_fault or do_page_fault.
  4. Find the VMA. __do_page_fault (line 408) looks the address up among the mappings. VMA: anonymous, private, rw-.
  5. handle_mm_fault. Allocate any missing upper tables, then handle_pte_fault (mm/memory.c line 4330) chooses the handler from the entry and the VMA.
  6. Handler. do_anonymous_page (mm/memory.c line 3469): take a free frame, zero it, map it writable.
  7. Return and retry. The entry now points at a new zeroed 4 KiB frame. The CPU re-executes the store, the walk succeeds and the TLB caches it; the next access to this page costs nothing extra.

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?

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"

5. mmap: files and memory as one thing

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:

  1. The file and the page cache. The first read of a file fills the kernel's page cache: one copy of each 4 KiB page in RAM, kept after the read (section 6).
  2. 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.
  3. 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.
  4. A second process maps the same file. Its entries point at the same frames, so RAM holds one copy however many processes map it; each process's RSS still counts all of it (section 13).
  5. A write to a private mapping copies one page. With 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.
  6. A cold fault reads around. A fault on a page not yet cached reads its neighbours too (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_PRIVATEMAP_SHARED
FileReads 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).
AnonymousPrivate 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.
SIGBUS, not an exception
If the file shrinks under a mapping (another process truncates or rewrites a dataset shard), touching a page past the new end raises SIGBUS and the process dies (mmap(2), SIGBUS). So does an I/O error on a network file system while faulting. Replace shared datasets by writing a new file and renaming it over the old one; mappings of the old file keep working.
Four flags worth knowing
MAP_POPULATE

fault everything in now (section 4).

MAP_NORESERVE

do not count this toward the commit limit (section 10).

MAP_FIXED

place exactly here, silently replacing whatever was mapped; use MAP_FIXED_NOREPLACE.

MAP_HUGETLB

back with pre-reserved huge pages (section 8).

Random rows from a dataset: read() against mmap measured

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

Loading weights: copy or map measured

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?

grep -A3 train.bin /proc/PID/smaps # Rss, Pss and Shared_Clean of one mapping

6. The page cache and reclaim: where "free" memory went

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").

Since 6.1: the multi-generational LRU not run here

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.

7. Copy-on-write: fork copies tables, writes copy pages

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.)

  1. Before fork. The parent maps four private pages, each writable, each in its own frame. Frames in use: 4.
  2. fork copies the tables. The child gets a copy of the parent's page tables, not of the pages: both point at frames A to D, and every entry is now read-only in both processes. Measured cost: about 19 us per resident MiB with 4 KiB pages, the table copy.
  3. The child reads page 1. A read through a read-only entry is allowed: no fault, no copy. In C that is the end of it. In Python, reading an object also writes its reference count, so it becomes a write (next step).
  4. The child writes page 2. The write hits a read-only entry in a writable mapping: a fault. 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.
  5. The parent writes page 2. Frame C now has one user left, the parent, so the fault just makes the parent's entry writable again: no copy.
  6. The child runs 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).
In the kernel: copy_present_pte, do_wp_page, wp_page_copy

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.

Python turns reads into writes, twice

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).

A list of a million ints, counted object by object: the model and the run that the root's OS simulators used to show

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?

Related flags, and the fork-with-threads trap

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

8. Huge pages: one entry for 2 MiB

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.

  1. One 2 MiB stretch, two ways. Left, 4 KiB pages: a level-2 entry points at a level-3 table of 512 entries, each pointing at a 4 KiB frame. Right, a transparent huge page: the level-2 entry points straight at one 2 MiB block.
  2. First touch. Writing every page faults 512 times on the left, once on the right (the fault zeroes all 2 MiB). Measured on a 64 MiB buffer: faults in ms against faults in ms (medians of 3), 512x fewer faults.
  3. TLB entries. Covering the stretch takes 512 TLB entries on the left and one on the right. The root measured this CPU's knee between 2,048 and 4,096 pages, so random access over more than 8 to 16 MiB of small pages misses the TLB, while with 2 MiB pages the same walk stays at 1.1 ns (section 3).
  4. Sparse use: bloat. Touch one byte in each 2 MiB: the left gets one 4 KiB page per stretch, the right the whole 2 MiB. Measured over 256 MiB: KiB against KiB, x more, for sparse structures (hash tables, sparse embedding rows, an arena with holes).
  5. fork copies one entry instead of 512. fork copies the tables (section 7): measured at 256 MiB resident, with 4 KiB pages against with THP; at 1 GiB, 19.8 ms against .
  6. No page-table saving. For each huge page the kernel deposits a spare 4 KiB table so it can split the page later (mm/huge_memory.c line 623), so VmPTE after touching 1 GiB was KiB either way.
The latency cost
The first THP run took ms against ms later, consistent with the kernel having to find or compact free 2 MiB blocks (cause not confirmed here); on a long-running, fragmented host, compaction stalls are the classic THP complaint.

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.

The THP knobs as read on this VM

/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.

hugetlbfs: a reserved pool not run here

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

9. Locked and pinned memory, and GPU memory mapping

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.
  • Calling t.pin_memory() right before one copy is usually slower than copying directly (it pays the staging copy itself); pin once, reuse.
  • The tutorial warns that "allocating a large number of tensors or sizable tensors in pinned memory can monopolize a substantial portion of RAM": pinned pages cannot be reclaimed, so the page cache that feeds your data loader shrinks.
Two more pinned-memory traps: asynchronous corruption, power-of-two rounding
  • Copies from pinned memory with non_blocking=True are asynchronous: modifying the source tensor before the copy finished corrupts the GPU copy.
  • PyTorch's pinned memory comes from its CachingHostAllocator, which rounds each request up to the next power of two by default, so a 600 MB pinned buffer locks 1 GiB of RAM (Memory allocators reads the source).

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).

10. Overcommit: promising more memory than exists

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):

ModeRule in 5.10Consequence
0, heuristic (default)refuse one request larger than RAM + swap; accept the restwild requests fail, everything else succeeds; the OOM killer settles the bill
1, always (this VM)accept everythingsparse arrays work; the 64 GiB request below succeeded
2, nevertotal 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.

11. Swap: anonymous pages written to disk

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.

zswap, zram and PSI in detail not run here

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.

12. Memory cgroups and the OOM killer: why a container dies

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

  1. Write a 768 MiB file. The written pages are page cache charged to the container: file climbs to 493 MiB and memory.current reaches the 512 MiB line, where the kernel reclaims inside the group (1,196 max events by the end of the write).
  2. Read it back once. Reading 768 MiB through a 512 MiB budget: older cache pages are dropped to make room for newer ones; file stays at about 506 MiB, events reach 4,335.
  3. Read it again. The cache is recycled again: 7,406 max events in all, anonymous memory never above 3 MiB.
  4. Done: no OOM. The limit capped the cache; no process was killed (oom_kill 0). Clean page cache is given back at the line.

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).

The other memory files: memory.high, low, min, swap.max, oom.group
FileMeaning
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.minprotection: below these the group's memory is reclaimed only reluctantly, or never
memory.swap.maxswap allowed (docker --memory-swap minus --memory)
memory.statalso file includes shmem; file_dirty, sock and more
memory.oom.groupif 1, "all tasks belonging to the cgroup or to its descendants are killed together or not at all"

Who the OOM killer picks, from the source

When reclaim fails, oom_badness scores every candidate process (mm/oom_kill.c lines 201 to 238) and the highest score is sent SIGKILL:

points = rss + swap + page_tables / 4 KiB + oom_score_adj × ⌊totalpages / 1000⌋
rss
resident pages: anonymous, file-mapped and shmem (in pages)
swap
pages of this process in swap
oom_score_adj
-1000 (never kill) to +1000, per process, in /proc/PID/oom_score_adj
totalpages
machine OOM: RAM + swap. cgroup OOM: memory.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?

The kernel's own number: oom_score reproduced on four processes, and the formula live

/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.

RSS (MiB)
oom_score_adj

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.

What an OOM kill looks like
No Python exception, no traceback: SIGKILL cannot be caught. The shell says 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}

13. VSZ, RSS, PSS, USS: four answers to "how much memory does it use?"

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:

VSZvirtual size: every mapped range, touched or not (section 1). Says nothing about memory.
RSSresident set: every resident page mapped by the process, shared or not. Sums overcount.
PSSproportional set: each page divided by the number of processes mapping it. Sums are right.
USSunique set: Private_Clean + Private_Dirty, what you would get back by killing this one process.

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

14. In ML: the mechanisms put to work

Each recipe applies a section above; what is new here is the sizing and the alerting.

Datasets: map, do not load

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).

DataLoader workers: keep the parent lean

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.

/dev/shm: size it and count it

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).

Limits: log which one kills you

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.

NUMA: when some memory is farther away not run here

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):

PolicyWhere pages goUse
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_BINDonly the given nodesnumactl --membind; strict, can OOM while another node is free
MPOL_PREFERREDthe given node if possiblesoft placement
MPOL_INTERLEAVEround-robin over nodes, page by pagebig 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

Mistakes and rehearsal

Common mistakes, each with what was measured
"RSS says each worker uses 250 MiB, so 8 workers need 2 GB."
RSS counts shared pages in every process. Measured here: three processes, 815 MiB of RSS, 345 MiB of PSS, 104 MiB of USS. Use PSS for totals and USS for "what does one more worker cost".
"The allocation succeeded, so the memory is there."
With overcommit (modes 0 and 1) an allocation is a promise; memory is taken at first touch, and the OOM killer settles any shortfall later, at a random-looking moment.
"free shows almost no free memory: we have a leak."
Look at "available", not "free". The page cache fills idle RAM on purpose and is given back on demand.
"The container's memory is full of page cache, so it is about to be killed."
Clean page cache is reclaimed at the limit (measured: thousands of "max" events, no kill). What kills is anonymous memory and shared memory that cannot be reclaimed without swap.
"Our workers only read the dataset, so copy-on-write cannot copy anything."
In Python, reading an object writes its reference count, and the garbage collector writes every tracked object's header. Measured: 15,732 pages copied by reading a list, 16,817 by one gc.collect(), 30 after gc.freeze().
"Huge pages always help."
They cut faults and TLB misses for dense memory, but bloat sparse memory (298x in the measurement here), can stall allocations on compaction, and do not reduce page-table memory in Linux.
"Set oom_score_adj = -1000 on the trainer so it is never killed."
Inside a default container you cannot lower it (no 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.
"pin_memory() before every .to('cuda') makes copies faster."
Pinning is itself a copy; doing it per transfer is usually slower than letting CUDA stage the copy. Pin buffers you reuse (the DataLoader's pinning thread does this).
Interview rehearsal: six questions with answers
Walk through what happens on the first write to a freshly malloc'd 1 GiB buffer.
glibc serves it with an anonymous private 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.
Why is fork fast even for a process using 50 GB, and when is it not?
Fork copies page tables and marks private pages read-only; pages are copied lazily on write. The table copy is still proportional to resident memory: about 19 us per resident MiB measured here with 4 KiB pages (about 1 s for 50 GB), 30x less with huge pages. After fork, every page either side writes costs a fault and a 4 KiB copy, which is where DataLoader worker memory comes from.
What is a TLB shootdown and why can munmap be expensive in a multi-threaded program?
Removing or changing a mapping requires every CPU that may cache the old translation to drop it. x86 interrupts each such CPU and waits; arm64 broadcasts a TLBI instruction. Measured here on arm64, an mprotect that must flush cost about 1.9 us regardless of how many other threads ran, against 0.65 us when nothing was cached.
Explain RSS, PSS and USS, and which one you would alert on for a fleet of identical workers.
RSS counts all resident mapped pages, PSS divides shared pages among sharers, USS counts private pages only. Alert on USS growth per worker (copy-on-write and leaks show there) and on the cgroup's memory.current minus reclaimable cache for the pod as a whole.
A training pod dies with exit code 137 and no traceback. How do you confirm the cause and fix it?
137 = 128 + SIGKILL. Check 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.
Why does mmap'ing model weights let 8 server processes share memory, and what breaks the sharing?
All map the same page-cache pages of the file (MAP_SHARED or read-only private), so RAM holds one copy. Any write to a private mapping, a dtype conversion, or a copy into a new tensor creates private anonymous pages per process.