Benchmark arena transport

Targeted benchmark: arena transport throughput (regular IPC vs ring vs pool).

Measures how the shared-memory arena affects the cost of shipping large payloads from a backend Pipeline running in a subprocess to the main process, via spdl.pipeline.run_pipeline_in_subprocess().

A backend pipeline produces a fixed dataset of {"data": payload} items; the main process receives them through one of three transports and does nothing with them (a no-op stand-in for a training loop), so the measured throughput isolates transfer + restore with no decode or other per-item work in the way:

  • no-arena — payloads are pickled over the multiprocessing queue (the default).

  • ring — SharedMemoryRingBuffer; the reader copies each payload out of shared memory (so it cannot hand out live views).

  • pool — SharedMemorySegmentPool; the reader restores each payload as a zero-copy view directly over shared memory.

It sweeps payload sizes x four payload types — bytes, NumPy arrays, Torch tensors, and spdl.io VideoPackets — each of which the arena offloads as a large binary.

Results

From --isolate at 32 MiB on a CPU-only host (--num-items 16 --runs 10): each (kind, transport) runs in its own freshly-spawned process, one at a time, so the CPU s and peak RSS columns are attributable to that one config (getrusage over the timed passes / from a pre-arena baseline; a single shared process would accumulate both across configs and could not separate them). The arena raises throughput and drops the CPU of moving a payload to near zero — the pool restores a zero-copy view, so it does essentially no per-item work, while plain IPC spends several CPU-seconds pickling and copying. bytes / NumPy gain the most. Torch transfers tensors through shared memory itself (its multiprocessing reducer), so plain IPC already avoids a bulk copy — its throughput barely moves and plain IPC is already its leanest memory; the ring even adds CPU (it copies out), yet the pool still drops its CPU to ~0. Packets gain less throughput (restoring rebuilds the AVPacket structures) but the pool slashes their CPU and memory too. peak RSS includes a fixed per-process baseline, so compare it within a row; for bytes / NumPy / packets the no-arena pickle buffers are the heaviest, and the pool the lightest.

kind     transport   recv MB/s   speedup   CPU s   peak RSS MB
------------------------------------------------------------
bytes    no-arena          719     1.00x     7.1          1872
bytes    ring             2684     3.73x     1.8          1015
bytes    pool             3760     5.23x     0.0           673
numpy    no-arena          647     1.00x     7.7          1865
numpy    ring             3202     4.95x     1.1          1009
numpy    pool             3767     5.82x     0.0           669
torch    no-arena         2899     1.00x     0.6           603
torch    ring             3106     1.07x     1.2          1262
torch    pool             3116     1.08x     0.0           834
packets  no-arena          555     1.00x     8.6          1885
packets  ring             1359     2.45x     3.3          1236
packets  pool             1622     2.92x     0.1           825
(recv MB/s with speedup vs no-arena; CPU s and peak RSS are per-config,
lower is better. Throughput speedup grows with payload size — at 2 / 8 MiB
it is smaller; see the size sweep below.)

In the plot below, each line is one (kind, transport) across payload sizes (a separate throughput sweep): colour and marker encode the payload type and line style the transport (dotted = no-arena, dashed = ring, solid = pool); the shaded band is the ~95% confidence interval of the mean:

../_static/data/example_benchmark_arena_transport.png

Example

$ python benchmark_arena_transport.py --sizes 2 8 32 --output results.csv
$ python benchmark_arena_transport_plot.py --input results.csv --output plot.png

Source

Source

