Monitoring CPU, page faults, memory and pressure of a data loader

The stage statistics reported by TaskStatsHook and the queues tell you which stage is slow, and whether the loader keeps up with its consumer. They do not tell you why a stage is slow, or what a loader that keeps up costs: a stage can compute, spend time in the kernel (allocating and faulting in memory, copying, waiting on system calls), wait for a CPU because its container’s quota is exhausted, or stall on memory or I/O pressure. When a loader runs in many worker processes, a host-wide CPU number does not say which process, or which threads in it, pay the cost.

Linux keeps the counters that answer these questions for every process and thread, and for every cgroup. SystemMonitor reads them periodically for a pipeline’s whole process family. This page shows how to enable it, which signals to read and how to read them together, how to go down to threads and stages, and how the monitor works.

Enabling the monitor

SystemMonitor is a BackgroundTask. Pass it to the pipeline running in the main process:

from functools import partial

from spdl.pipeline import SystemMonitor, build_pipeline

pipeline = build_pipeline(
    config,
    num_threads=8,
    background_tasks=[partial(SystemMonitor, interval=10, output_path="/tmp/sysmon.jsonl")],
)

Every interval seconds it samples the main process and all its descendants: the multiprocessing forkserver, every worker of a to() region and the process of run_pipeline_in_subprocess(). Each sample is a SystemStats with the increase of every counter over the interval, per process (ProcessStats), per thread name in each process (ThreadStats) and for the cgroup (CgroupStats). Values the kernel does not provide, or does not show to this user, are None, never zero.

Without output_path or callback, each sample is logged as one summary line:

[SystemMonitor pid=4021 10.0s] 66 processes, 1290 threads; CPU user 38.12 kernel 13.95
cores; faults minor 1,402,311/s major 0/s; RSS 431.2 GiB (anon 417.9 GiB); throttled
0.0% of periods; stall cpu 1.2% memory 0.0% io 0.3%

callback (or a subclass overriding SystemMonitor.interval_stats_callback()) receives each full SystemStats. output_path appends the full detail as JSON lines to a local file.

Choose the output by volume. The full detail lists every process and every thread group: a loader worker with 500 threads, most of them a native library’s, produced about 35 KB per sample, and 64 workers sampled every 20 seconds produced about 400 MB of log per host-hour, more than a log service returned in one query. To log a record per interval, or to write one to a table, send SystemStats.summary() instead: one aggregated record of about 2 KB with totals over the processes, the spread of faults between them, the busiest thread groups merged by name, the cgroup and pressure. A monitor in the main process then gives one such record per rank per interval (about 3 MB per host-hour for 8 ranks at 20 seconds):

def log_summary(stats):
    logger.info("system_stats %s", json.dumps(stats.summary()))

background_tasks = [partial(SystemMonitor, log_summary, interval=20)]

Keep the full detail for files written by each worker (output_path) or for a short diagnostic run.

The monitor can also run inside each worker of a region, which then monitors that worker alone:

pipeline = (
    PipelineBuilder()
    .add_source(keys)
    .to(
        ProcessPoolExecutorConfig(max_workers=8, mp_context="forkserver"),
        background_tasks=[
            partial(SystemMonitor, interval=10, output_path="/tmp/sysmon-{pid}.jsonl")
        ],
    )
    .pipe(read, concurrency=4)
    .pipe(transform, concurrency=2)
    .to(MAIN_PROCESS)
    .add_sink(3)
    .build(num_threads=4)
)

{pid} gives each worker its own file. A region’s background tasks run in the nested pipeline that executes the region’s stages in each worker, so the monitor lives as long as that pipeline: the worker’s lifetime with a continuous source; otherwise it restarts at every input stream boundary, taking a fresh baseline and reporting one interval later.

Use one placement or the other: a monitor in the main process already includes the workers. A process-family monitor is usually the right default; the per-worker form suits a process you cannot reach from its parent, such as a loader started by another launcher.

Note

