Benchmark pinned arena¶
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
8r"""Benchmarking shared-arena memory pinning
9========================================
10
11Compare a reusable pool and FIFO ring with ``pin_memory=False`` and ``True``.
12Pinned receiving memory can avoid an extra CPU staging copy before H2D.
13See :doc:`/optimization_techniques/shared_memory_arenas` for arena usage.
14
15Reference results
16-----------------
17
18Historical 8-MiB FP32 Torch batches, with three fresh-process repetitions per
19arm in one resource-matched GPU allocation and 256 fully checked batches per
20trial, gave the following results.
21
22.. image:: /_static/data/pinned_arena_8mib.png
23 :alt: Checked 8 MiB throughput, H2D helper time and CPU cost
24
25.. list-table:: Historical pageable versus pinned throughput
26 :header-rows: 1
27
28 * - Backend
29 - Pageable items/s
30 - Pinned items/s
31 - Pinned / pageable
32 * - Pool
33 - 137.09 ± 0.39
34 - 184.14 ± 5.73
35 - 1.343
36 * - Ring
37 - 104.06 ± 5.96
38 - 149.42 ± 5.83
39 - 1.436
40
41Mean ± sample SD, not confidence intervals. The checked end-to-end workflow
42includes generation, transport, synchronized H2D and full GPU verification;
43H2D helper wall time is not pure DMA.
44
45These numbers and the figure describe an earlier workflow, not a fresh run of
46the current public four-arm benchmark. The figure includes additional IPC and
47copy-out controls. Pinned ring output uses a different owning copy-out allocation,
48so its gain cannot be attributed to page locking alone.
49
50Pinning helped this workload but consumes page-locked host memory. Compare the
51end-to-end trade-off in your application; this is not a training-speed promise.
52"""
53
54from __future__ import annotations
55
56import argparse
57import gc
58import hashlib
59import inspect
60import json
61import math
62import multiprocessing as mp
63import os
64import platform
65import statistics
66import sys
67import time
68from collections.abc import Callable, Iterable, Iterator, Mapping
69from functools import partial
70from itertools import product
71from pathlib import Path
72from tempfile import TemporaryDirectory
73from typing import Any
74
75import numpy as np
76import torch
77from spdl.io import transfer_tensor_h2d
78from spdl.pipeline import (
79 iterate_in_subprocess,
80 SharedMemoryRingBuffer,
81 SharedMemorySegmentPool,
82)
83
84__all__ = [
85 "configure_process",
86 "make_payload",
87 "produce_payloads",
88 "verify_payload",
89 "restore_payload",
90 "transfer_payload",
91 "process_item",
92 "run_pass",
93 "run_benchmark",
94 "run_isolated",
95 "main",
96]
97
98_ARMS = (
99 "pool-pageable",
100 "pool-pinned",
101 "ring-pageable",
102 "ring-pinned",
103)
104_CPU_ARMS = ("pool-pageable", "ring-pageable")
105_DTYPES = {"fp32": ("float32", 4), "fp16": ("float16", 2), "uint8": ("uint8", 1)}
106_SCHEMA = "public-iterate-v1"
107_RETIRED_FLAGS = (
108 "--runtime-checks",
109 "--trace-dir",
110 "--threshold",
111 "--seam",
112 "--retain-items",
113 "--consumer-delay",
114 "--sample-interval",
115)
116
117
118def configure_process() -> None:
119 """Select one Torch CPU thread in each process before benchmark setup/timing.
120
121 Use this as the public subprocess initializer, not at module import time.
122 It does not initialize CUDA or change another process's thread count.
123
124 Example:
125 >>> configure_process()
126 >>> torch.get_num_threads()
127 1
128 """
129 torch.set_num_threads(1)
130
131
132def _pattern(count: int, sequence: int, leaf: int) -> bytes:
133 shift = (sequence * 17 + leaf * 29) % 251
134 cycle = bytes((i + shift) % 251 for i in range(251))
135 return (cycle * ((count + 250) // 251))[:count]
136
137
138def _leaf_sizes(size: int, kind: str, dtype: str) -> list[int]:
139 elements = max(1, size // _DTYPES[dtype][1])
140 if kind != "nested":
141 return [elements]
142 first = max(1, elements // 2)
143 return [first, max(1, elements - first), 3]
144
145
146def make_payload(size: int, kind: str, dtype: str, sequence: int) -> Any:
147 """Create fresh deterministic CPU data, including for independent verification.
148
149 Args:
150 size: Positive requested byte budget. Leaf lengths are dtype-rounded;
151 a nested payload also includes a three-element leaf.
152 kind: ``torch``, ``numpy`` or a ``nested`` dictionary/list/tuple tensor tree.
153 dtype: ``fp32``, ``fp16`` or ``uint8``.
154 sequence: Nonnegative item identity incorporated into every leaf.
155
156 Returns:
157 A CPU tensor, NumPy array or nested CPU tensor tree; no CUDA storage.
158
159 Example:
160 >>> make_payload(8192, 'torch', 'fp32', sequence=1).numel()
161 2048
162 """
163 if size <= 0 or sequence < 0 or kind not in ("torch", "numpy", "nested"):
164 raise ValueError("invalid payload size, sequence or kind")
165 if dtype not in _DTYPES:
166 raise ValueError("unsupported dtype")
167 arrays = [
168 np.frombuffer(_pattern(n, sequence, i), dtype=np.uint8)
169 .astype(_DTYPES[dtype][0])
170 .reshape(-1)
171 for i, n in enumerate(_leaf_sizes(size, kind, dtype))
172 ]
173 leaves: list[np.ndarray] | list[torch.Tensor]
174 if kind == "numpy":
175 leaves = arrays
176 else:
177 leaves = [torch.from_numpy(a) for a in arrays]
178 if kind == "nested":
179 return {"main": leaves[0], "nested": [leaves[1], (leaves[2],)]}
180 return leaves[0]
181
182
183def _map_leaves(batch: Any, fn: Callable[[Any], Any]) -> Any:
184 if isinstance(batch, dict):
185 return {key: _map_leaves(value, fn) for key, value in batch.items()}
186 if isinstance(batch, list):
187 return [_map_leaves(value, fn) for value in batch]
188 if isinstance(batch, tuple):
189 return tuple(_map_leaves(value, fn) for value in batch)
190 return fn(batch)
191
192
193def _leaves(batch: Any) -> Iterator[Any]:
194 if isinstance(batch, Mapping):
195 for value in batch.values():
196 yield from _leaves(value)
197 elif isinstance(batch, (list, tuple)):
198 for value in batch:
199 yield from _leaves(value)
200 else:
201 yield batch
202
203
204class _Payloads:
205 def __init__(self, config: dict[str, Any], worker: int) -> None:
206 self.config = config
207 self.worker = worker
208 self.epoch = 0
209
210 def __iter__(self) -> Iterator[dict[str, Any]]:
211 config, epoch = self.config, self.epoch
212 self.epoch += 1
213 for index in range(config["items"]):
214 if torch.cuda.is_initialized():
215 raise AssertionError("producer initialized CUDA")
216 sequence = (epoch * config["workers"] + self.worker) * config[
217 "items"
218 ] + index
219 start, cpu_start = time.perf_counter(), time.process_time()
220 payload = make_payload(
221 config["size"], config["kind"], config["dtype"], sequence
222 )
223 yield {
224 "sequence": sequence,
225 "worker": self.worker,
226 "epoch": epoch,
227 "payload": payload,
228 "producer": {
229 "pid": os.getpid(),
230 "generation_s": time.perf_counter() - start,
231 "generation_cpu_s": time.process_time() - cpu_start,
232 "cuda_initialized": torch.cuda.is_initialized(),
233 "cpu_threads": torch.get_num_threads(),
234 },
235 }
236 del payload
237 if torch.cuda.is_initialized():
238 raise AssertionError("producer initialized CUDA during production")
239
240
241def produce_payloads(
242 config: dict[str, Any], worker: int = 0
243) -> Iterable[dict[str, Any]]:
244 """Return a pickle-safe, reiterable CPU source for a public subprocess boundary.
245
246 Args:
247 config: ``size``, ``kind``, ``dtype``, ``items`` per epoch and ``workers``.
248 worker: Producer index in ``[0, workers)``.
249
250 Returns:
251 A reiterable source, not a single-use generator. Each epoch produces fresh
252 values and globally distinct sequence identifiers. Rows include generation
253 wall/CPU time and the producer's CUDA-uninitialized/thread-count receipt.
254 Pass ``configure_process`` as the boundary's initializer.
255
256 Example:
257 >>> cfg = dict(size=8192, kind='torch', dtype='fp32', items=2, workers=1)
258 >>> source = produce_payloads(cfg)
259 >>> [row['sequence'] for row in source]
260 [0, 1]
261 >>> [row['sequence'] for row in source]
262 [2, 3]
263 """
264 if config["items"] <= 0 or not 0 <= worker < config["workers"]:
265 raise ValueError("invalid producer item count or index")
266 return _Payloads(config, worker)
267
268
269def restore_payload(batch: Any) -> tuple[Any, dict[str, float]]:
270 """Prepare already-restored public boundary outputs as CPU tensor leaves.
271
272 No serialized blobs, registry or reader endpoints are accepted here. Arena
273 restoration belongs entirely to ``iterate_in_subprocess``.
274
275 Args:
276 batch: Tensor/array/tree already yielded by the public iterable.
277
278 Returns:
279 ``(tensor_batch, phases)``; phases measure only NumPy-to-Torch/tree
280 preparation, not the preceding transport or arena restoration.
281
282 Example:
283 >>> batch, phases = restore_payload(make_payload(16, 'numpy', 'fp32', 0))
284 >>> batch.numel()
285 4
286 """
287 start, cpu_start = time.perf_counter(), time.process_time()
288 result = _map_leaves(
289 batch,
290 lambda leaf: torch.from_numpy(leaf) if isinstance(leaf, np.ndarray) else leaf,
291 )
292 return result, {
293 "preparation_s": time.perf_counter() - start,
294 "preparation_cpu_s": time.process_time() - cpu_start,
295 }
296
297
298def _verify_tree(actual: Any, expected: Any, device: str, sequence: int) -> None:
299 if isinstance(expected, dict):
300 if not isinstance(actual, dict) or actual.keys() != expected.keys():
301 raise AssertionError("payload structure mismatch")
302 for key in expected:
303 _verify_tree(actual[key], expected[key], device, sequence)
304 elif isinstance(expected, (list, tuple)):
305 if type(actual) is not type(expected) or len(actual) != len(expected):
306 raise AssertionError("payload structure mismatch")
307 for value, target in zip(actual, expected, strict=True):
308 _verify_tree(value, target, device, sequence)
309 else:
310 if not isinstance(actual, torch.Tensor) or actual.device.type != device:
311 raise AssertionError("payload device/type mismatch")
312 if actual.dtype != expected.dtype or actual.shape != expected.shape:
313 raise AssertionError("payload shape/dtype mismatch")
314 if not torch.equal(actual.cpu(), expected):
315 raise AssertionError(
316 f"entire payload value mismatch for sequence {sequence}"
317 )
318
319
320def verify_payload(
321 batch: Any, size: int, kind: str, dtype: str, sequence: int, *, device: str = "cpu"
322) -> None:
323 """Check structure, dtype, shape, device and every value against fresh CPU data.
324
325 Args:
326 batch: Prepared tensor/tree to check, on CPU or CUDA.
327 size: Requested payload byte budget.
328 kind: Original ``torch``, ``numpy`` or ``nested`` payload kind.
329 dtype: Original ``fp32``, ``fp16`` or ``uint8`` dtype.
330 sequence: Expected producer item identity.
331 device: Required leaf device type, ``cpu`` or ``cuda``.
332
333 Raises:
334 AssertionError: Structure, layout, device or any value differs.
335
336 Example:
337 >>> batch = make_payload(8192, 'torch', 'fp32', 1)
338 >>> verify_payload(batch, 8192, 'torch', 'fp32', 1)
339 """
340 expected, _ = restore_payload(make_payload(size, kind, dtype, sequence))
341 _verify_tree(batch, expected, device, sequence)
342
343
344def transfer_payload(batch: Any) -> tuple[Any, dict[str, Any]]:
345 """Use only the public synchronized H2D helper, with its cache disabled.
346
347 Args:
348 batch: CPU tensor or supported tensor tree.
349
350 Returns:
351 ``(gpu_batch, phases)`` with measured helper completion wall/process-CPU
352 time only. Unmeasured internal pin/copy/stream phases are omitted.
353
354 Example:
355 On a CUDA consumer, call ``gpu, phases = transfer_payload(cpu_batch)``.
356 """
357 start, cpu_start = time.perf_counter(), time.process_time()
358 result = transfer_tensor_h2d(batch, num_caches=0)
359 return result, {
360 "host_h2d_completion_s": time.perf_counter() - start,
361 "helper_cpu_s": time.process_time() - cpu_start,
362 }
363
364
365def process_item(item: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
366 """Prepare, optionally transfer, and fully verify one public output.
367
368 Args:
369 item: Producer row already restored by the public subprocess iterable.
370 config: Payload settings and ``device`` (``cpu`` or ``cuda``).
371
372 Returns:
373 Scalar/list receipts only, with no retained tensors. Every arm uses this
374 identical consumer workflow. Source pinning is reported per leaf,
375 including small inline/pageable leaves.
376
377 Raises:
378 AssertionError: Producer CUDA/thread receipt or full value check fails.
379
380 Example:
381 Use this with rows from ``iterate_in_subprocess(produce_factory)``.
382 """
383 producer = item["producer"]
384 if producer["cuda_initialized"] or producer["cpu_threads"] != 1:
385 raise AssertionError("producer must use one CPU thread without CUDA")
386 batch, phases = restore_payload(item["payload"])
387 nbytes = sum(leaf.numel() * leaf.element_size() for leaf in _leaves(batch))
388 pinned = [leaf.is_pinned() for leaf in _leaves(batch)]
389 h2d: dict[str, Any] = {
390 "host_h2d_completion_s": None,
391 "helper_cpu_s": None,
392 }
393 checked = batch
394 if config["device"] == "cuda":
395 checked, h2d = transfer_payload(batch)
396 start = time.perf_counter()
397 verify_payload(
398 checked,
399 config["size"],
400 config["kind"],
401 config["dtype"],
402 item["sequence"],
403 device=config["device"],
404 )
405 return {
406 "sequence": item["sequence"],
407 "worker": item["worker"],
408 "epoch": item["epoch"],
409 "producer": producer,
410 "payload_bytes": nbytes,
411 **phases,
412 **h2d,
413 "verify_s": time.perf_counter() - start,
414 "source_is_pinned": pinned,
415 }
416
417
418def run_pass(
419 sources: Iterable[Iterable[dict[str, Any]]], config: dict[str, Any]
420) -> dict[str, Any]:
421 """Run one whole checked epoch, consuming producers in round-robin order.
422
423 Args:
424 sources: One public subprocess iterable per producer, already initialized.
425 config: Payload, per-producer ``items``, worker count and device settings.
426
427 Returns:
428 Epoch wall/consumer CPU time and per-item receipts. Wall includes epoch
429 command dispatch, generation, public transport/restore, preparation,
430 synchronized H2D if selected, full verification and final epoch completion.
431 ``next_output_s`` combines waiting, transport and restoration; it is not
432 an internal read/copy/registration timer. No payloads are retained.
433
434 Example:
435 Call once for warmup and again on the same sources for measured work.
436 """
437 iterators = [iter(source) for source in sources]
438 if len(iterators) != config["workers"]:
439 raise ValueError("one public boundary is required per producer")
440 rows = []
441 start, cpu_start = time.perf_counter(), time.process_time()
442 for _ in range(config["items"]):
443 for worker, iterator in enumerate(iterators):
444 fetch_start = time.perf_counter()
445 item = next(iterator)
446 fetch_s = time.perf_counter() - fetch_start
447 if item["worker"] != worker:
448 raise AssertionError("producer identity mismatch")
449 row = process_item(item, config)
450 row["next_output_s"] = fetch_s
451 rows.append(row)
452 del item
453 sentinel = object()
454 for iterator in iterators:
455 if next(iterator, sentinel) is not sentinel:
456 raise AssertionError("producer yielded too many items")
457 return {
458 "wall_s": time.perf_counter() - start,
459 "consumer_cpu_s": time.process_time() - cpu_start,
460 "items": rows,
461 }
462
463
464def _memory_sample() -> dict[str, Any]:
465 result: dict[str, Any] = {"consumer_pss_bytes": None, "tmpfs_available_bytes": None}
466 try:
467 for line in Path("/proc/self/smaps_rollup").read_text().splitlines():
468 if line.startswith("Pss:"):
469 result["consumer_pss_bytes"] = int(line.split()[1]) * 1024
470 except (FileNotFoundError, PermissionError, ProcessLookupError):
471 pass
472 try:
473 fs = os.statvfs("/dev/shm")
474 result["tmpfs_available_bytes"] = fs.f_bavail * fs.f_frsize
475 except (FileNotFoundError, PermissionError):
476 pass
477 return result
478
479
480def _source_receipt() -> dict[str, Any]:
481 module = sys.modules[__name__]
482 try:
483 source = inspect.getsource(module).encode("utf-8")
484 except (OSError, TypeError):
485 source = None
486 return {
487 "benchmark_sha256": hashlib.sha256(source).hexdigest()
488 if source is not None
489 else None,
490 "hash_scope": "benchmark_source_utf8",
491 "cuda_initialized": torch.cuda.is_initialized(),
492 "python": platform.python_version(),
493 "torch": str(torch.__version__),
494 "numpy": np.__version__,
495 "schema": _SCHEMA,
496 }
497
498
499def _make_arena(
500 arm: str, config: dict[str, Any]
501) -> SharedMemorySegmentPool | SharedMemoryRingBuffer:
502 unit = (
503 sum(_leaf_sizes(config["size"], config["kind"], config["dtype"]))
504 * _DTYPES[config["dtype"]][1]
505 + 512
506 )
507 pinned = arm.endswith("-pinned")
508 if arm.startswith("pool-"):
509 return SharedMemorySegmentPool(
510 segment_size=unit,
511 count=config["slots"],
512 acquire_timeout=config["timeout"],
513 pin_memory=pinned,
514 )
515 return SharedMemoryRingBuffer(
516 capacity=unit * config["slots"],
517 acquire_timeout=config["timeout"],
518 pin_memory=pinned,
519 )
520
521
522def _validate_config(arm: str, config: dict[str, Any]) -> None:
523 if arm not in _ARMS:
524 raise ValueError(f"unsupported or retired runtime arm: {arm}")
525 if config["device"] not in ("cpu", "cuda"):
526 raise ValueError("device must be cpu or cuda")
527 if config["device"] == "cpu" and arm not in _CPU_ARMS:
528 raise ValueError("pinned runtime arms require a CUDA consumer")
529 if min(config[key] for key in ("size", "items", "slots", "workers")) <= 0:
530 raise ValueError("size, items, slots and workers must be positive")
531 if config["warmup_epochs"] < 1 or config["local_rank"] < 0:
532 raise ValueError("warmup_epochs must be positive and local_rank nonnegative")
533 if not math.isfinite(config["timeout"]) or config["timeout"] <= 0:
534 raise ValueError("timeout must be finite and positive")
535 if (
536 config["kind"] not in ("torch", "numpy", "nested")
537 or config["dtype"] not in _DTYPES
538 ):
539 raise ValueError("unsupported payload kind/dtype")
540 retired = set(config).intersection(
541 ("threshold", "seam", "trace_dir", "retain_items", "consumer_delay")
542 )
543 if retired:
544 raise ValueError(f"retired internal configuration fields: {sorted(retired)}")
545
546
547def run_benchmark(arm: str, config: dict[str, Any]) -> dict[str, Any]:
548 """Run an ordinary public CPU/GPU comparison in the current consumer process.
549
550 Args:
551 arm: ``pool-pageable``, ``pool-pinned``, ``ring-pageable`` or ``ring-pinned``.
552 config: ``size``, ``kind``, ``dtype``, ``items``, ``workers``, ``slots``,
553 ``warmup_epochs``, ``timeout``, ``local_rank`` and ``device``.
554
555 Returns:
556 ``public-iterate-v1`` receipts: setup, excluded checked warmup epochs,
557 one measured epoch and throughput using only measured public metrics.
558 The consumer creates one arena per producer and transfers ownership to
559 ``iterate_in_subprocess``. That public iterable handles transport and
560 teardown. Thread/CUDA setup, warmup and finalizer cleanup are untimed.
561
562 Example:
563 >>> cfg = dict(size=8192, kind='torch', dtype='fp32', items=2, workers=1,
564 ... slots=2, warmup_epochs=1, timeout=60., local_rank=0, device='cpu')
565 >>> result = run_benchmark('pool-pageable', cfg)
566 >>> len(result['measured']['items'])
567 2
568 """
569 _validate_config(arm, config)
570 configure_process()
571 source = _source_receipt()
572 if config["device"] == "cuda":
573 os.environ["LOCAL_RANK"] = str(config["local_rank"])
574 torch.cuda.set_device(config["local_rank"])
575 sources: list[Any] = []
576 setup_start = time.perf_counter()
577 try:
578 for worker in range(config["workers"]):
579 sources.append(
580 iterate_in_subprocess(
581 partial(produce_payloads, config, worker),
582 initializer=configure_process,
583 mp_context="spawn",
584 buffer_size=config["slots"],
585 timeout=config["timeout"],
586 arena=_make_arena(arm, config),
587 )
588 )
589 setup_s = time.perf_counter() - setup_start
590 warmup = [run_pass(sources, config) for _ in range(config["warmup_epochs"])]
591 memory_before = _memory_sample()
592 measured = run_pass(sources, config)
593 return {
594 "schema": _SCHEMA,
595 "arm": arm,
596 "config": dict(config),
597 "source": source,
598 "setup_s": setup_s,
599 "warmup": warmup,
600 "measured": measured,
601 "items_per_s": len(measured["items"]) / measured["wall_s"],
602 "payload_gib_per_s": sum(row["payload_bytes"] for row in measured["items"])
603 / (1 << 30)
604 / measured["wall_s"],
605 "memory_before": memory_before,
606 "memory_after": _memory_sample(),
607 }
608 finally:
609 sources.clear()
610 gc.collect()
611
612
613def _benchmark_to_file(arm: str, config: dict[str, Any], path: str) -> None:
614 Path(path).write_text(json.dumps(run_benchmark(arm, config)), encoding="utf-8")
615
616
617def run_isolated(arm: str, config: dict[str, Any]) -> dict[str, Any]:
618 """Run one arm in a fresh spawned consumer, with fresh public producer boundaries.
619
620 Args:
621 arm: Supported runtime arm.
622 config: Settings accepted by ``run_benchmark``; ``timeout`` bounds the
623 complete isolated invocation, including setup/warmup/teardown.
624
625 Returns:
626 The consumer's JSON-compatible benchmark receipt. A temporary result file
627 conveys only the final report, never payloads or arena endpoint messages.
628
629 Raises:
630 RuntimeError: The consumer failed or did not write its final report.
631 TimeoutError: The invocation exceeded its configured total timeout.
632
633 Example:
634 Call ``run_isolated('pool-pageable', cfg)`` for fresh-process repetitions.
635 """
636 _validate_config(arm, config)
637 with TemporaryDirectory(prefix="spdl-public-pin-") as directory:
638 path = str(Path(directory) / "result.json")
639 process = mp.get_context("spawn").Process(
640 target=_benchmark_to_file, args=(arm, config, path)
641 )
642 process.start()
643 try:
644 process.join(config["timeout"])
645 if process.is_alive():
646 raise TimeoutError("isolated benchmark consumer timed out")
647 if process.exitcode != 0 or not Path(path).is_file():
648 raise RuntimeError(
649 f"isolated benchmark consumer failed: exit {process.exitcode}"
650 )
651 return json.loads(Path(path).read_text(encoding="utf-8"))
652 finally:
653 if process.is_alive():
654 process.terminate()
655 process.join(10)
656 if process.is_alive():
657 process.kill()
658 process.join(10)
659 process.close()
660
661
662def _legend() -> dict[str, str]:
663 return {
664 "protocol": (
665 "public-iterate-v1: public iterate_in_subprocess owns transport, "
666 "restoration and teardown; no private endpoint or transfer hooks."
667 ),
668 "historical": (
669 "Seven-arm fixed-8-MiB table/figure retain original-source measurements. "
670 "ring-original is retired; the changed protocol is not remeasured."
671 ),
672 "timing": (
673 "Setup and checked warmup epochs excluded. Measured epoch includes "
674 "generation, epoch dispatch/end, public transport/restore, preparation, "
675 "synchronized public H2D if selected and entire-value verification. "
676 "next_output_s combines waiting/transport/restore. Do not sum phases."
677 ),
678 "producer_cpu": (
679 "generation_cpu_s measures generation only, not total producer CPU. "
680 "consumer_cpu_s is measured-epoch process CPU, including verification."
681 ),
682 "pinning": (
683 "Per-leaf public is_pinned status is not proof of no staging. Small "
684 "inline leaves may stay pageable. Pinning is selected only through "
685 "the public arena constructor's pin_memory option."
686 ),
687 "memory": (
688 "Before/after consumer /proc PSS and host-wide /dev/shm free space; "
689 "not peaks, producer memory or registration/reservation totals."
690 ),
691 "repeats": (
692 "Fresh consumer/producers per arm/repetition, one arena per producer "
693 "and one CPU thread per process. Arms rotate per repeat. Sample SD "
694 "is null for one repeat; these are not independent GPU allocations."
695 ),
696 }
697
698
699def _parse_args(argv: list[str] | None) -> argparse.Namespace:
700 argv = list(sys.argv[1:] if argv is None else argv)
701 parser = argparse.ArgumentParser(
702 description="Public subprocess pinned-arena comparison"
703 )
704 retired = [
705 flag
706 for flag in _RETIRED_FLAGS
707 if any(value.split("=", 1)[0] == flag for value in argv)
708 ]
709 if retired:
710 parser.error(
711 f"retired internal benchmark flags: {', '.join(retired)}; "
712 "lifecycle tests remain in the library test suite"
713 )
714 parser.add_argument(
715 "--self-test",
716 action="store_true",
717 help="bounded checked public CPU workflows, not a performance sweep",
718 )
719 parser.add_argument(
720 "--source-receipt",
721 action="store_true",
722 help="benchmark source identity only; no private library/package probes",
723 )
724 parser.add_argument("--device", choices=("cpu", "cuda"), default="cuda")
725 parser.add_argument("--arms", nargs="+", choices=_ARMS)
726 parser.add_argument(
727 "--sizes",
728 nargs="+",
729 type=int,
730 default=[8],
731 help="requested MiB; overridden by --sizes-bytes",
732 )
733 parser.add_argument("--sizes-bytes", nargs="+", type=int)
734 parser.add_argument(
735 "--kinds", nargs="+", choices=("torch", "numpy", "nested"), default=["torch"]
736 )
737 parser.add_argument("--dtypes", nargs="+", choices=tuple(_DTYPES), default=["fp32"])
738 parser.add_argument("--workers", type=int, default=1)
739 parser.add_argument("--slots", type=int, default=4)
740 parser.add_argument("--items", type=int, default=8, help="per producer per epoch")
741 parser.add_argument(
742 "--warmup-epochs",
743 type=int,
744 default=1,
745 help="complete checked epochs excluded from measurement",
746 )
747 parser.add_argument("--repeats", type=int, default=3)
748 parser.add_argument("--timeout", type=float, default=600.0)
749 parser.add_argument(
750 "--local-rank", type=int, default=int(os.environ.get("LOCAL_RANK", "0"))
751 )
752 parser.add_argument("--output", help="JSON report file, otherwise stdout")
753 args = parser.parse_args(argv)
754 if args.self_test:
755 args.device, args.arms = "cpu", list(_CPU_ARMS)
756 args.sizes_bytes, args.kinds, args.dtypes = (
757 [8192],
758 ["torch", "numpy", "nested"],
759 ["fp32"],
760 )
761 args.workers, args.slots, args.items, args.repeats, args.warmup_epochs = (
762 1,
763 2,
764 2,
765 1,
766 1,
767 )
768 if args.arms is None:
769 args.arms = list(_CPU_ARMS if args.device == "cpu" else _ARMS)
770 if min(args.workers, args.slots, args.items, args.warmup_epochs, args.repeats) <= 0:
771 parser.error(
772 "workers, slots, items, warmup-epochs and repeats must be positive"
773 )
774 if not math.isfinite(args.timeout) or args.timeout <= 0 or args.local_rank < 0:
775 parser.error("timeout must be finite/positive; local-rank must be nonnegative")
776 if any(size <= 0 for size in (args.sizes_bytes or args.sizes)):
777 parser.error("sizes must be positive")
778 if args.device == "cpu" and any(arm not in _CPU_ARMS for arm in args.arms):
779 parser.error("pinned runtime arms require --device cuda")
780 return args
781
782
783def _summaries(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
784 groups: dict[tuple[Any, ...], list[float]] = {}
785 for row in rows:
786 config = row["config"]
787 key = (
788 row["arm"],
789 config["size"],
790 config["kind"],
791 config["dtype"],
792 config["workers"],
793 config["device"],
794 )
795 groups.setdefault(key, []).append(row["items_per_s"])
796 return [
797 {
798 "arm": key[0],
799 "size": key[1],
800 "kind": key[2],
801 "dtype": key[3],
802 "workers": key[4],
803 "device": key[5],
804 "items_per_s_mean": statistics.mean(values),
805 "items_per_s_stdev": statistics.stdev(values) if len(values) > 1 else None,
806 "fresh_process_repeats": len(values),
807 }
808 for key, values in groups.items()
809 ]
810
811
812def main(argv: list[str] | None = None) -> None:
813 """Run the four-arm public comparison CLI or bounded CPU/source checks.
814
815 Args:
816 argv: CLI arguments, or ``None`` to read ``sys.argv``.
817
818 Returns:
819 None; writes structured JSON to ``--output`` or stdout. Reports include
820 raw per-item receipts, grouped throughput means/sample SD and scope legend.
821 ``--device cpu`` selects only unpinned public workflows. ``--self-test``
822 checks bounded CPU epochs without CUDA; ``--source-receipt`` hashes only
823 this benchmark, not private library modules or installed native packages.
824
825 Raises:
826 SystemExit: Unsupported/retired CLI flags or invalid configuration.
827 RuntimeError: A public consumer/producer workflow failed.
828
829 Example:
830 >>> main(['--device', 'cpu', '--arms', 'pool-pageable', '--sizes-bytes', '8192',
831 ... '--items', '2', '--repeats', '1', '--output', 'cpu-results.json'])
832 """
833 args = _parse_args(argv)
834 report: dict[str, object]
835 if args.source_receipt:
836 report = {"schema": _SCHEMA, "source_receipt": _source_receipt()}
837 else:
838 rows: list[dict[str, Any]] = []
839 sizes = args.sizes_bytes or [size << 20 for size in args.sizes]
840 for size, kind, dtype, repeat in product(
841 sizes, args.kinds, args.dtypes, range(args.repeats)
842 ):
843 config = {
844 "size": size,
845 "kind": kind,
846 "dtype": dtype,
847 "repeat": repeat,
848 "workers": args.workers,
849 "slots": args.slots,
850 "items": args.items,
851 "warmup_epochs": args.warmup_epochs,
852 "timeout": args.timeout,
853 "local_rank": args.local_rank,
854 "device": args.device,
855 }
856 order = (
857 args.arms[repeat % len(args.arms) :]
858 + args.arms[: repeat % len(args.arms)]
859 )
860 rows.extend(run_isolated(arm, config) for arm in order)
861 report = {
862 "schema": _SCHEMA,
863 "legend": _legend(),
864 "results": rows,
865 "summary": _summaries(rows),
866 }
867 text = json.dumps(report, indent=2, allow_nan=False)
868 if args.output:
869 Path(args.output).write_text(text + "\n", encoding="utf-8")
870 else:
871 print(text)
872
873
874if __name__ == "__main__":
875 main()
API Reference¶
Functions
- configure_process() None[source]¶
Select one Torch CPU thread in each process before benchmark setup/timing.
Use this as the public subprocess initializer, not at module import time. It does not initialize CUDA or change another process’s thread count.
Example
>>> configure_process() >>> torch.get_num_threads() 1
- make_payload(size: int, kind: str, dtype: str, sequence: int) Any[source]¶
Create fresh deterministic CPU data, including for independent verification.
- Parameters:
size – Positive requested byte budget. Leaf lengths are dtype-rounded; a nested payload also includes a three-element leaf.
kind –
torch,numpyor anesteddictionary/list/tuple tensor tree.dtype –
fp32,fp16oruint8.sequence – Nonnegative item identity incorporated into every leaf.
- Returns:
A CPU tensor, NumPy array or nested CPU tensor tree; no CUDA storage.
Example
>>> make_payload(8192, 'torch', 'fp32', sequence=1).numel() 2048
- produce_payloads(config: dict[str, Any], worker: int = 0) Iterable[dict[str, Any]][source]¶
Return a pickle-safe, reiterable CPU source for a public subprocess boundary.
- Parameters:
config –
size,kind,dtype,itemsper epoch andworkers.worker – Producer index in
[0, workers).
- Returns:
A reiterable source, not a single-use generator. Each epoch produces fresh values and globally distinct sequence identifiers. Rows include generation wall/CPU time and the producer’s CUDA-uninitialized/thread-count receipt. Pass
configure_processas the boundary’s initializer.
Example
>>> cfg = dict(size=8192, kind='torch', dtype='fp32', items=2, workers=1) >>> source = produce_payloads(cfg) >>> [row['sequence'] for row in source] [0, 1] >>> [row['sequence'] for row in source] [2, 3]
- verify_payload(batch: Any, size: int, kind: str, dtype: str, sequence: int, *, device: str = 'cpu') None[source]¶
Check structure, dtype, shape, device and every value against fresh CPU data.
- Parameters:
batch – Prepared tensor/tree to check, on CPU or CUDA.
size – Requested payload byte budget.
kind – Original
torch,numpyornestedpayload kind.dtype – Original
fp32,fp16oruint8dtype.sequence – Expected producer item identity.
device – Required leaf device type,
cpuorcuda.
- Raises:
AssertionError – Structure, layout, device or any value differs.
Example
>>> batch = make_payload(8192, 'torch', 'fp32', 1) >>> verify_payload(batch, 8192, 'torch', 'fp32', 1)
- restore_payload(batch: Any) tuple[Any, dict[str, float]][source]¶
Prepare already-restored public boundary outputs as CPU tensor leaves.
No serialized blobs, registry or reader endpoints are accepted here. Arena restoration belongs entirely to
iterate_in_subprocess.- Parameters:
batch – Tensor/array/tree already yielded by the public iterable.
- Returns:
(tensor_batch, phases); phases measure only NumPy-to-Torch/tree preparation, not the preceding transport or arena restoration.
Example
>>> batch, phases = restore_payload(make_payload(16, 'numpy', 'fp32', 0)) >>> batch.numel() 4
- transfer_payload(batch: Any) tuple[Any, dict[str, Any]][source]¶
Use only the public synchronized H2D helper, with its cache disabled.
- Parameters:
batch – CPU tensor or supported tensor tree.
- Returns:
(gpu_batch, phases)with measured helper completion wall/process-CPU time only. Unmeasured internal pin/copy/stream phases are omitted.
Example
On a CUDA consumer, call
gpu, phases = transfer_payload(cpu_batch).
- process_item(item: dict[str, Any], config: dict[str, Any]) dict[str, Any][source]¶
Prepare, optionally transfer, and fully verify one public output.
- Parameters:
item – Producer row already restored by the public subprocess iterable.
config – Payload settings and
device(cpuorcuda).
- Returns:
Scalar/list receipts only, with no retained tensors. Every arm uses this identical consumer workflow. Source pinning is reported per leaf, including small inline/pageable leaves.
- Raises:
AssertionError – Producer CUDA/thread receipt or full value check fails.
Example
Use this with rows from
iterate_in_subprocess(produce_factory).
- run_pass(sources: Iterable[Iterable[dict[str, Any]]], config: dict[str, Any]) dict[str, Any][source]¶
Run one whole checked epoch, consuming producers in round-robin order.
- Parameters:
sources – One public subprocess iterable per producer, already initialized.
config – Payload, per-producer
items, worker count and device settings.
- Returns:
Epoch wall/consumer CPU time and per-item receipts. Wall includes epoch command dispatch, generation, public transport/restore, preparation, synchronized H2D if selected, full verification and final epoch completion.
next_output_scombines waiting, transport and restoration; it is not an internal read/copy/registration timer. No payloads are retained.
Example
Call once for warmup and again on the same sources for measured work.
- run_benchmark(arm: str, config: dict[str, Any]) dict[str, Any][source]¶
Run an ordinary public CPU/GPU comparison in the current consumer process.
- Parameters:
arm –
pool-pageable,pool-pinned,ring-pageableorring-pinned.config –
size,kind,dtype,items,workers,slots,warmup_epochs,timeout,local_rankanddevice.
- Returns:
setup, excluded checked warmup epochs, one measured epoch and throughput using only measured public metrics. The consumer creates one arena per producer and transfers ownership to
iterate_in_subprocess. That public iterable handles transport and teardown. Thread/CUDA setup, warmup and finalizer cleanup are untimed.- Return type:
public-iterate-v1receipts
Example
>>> cfg = dict(size=8192, kind='torch', dtype='fp32', items=2, workers=1, ... slots=2, warmup_epochs=1, timeout=60., local_rank=0, device='cpu') >>> result = run_benchmark('pool-pageable', cfg) >>> len(result['measured']['items']) 2
- run_isolated(arm: str, config: dict[str, Any]) dict[str, Any][source]¶
Run one arm in a fresh spawned consumer, with fresh public producer boundaries.
- Parameters:
arm – Supported runtime arm.
config – Settings accepted by
run_benchmark;timeoutbounds the complete isolated invocation, including setup/warmup/teardown.
- Returns:
The consumer’s JSON-compatible benchmark receipt. A temporary result file conveys only the final report, never payloads or arena endpoint messages.
- Raises:
RuntimeError – The consumer failed or did not write its final report.
TimeoutError – The invocation exceeded its configured total timeout.
Example
Call
run_isolated('pool-pageable', cfg)for fresh-process repetitions.
- main(argv: list[str] | None = None) None[source]¶
Run the four-arm public comparison CLI or bounded CPU/source checks.
- Parameters:
argv – CLI arguments, or
Noneto readsys.argv.- Returns:
None; writes structured JSON to
--outputor stdout. Reports include raw per-item receipts, grouped throughput means/sample SD and scope legend.--device cpuselects only unpinned public workflows.--self-testchecks bounded CPU epochs without CUDA;--source-receipthashes only this benchmark, not private library modules or installed native packages.- Raises:
SystemExit – Unsupported/retired CLI flags or invalid configuration.
RuntimeError – A public consumer/producer workflow failed.
Example
>>> main(['--device', 'cpu', '--arms', 'pool-pageable', '--sizes-bytes', '8192', ... '--items', '2', '--repeats', '1', '--output', 'cpu-results.json'])