Click here to see the source.
  1#!/usr/bin/env python3
  2# Copyright (c) Meta Platforms, Inc. and affiliates.
  3# All rights reserved.
  4#
  5# This source code is licensed under the BSD-style license found in the
  6# LICENSE file in the root directory of this source tree.
  7
  8
  9"""Targeted benchmark: arena transport throughput (regular IPC vs ring vs pool).
 10
 11Measures how the shared-memory arena affects the cost of shipping large payloads
 12from a backend :py:class:`~spdl.pipeline.Pipeline` running in a subprocess to the
 13main process, via :py:func:`spdl.pipeline.run_pipeline_in_subprocess`.
 14
 15A backend pipeline produces a fixed dataset of ``{"data": payload}`` items; the
 16main process receives them through one of three transports and does nothing with
 17them (a no-op stand-in for a training loop), so the measured throughput isolates
 18**transfer + restore** with no decode or other per-item work in the way:
 19
 20- **no-arena** — payloads are pickled over the multiprocessing queue (the default).
 21- **ring** — :py:class:`~spdl.pipeline.SharedMemoryRingBuffer`; the reader copies
 22  each payload out of shared memory (so it cannot hand out live views).
 23- **pool** — :py:class:`~spdl.pipeline.SharedMemorySegmentPool`; the reader
 24  restores each payload as a zero-copy view directly over shared memory.
 25
 26It sweeps payload sizes x four payload types — ``bytes``, NumPy arrays, Torch
 27tensors, and ``spdl.io`` ``VideoPackets`` — each of which the arena offloads as a
 28large binary.
 29
 30**Results**
 31
 32From ``--isolate`` at 32 MiB on a CPU-only host (``--num-items 16 --runs 10``):
 33each ``(kind, transport)`` runs in its own freshly-spawned process, one at a time,
 34so the ``CPU s`` and ``peak RSS`` columns are attributable to that one config
 35(``getrusage`` over the timed passes / from a pre-arena baseline; a single shared
 36process would accumulate both across configs and could not separate them). The
 37arena raises throughput *and* drops the CPU of moving a payload to near zero —
 38the pool restores a zero-copy view, so it does essentially no per-item work, while
 39plain IPC spends several CPU-seconds pickling and copying. ``bytes`` / NumPy gain
 40the most. Torch transfers tensors through shared memory itself (its
 41multiprocessing reducer), so plain IPC already avoids a bulk copy — its throughput
 42barely moves and plain IPC is already its leanest memory; the ring even adds CPU
 43(it copies out), yet the pool still drops its CPU to ~0. Packets gain less
 44throughput (restoring rebuilds the ``AVPacket`` structures) but the pool slashes
 45their CPU and memory too. ``peak RSS`` includes a fixed per-process baseline, so
 46compare it within a row; for ``bytes`` / NumPy / packets the no-arena pickle
 47buffers are the heaviest, and the pool the lightest.
 48
 49.. code-block:: text
 50
 51   kind     transport   recv MB/s   speedup   CPU s   peak RSS MB
 52   ------------------------------------------------------------
 53   bytes    no-arena          719     1.00x     7.1          1872
 54   bytes    ring             2684     3.73x     1.8          1015
 55   bytes    pool             3760     5.23x     0.0           673
 56   numpy    no-arena          647     1.00x     7.7          1865
 57   numpy    ring             3202     4.95x     1.1          1009
 58   numpy    pool             3767     5.82x     0.0           669
 59   torch    no-arena         2899     1.00x     0.6           603
 60   torch    ring             3106     1.07x     1.2          1262
 61   torch    pool             3116     1.08x     0.0           834
 62   packets  no-arena          555     1.00x     8.6          1885
 63   packets  ring             1359     2.45x     3.3          1236
 64   packets  pool             1622     2.92x     0.1           825
 65   (recv MB/s with speedup vs no-arena; CPU s and peak RSS are per-config,
 66   lower is better. Throughput speedup grows with payload size — at 2 / 8 MiB
 67   it is smaller; see the size sweep below.)
 68
 69In the plot below, each line is one (kind, transport) across payload sizes (a
 70separate throughput sweep): colour and marker encode the payload type and line
 71style the transport (dotted = no-arena, dashed = ring, solid = pool); the shaded
 72band is the ~95% confidence interval of the mean:
 73
 74.. image:: ../../_static/data/example_benchmark_arena_transport.png
 75
 76**Example**
 77
 78.. code-block:: shell
 79
 80   $ python benchmark_arena_transport.py --sizes 2 8 32 --output results.csv
 81   $ python benchmark_arena_transport_plot.py --input results.csv --output plot.png
 82"""
 83
 84from __future__ import annotations
 85
 86__all__ = [
 87    "Row",
 88    "create_video_data",
 89    "main",
 90    "read_csv",
 91    "run_transport",
 92    "write_csv",
 93]
 94
 95import argparse
 96import csv
 97import gc
 98import multiprocessing as mp
 99import os