With the forkserver start method, a process started through the forkserver reuses its parent’s forkserver. So when a pipeline runs in run_pipeline_in_subprocess() with mp_context="forkserver", its region workers are children of the main process’s forkserver, and siblings of the pipeline subprocess rather than its children. A monitor running in that subprocess sees only the subprocess. Run the monitor in the main process, or pass root_pid= with the main process’s ID (os.getpid() evaluated in the main process) to the monitor given to the subprocess.

Thread names

Per-thread numbers are grouped by the OS thread name (comm, at most 15 bytes). SPDL names its own threads at the OS level on every Python version: the event loop (spdl_event_loop), the pipeline’s thread pool (spdl_worker_t0, spdl_worker_t1, …), the synchronous source thread (spdl_sync_source) and the thread pools it rebuilds in region workers from a stage’s executor=. Give a stage that matters its own pool with a thread_name_prefix to see it under its own name:

.pipe(transform, concurrency=1,
      executor=ThreadPoolExecutor(1, thread_name_prefix="transform"))

Python 3.14 and later set the OS name of every thread from threading.Thread.name. Earlier versions do not, so other threads keep the executable’s name (for example python3.12) and are grouped together. That includes a stage’s own pool in the main process: before Python 3.14 its threads show up under their prefix only inside region workers, where SPDL rebuilds the pool. Whether a dedicated pool also changes performance is covered in Dedicated thread pools for stages.

The signals and how to read them together

No single counter tells the story. Faults, for example, are cheap when they are few and the CPUs are idle, and expensive when many threads fault at once in a container that is out of CPU quota. Read the signals as a set, per process first and per thread name second, next to the pipeline’s own statistics.

Signal

What it says

Queue occupancy and stage times (SPDL statistics)

Whether the loader keeps up with its consumer. A full sink queue means the loader is not the bottleneck, whatever the counters below say; they then measure what the loader costs, not why training is slow. See Understanding the performance statistics.

User and kernel CPU per process (utime, stime)

Where CPU goes. User time is your code and native libraries. Kernel time is system calls, copies, and allocating, zeroing and faulting in memory.

Minor and major faults (minflt, majflt)

A minor fault maps a page without I/O, most often the first touch of memory the allocator just got from the kernel. A major fault needed I/O: a memory-mapped file not in the page cache, or swap.

Context switches (voluntary, involuntary)

Voluntary switches are waits (I/O, locks, the GIL). Involuntary ones are preemptions: more runnable threads than CPUs.

Run delay per thread (schedstat)

Time a thread was runnable but not running. It shows CPU contention directly.

Resident, anonymous and file memory over time (rss, rss_anon, rss_file)

The loader’s memory footprint. Anonymous memory is heap and buffers; file memory is mapped files.

cgroup CPU throttling (nr_throttled, throttled_time)

The container ran out of its CPU quota and was paused until the next period.

Pressure stall (PSI) for CPU, memory and I/O

The share of time tasks in the cgroup were stalled waiting for that resource.

I/O bytes (read_bytes, rchar)

Bytes read from storage, and bytes read through system calls including the page cache.

Patterns to look for:

  • Kernel time up, user time flat, minor faults up. The extra work is memory churn: buffers allocated and faulted in, or memory returned to the kernel and faulted in again. Look at the allocator and at copies (see The allocator behind the counters). Multiply the minor faults per item by the page size (usually 4 KiB) and compare with the bytes the loader creates per item: roughly equal means each buffer is faulted in once, several times larger means memory is returned and faulted in again, or temporaries are larger than the output.

  • Kernel time up, faults flat. System calls and copies: look at voluntary context switches and I/O bytes.

  • Throttling, CPU pressure or run delay up. The loader is short of CPU rather than doing more work. Its stages get slower without any code change. Reduce the number of workers or threads, or the work per item, rather than tuning the code that waits.

  • Involuntary context switches up. More runnable threads than CPUs, from too many workers or threads, or from neighbours.

  • Memory pressure or major faults up. Reclaim of the page cache, or swap. Check the cgroup’s memory limit against its current use.

  • I/O pressure up with read bytes. Storage is the limit.

  • Anonymous memory that peaks early and stays. Allocators keep freed memory for reuse, and caches fill up. A peak in the first minute that is then retained is the working set plus what the allocator keeps; compare it with the cgroup’s memory limit.

  • A spread between workers. Workers that run the same code on the same kind of data should report similar counters per item. A spread, especially a bimodal one, points at per-process state such as the allocator’s rather than at the data. Put each worker’s numbers next to its own timing to see whether the slow workers are the ones with more faults.

