Scheduling and CPU time: context switches, CFS and EEVDF, affinity, cgroup limits

Who gets a CPU, for how long, and what it costs: the context switch, Linux's fair schedulers (CFS and EEVDF), the real-time classes, many CPUs and NUMA, container CPU limits, CPU accounting and the thread budget of a training job, measured on a Linux 5.10 kernel. A child page of Topic: operating-systems. Data as of October 2026. Reading: 39 min, plus 15 in closed details.

The idea in one screen

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

  1. One run queue per CPU, tried class by class. Each of this VM's 5 CPUs has its own queue, split by scheduling class: deadline, real-time, fair, idle, tried in that order; the first class with a runnable thread wins. Nearly every thread is in the fair class.
  2. Inside the fair class, the least virtual runtime runs next. Three threads on one CPU placed by their 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.
  3. A CPU limit is a stop, not fewer CPUs. The first 300 ms of section 9's run: five threads spend the 100 ms quota in a burst (100 / 5 = 20 ms of wall time if each has a CPU), then all of them stop (here ms at a stretch) until the period timer refills it measured. The CPU work done is the same as with one thread; the stall is the cost.

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.

Task
what Linux schedules: every thread is one.
Run queue
per CPU, its runnable tasks, split by scheduling class.
Class, policy
deadline, real-time, fair, idle, tried in that order; a thread's policy (SCHED_OTHER, BATCH, IDLE, FIFO, RR, DEADLINE) picks its class.
Nice, weight
nice -20 to 19 indexes a weight (1024 at nice 0, about 1.25 times per step); shares follow weights.
Virtual runtime
CPU time × 1024 / weight; the smallest runs next.
Lag, deadline
EEVDF's additions: service owed, and when the current request is due.
Affinity
the CPUs a thread (or, as a cpuset, a container) may run on.
cpu.weight, cpu.max
a container's share of contended CPUs, and its quota per period.
Throttling
the whole group taken off every CPU when its quota is spent.
Load average
a decaying count of runnable plus uninterruptible tasks, machine-wide.

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.

