A CPU runs one thread at a time. Linux keeps a run queue per CPU; ordinary threads share it in proportion to their weight (the one with the least weighted CPU time, its virtual runtime, runs next), and a container's CPU limit is a quota per 100 ms period that, once spent, stops every thread of the container until the next period.
Who runs next is a sort by virtual runtime; a CPU limit is a stop, not fewer CPUs
se.vruntime from /proc/PID/sched, 1 s into section 4's run; each block's height is the CPU time it has received measured. The nice-5 loop keeps pace with the nice-0 loop on a third of the CPU because its virtual runtime grows 3.06 times faster; the sleeper is always behind and runs as soon as it wakes.You need: what a process and a thread are (Processes and the system-call API) and that a container is a cgroup (Containers and isolation owns cgroups v2 in full). The intuition and OSTEP's classic policies are in the root, Topic: operating-systems section 3, and its OS simulators tab.
Measured on Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 5 CPUs, one NUMA node, no GPU), October 2026; labels: measured ran here, source from kernel source or documentation, model this page's simulator, not run here taught from sources.
| Mechanism | What it does | Measured here measured | When it bites in ML | Look with |
|---|---|---|---|---|
| Context switch | saves one thread's registers, loads another's | 1.30 to 1.56 us per switch; a cross-CPU wake-up 26 to 51 us in this VM | hundreds of threads on a few cores; tight producer and consumer hand-offs | grep ctxt /proc/PID/status |
| CFS (5.10) | runs the thread with the least weighted CPU time (vruntime) | nice 0 against nice 5: 3.06 times the CPU, weights say 3.057 | preprocessing next to training on the same cores | cat /proc/PID/sched |
| EEVDF (6.6+) | same fair share, plus a virtual deadline per thread | not run here: simulated from source | wake-up latency of loader and serving threads | chrt, sched_setattr |
| Other classes | real-time and deadline run before everything fair | SCHED_BATCH sleeper: 2.0 ms wake-up delay, against 44 us normal | never for training; batch or idle for background work | chrt -p PID |
| Affinity | limits the CPUs a thread may use | PyTorch sizes its pool from affinity, not from the quota | thread counts, GPU feeding, noisy cores | taskset -cp PID |
| cgroup cpu.max | quota per 100 ms period, then the whole group stops | 5 threads on 1 CPU: stalls of 77 to 83 ms every period | step-time spikes in Kubernetes pods with CPU limits | cat cpu.stat |
| cgroup cpu.weight | splits contended CPUs between groups | Docker's --cpu-shares 1024 became weight 39, not 100 | a neighbour container slows your step from 24.2 to 34.2 ms | cat cpu.weight |
| Load average | decaying count of running plus uninterruptible tasks | 3 tasks in D state, using no CPU, still count | "load 40" on a node whose CPUs are idle (stuck I/O) | cat /proc/loadavg, ps -eo stat |
Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 5 CPUs, CONFIG_HZ=1000, CONFIG_PREEMPT=y, one NUMA node, no GPU), image kb-os-lab:1 (the root's lab image), October 2026. Containers were not privileged; CAP_SYS_NICE was added where a run needed it (said there). Other agents' experiments shared the VM: every timing was repeated, the spread is shown, and the VM's load average at the time is recorded with each run. Things that need a newer kernel, privileges, hardware counters, real NUMA or a GPU are taught from primary sources and tagged not run here. Scripts and raw outputs: src/exp/ and src/raw/ in the repository. Kernel line numbers are Linux v5.10 unless marked v6.12.
| OSTEP chapter | Sections here |
|---|---|
| 4 The Process; 6 Mechanism: Limited Direct Execution | 1, 2 (the timer interrupt and the context switch) |
| 7 Scheduling: Introduction; 8 Multi-level Feedback Queue | 3 (and the root's OS simulators tab) |
| 9 Scheduling: Proportional Share (lottery, stride, CFS) | 3, 4, 5, 9 |
| 10 Multiprocessor Scheduling | 2, 7, 8 |
| 26 Concurrency: An Introduction; 27 Thread API | 1, 11 (threads are what gets scheduled; locks and futexes: the sibling Concurrency) |
The unit is the thread. Every thread is its own task (task_struct); a process is a group of tasks sharing one address space, so a PyTorch process with 5 compute threads competes as 5 tasks. The STAT letter of ps gives the state: R running or runnable (waiting only for a CPU), S sleeping until an event, D sleeping uninterruptibly (usually on I/O in the kernel), T stopped, Z exited, not yet reaped. Only R tasks need the scheduler.
Run queues. Each CPU has its own, split by scheduling class and tried highest first: stop (a per-CPU kernel helper), deadline, real-time, fair, idle (the hero, step 1). Almost everything you run is fair. The CPU changes thread at four kinds of moment:
sleep: it leaves the run queue. A voluntary switch.The root's training job (2 DataLoader workers, --threads 2) in a 2-CPU container, every thread read from /proc/PID/task/TID/ 7 s after start; "waiting" is time runnable but not running (schedstat, sched-stats docs), throttled time included.
The DataLoader workers above have run for less than a second. The job has been running for 7. Why?
for batch in loader creates a new iterator, and without persistent_workers=True each iterator forks fresh worker processes and joins the old ones (PyTorch's DataLoader docs). This job's epoch is 128 steps, about half a second here, so the worker pids changed every half second: . Each fork costs the start-up the root's Syscall tracer measured; at real epoch lengths it is negligible, at tiny ones it is not.ps -eLo pid,lwp,cls,ni,pri,psr,stat,pcpu,comm # one line per thread: class, nice, last CPU, state
ps output (depth)Inside each struct task_struct sits a struct sched_entity (weight, virtual runtime, total CPU time), the scheduling policy, the priority and the set of allowed CPUs (include/linux/sched.h, v5.10); the process id is the thread-group id. The per-CPU struct rq holds a deadline queue, a real-time queue and a fair queue (cfs_rq) (kernel/sched/sched.h, v5.10); the class order comes from the linker script, which lists them lowest first (include/asm-generic/vmlinux.lds.h line 128). Live, per thread: top -H -p PID.
ch. 6 Limited Direct Execution (6.3 Saving and Restoring Context); ch. 10 (cache affinity)
To run another thread, the CPU's state for the current one must be put away and the other's brought back, so that each resumes as if it had never stopped. On Linux v5.10 (arm64) that is context_switch() (kernel/sched/core.c line 3728). A switch is a pick, a page-table pointer and about twenty instructions of register swap; thread A is blue, thread B green:
__schedule() asks each class in order (deadline, real-time, fair, idle). The fair class returns the thread with the least virtual runtime: B.switch_mm_irqs_off() (core.c line 3765) points the MMU at B's page tables. Each address space has an ASID tag in the TLB, so nothing is flushed. If B is a thread of the same process this step is skipped.switch_to (line 3779) ends in cpu_switch_to (arch/arm64/kernel/entry.S line 892), about twenty instructions: store A's callee-saved registers x19 to x28, frame pointer, stack pointer and return address in A's task_struct, load B's. Its final ret lands on B's kernel stack.source: v5.10 __schedule, switch_mm_irqs_off, switch_to, cpu_switch_to. On arm64 the ASID means no TLB flush (the sibling Virtual memory page, section 3).
Two processes on one CPU pass a byte through two pipes 200,000 times (lmbench's method, as on the root); then two threads with a futex (the wait-and-wake primitive under every lock); then hand-offs across two CPUs. Five runs each, VM load about 5.
A switch between two processes on one CPU costs us (the root measured 1.33 us), between two threads no less ( us): with ASIDs the address space is nearly free, and the cost is the kernel's sleep-and-wake path. A cache line crosses CPUs in ns, but waking a sleeping thread on another CPU took us when that CPU was idle, 29 times longer than a switch ( us when a low-priority loop kept it awake): an inter-processor interrupt, and an idle virtual CPU woken by the hypervisor. That is this VM, not bare metal (why: section 5 of Virtualization and the GPU driver stack).
The indirect cost is cold caches (the new thread finds them full of someone else's data). Long slices keep it small: refilling 4 MiB at an illustrative 50 GB/s takes about 84 us, under 1% of a 9 ms slice (section 4: 9 ms each for two tasks). Our measurement in this VM was inconclusive (closed block below).
The Debug lab's "Too many threads" case ran 5 PyTorch threads on a 1-CPU quota. Which counter should explode?
When it bites in ML. Not through one switch (a step is milliseconds) but through numbers (hundreds of threads on a few cores, section 11), hand-offs (a DataLoader batch costs at least two wake-ups: fine per batch, ruinous per sample) and busy waiting: GNU OpenMP's idle threads spin before sleeping unless OMP_WAIT_POLICY=passive (libgomp docs), right on a dedicated node, wrong under a CPU quota.
grep ctxt /proc/PID/status; pidstat -w -t -p PID 1 # voluntary (cswch/s) and involuntary (nvcswch/s), per thread
sched_yield, and the cache-pollution measurement (depth)When a thread enters the kernel, the hardware and the entry code have already saved its user registers on that thread's own kernel stack. __switch_to() hands over the floating-point and SIMD registers lazily (arch/arm64/kernel/process.c line 552), then cpu_switch_to runs. Its final ret returns into the other task's kernel stack, which later returns to that task's user code.
// arch/arm64/kernel/entry.S, v5.10, lines 892-905 (abridged) SYM_FUNC_START(cpu_switch_to) mov x10, #THREAD_CPU_CONTEXT add x8, x0, x10 // x0 = previous task mov x9, sp stp x19, x20, [x8], #16 // store callee-saved registers ... stp x29, x9, [x8], #16 // frame pointer and stack pointer str lr, [x8] // where to resume add x8, x1, x10 // x1 = next task ldp x19, x20, [x8], #16 // restore callee-saved registers ...
sched_yield() is only a hint in CFS (it marks the caller to be skipped once, fair.c line 7167): of the calls actually switched.
Cold caches, measured measured. A loop walks a 4 MiB working set in random order (each load depends on the previous one) for 3 s alone on a CPU, then 6 s sharing that CPU with a busy loop that touches no memory, then with one that streams through 64 MiB; nanoseconds per load over the CPU time it actually got, three rounds:
The spread between rounds (alone: ns per load, as the VM's load rose) is as large as the effect, so this VM cannot give a clean number. Two things held in all three rounds: sharing with the streaming loop was the slowest, which is the cache effect; and sharing with the memory-free loop was also slower than alone, which is not a cache effect and which we cannot explain from inside the VM (the host may move virtual CPUs between core types).
perf stat -e context-switches,cpu-migrations -p PID; perf sched record; perf sched latency # not run here: needs perf_event access
ch. 7 Scheduling: Introduction; ch. 8 MLFQ; ch. 9 Proportional Share
OSTEP's first policies (FIFO, shortest job first, round robin, MLFQ) optimise turnaround time (finish minus arrival) or response time (first run minus arrival); the root's OS simulators tab runs them. Linux asks instead for proportional share: does each thread get its share? OSTEP chapter 9 gives three answers, the third Linux's:
OSTEP's stride example: A, B and C hold 100, 50 and 250 tickets, so with a big number of 10,000 their strides are . Starting from zero (ties to A, then B), the first eight picks are : C runs five times in eight, A twice, B once, and over any long window the shares are exactly 250 : 100 : 50. Replace "tickets" by "weight" and "stride" by "1024 / weight per unit of CPU time" and you have the core of CFS; the rest of the kernel code handles what the toy leaves out: sleepers, new threads, many CPUs (section 7) and groups (section 9).
ch. 9.7 The Linux Completely Fair Scheduler; CFS design doc
CFS "basically models an ideal, precise multi-tasking CPU" (the design doc), one that runs all n threads at once at 1/n speed each; it tracks how far each thread is behind that ideal and runs the one furthest behind.
A thread's nice value (-20 to 19, default 0) indexes a fixed table of weights, sched_prio_to_weight (core.c line 8457): nice 0 is 1024, each step about 1.25 times (nice -1 is 1277, nice 1 is 820, nice 5 is 335, nice 19 is 15), so that one level is "a gentle 10% change" in share against a competitor (the comment above the table). Two busy threads on one CPU get wa / (wa + wb) each: nice 0 against nice 5 is 1024 / 1359 = ; the root measured 75.38%, and this page (below).
Three busy threads share one CPU: two at nice 0 and one at nice 5. What does each nice-0 thread get?
Three tasks on one CPU: busy loops at nice 0 and nice 5, and a "sleeper" (runs about 1 ms, sleeps 5 ms); every 50 ms for 2 s we read se.vruntime and se.sum_exec_runtime from /proc/PID/sched. Predict: which stay together, virtual runtime or CPU time? The stage replays the readings: position on the rail is virtual runtime, height is CPU time received since the first reading.
se.vruntime. The rail moves with the queue (its ticks are 5 ms of virtual runtime), so the positions are relative; what matters is who is leftmost.min_vruntime (below), so a long sleep banks no extra credit.The readings as curves: the two busy loops' vruntimes advance together (never more than ms apart, under one slice) while their CPU time diverges times, the weight ratio 1024 / 335 = 3.057. That is the whole invariant of CFS, and the rule that produces it is charged at every tick and whenever the thread stops (update_curr(), fair.c line 842):
Runnable threads sit in a red-black tree ordered by vruntime and the leftmost runs next (the rail of Fig. 3): exactly stride scheduling. The queue keeps min_vruntime, a floor that only moves forward. The sleeper trails by a median ms: on each wake-up it is placed at most half a latency period (9 ms here) behind min_vruntime, so it runs at once but cannot bank more than 9 ms of credit however long it slept.
No fixed time slice: CFS aims to run every runnable thread once per scheduling period and gives each a share of it by weight. On this VM: .
Two nice-0 threads get 9 ms each, eight get 2.25 ms; beyond eight the period stretches (sixteen threads: 36 ms), which stops oversubscribed nodes switching themselves to death and is why their latency grows. A thread is preempted at the tick when its slice is used, or by a waking thread that is behind it by more than the wake-up granularity (1 ms × factor = 3 ms here). A new thread starts one virtual slice after min_vruntime (START_DEBIT), so forking cannot jump the queue.
Change any of this and watch it: the Fair-share stepper tab runs this exact rule set on threads you define, tick by tick, beside EEVDF.
cat /proc/PID/sched # se.vruntime, se.sum_exec_runtime, nr_switches, se.load.weight, policy, prio
renice -n 10 -p PID; nice -n 10 python preprocess.py # lower priority: weight 110 instead of 1024
Charging. update_curr() uses calc_delta_fair() (fair.c line 671); insertion is __enqueue_entity (line 575), the pick pick_next_entity (line 4435), the floor min_vruntime (line 540). A nice-5 thread's vruntime grows 3.06 times faster than its CPU time.
Period and slice. __sched_period and sched_slice (lines 687 and 701); sysctl_sched_latency (line 38), sysctl_sched_min_granularity (line 59); the factor from get_update_sysctl_factor (line 159).
Preemption at the tick (check_preempt_tick, line 4355): switched out when it has run longer than its slice, or, once it has run at least min_granularity, when its vruntime is ahead of the leftmost thread's by more than a slice. At wake-up (place_entity, line 4108; check_preempt_wakeup, line 6916): the woken thread is placed at max(its own vruntime, min_vruntime - latency / 2) and preempts if the running thread is ahead of it by more than the wake-up granularity, scaled by the woken thread's weight:
// kernel/sched/fair.c, v5.10, lines 6869-6880: should the woken thread se preempt curr?
static int wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
{
s64 gran, vdiff = curr->vruntime - se->vruntime;
if (vdiff <= 0)
return -1;
gran = wakeup_gran(se);
if (vdiff > gran)
return 1;
return 0;
}
Groups and autogroup. With cgroups, fairness is applied per level: a container is one entity in its parent's run queue with its own weight (cpu.weight, section 9), and threads compete inside it. Desktop kernels add autogroup: each session (a terminal, say) becomes its own group, so a make -j64 in one terminal cannot starve another; the side effect is that nice only works within a session. This kernel has it on (sched_autogroup_enabled = 1) but it only applies to tasks in the root cgroup (kernel/sched/autogroup.c line 109), never inside a container: two busy loops in different sessions (setsid) still split 75 : 25 by nice:
ch. 9 extended; EEVDF doc; LWN, 2023-03-09; LWN, Completing the EEVDF scheduler, 2024
The problem with CFS. Its latency comes from heuristics (the sleeper credit, the wake-up granularity, "buddies"), and a thread cannot say "short bursts, but soon" except by raising its weight, which also gives it more CPU. EEVDF (Stoica and Abdel-Wahab, 1995, Earliest Eligible Virtual Deadline First), merged in Linux 6.6 to replace CFS's pick, keeps virtual runtime and adds a request size per thread (its slice) and a virtual deadline:
avg_vruntime, fair.c line 653, v6.12): where an ideal fair CPU would have everyone now.pick_eevdf, line 907): a short slice means an early deadline, so latency is requested, not earned.The slice is 0.75 ms (sysctl_sched_base_slice) times the CPU factor: 2.25 ms on this VM's 5 CPUs, 3 ms on machines with 8 or more. Since 6.12 an ordinary thread can ask for its own with sched_setattr() and a sched_runtime, clamped to 0.1 to 100 ms (kernel/sched/syscalls.c line 306, v6.12); a woken thread with a shorter slice may then cut the current one's slice short (PREEMPT_SHORT). CFS's sched_latency_ns, sched_min_granularity_ns and sched_wakeup_granularity_ns are gone.
A trainer and a preproc thread are busy loops at nice 0; a loader wakes every 4 ms, needs 0.4 ms of CPU and sleeps (a thread that receives a batch and queues the next prefetch). One CPU, 1 ms tick, this VM's tunables, under 5.10's CFS rules and 6.12's EEVDF rules as this page's simulator implements them (the Fair-share stepper tab lists each rule's source line and what it leaves out). Predict: under which scheduler does the loader wait longest after waking?
The 40 ms, stretch by stretch
sched_setattr().The rule behind each: CFS's sleeper credit puts the woken loader 9 ms behind min_vruntime, beyond the 3 ms wake-up granularity. EEVDF gives it back only the lag it left with (about zero): eligible, but with a deadline 2.25 ms ahead, so a running loop inside its slice keeps the CPU (run to parity). With a 0.1 ms slice its deadline comes first and PREEMPT_SHORT lets it in: the wait nearly vanishes, its CPU share unchanged. EEVDF switches more often because its slices are shorter; the loader gets less CPU under plain EEVDF only because its waits delay each next cycle (8 cycles in 40 ms instead of 10).
On a 6.12 kernel, a serving process's request thread wakes, runs 200 us and sleeps, next to batch jobs on every core. Which change cuts its wake-up delay without giving it more CPU?
CFS forgot a sleeper's history (max(own, min_vruntime - 9 ms)). EEVDF remembers its lag (PLACE_LAG, place_entity, v6.12 line 5266): a thread that slept while owed service comes back owed it, and one that slept after running ahead comes back behind. A thread that blocks while ineligible is not removed at all until it becomes eligible (DELAY_DEQUEUE, features.h line 49), so sleeping cannot be used to shed negative lag. The base slice is set at line 76 and scaled by the CPU factor in update_sysctl (line 212).
beyond OSTEP; sched(7); sched-rt-group doc; sched-deadline doc
A thread's scheduling policy picks its class. Three policies live in the fair class and differ only in how they are treated there; three are in classes that always run first.
| Policy | Class | Rule | Set with |
|---|---|---|---|
| SCHED_OTHER (normal) | fair | weight from nice; wake-up preemption (sections 4 and 5) | default; nice, renice |
| SCHED_BATCH | fair | treated as CPU-bound: never preempts on wake-up (fair.c line 6960) | chrt -b 0 cmd |
| SCHED_IDLE | fair | weight 3, below nice 19's 15 (sched.h line 1734): runs on what nobody else wants | chrt -i 0 cmd |
| SCHED_FIFO | real-time | priority 1 to 99; runs until it blocks or a higher priority arrives; no slice | chrt -f 50 cmd |
| SCHED_RR | real-time | as FIFO, with a round-robin slice among equal priorities (sched_rr_timeslice_ms = 100 here) | chrt -r 50 cmd |
| SCHED_DEADLINE | deadline | runtime, deadline and period: earliest deadline first, each task limited to its runtime per period | chrt -d --sched-runtime ..., sched_setattr(2) |
Real-time is capped, and refused in containers. A SCHED_FIFO thread in an infinite loop would own its CPU forever, so all real-time threads together get at most sched_rt_runtime_us per sched_rt_period_us: 950,000 us of every 1,000,000 here, leaving 50 ms a second for everything else. This kernel is built with RT group scheduling, which gives each cgroup its own real-time budget, zero by default, and rejects real-time policies in a group with no budget (core.c line 5370), even with CAP_SYS_NICE (the recorded refusal is in the closed block).
SCHED_DEADLINE is the opposite design: declare runtime per period, be admitted only if all reservations fit, run earliest deadline first, be stopped at the reservation. A busy loop got exactly its 2 ms per 10 ms, 20% of a CPU, although its container's quota allowed a whole CPU (cpu.max limits only the fair class).
A thread sleeps 1 ms 3,000 times on one CPU and records how late each wake-up ran, beside busy loops of different classes and niceness. Predict: does a CPU crowded with four busy loops wake the sleeper later or sooner than an idle one?
Alone, the median wake-up was us late: the idle CPU had to wake (in a VM, through the hypervisor). With four busy loops it was lower, us: the CPU never sleeps and the sleeper credit lets the woken thread preempt at once. As SCHED_BATCH it waited us: no wake-up preemption, so it waits for a tick to end the running loop's slice. SCHED_IDLE loops ( us) and nice-19 ones ( us) are nearly invisible. The multi-millisecond maxima are the shared VM's.
nice -n 10 or SCHED_BATCH (preprocessing, evaluation), SCHED_IDLE for background jobs (log compaction, uploads). SCHED_DEADLINE is for periodic control loops (robotics, audio), not ML throughput.chrt -p PID; chrt -m # a thread's policy and priority; the ranges per policy
The task declares how much CPU (runtime) it needs by when (deadline) how often (period); the kernel admits it only if all declared bandwidths fit and stops it the moment it overruns until its next period, even when the VM has idle CPUs. The constant bandwidth server: update_curr_dl (deadline.c line 1239) stops the task when its runtime is spent. Admission is checked over a set of CPUs, so the task must be allowed to run on all of them (core.c line 5387). Both rules are visible from an unprivileged container (with CAP_SYS_NICE):
The negative dl.runtime is the overrun at the moment of reading. The wake-up runs used clock_nanosleep with timer slack set to 1 ns (so the remainder is scheduling delay); CAP_SYS_NICE was added for the negative nice value.
ch. 10 Multiprocessor Scheduling; sched-domains doc
One shared queue would need a lock every CPU fights over and would bounce threads between caches; Linux keeps one queue per CPU and pays with imbalance (three threads on one CPU while another idles). Three mechanisms fix it; a fourth stops them moving threads too eagerly:
select_task_rq_fair() (fair.c line 6697) chooses where a waking thread goes: its previous CPU if still a good idea, the waker's CPU if they share data (wake_affine), or an idle CPU nearby (select_idle_sibling).load_balance() (line 9532) over a hierarchy of scheduling domains (cores sharing a cache, then a package, then NUMA nodes), pulling threads from the busiest group to itself, more often for close levels.sched_migration_cost_ns (500,000 ns here) is "cache hot" and not moved if anything else can be (task_hot, line 7419).Migrations show as se.nr_migrations in /proc/PID/sched, the last CPU as the PSR column of ps. Placement matters: here waking a thread on an idle CPU cost us, against about 1.5 us for a switch on the same CPU.
A thread's CPU affinity is the set of CPUs it may run on (sched_setaffinity(2), taskset), inherited by children; --cpuset-cpus sets it for a whole container. It is a different mechanism from the quota of section 9, and programs see one and not the other. Predict: under --cpus 2, how many threads does PyTorch start?
os.cpu_count(), the affinity mask, nproc and PyTorch all say 5, and PyTorch starts 5 threads per pool, one per CPU.--cpus 2: a quota nobody reads. cpu.max now allows 2 CPUs of time per period, drawn as a ceiling over all five. Affinity is still 0 to 4, so every count still says 5 and PyTorch still starts 5 threads, spread over all five CPUs and sharing 2 CPUs of time (section 9 shows what that does).--cpuset-cpus 0,1: a fence programs see. The container may run only on CPUs 0 and 1. Affinity, nproc and PyTorch say 2 and PyTorch starts 2 threads; os.cpu_count() still counts the machine's 5.--cpus 1 --cpuset-cpus 0-3. Four CPUs allowed, so PyTorch starts 4 threads; the quota allows 1 CPU of time, so those 4 threads share one CPU's worth of quota.Python 3.13's os.process_cpu_count() follows affinity (os docs); nothing standard reads the quota. A cpuset is the one limit a program sizes itself to.
A Kubernetes pod with limits.cpu: 4 lands on a 64-core node (no CPU manager policy). What does torch.get_num_threads() return inside it?
cpu.max), which no thread-count default reads; the pod's affinity is the whole node unless the kubelet's static CPU manager pins it to exclusive cores (pods with integer CPU requests equal to limits, Kubernetes CPU management policies). So PyTorch starts a pool sized for the node and runs it on 4 CPUs' worth of quota: section 9 shows what that does.taskset -cp PID; taskset -c 0-7 python train.py # read or set affinity
grep -E 'nr_migrations|nr_switches' /proc/PID/sched; cat /sys/fs/cgroup/cpuset.cpus.effective
The boot parameters isolcpus= (remove CPUs from load balancing) and nohz_full= (stop the scheduler tick on CPUs that run a single task) keep the kernel out of pinned threads' way (kernel-parameters, NO_HZ doc); interrupts are steered separately through /proc/irq/N/smp_affinity. They need boot-time control of the host, so this VM cannot show them; they matter for trading and robotics far more than for training throughput. The wake-up helpers are wake_affine (fair.c line 5854) and select_idle_sibling (line 6213).
NUMA memory policy doc; numactl(8)
A two-socket GPU server is two computers sharing one address space: each socket has its own memory controller, PCIe lanes and GPUs, and reaching the other's crosses an interconnect: NUMA (non-uniform memory access). A process feeding GPU 3 should run on the CPUs of GPU 3's node and allocate its pinned host buffers there, or every host-to-device copy crosses sockets. This VM has one node, so this is from sources; memory policies (mbind, interleave) are Virtual memory's, section 14.
numactl --hardware (nodes, their CPUs and memory, distances); nvidia-smi topo -m (which CPUs and NUMA node each GPU and NIC is closest to); lscpu.numactl --cpunodebind=1 --membind=1 python train.py runs on node 1's CPUs and allocates from its memory.torchrun --numa-binding=node (torch/distributed/run.py line 754), which binds each local rank and its threads to the CPUs of the NUMA node holding its GPU; the modes node, socket, exclusive and core-complex are documented in torch/numa/binding.py line 44, whose docstring says binding "typically results in 1-10% overall performance improvements".kernel.numa_balancing: the kernel periodically unmaps pages to sample which node touches them, then moves tasks or pages to match (task_numa_fault, fair.c line 2626). Helpful for unpinned services, sometimes a source of latency spikes; explicit binding makes it moot.
cgroup v2: CPU interface files; CFS bandwidth control doc
A container's cgroup has two independent CPU knobs. cpu.weight is relative: it matters only when CPUs are contended, and splits them between groups the way nice splits them between threads. cpu.max is absolute: a cap even on an idle machine. (cpuset.cpus is affinity, section 7; the rest of cgroups is Containers and isolation's.)
cpu.weight runs from 1 to 10,000, default 100, and becomes the group's CFS weight as weight × 1024 / 100: a default group weighs one nice-0 thread in its parent's queue. The trap is the translation. Docker's --cpu-shares and Kubernetes' requests.cpu speak cgroup v1 "shares" (default 1024), which the runtime converts to a weight: runc 1.1's linear map, 1 + (shares - 2) × 9,999 / 262,142, sends the default 1024 shares to weight 39, not 100; the newer quadratic map in the opencontainers/cgroups library sends 1024 to 100 (sources in the closed block).
Measured with this VM's Docker 20.10 (the old map): busy containers with --cpu-shares 1024 and 512 on one CPU got weights and split it (predicted 39 / 59 = 66.1%). Then a one-thread training step (eight 512 × 512 matmuls) at weight 100 beside a neighbour:
A neighbour started with Docker's "default" --cpu-shares 1024 got weight 39 and still took of the shared CPU, slowing the step from to ms (the weights predict × 139 / 100 = ms); a neighbour at --cpu-shares 128 (weight 5) cost ms (predicted ). Weight protects you only in proportion to everyone else's, and only when you are actually competing for the same CPUs.
cpu.max holds "$MAX $PERIOD": $MAX microseconds of CPU per $PERIOD (default 100,000 us); --cpus 2 writes 200000 100000. CFS bandwidth control enforces it in three steps:
sched_cfs_bandwidth_slice_us = 5,000 us and charges the time its threads run.throttle_cfs_rq() removes the whole group from that CPU's run queue: every thread of the container stops, runnable or not, until the next refill.So the quota is spent at the speed of however many threads are running. Five threads on a 1-CPU quota burn 100 ms of CPU in 20 ms of wall time and then all stop for 80 ms. Predict what one thread and five threads look like on the same quota, then step through the measured runs (inside a container with a CPU limit, N threads spin for 1 s, and each records every gap of more than 300 us in its own progress, the time it was not running):
Threads beyond the quota do not wait politely: they all stop together
--cpu-period 10000 --cpu-quota 10000: each runs in short bursts and stops for the rest of every period; the stall is capped near 10 - 10 / 5 = 8 ms (measured up to 20.3 ms on the shared VM), but 103 of 103 periods were throttled.One lane per thread, blocks where it ran, gaps where it was stopped; glass panes where the quota was refilled (the end of each stretch with every thread stopped). measured: src/exp/schedlab.c mode throttle, raw/throttle.txt.
With as many threads as the quota allows, nothing stops. With five, every thread stops for ms in each 100 ms period (predicted: 100 - 100 / 5 = 80 ms). The CPU used is the same in every run: throttling costs not work but latency, which a training step, a request or a GPU waiting for its next batch feels. A 10 ms period caps the stall near 8 ms (measured up to ms) for ten times as many throttling events. throttled_usec sums over every CPU the group was on, so it can exceed the run's wall time.
Fixes. Size pools and workers to the quota (section 11); in Kubernetes, set requests without limits so pods share idle CPU by weight, use a shorter period (the kubelet's CPUCFSQuotaPeriod feature gate, helpers_linux.go line 73), or give the pod exclusive cores with the static CPU manager policy (section 7).
cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/cpu.weight /sys/fs/cgroup/cpu.stat # inside the container
docker run --cpus 2 --cpu-shares 512 --cpuset-cpus 0-3 ...; systemd-run -p CPUQuota=200% -p CPUWeight=50 ...
Weights. The kernel conversion is in core.c line 8286. Kubernetes turns a request into shares as milli-CPUs × 1024 / 1000 (pkg/kubelet/cm/helpers_linux.go line 88, v1.34.0). The linear map is runc's libcontainer/cgroups/utils.go line 423, runc v1.1.2; the quadratic one is in opencontainers/cgroups from v0.0.3 (utils.go line 425), and runc v1.3.6 and v1.4.0 depend on versions that have it, per their go.mod.
The refill is __refill_cfs_bandwidth_runtime (fair.c line 4601) called from do_sched_cfs_period_timer (line 4942); the 5 ms borrowing slice is set at line 129 (the same value read here); charging is __account_cfs_rq_runtime (line 4653); the throttle itself throttle_cfs_rq() (line 4741). Periods may be 1 ms to 1 s and quotas at least 1 ms (core.c lines 7891 to 7919). Kernels from 5.14 add cpu.max.burst, which lets unused quota carry over to absorb short bursts (sched-bwc doc) not on this kernel.
ch. 6 (the timer is also the accountant); proc_stat(5); proc_loadavg(5)
Three ledgers: per task (utime, stime: what time reports), per cgroup (cpu.stat), per CPU (/proc/stat). User time is your code; system time is the kernel working for you (system calls, page faults). With threads, user + system can exceed wall time measured:
Four threads finished the same matmuls in 1.46 s instead of 2.39 s, with about the same CPU time (user 2.52 s against 2.40 s): parallelism shortens wall time, not CPU time. "CPU 182%" means 1.82 CPUs busy on average, not 4.
Utilisation says how busy a CPU was, not how long threads queued for it; the second field of /proc/PID/task/TID/schedstat does (sched-stats doc). For the 4-thread matmul, 4 CPUs allowed, on the shared VM, the main thread and the three pool threads each ran 2.7 to 3.3 s and waited 0.11 to 0.31 s for a CPU (raw output in the closed block). In section 1, the training job's main thread had waited for a CPU in 7 s. Kernels with pressure stall information expose the same idea per cgroup as cpu.pressure ("some" = share of time at least one task waited, PSI doc); this kernel is built without it not run here.
The three numbers of /proc/loadavg are decaying averages (about 1, 5 and 15 minutes) of the tasks runnable or in uninterruptible sleep (D state), over all CPUs: a Linux change from classic Unix, so that load reflects demand for disks too (Brendan Gregg, Linux Load Averages: Solving the Mystery, 2017). Here three processes sit in D state for 60 s using no CPU (a vfork parent waits for its child). Predict how far the 1-minute load rises:
The 1-minute load rose by about one over the minute although the container used almost no CPU. The dashed line is the kernel's formula fed with the three tasks alone; the measured line sits above it because other agents' work counts too (load is machine-wide, not per container). Every 5 seconds, in fixed point with 11 fractional bits:
Three tasks held for a full minute would add 1.9 (3 × (1 - 1/e)), not 3: the average needs about 5 minutes to settle.
ps -eo pid,stat,wchan:30,comm | awk '$2 ~ /D/' before blaming the scheduler. To ask "are my threads short of CPU", read run-queue waiting (schedstat, or cpu.pressure where it exists) and nr_throttled, not load.cat /proc/loadavg; vmstat 1 # r = runnable, b = blocked (D), us sy id wa st
cat /proc/PID/task/*/schedstat # on-CPU ns, waiting ns, timeslices, per thread
Accounting says how much CPU a job used; a profiler says on what. A sampling profiler records running stacks many times a second, so it sees only time on a CPU: waiting for one (run queue, throttling), for I/O or for a lock is invisible to it. Match the question to the tool:
| Question | Tool | What to look for |
|---|---|---|
| Is it user or kernel time? | time, pidstat -u -t 1, cpu.stat | high system time: too many small system calls or page faults (the root's Debug lab case "High system time: millions of tiny reads") |
| Which Python function is on the CPU? | py-spy top --pid PID, py-spy record -o p.svg --pid PID | wide frames at the top of the flame graph; add --native to see inside C and C++ extensions, --subprocesses for DataLoader workers |
| Where is a stuck or slow process waiting? | py-spy dump --pid PID | the main thread in the DataLoader's next() means the GPU waits for data; in a lock or futex, a hang |
| Which native or kernel function is hot? | perf top, perf record -g -p PID then perf report | kernel symbols such as page-fault or copy routines; needs perf_event access, which unprivileged containers lack (this VM: CAP_SYS_ADMIN, since Docker 20.10 does not know CAP_PERFMON) |
| Is it short of CPU rather than slow? | schedstat, nr_throttled, perf sched latency | waiting time and throttled periods: no profiler shows these |
py-spy reads a running process from outside without restarting it (py-spy); in a container it needs CAP_SYS_PTRACE (the root's Debug lab added it). Reading flame graphs: Capacity planning and performance; the PyTorch profiler on a training step: Making training fast.
Per task: utime and stime are fields 14 and 15 of /proc/PID/stat; per cgroup, cpu.stat has usage_usec, user_usec and system_usec. The per-CPU ledger (/proc/stat, in ticks of 10 ms) splits time into user, nice (user time of positively niced tasks), system, idle, iowait (idle while some I/O was outstanding: not busy, just waiting), irq, softirq and steal:
Steal is time a virtual CPU wanted to run but the hypervisor ran something else; the guest can only count it if the hypervisor provides a paravirtual steal clock (kernel/sched/cputime.c line 237). Here it is 0, which does not mean nothing was stolen: this guest is not told. On cloud VMs that report it, a rising steal column is the first thing to check when the same job gets slower on the same instance type. CONFIG_PSI is not set on this kernel.
The load update runs every LOAD_FREQ = 5 s (include/linux/sched/loadavg.h line 20; EXP_1 at line 21); n is folded by calc_load_fold_active (loadavg.c line 79); a task going to sleep counts as uninterruptible when its state is TASK_UNINTERRUPTIBLE without TASK_NOLOAD (core.c line 4467). The D-state run:
A training process gets some CPUs (a quota, a cpuset, a node) and every thread it starts spends from them. The defaults are sized for the whole machine, so they overspend whenever the job gets less, and a GPU waiting for its next batch is the symptom. The data pipeline itself is Storage and loading at scale's; here is what its threads cost.
| Pool | Default size | Set with |
|---|---|---|
| Intra-op (one operator split across threads: matmul, convolution) | the CPUs in the affinity mask (5 here; section 7) | torch.set_num_threads(n), OMP_NUM_THREADS, MKL_NUM_THREADS |
| Inter-op (independent operators in parallel, TorchScript and some backends) | the same | torch.set_num_interop_threads(n) (before any parallel work) |
| DataLoader workers (processes) | 0 | num_workers; each worker sets its own torch threads to 1 (worker.py line 274, v2.14.1) |
| Pin-memory thread (copies batches into page-locked memory) | 1 if pin_memory=True | (dataloader.py line 1198) |
| Per-process launchers | torchrun sets OMP_NUM_THREADS=1 when it starts several processes and the variable is unset (run.py line 980) | set it yourself, per process |
| Libraries inside workers (tokenizers, OpenCV, NumPy's BLAS) | often all CPUs, per worker | their own variables (e.g. TOKENIZERS_PARALLELISM, OPENBLAS_NUM_THREADS) |
One process with 4 workers that each start a 5-thread tokenizer pool, plus PyTorch's pools, runs dozens of busy threads in a 2-CPU container: oversubscription.
One training loop: a Dataset whose samples cost real CPU (four FFT round trips over 8,192 floats, standing in for decode), batches of 64, and a "model step" of six pairs of 64 × 1024 by 1024 × 1024 matmuls on T threads (no GPU here). T in 1, 2, 4, 5 (PyTorch's default here), W in 0, 1, 2, 4 workers, 20 timed steps, under --cpus 1, 2 and 4; the grid three times. Details of the run in the closed block.
Under a 1-CPU quota, which configuration gave the fastest steps?
The default (5 threads, sized from the machine) was the worst or near the worst choice at every quota smaller than the machine. With one CPU, workers did not help at all; with two or four, the best was a couple of compute threads plus a couple of workers, about one busy thread per CPU of quota. The best point depends on your decode against your model step; the rule does not.
Each cell: the median over the three repeats of that run's median step time (or of the chosen metric); click a cell for every repeat. "Periods throttled" is nr_throttled / nr_periods from cpu.stat over the 20 timed steps; "waiting for data" is the share of step time the main loop spent in next(iterator). Raw output: src/raw/grid.txt.
cpu.max[0] / cpu.max[1] (or the cpuset size, or the Kubernetes limit) divided by the training processes on the node; compute threads + busy workers ≈ budget.persistent_workers=True (section 1).nr_throttled, involuntary switches in the thousands, the main thread waiting on a run queue, or py-spy dump showing it in next(it) (the root's Debug lab case "The training loop waits for data: DataLoader-bound").torchrun --numa-binding=node (section 8).nice -n 10 or SCHED_BATCH, SCHED_IDLE for uploads (section 6); never real-time.# size PyTorch's pools from the container's quota (or affinity), not from os.cpu_count() import os, math, torch def cpu_budget(): n = len(os.sched_getaffinity(0)) # cpuset / taskset try: q, p = open("/sys/fs/cgroup/cpu.max").read().split() if q != "max": n = min(n, max(1, math.floor(int(q) / int(p)))) except OSError: pass # cgroup v1 or no cgroup return n b = cpu_budget() // int(os.environ.get("LOCAL_WORLD_SIZE", "1")) torch.set_num_threads(max(1, b // 2)); num_workers = max(0, b - b // 2)
The split between threads and workers in the last line is a starting point, not a rule; measure your own step the way the grid above did.
Script src/exp/grid.py: 3 warm-up steps then 20 timed steps per cell, torch.set_num_threads(T), the step on the CPU because there is no GPU, in containers started with --cpus 1, 2 and 4. The VM's 1-minute load at the start of each repeat: (other agents' experiments ran at the same time).
"The container has 2 CPUs, so it has 2 CPUs."It has 200 ms of CPU time per 100 ms, spendable on all 5 (or 128) CPUs at once. Programs see the whole machine and size themselves to it; the quota then stops them in bursts (section 9).
"More DataLoader workers is always faster."Only while there are idle CPUs to run them. On a 1-CPU quota, adding workers made every configuration slower here (section 11). Workers count against the same budget as compute threads.
"nice 19 means it gets 5% of the CPU."Nice is a weight, so the share depends on who else is runnable: alone, a nice-19 thread gets the whole CPU; against one nice-0 thread it gets 15 / 1039 = 1.4%.
"High load average means the CPUs are saturated."On Linux it also counts tasks in uninterruptible sleep, usually I/O; three D-state tasks using no CPU raised it here (section 10). Look at run-queue waiting and throttling instead.
"Pinning threads makes things faster."Pinning removes the load balancer's freedom; two busy threads pinned to one core run at half speed while others idle. Pin whole processes to NUMA nodes or exclusive core sets, not individual threads, unless you have measured.
"Give the important process real-time priority."A SCHED_FIFO thread that spins can starve kernel threads on its CPU (until the 95% real-time cap) and every ordinary thread; inside containers it is refused anyway (section 6). Use weight (nice, cpu.weight) or exclusive cores.
"cpu.stat's throttled_usec is how long my job was stopped."It is summed over the CPUs the group was throttled on, so it can exceed wall time (3.8 s of throttling in a 1.1 s run with 5 threads, section 9). Compare nr_throttled with nr_periods instead.
"EEVDF settings are the CFS sysctls."On 6.6+ kernels sched_latency_ns, sched_min_granularity_ns and sched_wakeup_granularity_ns no longer exist; latency is requested per thread with a slice (section 5). Tuning guides written for CFS do not apply.
What exactly happens in a context switch, and what does it cost?The current thread enters the kernel (its user registers are saved on its kernel stack), the scheduler picks the next task, the address space is switched if the process differs (on arm64 with ASIDs, without a TLB flush), and the callee-saved registers and stack pointer are swapped (cpu_switch_to). Direct cost here: about 1.5 us including the sleep and wake path; the bigger costs are indirect (cold caches and TLB) and, across CPUs, the wake-up interrupt (26 to 51 us in this VM).
How does CFS decide who runs next, and how does nice change it?Each thread accumulates virtual runtime = CPU time × 1024 / weight; CFS runs the thread with the smallest, kept in a red-black tree. Nice maps to a weight (1024 at nice 0, × 1.25 per step), so a heavier thread's vruntime grows more slowly and it is picked more often: shares are proportional to weights. Slices are the period (6 ms × factor, stretched beyond 8 threads) times the weight fraction.
Why did Linux move from CFS to EEVDF, and what changes for a latency-sensitive thread?CFS achieved latency through heuristics (sleeper credit, wake-up granularity, buddies). EEVDF keeps vruntime but adds lag, eligibility and a virtual deadline (vruntime + slice / weight), picking the eligible thread with the earliest deadline. A thread can request a shorter slice (6.12, sched_setattr), getting earlier deadlines and lower wake-up delay without more CPU share.
A pod with a 4-CPU limit on a 64-core node trains 5 times slower than on a laptop. Diagnose.PyTorch, OpenMP and every library size their pools from the visible CPUs (64), not from the quota. 64 threads burn the 400 ms quota in about 6 ms of each 100 ms period and the whole pod is throttled for the rest. Evidence: nr_throttled close to nr_periods, huge involuntary switch counts. Fix: set thread and worker counts from the quota, remove the limit (keep a request), or use exclusive cores.
What is the difference between cpu.weight and cpu.max?Weight is relative and work-conserving: it only divides contended CPU time, and an idle machine gives any group everything. Max is a hard cap enforced per period even when CPUs are idle, implemented by throttling the whole group when its runtime pool is empty. Kubernetes requests become weights, limits become cpu.max.
What does load average measure on Linux?An exponentially damped average (1, 5, 15 minutes, updated every 5 s) of runnable plus uninterruptible tasks over the whole machine. It is not utilisation, not per CPU and not per container; D-state tasks raise it without using CPU.
Why can't you run SCHED_FIFO in a Docker container, and what is SCHED_DEADLINE for?With RT group scheduling each cgroup has its own real-time budget, zero by default, and setting a real-time policy in a group with no budget fails with EPERM. SCHED_DEADLINE reserves runtime per period with admission control and EDF ordering; the kernel throttles it at its reservation, which makes it suitable for periodic control loops.
Define up to five threads on one CPU and run them through Linux 5.10's CFS and Linux 6.12's EEVDF, step by step. model
The rules are the ones in Reading sections 4 and 5, each taken from the kernel source (listed below). The same code drives the animation in section 5, and it produces the same schedules as the Python reference in src/simref.py on every checked scenario. Try: the presets first; then give the loader nice -5 under CFS and watch its CPU share rise while its wait stays zero; give it a 0.1 ms slice under EEVDF; or add a ninth busy thread and watch CFS's period stretch.
It is a workbench, not an animation to watch: nothing plays until you press Play or step, and every preset or edit reruns both schedulers.
CFS, Linux v5.10 kernel/sched/fair.c: vruntime += Δ × 1024 / weight (update_curr 842, calc_delta_fair 671); weights from sched_prio_to_weight (core.c 8457); pick the smallest vruntime, with the wake-up "next buddy" (pick_next_entity 4435); period and slice (687, 701) with latency 6 ms, min_granularity 0.75 ms and wake-up granularity 1 ms, each × factor (lines 38, 59, 82; factor 1 + log2(min(CPUs, 8)), line 159); tick preemption (check_preempt_tick 4355); wake-up placement at max(own vruntime, min_vruntime - latency / 2) (place_entity 4108) and wake-up preemption (wakeup_preempt_entity 6869, check_preempt_wakeup 6916).
EEVDF, Linux v6.12 kernel/sched/fair.c: V = weighted mean vruntime (avg_vruntime 653); eligible when v ≤ V (726); deadline = v + slice × 1024 / weight, renewed with a reschedule when reached (update_deadline 1007, update_curr 1216); pick the eligible thread with the earliest deadline, keeping the current one until its slice ends (pick_eevdf 907, RUN_TO_PARITY); lag kept across sleep and inflated on placement, half a slice for a new thread (place_entity 5266); a thread that sleeps while ineligible stays queued until picked, then leaves with its lag clipped to zero (DELAY_DEQUEUE, DELAY_ZERO; dequeue_entity 5476, pick_next_entity 5613, requeue_delayed_entity 6919); a woken thread with a shorter slice may cancel the current one's protection (PREEMPT_SHORT, 1166 and 1177); base slice 0.75 ms × factor (line 76); custom slices clamped to 0.1 to 100 ms (syscalls.c 306).
Left out: more than one CPU and load balancing (section 7), group scheduling, the "last buddy" (only with 8 or more runnable threads), the skip buddy of sched_yield, PELT load tracking, hrtick, fixed-point rounding (floats here; nanosecond differences), the cost of the switch itself, and anything outside the fair class. All threads start at t = 0 (busy loops runnable, periodic threads asleep until their first wake-up; under CFS a periodic thread starts as if it had slept for a long time).
Links checked on 5 October 2026. Times are estimates for the part worth reading. Suggested order: this page's Reading tab with OSTEP chapters 6 to 10 beside it; the root's OS simulators for the homework; the Fair-share stepper to test your understanding of CFS and EEVDF; then the kernel documents for whichever knob you are tuning.
Up to five threads on one CPU through Linux 5.10's CFS and 6.12's EEVDF, tick by tick, with each rule's source line.After sections 4 and 5.
Section 3 is the intuition for this page; the running job is followed through the whole OS.
On the root page: FIFO, SJF, STCF, round robin, MLFQ and a CFS-like scheduler on the same jobs, checked against OSTEP's homework simulators, with the measured nice split and context-switch cost.
On the root page, the CPU cases: "Step time quadruples under a CPU limit: cgroup throttling", "Too many threads for the CPUs you have: os.cpu_count() sees the whole machine", "The training loop waits for data: DataLoader-bound", "High system time: millions of tiny reads".
The process and thread structures this page schedules; fork, the DataLoader start methods, signals.
Address spaces and ASIDs (the switch of section 2), NUMA memory policies (section 8).
Per-thread arenas: why thread counts also cost memory.
Threads, futexes and locks: the voluntary switches of this page, from the other side.
The I/O waits behind D state and iowait (section 10).
cgroups v2 in full, delegation, PSI, Kubernetes requests and limits mapped to cgroup files.
Virtual CPUs, steal time and why a cross-CPU wake-up is slow in a VM.
Data curation's page on the data pipeline: formats, shards, streaming and loader prefetch, whose threads section 11 budgets.
Reading flame graphs, py-spy on services, on-CPU against wall-clock profiling (section 10 links it).
Where CPU quotas, NUMA binding and data loading meet real GPU clusters.
DataLoader, torchrun and the thread pools in context.
The GIL and free-threaded Python (sections 1 and 3): what Python threads mean to the scheduler. 19 min, plus 10
tokio and libuv: user-space schedulers running on top of this one.
Cores, caches, sockets and NUMA from the hardware side.
ch. 4 Processes, ch. 6 Limited direct execution, ch. 7 Scheduling, ch. 8 MLFQ, ch. 9 Proportional share, ch. 10 Multiprocessor scheduling; homework simulator cpu-sched-lottery.The chapter map is in the Reading tab's first section.
How to observe everything on this page in production: run-queue latency, saturation, the tools and their pitfalls.
The kernel's own descriptions of both fair schedulers.
Lag, eligibility and deadlines explained, then delayed dequeue and custom slices.
The paper behind EEVDF: lag bounds and the proof.
Tickets, currencies and compensation: proportional share from first principles.
Load-balancing bugs that left cores idle while threads waited: why per-CPU queues are hard.
Quota, period, slices, burst and the throttling statistics of section 9.
cpu.weight, cpu.max, cpu.stat, cpu.pressure and the cpuset files.
Admission control, CBS, and why real-time in a cgroup needs a budget.
The load-balancing hierarchy of section 7; the schedstat fields of section 10.
The history and the code behind counting uninterruptible tasks.
Every policy, priority range and system call, with their limits.
Requests, limits, and exclusive cores for pods.
Measurements: Docker Desktop's Linux VM on an Apple M1 laptop, Linux 5.10.104-linuxkit, October 2026. Kernel source excerpts: Linux v5.10 and v6.12, stored with line numbers in this page's src/inputs/kernel_extract.txt.