Compare arms (for example a baseline and a change) that process the same data with the same item and batch shapes on the same machine type, and report the ratio per counter, per process type and per thread group, not just the total CPU.

Down to threads and stages

Per-process numbers say which process pays. The thread groups of each process say which threads: the event loop’s user time comes from async ops, stage bookkeeping and sources iterated on the loop, and if it approaches one CPU-second per second the loop itself is the bottleneck. A native library’s own threads (for example a decoder’s thread pool) appear under their own names.

Turning thread groups into numbers per stage depends on whether a stage has threads of its own:

  • Threads a stage owns. A stage given executor=ThreadPoolExecutor(n, thread_name_prefix="decode") shows up as the decode group in region workers, and in the main process on Python 3.14 and later (see Thread names). Divide by the items the stage processed (from its statistics).

  • Shared-pool threads. Synchronous stages that share the pipeline’s thread pool run on whichever of its threads is free, so a thread’s counters mix several stages. Per-stage numbers there need an in-process measurement around each op call, described next. This is the one measurement SystemMonitor does not make: it reads counters per thread, not per call, and no hook SPDL offers runs on the thread that executes the op.

Advanced: measuring each op call

SPDL runs a synchronous op on a thread of an executor. Wrapping the op so that it reads getrusage(RUSAGE_THREAD) (resource.getrusage()) before and after its body therefore measures exactly the work of that call, on the thread that did it.

Note

This cannot be done in a TaskHook. Its task_hook runs on the event-loop thread around the awaited task, while the op body runs on an executor thread, so RUSAGE_THREAD read there measures the event loop. The measurement must run inside the function the executor calls.

The wrapper below accumulates the deltas per stage, under a lock because several threads run the same op, and writes each process’s totals to a JSON file. It is picklable, so it works for a stage inside a to() region and for run_pipeline_in_subprocess().

import json
import logging
import multiprocessing.util
import os
import resource
import threading
import time

_FIELDS = ("ru_utime", "ru_stime", "ru_minflt", "ru_majflt", "ru_nvcsw", "ru_nivcsw")


class MeasuredOp:
    """Wrap a sync op and accumulate its per-thread resource usage per process."""

    def __init__(self, name, op, out_dir, flush_every=1000):
        self.name, self.op = name, op
        self.out_dir, self.flush_every = out_dir, flush_every
        self._reset()

    def _reset(self):
        self._lock = threading.Lock()
        self._dump_lock = threading.Lock()
        self._items = 0
        self._wall = 0.0
        self._totals = dict.fromkeys(_FIELDS, 0)
        self._registered = False

    # Only the configuration crosses a process boundary; each process counts its own.
    def __getstate__(self):
        return {k: self.__dict__[k] for k in ("name", "op", "out_dir", "flush_every")}

    def __setstate__(self, state):
        self.__dict__.update(state)
        self._reset()

    def __call__(self, item):
        before = resource.getrusage(resource.RUSAGE_THREAD)
        t0 = time.perf_counter()
        try:
            return self.op(item)
        finally:
            wall = time.perf_counter() - t0
            after = resource.getrusage(resource.RUSAGE_THREAD)
            self._add(before, after, wall)

    def _add(self, before, after, wall):
        with self._lock:
            self._items += 1
            self._wall += wall
            for f in _FIELDS:
                self._totals[f] += getattr(after, f) - getattr(before, f)
            if not self._registered:
                # Write the final totals when a worker process exits normally.
                multiprocessing.util.Finalize(self, self.dump, exitpriority=10)
                self._registered = True
            flush = self._items % self.flush_every == 0
        if flush:
            self.dump()

    def dump(self):
        # One writer at a time, so snapshots never race on the temporary file. A
        # failed write is logged, never raised into the op that triggered the flush.
        with self._dump_lock:
            with self._lock:
                record = {"stage": self.name, "pid": os.getpid(), "items": self._items,
                          "wall": self._wall, **self._totals}
            path = os.path.join(self.out_dir, f"{self.name}-{os.getpid()}.json")
            try:
                with open(path + ".tmp", "w") as f:
                    json.dump(record, f)
                os.replace(path + ".tmp", path)
            except OSError:
                logging.getLogger(__name__).warning(
                    "Failed to write %s", path, exc_info=True)