The page in one table, with what was measured (reference)
MechanismWhat it doesMeasured here measuredWhen it bites in MLLook with
Context switchsaves one thread's registers, loads another's1.30 to 1.56 us per switch; a cross-CPU wake-up 26 to 51 us in this VMhundreds of threads on a few cores; tight producer and consumer hand-offsgrep 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.057preprocessing next to training on the same corescat /proc/PID/sched
EEVDF (6.6+)same fair share, plus a virtual deadline per threadnot run here: simulated from sourcewake-up latency of loader and serving threadschrt, sched_setattr
Other classesreal-time and deadline run before everything fairSCHED_BATCH sleeper: 2.0 ms wake-up delay, against 44 us normalnever for training; batch or idle for background workchrt -p PID
Affinitylimits the CPUs a thread may usePyTorch sizes its pool from affinity, not from the quotathread counts, GPU feeding, noisy corestaskset -cp PID
cgroup cpu.maxquota per 100 ms period, then the whole group stops5 threads on 1 CPU: stalls of 77 to 83 ms every periodstep-time spikes in Kubernetes pods with CPU limitscat cpu.stat
cgroup cpu.weightsplits contended CPUs between groupsDocker's --cpu-shares 1024 became weight 39, not 100a neighbour container slows your step from 24.2 to 34.2 mscat cpu.weight
Load averagedecaying count of running plus uninterruptible tasks3 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
How this page was measured, and the OSTEP chapter map (provenance)

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 map for this page (free online)
OSTEP chapterSections here
4 The Process; 6 Mechanism: Limited Direct Execution1, 2 (the timer interrupt and the context switch)
7 Scheduling: Introduction; 8 Multi-level Feedback Queue3 (and the root's OS simulators tab)
9 Scheduling: Proportional Share (lottery, stride, CFS)3, 4, 5, 9
10 Multiprocessor Scheduling2, 7, 8
26 Concurrency: An Introduction; 27 Thread API1, 11 (threads are what gets scheduled; locks and futexes: the sibling Concurrency)

1. What gets scheduled: threads, states, run queues

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:

1. it blocksA read, a lock, sleep: it leaves the run queue. A voluntary switch.
2. the timer tickEvery 1 ms here (CONFIG_HZ=1000) an interrupt charges the running thread and may take the CPU away. An involuntary switch. Without it a spinning thread would keep the CPU forever (OSTEP's limited direct execution).
3. a wake-upA woken thread that deserves the CPU more than the current one preempts it at once.
4. the switch pointThe decision sets a "need to reschedule" flag; the switch happens at the next safe point, which with CONFIG_PREEMPT=y (this VM) includes most kernel code.

The running job, seen by the scheduler measured

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?

ps -eLo pid,lwp,cls,ni,pri,psr,stat,pcpu,comm # one line per thread: class, nice, last CPU, state

In the source, and the raw 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.

2. The context switch: what is saved and what it costs

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:

  1. Thread A runs in user mode. Its registers are in the CPU and the MMU walks A's page tables. The kernel is not running at all: it gets the CPU back only through a system call, an interrupt (the 1 ms timer tick here) or a fault.
  2. A enters the kernel. A blocks in a read or a lock (voluntary), or the tick finds its slice used up (involuntary). The entry code saves A's user registers on A's own kernel stack. This happens on every system call, switch or not.
  3. Pick the next thread. __schedule() asks each class in order (deadline, real-time, fair, idle). The fair class returns the thread with the least virtual runtime: B.
  4. Switch the address space. 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.
  5. Swap registers and stack. 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.
  6. B resumes. B finishes the kernel path it slept in and returns to user mode with the registers it saved on its own kernel stack. Measured here: 1.30 to 1.56 us for a switch between processes, sleep and wake path included (chart below).

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

What it costs here measured

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

A switch on one CPU is microseconds; waking a thread on another CPU is tens

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

The switch in the source, 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

3. Fair share: from stride scheduling to CFS

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:

Lottery (1994)Each job holds tickets; every slice the scheduler draws a random ticket. Shares are right on average, noisy over short windows (Waldspurger and Weihl, OSDI 1994).
StrideDeterministic: each job has a stride = a big number / its tickets and a pass counter; run the job with the smallest pass, then add its stride to its pass. Exact shares every round.
CFS (2007)Stride scheduling in units of time: the pass is virtual runtime, which grows by the CPU time used divided by the weight. Run the smallest. Section 4.

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

4. CFS: weights, virtual runtime, slices (Linux 2.6.23 to 6.5; the kernel measured here)

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.

Weights: what nice means

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?

Virtual runtime: the one number CFS sorts by measured

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.

  1. Three tasks, one queue. The first reading: the two loops and the sleeper on the rail, ordered by 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.
  2. The leftmost runs, and its virtual runtime grows. The first second of readings: whichever task is leftmost gets the CPU and moves right, until another is further left. The two loops leapfrog and stay within a few milliseconds of each other on the rail.
  3. Equal virtual time, unequal real time. The second second: on the rail the loops are still together, but the nice-0 loop's block has grown times as tall as the nice-5 loop's, the weight ratio 1024 / 335 = 3.057. A heavier task's virtual runtime grows more slowly, so it is leftmost more often.
  4. The sleeper trails, but never far. Close in on the sleeper: it is always behind the loops (median ms) and runs as soon as it wakes; it cannot fall further behind than half a latency period, 9 ms, below 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):

vruntime += Δexec × 1024 / weight
Δexec
nanoseconds of CPU just used
weight
from the nice table; 1024 at nice 0, so a nice-0 thread's vruntime is its CPU time

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.

Equal virtual time, unequal real time

How long a thread runs: period and slice

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

period = latency if n ≤ 8, else n × min_granularity; slicei = period × wi / Σw
latency
6 ms × factor
min_granularity
0.75 ms × factor; 8 = latency / min_granularity
factor
1 + log2(min(CPUs, 8)): 3 on this VM's 5 CPUs, 4 on 8 or more

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

The rules line by line, and autogroup (depth)

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:


EEVDF makes latency a request: the loader waits until it asks for a short slice

5. EEVDF: the same fairness, with deadlines (Linux 6.6 and later) not run here

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:

V, the virtual clockThe weighted mean of the queued vruntimes (avg_vruntime, fair.c line 653, v6.12): where an ideal fair CPU would have everyone now.
lagw × (V - v): service owed (positive) or overdrawn (negative); lags sum to zero.
eligiblelag ≥ 0, that is v ≤ V (line 726): only threads owed service may run.
virtual deadlined = v + slice × 1024 / w, renewed when a slice is used up (line 1007).
the pickThe eligible thread with the earliest deadline (pick_eevdf, line 907): a short slice means an early deadline, so latency is requested, not earned.
run to parityA picked thread keeps the CPU until its slice ends or it turns ineligible (RUN_TO_PARITY, features.h line 20).

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.

One CPU, three threads, two schedulers model

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

  1. The two loops share the CPU. All three threads start at 0; CFS picks the trainer, and the loader is asleep until 1.5 ms.
  2. The loader wakes and preempts at once. At 1.5 ms it wakes 9 ms behind min_vruntime, more than the 3 ms wake-up granularity, so it takes the CPU immediately: zero wait. It runs 0.4 ms, sleeps, and preproc runs.
  3. Every 4 ms, the same. Wake-ups at 5.5, 9.5, 13.5 and 17.5 ms are each served at once; the trainer and preproc take turns between them.
  4. Forty milliseconds, no wait at all. 10 wake-ups served with a mean wait of 0; trainer and preproc 18.0 ms of CPU each, the loader 4.0 ms; 10 involuntary switches.

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

How far to trust this
A one-CPU model checked line by line against the source, not against a 6.6+ kernel (this VM runs 5.10). With an idle CPU the loader would simply be woken there (section 7); the difference matters when every CPU is busy, as on an oversubscribed training node. Custom slices (6.12) were added as "a new feature intended to help latency-sensitive tasks" (LWN, Completing the EEVDF scheduler).

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?

Sleeping and waking under EEVDF: lag kept, delayed dequeue (depth)

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

6. The other classes: real-time, deadline, batch and idle

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.

PolicyClassRuleSet with
SCHED_OTHER (normal)fairweight from nice; wake-up preemption (sections 4 and 5)default; nice, renice
SCHED_BATCHfairtreated as CPU-bound: never preempts on wake-up (fair.c line 6960)chrt -b 0 cmd
SCHED_IDLEfairweight 3, below nice 19's 15 (sched.h line 1734): runs on what nobody else wantschrt -i 0 cmd
SCHED_FIFOreal-timepriority 1 to 99; runs until it blocks or a higher priority arrives; no slicechrt -f 50 cmd
SCHED_RRreal-timeas FIFO, with a round-robin slice among equal priorities (sched_rr_timeslice_ms = 100 here)chrt -r 50 cmd
SCHED_DEADLINEdeadlineruntime, deadline and period: earliest deadline first, each task limited to its runtime per periodchrt -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).