100import resource
101import statistics
102import sys
103import tempfile
104import time
105from collections.abc import Iterator
106from dataclasses import asdict, dataclass, fields
107from itertools import product
108from typing import Any, Literal
109
110import numpy as np
111import spdl.io
112import torch
113from spdl.pipeline import (
114    PipelineBuilder,
115    run_pipeline_in_subprocess,
116    SharedMemoryRingBuffer,
117    SharedMemorySegmentPool,
118)
119
120_IsolatedSuccess = tuple[Literal["ok"], list[float], float, float]
121_IsolatedFailure = tuple[Literal["err"], str, float, float]
122_IsolatedResult = _IsolatedSuccess | _IsolatedFailure
123
124_KINDS = ("bytes", "numpy", "torch", "packets")
125_TRANSPORTS = ("no-arena", "ring", "pool")
126# 4K frames: at the benchmark's payload sizes the encoder fills the bitrate with
127# real frame data instead of mostly CBR filler, so the packets resemble a real
128# high-resolution decode workload.
129_VIDEO_SIZE = "3840x2160"
130
131
132@dataclass(frozen=True)
133class Row:
134    """Row()
135
136    One benchmark measurement: throughput for a (size, kind, transport)."""
137
138    size_mb: int
139    """Requested payload size in MiB (the sweep knob)."""
140
141    kind: str
142    """Payload kind: ``"bytes"``, ``"numpy"``, ``"torch"``, or ``"packets"``."""
143
144    transport: str
145    """Transport used: ``"no-arena"``, ``"ring"``, or ``"pool"``."""
146
147    items_per_s: float
148    """Mean items received per second over the timed passes."""
149
150    mb_per_s: float
151    """Mean payload throughput in MB/s (``items_per_s`` x payload bytes)."""
152
153    mb_per_s_lo: float
154    """Lower bound of the ~95% confidence interval of ``mb_per_s`` (normal
155    approximation over the timed passes)."""
156
157    mb_per_s_hi: float
158    """Upper bound of the ~95% confidence interval of ``mb_per_s``."""
159
160    speedup: float
161    """``items_per_s`` relative to the no-arena baseline for this (size, kind)."""
162
163    peak_rss_mb: float = 0.0
164    """Peak resident memory of the config's process tree (consumer + producer), in
165    MB. Only populated by ``--isolate``; ``0`` otherwise. Shared arena pages may be
166    counted in both processes, so treat it as an upper-bound proxy and compare
167    within a (size, kind) row across transports."""
168
169    cpu_sec: float = 0.0
170    """Total CPU seconds (user + system, consumer + producer) the config consumed.
171    Only populated by ``--isolate``; ``0`` otherwise. Lower is better — moving a
172    payload via the arena should cost less CPU than the pickle + copy of plain IPC."""
173
174
175def create_video_data(target_bytes: int, duration_seconds: float = 2.0) -> bytes:
176    """Generate an H.264 MP4 whose stream is approximately ``target_bytes``.
177
178    Encodes low-entropy frames at a constant target bitrate (x264 CBR, which pads
179    with filler to hold the rate), so the serialized ``VideoPackets`` payload
180    scales with the requested size rather than collapsing to the content's natural
181    compressed size. Uses ``spdl.io``'s in-process encoder rather than the
182    ``ffmpeg`` CLI, so it also works on minimal container images that do not ship
183    the CLI.
184
185    Args:
186        target_bytes: Desired size of the encoded video stream, in bytes.
187        duration_seconds: Clip duration; the bitrate is derived from it.
188
189    Returns:
190        The encoded MP4 file contents as raw bytes.
191    """
192    width, height = (int(x) for x in _VIDEO_SIZE.split("x"))
193    frame_rate = (30, 1)
194    num_frames = max(1, round(frame_rate[0] / frame_rate[1] * duration_seconds))
195    bit_rate = max(64_000, int(target_bytes * 8 / duration_seconds))
196    kbps = bit_rate // 1000
197    batch_size = 4  # bound peak memory: 4K yuv444p frames are ~25 MiB each
198    with tempfile.NamedTemporaryFile(suffix=".mp4") as tmp_file:
199        muxer = spdl.io.Muxer(tmp_file.name)
200        encoder = muxer.add_encode_stream(
201            config=spdl.io.video_encode_config(
202                height=height,
203                width=width,
204                pix_fmt="yuv444p",
205                frame_rate=frame_rate,
206                bit_rate=bit_rate,
207            ),
208            encoder="libx264",
209            # CBR with a tight VBV so the encoder pads low-entropy frames with
210            # filler up to the target rate (mirrors the ffmpeg nal-hrd=cbr path).
211            encoder_config={
212                "preset": "ultrafast",
213                "x264-params": f"nal-hrd=cbr:vbv-maxrate={kbps}:vbv-bufsize={kbps}",
214            },
215        )
216        with muxer.open():
217            for start in range(0, num_frames, batch_size):
218                n = min(batch_size, num_frames - start)
219                array = np.zeros((n, 3, height, width), dtype=np.uint8)
220                frames = spdl.io.create_reference_video_frame(
221                    array=array,
222                    pix_fmt="yuv444p",
223                    frame_rate=frame_rate,
224                    pts=start,
225                )
226                if (packets := encoder.encode(frames)) is not None:
227                    muxer.write(0, packets)
228            if (packets := encoder.flush()) is not None:
229                muxer.write(0, packets)
230        with open(tmp_file.name, "rb") as f:
231            return f.read()
232
233
234def _make_payload(kind: str, size: int, video_bytes: bytes | None) -> object:
235    """Build one payload of ``kind`` whose serialized size is roughly ``size``."""
236    if kind == "bytes":
237        return bytes(size)
238    if kind == "numpy":
239        return np.zeros(max(1, size // 4), dtype=np.float32)
240    if kind == "torch":
241        return torch.zeros(max(1, size // 4), dtype=torch.float32)
242    if kind == "packets":
243        assert video_bytes is not None
244        return spdl.io.demux_video(video_bytes)
245    raise ValueError(f"unknown kind: {kind}")
246
247
248def _payload_nbytes(kind: str, size: int, video_bytes: bytes | None) -> int:
249    """The on-the-wire size of one payload, used to size the arena."""
250    payload: Any = _make_payload(kind, size, video_bytes)
251    if kind == "packets":
252        return len(payload.__getstate__())
253    if kind == "numpy":
254        return int(payload.nbytes)
255    if kind == "torch":
256        return int(payload.element_size() * payload.nelement())
257    return len(payload)
258
259
260@dataclass(frozen=True)
261class _Dataset:
262    """A picklable finite dataset: yields ``num_items`` payload items.
263
264    Only the small spec is pickled into the subprocess; the payload itself is
265    built lazily in ``__iter__`` (i.e. in the worker), so shipping the dataset
266    across the process boundary stays cheap regardless of payload size.
267
268    Most kinds reuse one payload object so the measured per-item cost is transfer
269    + restore rather than construction. Torch is the exception: it moves a CPU
270    tensor's storage into shared memory in place on the first IPC send and reuses
271    it afterwards, so reusing one tensor would hide the real cost (a fresh
272    shared-memory segment per distinct tensor). It therefore yields a distinct
273    tensor per item, matching how a real pipeline produces tensors.
274    """
275
276    kind: str
277    size: int
278    num_items: int
279    video_bytes: bytes | None = None
280
281    def __iter__(self) -> Iterator[dict[str, object]]:
282        # Torch moves a CPU tensor's storage into shared memory in place on the
283        # first cross-process send and reuses that same segment for later sends of
284        # the *same* tensor (torch.multiprocessing's reducer + its storage cache).
285        # So if the benchmark reused one tensor, every send after the first would
286        # be nearly free and hide the real per-item cost (a fresh shm segment per
287        # distinct tensor) — build a distinct tensor per item for torch instead.
288        reused = (
289            None
290            if self.kind == "torch"
291            else _make_payload(self.kind, self.size, self.video_bytes)
292        )
293        for _ in range(self.num_items):
294            payload = (
295                reused
296                if reused is not None
297                else _make_payload(self.kind, self.size, self.video_bytes)
298            )
299            yield {"data": payload}
300
301
302def _make_arena(
303    transport: str, payload_nbytes: int, buffer_size: int, num_items: int
304) -> SharedMemoryRingBuffer | SharedMemorySegmentPool | None:
305    """Construct the arena for a transport mode, sized to hold a whole iteration.
306
307    The arena does not block the writer when full — it raises "shared-memory
308    arena full" and relies on the pipeline's queue backpressure to bound the
309    in-flight units. That bound only holds when the reader keeps up; when restore
310    is much slower than offload (e.g. rebuilding ``VideoPackets`` on a busy host),
311    the writer can get a whole iteration ahead. So size the arena for the
312    worst case — every item of one iteration in flight at once — which never
313    overruns regardless of the producer/consumer speed gap.
314    """
315    if transport == "no-arena":
316        return None
317    slots = max(2 * buffer_size + 6, num_items + 2)
318    unit = max(1 << 20, payload_nbytes * 2)  # headroom for envelope + alignment
319    if transport == "ring":
320        return SharedMemoryRingBuffer(capacity=unit * slots)
321    if transport == "pool":
322        return SharedMemorySegmentPool(segment_size=unit, count=slots)
323    raise ValueError(f"unknown transport: {transport}")
324
325
326def run_transport(
327    dataset: _Dataset,
328    transport: str,
329    *,
330    payload_nbytes: int,
331    num_items: int,
332    buffer_size: int,
333    runs: int,
334    duration_sec: float = 0.0,
335    usage: list[float] | None = None,
336) -> list[float]:
337    """Run the backend pipeline once per timed pass; return per-pass items/second.
338
339    Builds a one-stage backend pipeline (source -> sink) that runs in a
340    subprocess via :py:func:`run_pipeline_in_subprocess`, ships its items to the
341    main process over ``transport``, and consumes them in a no-op loop. One warmup
342    pass is discarded; the per-pass throughput of each timed pass is returned so
343    the caller can summarize it (mean + confidence interval). The subprocess and
344    arena are reused across passes and torn down at the end.
345
346    Args:
347        dataset: The (picklable) backend data source.
348        transport: One of ``"no-arena"``, ``"ring"``, ``"pool"``.
349        payload_nbytes: On-the-wire size of one payload, used to size the arena.
350        num_items: Number of items per pass (must match ``dataset.num_items``).
351        buffer_size: Pipeline sink buffer size / arena in-flight unit count.
352        runs: Number of timed passes (used when ``duration_sec`` is not positive).
353        duration_sec: If positive, keep running timed passes until this many
354            seconds have elapsed instead of stopping after ``runs`` passes — used
355            for sustained, fixed-duration host-stat sampling by an external sampler.
356        usage: If given, one element is appended: the CPU seconds (user + system,
357            this process + the producer subprocess) spent across the timed passes.
358            The snapshot is taken *after* the warmup pass, so process-startup and
359            import costs are excluded and only the transport's per-item work counts.
360
361    Returns:
362        One throughput sample (items per second) per timed pass.
363    """
364    arena = _make_arena(transport, payload_nbytes, buffer_size, num_items)
365    config = (
366        PipelineBuilder()
367        .add_source(dataset)
368        .add_sink(buffer_size=buffer_size)
369        .get_config()
370    )
371    src = run_pipeline_in_subprocess(
372        config, num_threads=1, arena=arena, buffer_size=buffer_size
373    )
374    try:
375        for item in src:  # warmup pass (subprocess spawn + first-touch costs)
376            del item
377        cpu_base = _cpu_now()  # after warmup: imports + arena warm-up excluded
378        samples: list[float] = []
379        deadline = time.perf_counter() + duration_sec
380        while True:
381            n = 0
382            t0 = time.perf_counter()
383            for item in src:
384                n += 1
385                del item  # release the view so the pool can recycle the segment
386            samples.append(num_items / (time.perf_counter() - t0))
387            assert n == num_items, f"{transport}: expected {num_items}, got {n}"
388            done_by_count = duration_sec <= 0 and len(samples) >= runs
389            done_by_time = duration_sec > 0 and time.perf_counter() >= deadline
390            if done_by_count or done_by_time:
391                break
392        if usage is not None:
393            usage.append(_cpu_now() - cpu_base)
394        return samples
395    finally:
396        # Drop the iterable so its finalizer closes + unlinks the arena before the
397        # next config reuses the shared-memory namespace.
398        del src
399        gc.collect()
400
401
402def _confidence_interval(samples: list[float]) -> tuple[float, float]:
403    """~95% confidence interval of the mean (normal approximation).
404
405    Degenerate cases (a single pass) return ``(mean, mean)``.
406    """
407    mean = statistics.mean(samples)
408    if len(samples) < 2:
409        return mean, mean
410    half = 1.96 * statistics.stdev(samples) / (len(samples) ** 0.5)
411    return mean - half, mean + half
412
413
414def _run_config(size_mb: int, kind: str, args: argparse.Namespace) -> list[Row]:
415    """Benchmark one (size, kind) across the selected transports; one Row each."""
416    size = size_mb << 20
417    # For packets, synthesize a clip whose serialized payload tracks ``size`` (the
418    # other kinds build a payload of exactly ``size`` bytes directly).
419    vb = create_video_data(size) if kind == "packets" else None
420    payload_nbytes = _payload_nbytes(kind, size, vb)
421    dataset = _Dataset(kind, size, args.num_items, vb)
422    factor = payload_nbytes / 1e6  # items/s -> MB/s
423    # First pass: run each transport in the requested order (order is preserved so
424    # the --duration-sec window markers stay aligned with an external sampler) and
425    # collect its mean + CI.
426    measured: list[tuple[str, float, float, float]] = []
427    for i, transport in enumerate(args.transports):
428        if i and args.gap_sec:
429            time.sleep(args.gap_sec)  # idle valley between per-transport windows
430        if args.duration_sec:
431            # Timestamped window markers so externally-sampled host stats (e.g. an
432            # external once-per-minute CPU/memory sampler) can be attributed to each config.
433            print(
434                f"### begin {kind} {size_mb}M {transport} ts={time.time():.0f}",
435                flush=True,
436            )
437        samples = run_transport(
438            dataset,
439            transport,
440            payload_nbytes=payload_nbytes,
441            num_items=args.num_items,
442            buffer_size=args.buffer_size,
443            runs=args.runs,
444            duration_sec=args.duration_sec,
445        )
446        if args.duration_sec:
447            print(
448                f"### end   {kind} {size_mb}M {transport} ts={time.time():.0f}",
449                flush=True,
450            )
451        mean = statistics.mean(samples)
452        lo, hi = _confidence_interval(samples)
453        measured.append((transport, mean, lo, hi))
454    # Second pass: resolve the no-arena baseline after every transport is measured,
455    # so speedup does not depend on the order transports were run (and defaults to
456    # 1.0 when no-arena was not among --transports).
457    baseline = next((m for (t, m, _lo, _hi) in measured if t == "no-arena"), 0.0)
458    return [
459        Row(
460            size_mb=size_mb,
461            kind=kind,
462            transport=transport,
463            items_per_s=mean,
464            mb_per_s=mean * factor,
465            mb_per_s_lo=lo * factor,
466            mb_per_s_hi=hi * factor,
467            speedup=mean / baseline if baseline else 1.0,
468        )
469        for transport, mean, lo, hi in measured
470    ]
471
472
473def _live_child_cpu_sec(pid: int) -> float:
474    """Sum CPU of living descendants, including children spawned by other threads."""
475    seen: set[int] = set()
476    pending = [pid]
477    ticks = os.sysconf("SC_CLK_TCK")
478    total = 0.0
479    while pending:
480        parent = pending.pop()
481        try:
482            threads = os.listdir(f"/proc/{parent}/task")
483        except (FileNotFoundError, ProcessLookupError):
484            if parent == pid:
485                raise
486            continue
487        for tid in threads:
488            try:
489                with open(f"/proc/{parent}/task/{tid}/children") as f:
490                    children = [int(value) for value in f.read().split()]
491            except (FileNotFoundError, ProcessLookupError):
492                continue
493            for child in children:
494                if child in seen:
495                    continue
496                seen.add(child)
497                pending.append(child)
498                try:
499                    with open(f"/proc/{child}/stat") as f:
500                        fields = f.read().rsplit(")", 1)[1].split()
501                    # Include reaped descendants of a still-living child too.
502                    child_ticks = sum(int(fields[i]) for i in (11, 12, 13, 14))
503                except (FileNotFoundError, ProcessLookupError):
504                    continue
505                except (IndexError, ValueError):
506                    try:
507                        os.kill(child, 0)
508                    except ProcessLookupError:
509                        continue
510                    # A malformed sample from an extant or uncertain PID is not zero.
511                    raise
512                total += child_ticks / ticks
513    return total
514
515
516def _cpu_now() -> float:
517    """CPU seconds for this process and reaped children, plus live descendants on Linux."""
518    s = resource.getrusage(resource.RUSAGE_SELF)
519    c = resource.getrusage(resource.RUSAGE_CHILDREN)
520    cpu_sec = s.ru_utime + s.ru_stime + c.ru_utime + c.ru_stime
521    if sys.platform == "linux":
522        cpu_sec += _live_child_cpu_sec(os.getpid())
523    return cpu_sec
524
525
526def _peak_rss_mb() -> float:
527    """Peak RSS (self + reaped children) in MB (``ru_maxrss`` is KiB on Linux)."""
528    s = resource.getrusage(resource.RUSAGE_SELF)
529    c = resource.getrusage(resource.RUSAGE_CHILDREN)
530    return (s.ru_maxrss + c.ru_maxrss) / 1024
531
532
533def _isolated_worker(
534    kind: str,
535    size: int,
536    transport: str,
537    payload_nbytes: int,
538    num_items: int,
539    buffer_size: int,
540    runs: int,
541    vb: bytes | None,
542    q: "mp.Queue[_IsolatedResult]",
543) -> None:
544    """Run one config in this fresh process; report samples + CPU + peak RSS.
545
546    Run as the target of a freshly-spawned process. Because the process starts
547    clean and exits after one config, the measurements attribute resources to
548    *this* config alone — a single long-lived process accumulates them across
549    configs and cannot separate them, which is the whole point of ``--isolate``.
550    CPU is measured over the timed passes only (excludes this worker's and the
551    producer's import/startup cost); peak RSS is the growth from a baseline taken
552    before the arena and payloads are built. The video bytes are encoded in the
553    parent and passed in, so the encoder's footprint does not land in this peak.
554    """
555    try:
556        rss_base = _peak_rss_mb()
557        usage: list[float] = []
558        dataset = _Dataset(kind, size, num_items, vb)
559        samples = run_transport(
560            dataset,
561            transport,
562            payload_nbytes=payload_nbytes,
563            num_items=num_items,
564            buffer_size=buffer_size,
565            runs=runs,
566            usage=usage,
567        )
568        cpu = usage[0] if usage else 0.0
569        q.put(("ok", samples, cpu, _peak_rss_mb() - rss_base))
570    except Exception as e:  # surface failure instead of hanging the parent
571        q.put(("err", f"{type(e).__name__}: {e}", 0.0, 0.0))
572
573
574def _run_isolated(
575    mp_ctx: "mp.context.BaseContext",
576    kind: str,
577    size: int,
578    transport: str,
579    payload_nbytes: int,
580    num_items: int,
581    buffer_size: int,
582    runs: int,
583    vb: bytes | None,
584) -> tuple[list[float], float, float]:
585    """Run ``_isolated_worker`` in a fresh process; return ``(samples, cpu, rss)``."""
586    q: "mp.Queue[_IsolatedResult]" = mp_ctx.Queue()
587    context = mp_ctx
588    p = context.Process(  # type: ignore[attr-defined]
589        target=_isolated_worker,
590        args=(
591            kind,
592            size,
593            transport,
594            payload_nbytes,
595            num_items,
596            buffer_size,
597            runs,
598            vb,
599            q,
600        ),
601    )
602    p.start()
603    status, payload, cpu, rss = q.get()
604    p.join()
605    if status != "ok":
606        raise RuntimeError(str(payload))
607    return payload, cpu, rss  # type: ignore[return-value]
608
609
610def _run_config_isolated(
611    size_mb: int, kind: str, args: argparse.Namespace, mp_ctx: "mp.context.BaseContext"
612) -> list[Row]:
613    """Benchmark one (size, kind), each transport in its own fresh process.
614
615    Per-process isolation is what makes the CPU-time and peak-RSS columns
616    meaningful: each transport's footprint is measured from a clean slate, so the
617    arena's shared-memory cost and the no-arena pickle/copy cost are attributable
618    rather than piled into one accumulating process.
619    """
620    size = size_mb << 20
621    # Encode in the parent so the (large) encoder footprint stays out of the
622    # per-config worker's peak RSS.
623    vb = create_video_data(size) if kind == "packets" else None
624    payload_nbytes = _payload_nbytes(kind, size, vb)
625    factor = payload_nbytes / 1e6  # items/s -> MB/s
626    # First pass: measure each transport in its own process.
627    measured: list[tuple[str, float, float, float, float, float]] = []
628    for transport in args.transports:
629        samples, cpu, rss = _run_isolated(
630            mp_ctx,
631            kind,
632            size,
633            transport,
634            payload_nbytes,
635            args.num_items,
636            args.buffer_size,
637            args.runs,
638            vb,
639        )
640        mean = statistics.mean(samples)
641        lo, hi = _confidence_interval(samples)
642        measured.append((transport, mean, lo, hi, cpu, rss))
643    # Second pass: resolve the no-arena baseline after every transport is measured,
644    # so speedup is order-independent (and defaults to 1.0 when no-arena was not
645    # among --transports).
646    baseline = next((m for (t, m, *_rest) in measured if t == "no-arena"), 0.0)
647    return [
648        Row(
649            size_mb=size_mb,
650            kind=kind,
651            transport=transport,
652            items_per_s=mean,
653            mb_per_s=mean * factor,
654            mb_per_s_lo=lo * factor,
655            mb_per_s_hi=hi * factor,
656            speedup=mean / baseline if baseline else 1.0,
657            peak_rss_mb=rss,
658            cpu_sec=cpu,
659        )
660        for transport, mean, lo, hi, cpu, rss in measured
661    ]
662
663
664def _table_header() -> str:
665    """Header for the pivoted table (one transport column group per row)."""
666    return f"{'kind':<8} {'size':>5} {'no-arena':>9} {'ring':>15} {'pool':>15}"
667
668
669def _cell(
670    idx: dict[tuple[int, str, str], Row], size_mb: int, kind: str, transport: str
671) -> str:
672    """MB/s for one (size, kind, transport), with speedup in (x); ``-`` if not run."""
673    r = idx.get((size_mb, kind, transport))
674    if r is None:
675        return "-"
676    if transport == "no-arena":
677        return f"{r.mb_per_s:.0f}"
678    return f"{r.mb_per_s:.0f} ({r.speedup:.2f}x)"
679
680
681def _table_row(idx: dict[tuple[int, str, str], Row], size_mb: int, kind: str) -> str:
682    """One pivoted row: no-arena/ring/pool MB/s, with ring/pool speedup in (x)."""
683    na = _cell(idx, size_mb, kind, "no-arena")
684    ring = _cell(idx, size_mb, kind, "ring")
685    pool = _cell(idx, size_mb, kind, "pool")
686    return f"{kind:<8} {size_mb:>4}M {na:>9} {ring:>15} {pool:>15}"
687
688
689def _print_table(rows: list[Row]) -> None:
690    """Print one row per (size, kind); transports are columns (MB/s, speedup)."""
691    idx = {(r.size_mb, r.kind, r.transport): r for r in rows}
692    keys = sorted(
693        {(r.size_mb, r.kind) for r in rows},
694        key=lambda k: (_KINDS.index(k[1]), k[0]),
695    )
696    header = _table_header()
697    print(header)
698    print("-" * len(header))
699    for size_mb, kind in keys:
700        print(_table_row(idx, size_mb, kind))
701    print("(throughput in MB/s; (Nx) = speedup over the no-arena baseline)")
702
703
704def _print_isolate_table(rows: list[Row]) -> None:
705    """One row per (size, kind, transport): throughput, CPU time, peak RSS.
706
707    Used for ``--isolate`` runs, where CPU and RSS are per-config (each transport
708    ran in its own process).
709    """
710    rows = sorted(
711        rows,
712        key=lambda r: (_KINDS.index(r.kind), r.size_mb, _TRANSPORTS.index(r.transport)),
713    )
714    header = (
715        f"{'kind':<8} {'size':>5} {'transport':<9} {'recv MB/s':>10} "
716        f"{'speedup':>8} {'CPU s':>7} {'peak RSS MB':>12}"
717    )
718    print(header)
719    print("-" * len(header))
720    for r in rows:
721        print(
722            f"{r.kind:<8} {r.size_mb:>4}M {r.transport:<9} {r.mb_per_s:>10.0f} "
723            f"{r.speedup:>7.2f}x {r.cpu_sec:>7.1f} {r.peak_rss_mb:>12.0f}"
724        )
725    print(
726        "(recv MB/s with speedup vs no-arena; CPU s and peak RSS are per-config, "
727        "lower is better)"
728    )
729
730
731def write_csv(rows: list[Row], path: str) -> None:
732    """Write benchmark rows to ``path`` as CSV (one column per :class:`Row` field)."""
733    names = [f.name for f in fields(Row)]
734    with open(path, "w", newline="") as f:
735        writer = csv.DictWriter(f, fieldnames=names)
736        writer.writeheader()
737        writer.writerows(asdict(r) for r in rows)
738    print(f"wrote {len(rows)} rows to {path}")
739
740
741def read_csv(path: str) -> list[Row]:
742    """Read benchmark rows written by :py:func:`write_csv`."""
743    with open(path, newline="") as f:
744        return [
745            Row(
746                size_mb=int(d["size_mb"]),
747                kind=d["kind"],
748                transport=d["transport"],
749                items_per_s=float(d["items_per_s"]),
750                mb_per_s=float(d["mb_per_s"]),
751                mb_per_s_lo=float(d["mb_per_s_lo"]),
752                mb_per_s_hi=float(d["mb_per_s_hi"]),
753                speedup=float(d["speedup"]),
754                peak_rss_mb=float(d.get("peak_rss_mb") or 0.0),
755                cpu_sec=float(d.get("cpu_sec") or 0.0),
756            )
757            for d in csv.DictReader(f)
758        ]
759
760
761def _parse_args() -> argparse.Namespace:
762    parser = argparse.ArgumentParser(
763        description="Arena transport throughput: regular IPC vs ring vs pool"
764    )
765    parser.add_argument("--num-items", type=int, default=300)
766    parser.add_argument("--buffer-size", type=int, default=3)
767    parser.add_argument(
768        "--sizes", type=int, nargs="+", default=[2, 8, 32], help="payload sizes (MiB)"
769    )
770    parser.add_argument("--runs", type=int, default=3)
771    parser.add_argument(
772        "--kinds",
773        nargs="+",
774        choices=_KINDS,
775        default=list(_KINDS),
776        help="payload types to benchmark",
777    )
778    parser.add_argument(
779        "--transports",
780        nargs="+",
781        choices=_TRANSPORTS,
782        default=list(_TRANSPORTS),
783        help="transports to benchmark (use one at a time to isolate host stats)",
784    )
785    parser.add_argument(
786        "--duration-sec",
787        type=float,
788        default=0.0,
789        help="if >0, run each (transport, kind, size) for this long instead of "
790        "--runs passes — for sustained host-stat sampling by an external sampler",
791    )
792    parser.add_argument(
793        "--gap-sec",
794        type=float,
795        default=0.0,
796        help="idle seconds inserted between transports, to separate per-transport "
797        "windows for once-per-minute host-stat sampling",
798    )
799    parser.add_argument(
800        "--isolate",
801        action="store_true",
802        help="run each (size, kind, transport) in its own fresh process and report "
803        "per-config CPU time and peak RSS (clean memory/CPU attribution, no "
804        "carryover between configs)",
805    )
806    parser.add_argument("--output", help="optional path to write results as CSV")
807    return parser.parse_args()
808
809
810def main() -> None:
811    """Sweep payload sizes x types x transports; print a table and optionally a CSV."""
812    args = _parse_args()
813    # spawn (not fork) so each isolated worker starts from a clean interpreter,
814    # giving comparable per-config peak RSS rather than inheriting the parent's.
815    mp_ctx = mp.get_context("spawn") if args.isolate else None
816    rows: list[Row] = []
817    for size_mb, kind in product(args.sizes, args.kinds):
818        try:
819            if mp_ctx is not None:
820                rows.extend(_run_config_isolated(size_mb, kind, args, mp_ctx))
821            else:
822                rows.extend(_run_config(size_mb, kind, args))
823        except (OSError, RuntimeError) as e:
824            # Building a kind's payload (e.g. encoding the packets clip) can fail
825            # on some hosts; skip that kind rather than abort the whole sweep.
826            print(f"### skip {kind} {size_mb}M: {type(e).__name__}: {e}", flush=True)
827    if args.isolate:
828        _print_isolate_table(rows)
829    else:
830        _print_table(rows)
831    if args.output:
832        write_csv(rows, args.output)
833
834
835if __name__ == "__main__":
836    main()

API Reference

Functions

create_video_data(target_bytes: int, duration_seconds: float = 2.0) → bytes[source]

Generate an H.264 MP4 whose stream is approximately target_bytes.

Encodes low-entropy frames at a constant target bitrate (x264 CBR, which pads with filler to hold the rate), so the serialized VideoPackets payload scales with the requested size rather than collapsing to the content’s natural compressed size. Uses spdl.io’s in-process encoder rather than the ffmpeg CLI, so it also works on minimal container images that do not ship the CLI.

Parameters:
  • target_bytes – Desired size of the encoded video stream, in bytes.

  • duration_seconds – Clip duration; the bitrate is derived from it.

Returns:

The encoded MP4 file contents as raw bytes.

main() → None[source]

Sweep payload sizes x types x transports; print a table and optionally a CSV.

read_csv(path: str) → list[Row][source]

Read benchmark rows written by write_csv().

run_transport(dataset: _Dataset, transport: str, *, payload_nbytes: int, num_items: int, buffer_size: int, runs: int, duration_sec: float = 0.0, usage: list[float] | None = None) → list[float][source]

Run the backend pipeline once per timed pass; return per-pass items/second.

Builds a one-stage backend pipeline (source -> sink) that runs in a subprocess via run_pipeline_in_subprocess(), ships its items to the main process over transport, and consumes them in a no-op loop. One warmup pass is discarded; the per-pass throughput of each timed pass is returned so the caller can summarize it (mean + confidence interval). The subprocess and arena are reused across passes and torn down at the end.

Parameters:
  • dataset – The (picklable) backend data source.

  • transport – One of "no-arena", "ring", "pool".

  • payload_nbytes – On-the-wire size of one payload, used to size the arena.

  • num_items – Number of items per pass (must match dataset.num_items).

  • buffer_size – Pipeline sink buffer size / arena in-flight unit count.

  • runs – Number of timed passes (used when duration_sec is not positive).

  • duration_sec – If positive, keep running timed passes until this many seconds have elapsed instead of stopping after runs passes — used for sustained, fixed-duration host-stat sampling by an external sampler.

  • usage – If given, one element is appended: the CPU seconds (user + system, this process + the producer subprocess) spent across the timed passes. The snapshot is taken after the warmup pass, so process-startup and import costs are excluded and only the transport’s per-item work counts.

Returns:

One throughput sample (items per second) per timed pass.

write_csv(rows: list[Row], path: str) → None[source]

Write benchmark rows to path as CSV (one column per Row field).

Classes

class Row[source]

One benchmark measurement: throughput for a (size, kind, transport).

cpu_sec: float = 0.0

Total CPU seconds (user + system, consumer + producer) the config consumed. Only populated by --isolate; 0 otherwise. Lower is better — moving a payload via the arena should cost less CPU than the pickle + copy of plain IPC.

items_per_s: float

Mean items received per second over the timed passes.

kind: str

"bytes", "numpy", "torch", or "packets".

Type:

Payload kind

mb_per_s: float

Mean payload throughput in MB/s (items_per_s x payload bytes).

mb_per_s_hi: float

Upper bound of the ~95% confidence interval of mb_per_s.

mb_per_s_lo: float

Lower bound of the ~95% confidence interval of mb_per_s (normal approximation over the timed passes).

peak_rss_mb: float = 0.0

Peak resident memory of the config’s process tree (consumer + producer), in MB. Only populated by --isolate; 0 otherwise. Shared arena pages may be counted in both processes, so treat it as an upper-bound proxy and compare within a (size, kind) row across transports.

size_mb: int

Requested payload size in MiB (the sweep knob).

speedup: float

items_per_s relative to the no-arena baseline for this (size, kind).

transport: str

"no-arena", "ring", or "pool".

Type:

Transport used