Use it in place of the op, keeping the stage’s name, and give each arm its own, empty output directory, so that files from an earlier run are not summed into this one:

read_op = MeasuredOp("read", read, out_dir)
transform_op = MeasuredOp("transform", transform, out_dir)
builder.pipe(read_op, concurrency=4, name="read").pipe(transform_op, name="transform")

Sum the totals and the item counts of every process before dividing; averaging the per-process averages weights a worker that processed few items as much as one that processed many. The per-process files also give each stage’s numbers per worker, which can show which stage a spread between workers comes from:

import collections
import glob
import json
import statistics

totals = collections.defaultdict(collections.Counter)
per_worker = collections.defaultdict(list)
for path in glob.glob(f"{out_dir}/*.json"):
    with open(path) as f:
        r = json.load(f)
    stage = r.pop("stage")
    totals[stage].update({k: v for k, v in r.items() if k != "pid"})
    if r["items"]:
        per_worker[stage].append(r["ru_minflt"] / r["items"])

for stage, t in totals.items():
    n, w = t["items"], sorted(per_worker[stage])
    print(f"{stage}: {n} items | per item: user {t['ru_utime'] / n * 1e3:.2f} ms, "
          f"sys {t['ru_stime'] / n * 1e3:.2f} ms, minflt {t['ru_minflt'] / n:.1f} "
          f"(workers: min {w[0]:.1f} median {statistics.median(w):.1f} max {w[-1]:.1f})")

A few details:

  • Normalize by the unit the stage processes: rows for a per-row stage, batches after PipelineBuilder.aggregate().

  • Generator ops. For a synchronous generator, SPDL calls the op once to create the generator and then calls next() on an executor thread for each output, so most of the work happens outside the wrapped call. Wrap the generator too.

  • Process exit. multiprocessing.util.Finalize runs when a multiprocessing worker returns normally. A worker that is terminated runs no finalizer, so the periodic flush_every dump bounds what can be lost.

  • Overhead. Each call adds two getrusage system calls and an uncontended lock, a few microseconds: negligible for ops that take milliseconds, too much for ops that take microseconds.

The allocator behind the counters

Most minor faults in a data loader come from the memory allocator handing out pages that are new to the process. Two behaviours matter:

  • Copies. Every buffer the code creates is touched for the first time once. An extra per-item copy of a large container shows up directly as more faults per item in the stage that makes the copy, with kernel time rising along with it.

  • Returning memory to the kernel. Allocators keep freed memory for reuse, then return unused pages to the kernel after some time or above some size. jemalloc, for example, purges dirty pages after a decay time (dirty_decay_ms; jemalloc’s default is 10 s). Memory that is returned and then needed again is faulted in again. A loader whose working set is reused on a period longer than the decay time pays these faults repeatedly, and the kernel time for them grows when many threads fault and purge at once.