Wake-up delay by policy and neighbour measured

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.

Batch threads wait for the tick; normal ones preempt at once

For a training job
Never real-time: it starves kernel threads and the DataLoader, hits the 950 ms per second cap, and containers forbid it. Work that should yield to training: 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 recorded refusal, and SCHED_DEADLINE in the source (depth)

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.

7. Many CPUs: load balancing and affinity

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:

at wake-upselect_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).
periodicallyEach CPU runs 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.
when idleA CPU about to go idle first tries to pull work (newidle balancing): work stealing, in OSTEP's words.
cache hotA thread that ran within 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.

Affinity: what programs see measured

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?

  1. No limits: the machine. A container with no CPU flags: affinity covers all 5 CPUs, so os.cpu_count(), the affinity mask, nproc and PyTorch all say 5, and PyTorch starts 5 threads per pool, one per CPU.
  2. --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).
  3. --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.
  4. Both: --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?

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

Isolating CPUs for latency-critical threads (depth, not run here)

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

8. NUMA and pinning for GPU feeding not run here

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.

  • See the topology: 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.
  • Bind by hand: numactl --cpunodebind=1 --membind=1 python train.py runs on node 1's CPUs and allocates from its memory.
  • Bind per rank with torchrun: PyTorch 2.14.1 has 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".
