Topic: operating-systems

What the operating system does for one training job, as a map: where each part sits between your Python call and the hardware, what each crossing costs, and which child page owns it (processes, scheduling, virtual memory, allocators, concurrency, storage, containers, virtual machines and the GPU driver), with OSTEP's three pieces as the backbone and real runs on a Linux kernel. Data as of October 2026. Reading: 26 min, plus 7 in closed details.

The idea

The core idea. An operating system turns one machine into many private ones: every program gets its own memory, a share of the CPUs and handles on files and devices, all owned by one kernel that the program can reach only through a system call. A training job runs at full speed between those crossings and pays at each one: a system call, a page fault, a context switch, a CPU-quota stall, an fsync, a VM exit.

  1. One job, three layers. The running job of this topic, a tiny CPU-only PyTorch run, once its DataLoader has started: the trainer python train.py (PID 13, 5 threads) and its two worker processes (PIDs 19 and 21, 4 threads each), on the glass plate of user space. Below it the kernel, which alone touches the hardware: the CPUs, RAM, the drive and the GPU. A program runs on the CPU directly, in user mode, and the kernel regains control only at a system call, a fault or an interrupt (OSTEP's limited direct execution). Owner: Processes and the system-call API, whose Fig. 1 draws these processes over their kernel records.
  2. One door: the system call. Whatever the job needs from the kernel goes down through one trapping instruction (svc #0, syscall) and comes back as a number: 281 ns for getppid here, against 1.3 ns for a function call. CPython, libtorch and glibc all end in the same few hundred calls (the Syscall tracer records them). Section 1 prices every crossing; Fig. 2 on Processes follows one os.read() down and back.
  3. CPU time: the scheduler. Thirteen threads, five CPUs. Each CPU has a run queue; the scheduler, woken by the timer interrupt, decides which thread runs next, and a container's CPU limit is a quota that stops the whole group once spent (section 3). Owner: Scheduling and CPU time, Fig. 1.
  4. Memory: the page tables. Every address a thread uses goes through its process's page tables to a 4 KiB frame of RAM. Fork shares frames copy-on-write, so the three processes' RSS adds up to 815 MiB while their PSS is 345 MiB (section 4). Owner: Virtual memory, Fig. 1; fork's sharing is its Fig. 6.
  5. Inside the process: the allocator. Allocators get large regions from the kernel rarely and hand out small pieces often; what your code frees stays with them, which is why RSS rarely drops after del (section 5). Owner: Memory allocators, Fig. 1.
  6. Waiting: two kernel queues. A thread waiting for another thread sleeps on a futex, and enters the kernel only when the lock is contended (8,382 futex calls for 20 million lock and unlock pairs here); a thread waiting for I/O sleeps in epoll (section 6). Owner: Concurrency, Fig. 1.
  7. A checkpoint: the page cache, then the drive. torch.save's write() returns once the bytes are in the page cache (1.4 µs for 4 KiB); only fsync waits for the drive (1,305 µs), and only fsync and rename decide what a crash leaves (section 7). Owner: Storage and file systems, Fig. 1; the safe save is its Fig. 5.
  8. A container: a fence, not a second kernel. The same processes, started with namespaces (what they see) and a cgroup (what they may use; this topic's containers ran with --cpus 2 --memory 3g), on the one shared kernel (section 8). Owner: Containers and isolation, Fig. 1.
  9. The GPU: the hot path skips the kernel. libcuda, in the trainer, writes commands into memory the GPU reads and rings a doorbell; the kernel driver nvidia.ko is entered by ioctl only for setup, allocation and errors. In a cloud VM a hypervisor sits under the kernel, and this lab runs in one too (section 9). Owner: Virtualization and the GPU driver stack, whose Fig. 10 takes one CUDA call down.

A map, not a mechanism: each step lights the part one child page owns. PIDs, threads, RSS, PSS, the CPU count, the system-call cost and the futex count are this page's own runs (src/read/code/out/); the write and fsync costs are the ladder's, from Storage and file systems.

You need nothing beyond Python: this root starts from zero. Caches and the machine under the OS, from the programmer's side, are C++: the machine underneath.

New terms on this page (each used in the comparisons below):
Kernel: the core of the OS, running in the CPU's privileged mode with full control of the hardware; on this page Linux means the kernel.
User mode, kernel mode: the CPU's two privilege modes (EL0 and EL1 on ARM64, rings 3 and 0 on x86-64); user mode cannot touch devices or the memory map.
System call: a numbered request to the kernel through one trapping instruction, the only way in.
Process: a running program: an address space, registers, open file descriptors, credentials and a PID.
Thread: a second flow of execution in the same process: own registers and stack, shared memory and files.
Virtual address, page: every address a program uses is translated by the MMU, page by page (4 KiB here), through per-process page tables.
Page fault: the trap on a page with no valid entry; minor if no I/O is needed, major if the device must be read.
Page cache: file data the kernel keeps in otherwise free memory; read and write go through it.
Context switch: saving one thread's registers and loading another's, plus a new address space if the process changes.
Namespace, cgroup: what a group of processes can see; how much of each resource it may use. A container is both.
fsync: the call that returns only when a file's data and metadata are on the device.
Hypervisor, driver: the program that runs whole operating systems as guests; kernel code that runs one kind of device.

The topic in one screen: what the kernel shares out, and where each part bites a training job

PageWhat the kernel shares outThe mechanism, in one lineWhere it bites a training jobCheck firstMeasured here
Processes and the system-call APIthe right to run a program; handles on files, pipes and socketsa process is a kernel record changed only by system calls: fork copies it, exec replaces the program, wait collects its end, a signal interrupts itDataLoader start methods; SIGTERM that never reaches a shell-wrapped PID 1; zombie workersps -eo pid,ppid,stat,cmd, /proc/PID/statusfirst batch 0.021 s with fork, 0.836 s with spawn
Scheduling and CPU timeCPU timea run queue per CPU; the fair class runs the thread with the least virtual runtime; a cgroup quota stops the whole group once spentlow GPU utilisation from throttled or oversubscribed DataLoader workers; thread pools sized from the host's CPU countcpu.stat (nr_throttled), top -Ha nice-5 loop gets about a third of a CPU against nice 0 (its virtual runtime grows 3.06 times faster)
Virtual memoryphysical memoryevery address translated page by page through a tree of tables and the TLB; pages filled at first touch; fork shares pages copy-on-writeworker memory climbing as reference counts copy shared pages; exit 137 from the cgroup OOM killersmaps_rollup (PSS, Private_Dirty), memory.eventsfork + exit + wait grows about 19 microseconds per resident MiB
Memory allocatorsmemory inside one processallocators buy big regions rarely and hand out small pieces often; freed memory stays with the allocatorRSS that never drops after del; "CUDA out of memory" with gigabytes reservedmemory_allocated against memory_reserved, tracemalloc1,562 KiB of live data held as 110,524 KiB of RSS
Concurrencyshared memory, and waitingan atomic instruction for every shared update; a futex sleeps a thread only when a lock is contended; epoll or io_uring for I/Oa hang after fork with threads; the GIL capping Python threadspy-spy dump, strace -c -fan uncontended lock is one atomic instruction (about 10 ns)
Storage and file systemsdurable bytes on deviceswrites land in the page cache and reach the device later; fsync and rename decide what a crash leavesan empty or torn checkpoint after a crash; a slow first epochstrace the save (fsync, rename, directory fsync); vmstat 1write() 1.4 us against fsync 1,305 us for one 4 KiB record
Containers and isolationa private view and a budget on the one shared kernelnamespaces, cgroups, capabilities and seccomp, and an overlayfs image; no second kernelexit 137; a full /dev/shm; the host's CPU count; untrusted code/sys/fs/cgroup/memory.max, cpu.maxdocker run --rm took about 0.4 s, of which the namespaces were about 4 ms
Virtualization and the GPU driver stackthe whole machine to guests; the GPU to processesguest code runs on the CPU directly and exits only at boundaries; a CUDA launch is stores into mapped memory plus a doorbell"CUDA driver version is insufficient"; sharing one GPU (MIG, MPS, time slicing)nvidia-smi against torch.version.cudaone VM exit costs about 0.92 µs

Every number was measured on this topic's lab machine (below) by the page in the first column. OSTEP's three pieces map onto the rows: virtualization (processes, scheduling, virtual memory, allocators), concurrency, persistence (storage); containers, virtual machines and the GPU driver are beyond the book, and are where an ML job actually runs.

How this topic knows what it says

Every output on these pages was produced for real, on 2026-10-05, inside the Docker image kb-os-lab:1 (Debian 12, Python 3.11.2, PyTorch 2.14.1 CPU build), on Linux 5.10.104 running in Docker Desktop's virtual machine on an Apple M1 laptop with 5 CPUs and about 10 GB of memory: measured here. A virtual machine on a laptop is not a training server, so absolute numbers are this machine's, and ratios are the lesson. What needs a GPU, a newer kernel (6.6 and later) or several memory nodes is taught from man pages, kernel documentation, kernel source at a pinned version, or vendor documentation and labelled not run here. Scripts and raw outputs: src/read/code/.

1. The boundary, and what each crossing costs

A computer has a few CPUs, one physical memory and some devices; dozens of programs want them at once, none trusts the others, and none wants to know how an NVMe drive is programmed. The kernel owns five things on their behalf: CPU time, memory, devices (each run by a driver), files and the network (sockets and TCP: Networking foundations). A program never touches any of them directly. It runs on the CPU at full speed in user mode, and the kernel regains control only at a system call, a fault or a timer interrupt; OSTEP calls this limited direct execution. Every subsystem in the table above is a kind of crossing, and the children measure what each one costs. The ladder beside this text puts sixteen of those costs, all measured on this topic's lab machine, on one log scale.

Python, C++, Rust and Node do not talk to the kernel in their own ways: they all end in the same few hundred system calls, usually through the C library (glibc here). The Syscall tracer records every call of the running job and traces one small file read in five languages.

Go deeper: the system-call boundary, its instruction and its cost are section 2 of Processes and the system-call API (one os.read() down and back is its Fig. 2); the hypervisor's crossing is section 2 of Virtualization and the GPU driver stack (one VM exit, measured, is its Fig. 3).

Each step down the ladder costs about ten to a thousand times the one above: fast code is code that crosses less

A function call (not inlined) Processes
1.3 ns
An uncontended lock: one atomic instruction Concurrency
about 10 ns
clock_gettime through the vDSO: no crossing at all Processes
23.6 ns
The cheapest system call, getppid Processes
281 ns
pread of 4 KiB already in the page cache Virtual memory
607 ns
One VM exit to the hypervisor Virtualization
0.92 µs
A context switch on one CPU Scheduling
1.33 µs
write() of 4 KiB into the page cache Storage
1.4 µs
fork + exit + wait of a small process Processes
80 µs
fdatasync of a 4 KiB overwrite Storage
393 µs
fsync of the same record (a journal commit) Storage
1,305 µs
Creating five namespaces (unshare) Containers
about 4 ms
fork + exit + wait with 512 MiB resident Virtual memory
6.8 ms
First DataLoader batch, workers started with fork this page, section 2
0.021 s
docker run --rm of the lab image Containers
about 0.4 s
First DataLoader batch, workers started with spawn this page, section 2
0.836 s
1 ns1 µs1 ms1 s

Log scale, one machine (the lab VM, 2026-10-05), each number from the page named beside it or from this page's own runs (src/read/code/, src/sim/real/, src/trace/raw/). Grey: stays in user space; blue: enters the kernel or the hypervisor; green: waits for the device. The ratio between a function call and the cheapest system call, in the hundreds, explains buffered I/O, large reads, and the vDSO (kernel code mapped into every process so that asking the time never enters the kernel).

2. Processes and threads: the unit the kernel runs

A process is a program in execution: an address space (its private memory), registers, a table of open file descriptors (small integers naming files, pipes and sockets; 0, 1 and 2 are stdin, stdout and stderr), credentials and a PID. Unix builds every process from four calls: fork() copies the caller, exec() replaces the program inside the process, wait() collects a child's exit status, exit() ends it; a shell running python train.py is fork, exec in the child, wait in the parent. A signal interrupts a process with a small numbered message: SIGTERM asks it to stop (what Kubernetes, Slurm and spot preemption send first), SIGKILL stops it and cannot be caught. The kernel publishes each process's state as text under /proc/<pid>/; ps and top only read it.

The distinction that runs through every child: process or thread. On Linux both are made by clone(), whose flags say what to share. Threads share memory, so they are cheap and need locks (Concurrency); processes are isolated, so a crash or a leak in one does not take the others down and, in CPython, each has its own GIL. A training node is a small tree of both: torchrun, one trainer process per GPU, each trainer's operator threads, and its DataLoader worker processes. How the workers start changes their cost: on the running job, time from iter(DataLoader) to the first batch was 0.021 s with fork against 0.836 s with spawn and 0.763 s with forkserver (medians of 7 runs each with 2 CPUs, 2026-10-05, in src/trace/raw/timing_first_batch.txt); spawn and forkserver pay for a fresh interpreter that re-imports torch. Linux's default is fork through Python 3.13 and forkserver from 3.14; fork is cheap because it copies page tables, not pages (Virtual memory, section 7), and unsafe once the parent has threads or has initialised CUDA.

Depth: the three start methods, and which one you get

Python's multiprocessing, which the PyTorch DataLoader uses for its workers, can start a child in three ways:

MethodWhat happensGoodBad
forkfork() only: the child is a copy of the parent at that momentInstant; the dataset object and everything built so far are already thereUnsafe if the parent has threads (only the calling thread is copied, so a lock another thread held stays locked forever in the child) or has initialised CUDA
spawna fresh Python interpreter (fork then exec, or posix_spawn), which re-imports your main module and receives the pickled datasetClean child, safe with threads and CUDASlow (every worker re-imports torch); needs if __name__ == "__main__":; everything passed must pickle
forkservera single clean "server" process is started once (like spawn); each new worker is forked from itSafe, and faster than spawn after the firstStill pickles arguments; the server costs one interpreter start

Which one you get by default depends on the Python version and the platform: on Linux, fork through Python 3.13 and forkserver from 3.14 ("On POSIX platforms the default start method was changed from fork to forkserver to retain the performance but avoid common multithreaded process incompatibilities", Python 3.14 docs); on macOS, spawn since 3.8, because "macOS system libraries may start threads" (Python 3.11 docs). Since 3.12, os.fork() raises a DeprecationWarning when Python detects that the process has several threads. PyTorch's DataLoader follows the same defaults (torch.utils.data docs, 2.14). The running job uses Python 3.11 on Linux, so fork. Code that relies on fork-only behaviour, such as a global built at import and read by workers, changes behaviour on upgrading to 3.14: name the start method explicitly (multiprocessing_context=).

Go deeper: Processes and the system-call API (fork, exec, wait and PID 1, signals, descriptors, the DataLoader and torchrun, preemption measured; fork is its Fig. 3, a signal its Fig. 5); the Syscall tracer (the start methods' system calls); the Debug lab (zombies, ignored SIGTERM, fork after threads).

3. Scheduling: more runnable threads than CPUs

The running job alone has a main thread, PyTorch's operator threads, two worker processes and some helpers, on 5 CPUs shared with other containers. The scheduler decides which thread runs on which CPU and for how long. It gets control because the kernel programs a timer interrupt at boot; a switch saves one thread's registers into its kernel record and loads another's (a context switch, section 1). OSTEP builds policies up from FIFO (run in arrival order: a long job delays everyone behind it), through SJF and STCF (excellent turnaround, but they need to know job lengths) and round robin (good response, poor turnaround), to the multi-level feedback queue, which learns from behaviour; the OS simulators run all of them on the same jobs. Linux shares CPUs in proportion to weight instead: CFS from 2.6.23, EEVDF since 6.6, with nice from -20 to 19 picking the weight.

The distinction that matters for a training job: a CPU limit is a stop, not fewer CPUs. A container's limit is a cgroup quota per period: with --cpus 2 the file cpu.max reads 200 ms per 100 ms period, spendable on any of the 5 CPUs. Five busy threads spend it in the first 40 ms and are then throttled, not scheduled at all, for the remaining 60 ms; cpu.stat's nr_throttled counts the periods. Python and PyTorch's default thread pool still see 5 CPUs, so size torch.set_num_threads and num_workers from the quota, not from os.cpu_count(). A starving GPU is often this: workers that cannot produce batches as fast as the GPU consumes them. Kubernetes CPU limits become exactly this quota (requests become a relative weight, cpu.weight), which is why some clusters set CPU requests but no CPU limit on training pods.

Go deeper: Scheduling and CPU time (run queues, the switch measured, CFS and EEVDF, affinity and NUMA, cpu.weight and cpu.max, where the CPU goes, a training job's CPU budget; a CFS run queue measured is its Fig. 3, a quota throttling a job its Fig. 5); the OS simulators (FIFO to MLFQ); the Debug lab (throttling, too many threads).

4. Virtual memory: a private, huge memory for every process

Every address a program uses is a virtual address. On every load and store the MMU translates it, page by page (4 KiB here), through a per-process page table: a tree of four levels of 512 entries on ARM64 and x86-64 with 48-bit addresses. The TLB caches recent translations, so a hit costs nothing and a miss costs a walk. The kernel fills the tree lazily: allocating memory or mapping a file only records a promise, and the first touch of each page traps as a page fault. File pages live in the page cache, which mmap maps straight into the process (how np.memmap and safetensors read without copying). After fork, parent and child share every page read-only until one writes (copy-on-write), and Python's reference counts turn reads into writes. When memory runs out the kernel reclaims cache, may swap, and finally the OOM killer sends SIGKILL: inside a container the job vanishes with exit code 137 (128 + 9), no traceback.

The distinction across the children: memory promised, resident, shared and private are four different numbers. VSZ counts what was promised (the job reserves 1 GiB it never touches; this lab's VM overcommits), RSS what is resident, counting shared pages once per process, PSS divides each shared page among its sharers, USS is what only this process holds. For the running job's three processes, 815 MiB of RSS were 345 MiB of PSS, so summing workers' RSS overstates memory; and RSS also counts what allocators hold but no longer use (section 5).

Depth: what a TLB miss costs here, measured with a pointer chase

measured here (src/read/code/tlb.c, median of 5 runs): a pointer chase visits N cache lines in random order. Packed, the N lines sit side by side and fit in few pages; spread, each line sits in its own 4 KiB page, so every access needs a different translation; a third run spreads the lines the same way inside memory advised to use 2 MiB transparent huge pages. Same number of cache lines, so the gap between the runs is mostly translation. Nanoseconds per access, packed, spread and spread on huge pages: 1.01, 3.08 and 1.00 at 256 lines; 1.01, 8.03 and 6.90 at 1,024; 5.70, 33.64 and 8.37 at 4,096; 7.22, 76.09 and 46.67 at 32,768. Huge pages remove most of the miss cost until they too run out of TLB reach. In this VM a miss is also a two-stage walk (the guest's tables, then the hypervisor's), dearer than on bare metal. The OS simulators time the same effect per page and replay OSTEP's TLB homework; Virtual memory, section 3, explains reach.

Go deeper: Virtual memory (the walk as a stepper, the TLB, faults, mmap and the page cache, copy-on-write with measured page counts, huge pages, pinned memory, overcommit, swap, cgroups and the OOM killer, VSZ to USS; the four-level walk is its Fig. 2, copy-on-write after fork its Fig. 6) and its Address translator tab; the OS simulators (the TLB on an array walk, page replacement); the Debug lab (worker memory growth, OOM kills, /dev/shm).

5. Allocators: between your tensors and the kernel's pages

The kernel hands out memory in whole pages and only through system calls; programs ask for millions of small, short-lived pieces. A user-space allocator sits in between: it gets large regions rarely (brk or mmap), cuts them into pieces often, and keeps freed pieces for reuse. One training job runs several: pymalloc for small Python objects, glibc's malloc (with an arena per thread, roughly) for NumPy and C extensions, mimalloc inside PyTorch's Linux arm64 wheels for CPU tensors, and on a GPU PyTorch's caching allocator, which keeps freed GPU blocks instead of returning them to the driver.

The distinction: freed is not returned. Freed memory stays with the allocator until a whole page, arena or segment is empty, so RSS measures what allocators hold, and free memory in the wrong-shaped pieces is fragmentation. The same shape appears one level up on the GPU: "CUDA out of memory" with gigabytes reserved by PyTorch but no single free block large enough, which PyTorch's own message answers with expandable_segments:True. torch.cuda.memory_allocated() counts live tensors, memory_reserved() everything the cache holds.

Go deeper: Memory allocators (free lists and the free-list lab, glibc's bins and thresholds, arenas, fragmentation measured, jemalloc, tcmalloc and mimalloc on the same job, pymalloc and the cycle collector, the CUDA caching allocator as a simulator, diagnosing growth; fragmentation to scale is its Fig. 5, the caching allocator its Fig. 6).

6. Concurrency: threads that share memory

Threads share one address space, which is what makes them useful and what makes them dangerous: the scheduler can stop a thread between any two instructions, and on several CPUs two threads really do run at once. count = count + 1 is three instructions (load, add, store); two threads that each add 1 ten million times on two CPUs ended at 10,747,160 instead of 20,000,000 here. Code on shared data that must not run in two threads at once is a critical section; a lock or an atomic instruction (one indivisible read-modify-write) protects it. Two locks taken in opposite orders can wait for each other forever: a deadlock, cured by one global lock order. CPython's GIL lets one thread run bytecode at a time, which is why the DataLoader uses processes for Python-heavy work.

The distinction: every wait on Linux ends in one of two kernel queues. A thread waiting for another thread sleeps on a futex: the lock word lives in user memory, is taken with an atomic instruction, and only a thread that must wait asks the kernel to put it to sleep (20 million lock and unlock pairs under contention made 8,382 futex calls here). A thread waiting for I/O sleeps in epoll (asyncio, Node's libuv and tokio are loops around it) or collects completions from io_uring's rings. Choosing threads, processes or an event loop is choosing which queue your work waits in.

Go deeper: Concurrency (threads and their cost, races as interleavings stepped instruction by instruction in its section 2, atomics and memory order, locks measured, the futex, condition variables and semaphores, deadlock, the GIL and free-threaded Python, epoll and io_uring, choosing; the race is its Fig. 2, the futex its Fig. 3); the OS simulators (OSTEP's x86.py race, lock and deadlock, step by step); the Debug lab (the hang after fork with threads).

7. Persistence: getting a checkpoint safely onto disk

A storage device sits behind a driver and the block layer; a file system (ext4, XFS) turns its blocks into files, directories and names, keeping an inode per file (size, owner, block locations); the page cache (section 4) sits on top. write() and torch.save return once the bytes are in the page cache; the kernel's flusher threads write dirty pages out later, on their own schedule. A journal keeps the file system's own structures consistent across a crash; it does not protect your file's contents.

The distinction: returned is not durable. What a crash can leave is decided only by fsync (of the file, and of its directory, since fsync does not cover the file's name) and rename, which replaces a name atomically. The safe checkpoint is: write to a temporary file, fsync it, rename it over the old one, fsync the directory; a restart then sees the whole old checkpoint or the whole new one. Measured here, a 4 KiB write() took 1.4 us and an fsync of it 1,305 us; the protocol costs milliseconds against a training step and saves days. On a cluster the same rule applies to the whole set of shards, and object stores have no rename at all.

Depth: two real stories behind the protocol (2009, 2018)

2009, ext4's zero-length files. With delayed allocation, ext4 wrote file data much later than its rename; after crashes, users found "pretty much any file written to by any application (during the previous boot) was 0 bytes". Ted Ts'o's answer: applications had come to depend on ext3's behaviour "even though POSIX never really made any such guarantee"; ext4 then added a heuristic that forces the data out when a file is renamed over another (LWN, 2009-03-11). Do not rely on that heuristic: call fsync.

2018, fsyncgate. PostgreSQL assumed that a successful fsync meant everything written since the last one was safe. After a device error, Linux could report the error once and mark the pages clean, so a retried fsync succeeded with the data lost (LWN, 2018-04-18). Lesson for checkpoints: if fsync fails, treat that checkpoint as lost and write it again from memory; never just retry the fsync.

Go deeper: Storage and file systems (devices and NVMe queues, the VFS, readahead, writeback, the fsync family and its failures, atomic replace with a crash lab, journaling modes, direct I/O, NFS, checkpoint libraries, data loading; one overwrite layer by layer is its Fig. 4, the safe save call by call its Fig. 5); cluster storage is Storage and data movement; the OS simulators crash a write at every step with and without a journal; the Syscall tracer shows both save patterns on the real job.

8. Containers: one kernel, many private views

A container is ordinary processes on the host's kernel, started with four kinds of restriction: namespaces (what it can see: its own PIDs, mounts, network, hostname, IPC, users), cgroups (how much it may use: CPU quota, memory limit, PIDs, I/O), capabilities and seccomp (what it may do: root's powers split up and mostly dropped, every system call checked against an allowlist at kernel entry), and an image (what files it has: read-only layers plus one writable layer, merged by overlayfs as its root).

The distinction: a container is not a VM. There is no second kernel, so a container keeps well-behaved jobs apart but a kernel bug reachable through an allowed system call is a way out; untrusted code goes in gVisor (a user-space kernel) or a microVM such as Firecracker. Read from inside one of this topic's containers (docker run --cpus 2 --memory 3g --pids-limit 256): ps sees two processes with the shell as PID 1, 14 capabilities remain, Seccomp: 2 means a filter is active, the root file system is overlay, and the limits are plain files under /sys/fs/cgroup. Reaching memory.max runs the OOM killer inside the cgroup (exit 137, OOMKilled, counted in memory.events); a GPU image brings the CUDA runtime and PyTorch, the host brings the driver.

Depth: the four restrictions, read from inside one container

measured here (src/read/code/container_view.sh, output in src/read/code/out/container_view.txt), inside docker run --cpus 2 --memory 3g --pids-limit 256: each namespace is a separate kernel object (its own number in /proc/self/ns), except time (4026531834) and user (4026531837), which are the kernel's initial namespaces, 0xEFFFFFFA and 0xEFFFFFFD in include/linux/proc_ns.h lines 45 and 48 (v6.12): shared with the host; the process sees itself at the root of its own cgroup (0::/); the limits are plain files; ps sees only two processes, with the shell as PID 1; 14 capabilities remain of root's full set (no cap_sys_admin, no cap_sys_ptrace, which is why this topic's strace runs needed --cap-add SYS_PTRACE); Seccomp: 2 means a filter is active (Docker's default profile "is an allowlist which specifies the calls that are allowed", Docker docs); and the root file system is overlay.

Go deeper: Containers and isolation (a container built by hand, namespaces, PID 1 and docker stop, images and overlayfs, cgroups v2, memory.max against memory.high, capabilities and user namespaces, seccomp, LSMs, runtimes, sandboxes, GPU containers, Kubernetes requests and limits as cgroup files; one process's namespaces are its Fig. 2, the cgroup tree its Fig. 4); the Debug lab (OOM kill, /dev/shm, CPU throttling, the pids limit).

9. Virtual machines and the GPU driver stack

A hypervisor (KVM, Xen, the cloud providers' own, Apple's Hypervisor.framework under Docker Desktop) runs whole guest operating systems, each believing it owns a machine; the CPU helps with an extra privilege level and a second layer of page tables from guest-physical to host-physical addresses. A cloud GPU instance is almost always such a guest, and this lab is one too: its cross-CPU wake-ups and TLB misses are dearer than on bare metal. The IOMMU translates and checks every DMA address a device issues, which is what lets a whole GPU be passed to one VM; MIG, MPS and time slicing share one GPU among jobs.

The distinction: the hot path never asks permission. Guest code runs directly on the CPU and exits to the hypervisor only at boundaries; a CUDA kernel launch goes from PyTorch through the runtime (libcudart, in your wheel) to the user-mode driver (libcuda, installed with the host's driver), which writes commands into memory the GPU reads and rings a doorbell, while the kernel driver (nvidia.ko) is entered by ioctl only for setup, allocation and errors. The Python call returns long before the GPU finishes, because launches are asynchronous until something waits (.item(), .cpu(), torch.cuda.synchronize()); an strace -f of a CUDA PyTorch program shows a burst of openat("/dev/nvidia..."), mmap and ioctl calls at start-up and very few during steady training. So the two version numbers come from two places: the driver from the host (nvidia-smi), the runtime from the image (torch.version.cuda); "CUDA driver version is insufficient for CUDA runtime version" means a new image on an old host.

Go deeper: Virtualization and the GPU driver stack (VMs against containers, VM exits measured, cloud instances, nested paging, interrupts, virtio, the IOMMU and passthrough, sharing a GPU, one CUDA call down to the driver and GSP in its section 9 and Fig. 10, version compatibility, GPU memory from the OS side; sharing one GPU is its Fig. 8). Writing kernels is Topic: cuda-and-gpu-programming; the silicon, Topic: hardware.

10. When it breaks: from symptom to subsystem

A failure in a training job shows up in one place and lives in another: a vanished job is memory, a starving GPU is often CPU, a corrupt checkpoint is persistence. This table spans every child; the last column is the page that owns the mechanism.

What you seeLikely subsystemCheck firstOwner
Job vanishes, exit code 137, no traceback; pod OOMKilledMemory: cgroup OOM killcat /sys/fs/cgroup/memory.events (oom_kill), dmesg on the hostVirtual memory, Containers
"DataLoader worker (pid N) is killed by signal: Killed"Memory: a worker OOM-killedPSS per worker (smaps_rollup), memory.eventsProcesses, Virtual memory
"bus error", "unable to write to file </torch_...>"Shared memory: /dev/shm too smalldf -h /dev/shm; --shm-size or --ipc=hostContainers
Worker memory grows all epochCopy-on-write through refcountsPrivate_Dirty per worker over timeVirtual memory
GPU utilisation low, steps unevenCPU: too few workers, throttling, oversubscriptioncpu.stat nr_throttled; top -H; py-spy dump of the main processScheduling
Each step slower in a container than on a laptopCPU quota against thread countcpu.max vs torch.get_num_threads()Scheduling
Job hangs at start with workers, fine with num_workers=0Fork after threads or CUDApy-spy dump --pid of a worker (stuck in a lock); try spawnProcesses, Concurrency
"CUDA out of memory" with memory reservedAllocator fragmentationtorch.cuda.memory_summary(); expandable_segmentsMemory allocators
Preempted job lost its progressSignals: SIGTERM not handled or not deliveredIs your script PID 1? Is there a handler and a checkpoint path?Processes
Checkpoint empty or corrupt after a crashPersistence: no fsync or no renamestrace the save: is there fsync, rename, directory fsync?Storage
First epoch slow, later ones fastPage cache cold against warmvmstat 1 (bi), iostat -x 1, major faultsVirtual memory, Storage
High sys time in topToo many system calls (small reads, polling)strace -c -f -p PIDProcesses
Process in state D, cannot be killedStuck in device or network file system I/Ocat /proc/PID/stack (root), cat /proc/PID/wchanProcesses, Storage
"Too many open files"File descriptor limitulimit -n, ls /proc/PID/fd | wc -lProcesses
"CUDA driver version is insufficient for CUDA runtime version"Driver against runtime versionsnvidia-smi against torch.version.cudaVirtualization

Each row with a failure that can happen without a GPU is reproduced, with real output, in the Debug lab tab, which also has a "what would you check first?" drill.

The toolbox, by subsystem

One line per subsystem; each child page gives the files and commands for its own part.

Processesps -eo pid,ppid,stat,rss,cmd, pstree -p, /proc/PID/status, py-spy dump (Python stacks of a live process)
CPUtop -H (threads), vmstat 1 (r, cs, us, sy), pidstat -t 1, perf top, cgroup cpu.stat
Memoryfree -m, /proc/meminfo, smaps_rollup (PSS), memory.current and memory.events
Files and I/Oiostat -x 1, lsof -p PID, df -h, vmstat bi/bo
System callsstrace -f -tt -T, strace -c (counts); the Syscall tracer tab
Everything, cheaplyeBPF tools (bpftrace, the bcc tools like execsnoop, opensnoop, biolatency) and perf, where the kernel and permissions allow; Brendan Gregg's books and site (Further reading)
Ten questions that cross the pages, with short answers (optional rehearsal)
1. What happens, at the OS level, when you run python train.py?
The shell forks; the child execs the Python binary; the kernel maps the executable and the dynamic loader, which maps libpython and libc; the interpreter starts, opens and reads your script, and imports modules (many openat, read and mmap calls). The parent shell waits. (Processes and the system-call API; the Syscall tracer records it.)
2. Process against thread?
A process has its own address space and resources; threads share their process's address space and files and have only their own registers and stack. On Linux both are made by clone() with different sharing flags. Threads are cheaper and share data directly; processes isolate failures and, in CPython, get their own GIL.
3. Why is fork fast even for a 20 GB process, and when is it not?
It copies page tables, not pages, and marks pages copy-on-write. It is still proportional to resident memory (6.8 ms for 512 MiB here, against 80 µs for a small process), and every page either side writes later is copied then. Python refcount updates make reading objects count as writing.
4. What is a page fault, and minor against major?
A trap on access to a page with no valid page-table entry. Minor: the kernel fixes the entry without I/O (zeroed page, page already cached). Major: it must read from the device. Measured here: 65 major faults to touch a cold 8 MiB file (readahead), 129 minor ones once warm (fault-around).
5. Why does the sum of RSS of my DataLoader workers exceed the machine's memory?
RSS counts shared pages once per process. PSS divides each shared page among its sharers and adds up correctly: 815 MiB of RSS against 345 MiB of PSS for the running job's three processes.
6. What does fsync guarantee, and what does it not?
That the file's data and metadata reached the device before it returns (if the device honours flushes). Not that the file's name is durable (fsync the directory), not atomicity of replacement (use rename), and after an error, not that a retry recovers lost pages.
7. How does a mutex avoid a system call?
A futex: the lock word lives in user memory and is taken with an atomic instruction; only a thread that must wait calls futex() to sleep, and the unlocker calls it only if someone is waiting. Here 20 million lock/unlock pairs under contention made 8,382 futex calls.
8. What is a container, exactly?
Processes on the host kernel with namespaces (what they see), cgroups (how much they use), dropped capabilities and a seccomp filter (what they may do), and an image mounted as root through overlayfs. No second kernel: that is a VM.
9. Why might a training job get slower when moved into Kubernetes with a CPU limit of 4?
The limit is a CFS quota (400 ms per 100 ms period). PyTorch and the DataLoader size their threads from the host's CPU count, burn the quota early in each period and are throttled for the rest. Size threads and workers from the limit; watch nr_throttled.
10. Why is "CUDA out of memory" possible when nvidia-smi or the error says gigabytes are free?
The caching allocator holds freed blocks; fragmented segments may have plenty reserved but no contiguous block of the requested size, or the free memory belongs to another process. memory_allocated against memory_reserved tells which; expandable_segments reduces fragmentation.
OSTEP reading map: which chapters go with which section
Section here, and its child pageOSTEP chapters (v1.10)When to read
1 What an OS does2 Introduction; 6 Direct ExecutionFirst: the vocabulary for everything else
2 Processes4 Processes; 5 Process APIDo ch. 5's fork and exec homework
3 Scheduling7 CPU Scheduling; 8 Multi-level Feedback; 9 Lottery Scheduling; 10 Multi-CPU SchedulingCh. 7 and 8 now; 10 when you tune thread counts
4 Virtual memory13 Address Spaces; 15 Address Translation; 18 Introduction to Paging; 19 TLBs; 20 Advanced Page Tables; 21 and 22 Swapping; 23 Complete VM SystemsThe core of the book for ML engineers; 18 to 20 especially
5 Allocators14 Memory API; 17 Free Space ManagementBefore reading about the CUDA caching allocator
6 Concurrency26 Concurrency and Threads; 27 Thread API; 28 Locks; 30 Condition Variables; 31 Semaphores; 32 Concurrency Bugs; 33 Event-based Concurrency28, 32 and 33 first
7 Persistence36 I/O Devices; 39 Files and Directories; 40 File System Implementation; 42 FSCK and Journaling; 44 Flash-based SSDs; 49 NFS39 and 42 before writing any checkpoint code
8 Containers, 9 VMs53 to 57 Security; appendix Virtual MachinesLast; OSTEP has no container chapter

Chapter numbers and titles from the table of contents at pages.cs.wisc.edu/~remzi/OSTEP, version 1.10 (November 2023), checked 2026-10-05.

11. The child pages, in reading order

Times are each page's own header, as of 2026-11-07: core reading, plus optional closed details. Every page uses the same lab machine and the same running job, so numbers carry from one to the next.

Processes and the system-call API: fork, exec, signals, file descriptors Child page, about 50 min, plus 19 in closed details.The process as a kernel record and every call that changes it: the system-call boundary and its cost, fork and threads, exec, wait and PID 1, signals, descriptors and pipes, the DataLoader and torchrun, preemption measured.
Scheduling and CPU time: context switches, CFS and EEVDF, affinity, cgroup limits Child page, about 39 min, plus 15 in closed details.Run queues and the context switch measured, proportional share, CFS and EEVDF, the other classes, load balancing, affinity and NUMA, cpu.weight and cpu.max throttling, CPU accounting and profilers, a training job's CPU budget.
Virtual memory: paging, the TLB, mmap, copy-on-write, huge pages, the OOM killer Child page, about 39 min, plus 13 in closed details.The address space and the page-table walk, the TLB, faults, mmap and the page cache, copy-on-write measured, huge pages, pinned memory, overcommit, swap, cgroup limits and the OOM killer, VSZ to USS.
Memory allocators: malloc, arenas, fragmentation, and PyTorch's caching allocator Child page, about 41 min, plus 10 in closed details.Free lists, glibc's malloc and arenas, fragmentation measured, jemalloc, tcmalloc and mimalloc on the same job, pymalloc and the cycle collector, the CUDA caching allocator, diagnosing growth.
Concurrency: threads, locks, futexes, deadlock, and event-driven I/O Child page, about 38 min, plus 15 in closed details.Threads and their cost, races as interleavings, atomics and memory order, locks measured, the futex, condition variables, deadlock, the GIL and free-threaded Python, epoll and io_uring, choosing threads, processes or async.
Storage and file systems: the page cache, fsync, journaling, and checkpoints Child page, about 43 min, plus 19 in closed details.Devices and NVMe queues, the VFS, readahead, writeback, the fsync family and its failures, atomic replace and a crash lab, journaling, direct I/O, NFS, checkpoint writes, data loading.
Containers and isolation: namespaces, cgroups v2, seccomp, sandboxes Child page, about 51 min, plus 14 in closed details.A container built by hand, namespaces, PID 1, images and overlayfs, cgroups v2 and memory limits, capabilities, seccomp, LSMs, runtimes, gVisor and microVMs, GPU containers, Kubernetes requests and limits as cgroup files.
Virtualization and the GPU driver stack: hypervisors, IOMMU, MIG, one CUDA call down Child page, about 47 min, plus 26 in closed details.VMs against containers, VM exits measured, cloud instances, nested paging, virtio, the IOMMU and passthrough, sharing a GPU (MIG, MPS, time slicing), one CUDA call down to the driver and GSP, version compatibility.

This page's other tabs span the children: the OS simulators (OSTEP's homework simulators for scheduling, the TLB and page replacement, races and locks, crash consistency, checked against OSTEP), the Syscall tracer (every system call of the running job, by phase and process) and the Debug lab (training-job failures reproduced in containers, each with its fix).