Keeping freed memory longer trades resident memory for fewer faults and less kernel time. The allocator’s settings (for jemalloc, dirty_decay_ms and muzzy_decay_ms, set through its MALLOC_CONF environment variable before the process starts; for glibc, M_TRIM_THRESHOLD, M_MMAP_THRESHOLD and MALLOC_ARENA_MAX) are therefore worth measuring as arms of their own, with memory reported next to the counters.

Debugging the kernel time of a cached loader shows how these signals were used to debug a production loader.

How the monitor works

The counters are kept by the kernel per thread and per process, whatever the thread runs, and are readable from outside. A single sampler can therefore cover the whole process family without any hook inside the workers:

  • The process family. Starting from the monitored process, the monitor lists each process’s children, then their children: with the forkserver start method, region workers are children of the forkserver, not of the main process. The kernel lists a thread’s children in /proc/<pid>/task/<tid>/children when it is built with CONFIG_PROC_CHILDREN. Without that file the tree comes from the parent pid of every /proc/<pid>/stat, which costs tens of milliseconds of kernel time on a host with thousands of processes, so the monitor rescans every discovery_interval seconds, or as soon as a known member exits, and reads only processes that appeared since its last scan.

  • Each process. /proc/<pid>/stat gives faults and CPU times, including threads that have exited and the totals of children the process has reaped; status gives memory and context switches; io the I/O bytes; optionally smaps_rollup the PSS.

  • Each thread. /proc/<pid>/task/<tid>/stat, status and schedstat give the thread’s name, faults, CPU times, context switches, run time and run delay.

  • The cgroup. The monitor locates the cgroup of its own process through /proc/self/cgroup and /proc/self/mountinfo (falling back to /sys/fs/cgroup for cgroup v2), and reads cpu.stat, the memory.* files and the *.pressure files; host-wide PSI comes from /proc/pressure. On hybrid hosts, where the controllers are on cgroup v1 and the unified hierarchy is empty, it reads the v1 controllers.

  • Deltas. Each report is the difference from the previous sample. A process or thread seen for the first time reports its counters since it started, and is marked new.

Gaps:

  • Threads that exit between samples lose their last interval from the per-thread view. The per-process numbers still include it, so per-process totals are complete even when the thread groups do not add up to them.

  • Processes that exit between samples lose their last interval from both views. When the parent reaps the process, the parent’s cminflt, cmajflt, cutime and cstime grow by the child’s whole-lifetime totals.

Cost

The monitor is a coroutine on the pipeline’s event loop and owns no thread or executor. It hands reading and parsing the files, and writing output_path, to loop.run_in_executor(executor, ...), so none of it runs on the loop. By default (executor=None) that is the running loop’s default executor: in a pipeline, the thread pool that runs the stages, so a sample briefly occupies one of its slots. To keep sampling out of that pool, pass an executor of your own; you own it and shut it down:

from concurrent.futures import ThreadPoolExecutor

sysmon_pool = ThreadPoolExecutor(1, thread_name_prefix="sysmon")
pipeline = build_pipeline(
    config,
    num_threads=8,
    background_tasks=[partial(SystemMonitor, interval=10, executor=sysmon_pool)],
)
...
sysmon_pool.shutdown()

An executor cannot be pickled, so this form is for a monitor in the main process. A region’s background tasks are pickled to its workers; keep the default there.

When spdl.io is installed, a native reader reads and parses all files of a sample in one call that releases the GIL; the GIL is held only to hand over the arguments and to turn the results into deltas. A sample takes about 35 microseconds per monitored thread, mostly kernel time: about 1 ms for a single worker with 20 threads, 4 ms with 100 and 18 ms with 500. Without spdl.io an equivalent pure-Python reader is used.

Measured on a host with about 2,260 processes, Python 3.12, sampling a family of forkserver workers with 20 threads each:

Reader

Family

Per sample

GIL held

With another thread running Python

Python

35 processes, 644 threads

43.7 ms

about 20 ms

5,045 ms

native

35 processes, 644 threads

24.3 ms

1.8 ms

30.8 ms

native

67 processes, 1,283 threads