Automatic NUMA balancing (depth)

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.

9. cgroup CPU control: cpu.weight, cpu.max and throttling

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: shares of a contended CPU

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.

A "default" neighbour at weight 39 still takes a third of your CPU

cpu.max: the quota, and why it stalls

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:

  1. Each group has a global pool, refilled to the quota at every period by a timer.
  2. Each CPU running the group's threads borrows from the pool in slices of sched_cfs_bandwidth_slice_us = 5,000 us and charges the time its threads run.
  3. When a CPU's slice runs out and the pool is empty, 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

  1. One thread, a 1-CPU quota. It runs throughout: one busy thread cannot use more than the quota, so nothing is throttled (0 of 10 periods); its few short gaps, at most 2.2 ms, are the VM's own interruptions.
  2. Five threads: a burst after each refill. At about 66 ms the timer refills the quota and all five run at once, each for 23 to 32 ms: they spend the quota at five times the speed of one thread.
  3. The quota is spent: the whole group stops. Every thread leaves its CPU together, runnable or not, until the next refill: the red stretch, with no thread running.
  4. And again, every period. Burst, stop, refill: each thread's longest stop was 77 to 83 ms against a predicted 100 - 100 / 5 = 80 ms, and all 11 periods of the run were throttled.
  5. A 10 ms period: shorter stops, ten times as many. Five threads on --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.

Measured on the root page
The root's Debug lab: a matmul step at 138 ms with 2 CPUs and 701 ms with half a CPU (2 threads), throttled in every period ("Step time quadruples under a CPU limit"); 5 threads on 1 CPU at 496 ms per step against 210 ms with 1 thread ("Too many threads for the CPUs you have"). Section 11 measures the whole grid.

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 and bandwidth control in the source, limits and burst (depth)

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.

10. Accounting: where CPU time goes, and what load average means

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.

Waiting for a CPU, per thread measured

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.

Load average: runnable plus uninterruptible, machine-wide measured

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:

load = load × e + n × (1 - e), e = exp(-5 s / 1 min) = 1884 / 2048
n
runnable tasks + tasks in uninterruptible sleep
e
EXP_1 = 1884; EXP_5 = 2014 and EXP_15 = 2037 for the other two

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.

Three tasks using no CPU still raise the load

For a training node
"Load 40" on a node whose CPUs show idle almost always means tasks stuck in D state: a hung NFS, Lustre or FUSE mount, or a dying disk. Check 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

Where the CPU goes: which tool answers which question not run here

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:

QuestionToolWhat to look for
Is it user or kernel time?time, pidstat -u -t 1, cpu.stathigh 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 PIDwide 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 PIDthe 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 reportkernel 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 latencywaiting 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.

The per-CPU ledger, steal time, and the load formula in the source (depth)

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:

11. The CPU budget of a training job: threads, workers, pinning

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.

Who starts threads in a PyTorch job

PoolDefault sizeSet 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 sametorch.set_num_interop_threads(n) (before any parallel work)
DataLoader workers (processes)0num_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 launcherstorchrun 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 workertheir 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.

The budget, measured measured

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?

What the grid says, quota by quota (depth)

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.

The fastest cells keep compute threads plus busy workers near the quota

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.

Recipes

  1. Read the budget, then set every pool: 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.
  2. Keep workers alive with persistent_workers=True (section 1).
  3. A starving GPU's signature: rising 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").
  4. Multi-socket GPU nodes: torchrun --numa-binding=node (section 8).
  5. Noisy neighbours: weights help only under contention and in proportion (section 9); exclusive cores are the only real isolation.
  6. Background work yields: 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.

How the grid was run (provenance)

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

Depth: mistakes and interview rehearsal

Common mistakes, each with what this page measured (8)

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

Interview rehearsal: seven questions with short answers (optional)

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.