51.0 ms

3.8 ms

Most of a native sample is kernel time for about three small reads per thread: 0.25-0.5% of one core at a 10 second interval.

The last column is the important one. Python releases and re-acquires the GIL around every open, read and directory entry. When another thread is busy running Python code, as the training loop of the main process is, each re-acquisition can wait for the interpreter’s switch interval (5 ms by default), and one sample of a few hundred files took 5 seconds. A monitor that slow is not just late: its samples no longer line up with the interval, and on the default executor it holds one of the stages’ threads for that long. Install spdl.io when monitoring a busy process, or, without it, pass a dedicated executor.

smaps_rollup=True adds PSS. It walks every memory mapping of a process while holding its memory-map lock, which can delay that process’s page faults, so it is off by default.

Compatibility

The file formats are defined by the kernel, not the distribution. The monitor parses stat from the last ), since thread names may contain spaces and parentheses, ignores fields the kernel appends, and parses the other files by key. A value can be unavailable, and is then None:

  • smaps_rollup needs Linux 4.14, RssAnon and the other Rss* keys 4.5, and io needs task I/O accounting and permission to trace the process.

  • cgroup v1 provides CPU usage, throttling and memory, but no user/kernel split, OOM kill count or pressure. PSI needs cgroup v2 (or /proc/pressure) with CONFIG_PSI, and can be disabled at boot with psi=0.

  • In containers, PID namespaces and hidepid mounts can hide processes, and sandboxed kernels may omit files. A process that exits during a sample is skipped.

  • CPU times use the runtime clock tick (SC_CLK_TCK) and memory the runtime page size (4 KiB on most systems, 64 KiB on some ARM systems).

The monitor reads Linux files only. On other operating systems it logs a warning and does not sample.

Reading the numbers in code

getrusage(RUSAGE_THREAD), /proc/<pid>/task/<tid>/stat and ThreadStats expose the same per-thread counters, so the monitor’s numbers can be checked against what a thread measures for itself:

getrusage field

/proc source

ThreadStats field

Meaning

ru_utime

stat field 14 (clock ticks)

utime (seconds)

CPU time in user mode.

ru_stime

stat field 15 (clock ticks)

stime (seconds)

CPU time in the kernel on behalf of the thread.

ru_minflt

stat field 10

minflt

Minor page faults.

ru_majflt

stat field 12

majflt

Major page faults.

ru_nvcsw

status: voluntary_ctxt_switches

voluntary_ctxt_switches

Voluntary context switches.

ru_nivcsw

status: nonvoluntary_ctxt_switches

nonvoluntary_ctxt_switches

Involuntary context switches.

ProcessStats carries the same counters per process, plus memory and I/O. To act on the numbers rather than log them, read them in a callback. Values the kernel does not provide are None:

def report(stats):
    for p in stats.processes:
        logger.info("pid=%d %s: user %ss kernel %ss minflt %s",
                    p.pid, p.name, p.utime, p.stime, p.minflt)
    for t in stats.threads:
        logger.info("pid=%d [%s x%d]: kernel %ss minflt %s",
                    t.pid, t.name, t.num_threads, t.stime, t.minflt)

background_tasks = [partial(SystemMonitor, report, interval=10)]

With threads=False the monitor reports processes and the cgroup only and skips the three files it reads per thread, most of the cost of a sample. root_pid and include_descendants=False narrow it to another process or to one process.

Caveats

  • Linux only. /proc, cgroups and resource.RUSAGE_THREAD exist on Linux only.

  • Async ops are not attributable to a stage by thread: they run as coroutines interleaved on the event-loop thread. Attribute the event-loop thread as a whole, or move the CPU-heavy part into a synchronous op.

  • Sampling granularity. CPU times are in clock ticks (typically 10 ms), so short intervals are coarse. Align the interval with the stage statistics when you divide by item counts.

  • Observer effect. Measure the arms you compare with the same monitoring enabled, and compare end-to-end throughput without it.