"""Comparing codec assignments on the same tensors. See DESIGN.md, "Comparison".
Every run is in memory: no file is read or written. A row's seconds are the codec's own encode and decode over the
chunks, not the cost of a real save or load; `BenchRow` says exactly what they cover and what a real save or load
adds. End-to-end save and load times belong to the experiment harness, which measures them on real files.
No memory number is reported: a `tracemalloc` peak counts mostly the payloads held, misses the memory native code
allocates, and grows with `threads`, so it does not compare codecs.
The chunks of every tensor of a role are in flight together on the pool, as `write_archive` and a read of several
tensors code them; with `threads=1` nothing runs in parallel. A tensor whose codec's `Codec.with_threads` returns a
copy (`zipnn/1` does) is the exception: it is coded alone, one chunk after another with all `threads` threads inside
each chunk, as `write_archive` and `Archive.read` run it.
"""
from __future__ import annotations
import json
import os
import platform
import subprocess
import sys
import threading
import time
import warnings
import zlib
from collections import Counter, defaultdict
from collections.abc import Iterator, Mapping, Sequence
from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import suppress
from importlib.metadata import version
from pathlib import Path
from typing import Literal, NamedTuple, TypeVar
from pydantic import BaseModel, JsonValue, model_validator
from jabara import __version__
from jabara.assign import Assigner, CodecChoice, UniformAssigner
from jabara.codecs import Codec, codec_ids, get_codec
from jabara.container import (
CHUNK_SIZE,
_chunk_lengths,
_decode_tasks,
_Decoded,
_encode_tasks,
_max_abs_diff,
_resolve,
_thread_count,
_Workers,
is_reference,
seal_chunks,
)
from jabara.errors import ChecksumError, MissingBaseError, MissingDependencyError
from jabara.types import TensorMeta, TensorRecord, as_memoryview
#: Untimed rounds that run before the timed ones. In a round, each candidate in turn encodes and then decodes once.
WARMUP_PASSES = 1
#: The largest slice of a tensor, in bytes, that the warm-up before the first row codes with each codec.
WARMUP_BYTES = 1 << 16
#: Seconds that every thread about to code a timed pass stays busy, untimed, right before the pass. See DESIGN.md,
#: "Comparison": on one machine a 100 ms load of all cores by threads of their own removed the effect of the other
#: candidates of a call on the time of two codecs, and 30 ms did not. This spin narrowed the spread of a candidate
#: measured alone there; it moved the effect of the other candidates in both directions.
SPIN_SECONDS = 0.1
OPTIONAL_PACKAGES = ("torch", "zipnn")
# What a spinning thread checksums: the buffer of the measurement behind SPIN_SECONDS. zlib.crc32 releases the GIL;
# it is bound here so that a spin never counts as one of the checksums the coding computes.
_SPIN_BUFFER = bytes(8 << 20)
_spin_crc32 = zlib.crc32
_PROBE = TensorMeta(name="probe", dtype="float32", shape=(1,))
T = TypeVar("T")
[ドキュメント]
class CodecUse(BaseModel, frozen=True, extra="forbid"):
"""A codec id and its full parameters, and how many tensors of a row it coded."""
#: The id of the codec.
codec_id: str
#: The codec's full parameters, defaults filled in.
params: dict[str, JsonValue]
#: How many tensors of the row it coded.
tensors: int
[ドキュメント]
class BenchEnvironment(BaseModel, frozen=True, extra="forbid"):
"""Where and how the numbers were taken. `load_average_1m` is read once, before the first candidate runs.
`cpu_model` is the processor name the OS reports (`None` where it reports none). `optional_packages` holds the
versions of the optional packages a codec can load (`zipnn`, `torch`) that are loaded when the run ends.
"""
#: The version of Jabara.
jabara: str
#: The Python version, as `platform.python_version()` returns it.
python: str
#: The string `platform.platform()` returns.
platform: str
#: The string `platform.machine()` returns.
machine: str
#: The processor name the OS reports; `None` when it reports none.
cpu_model: str | None
#: The number of CPUs; `None` when unknown.
cpu_count: int | None
#: The one-minute load average, read once before the first candidate runs; `None` where the OS has none.
load_average_1m: float | None
#: The size of the thread pool.
threads: int
#: How many timed runs each row has.
repeats: int
#: How many untimed passes ran before the timed runs.
warmup_passes: int
#: How long, in seconds, the threads about to code each timed pass were kept busy, untimed, right before it.
spin_seconds: float
#: The chunk size in bytes.
chunk_size: int
#: The version of NumPy.
numpy: str
#: The version of zstandard.
zstandard: str
#: The versions of the optional packages loaded when the run ends.
optional_packages: dict[str, str]
[ドキュメント]
class BenchRow(BaseModel, frozen=True, extra="forbid", ser_json_inf_nan="constants"):
"""One candidate on all tensors of one role.
`encode_seconds_all` holds each of `repeats` wall-clock runs (`time.perf_counter`), in run order, of
`Codec.encode` over every chunk of every tensor of the role, after `warmup_passes` untimed passes;
`encode_seconds` is the smallest. The chunks run as `write_archive` runs them: on the container's thread pool,
or one after another with the copy that `Codec.with_threads` returns. A run includes slicing the chunks and
the base reference and handing them to the pool or the copy, and nothing else. `decode_seconds_all` and
`decode_seconds` are the same for `Codec.decode` plus the length and CRC-32 check of each decoded chunk that
`Archive.read` also does. When any decode pass fails that check, `decode_error` holds the reader's message and
both decode fields are `None`, so a broken codec has no decode time to rank. Throughput is
`raw_bytes / seconds`. Each timed run starts right after the pool's threads and the calling thread have run a busy
loop for `BenchEnvironment.spin_seconds`; see DESIGN.md, "Comparison", for what that was observed to change.
These seconds are the codec's share of a save or load, not its cost. A real save (`write_archive`) also
computes the CRC-32 of the input, decodes the whole base tensor first when `needs_base`, decodes every chunk
once more to check it when `check_decode`, and writes the file. A real load (`Archive.read`) also decodes the
whole base tensor first when `needs_base`, and reads the file. `needs_base` is true when a tensor of the row is
coded with a delta codec; `check_decode` is true when one is coded with a lossy codec, so it is `not lossless`.
`codecs` lists each distinct codec id and full parameters (defaults filled in, as an archive index records
them) that coded the role's tensors, with the number of tensors each coded. `stored_bytes` is the sum of chunk
payload lengths from one untimed encode pass, without the archive index and magic. `lossless` is the codecs'
own claim; `bit_exact` compares the decoded bytes with the input and is false when decoding failed.
`fallback_tensors` counts the tensors for which the candidate chose a delta codec but the base had no
reference, so they were coded with the choice's `fallback`.
"""
#: The name of the candidate.
candidate: str
#: The role of the tensors the row covers.
role: str
#: The codecs that coded the role's tensors, with how many tensors each coded.
codecs: list[CodecUse]
#: The tensor bytes before coding.
raw_bytes: int
#: The sum of the chunk payload lengths from one untimed encode pass.
stored_bytes: int
#: The smallest of `encode_seconds_all`.
encode_seconds: float
#: The wall-clock seconds of each timed encode run, in run order.
encode_seconds_all: list[float]
#: The smallest of `decode_seconds_all`; `None` when a decode failed.
decode_seconds: float | None
#: The wall-clock seconds of each timed decode run; `None` when a decode failed.
decode_seconds_all: list[float] | None
#: The reader's message when a decode pass failed; otherwise `None`.
decode_error: str | None
#: True when every codec of the row is lossless.
lossless: bool
#: True when a tensor of the row is coded with a delta codec.
needs_base: bool
#: True when a tensor of the row is coded with a lossy codec, so the writer decodes each chunk to check it.
check_decode: bool
#: Whether the decoded bytes equal the input; false when decoding failed.
bit_exact: bool
#: The largest absolute difference between the decoded values and the input, recomputed from the decoded bytes; `None` when a decode failed.
max_abs_err: float | None
#: How many tensors were coded with the choice's `fallback` because the base had no reference.
fallback_tensors: int
@model_validator(mode="after")
def _timings_agree(self) -> BenchRow:
failed = self.decode_error is not None
if failed != (self.decode_seconds is None) or failed != (self.decode_seconds_all is None):
raise ValueError("a row has decode_seconds exactly when it has no decode_error")
if not self.encode_seconds_all or self.encode_seconds != min(self.encode_seconds_all):
raise ValueError("encode_seconds must be the smallest of encode_seconds_all")
if self.decode_seconds_all is not None and (
not self.decode_seconds_all or self.decode_seconds != min(self.decode_seconds_all)
):
raise ValueError("decode_seconds must be the smallest of decode_seconds_all")
if self.decode_error is not None and (self.bit_exact or self.max_abs_err is not None):
raise ValueError("a row whose decode failed is not bit_exact and has no max_abs_err")
if self.check_decode == self.lossless:
raise ValueError("the writer runs a check decode exactly when a codec of the row is lossy")
return self
[ドキュメント]
class BenchReport(BaseModel, frozen=True, extra="forbid", ser_json_inf_nan="constants"):
"""The result of `compare`: the environment of the run and one row per candidate and role. `model_dump_json()`
writes the file that the results viewer reads.
"""
#: The report version, always 1.
bench: Literal[1]
#: Where and how the numbers were taken.
environment: BenchEnvironment
#: One row per candidate and role.
rows: list[BenchRow]
class _Job(NamedTuple):
record: TensorRecord
codec: Codec
data: memoryview
lengths: list[int]
ref: memoryview | None
fell_back: bool
def _jobs(records: list[TensorRecord], assigner: Assigner, base: Mapping[str, TensorRecord] | None) -> list[_Job]:
jobs = []
for record in records:
meta = record.meta
data = as_memoryview(record.data)
if len(data) != meta.nbytes:
raise ValueError(f"tensor {meta.name!r}: got {len(data)} bytes, expected {meta.nbytes}")
other = base.get(meta.name) if base is not None else None
matches = other is not None and is_reference(other.meta, meta)
choice = assigner.choose(meta)
_, codec = _resolve(meta, choice, has_base=matches)
ref = as_memoryview(other.data) if codec.needs_ref and other is not None else None
fell_back = get_codec(choice.codec_id, choice.params).needs_ref and not codec.needs_ref
jobs.append(_Job(record, codec, data, _chunk_lengths(len(data), CHUNK_SIZE, meta.itemsize), ref, fell_back))
return jobs
def _check_reference(name: str, jobs: list[_Job]) -> None:
fell_back = sum(j.fell_back for j in jobs)
if fell_back and fell_back == sum(j.fell_back or j.codec.needs_ref for j in jobs):
raise MissingBaseError(
f"candidate {name!r}: none of its {fell_back} delta tensors has a reference in the base "
"(same name, dtype, and shape), so every one would be measured with the fallback codec"
)
def _encode(jobs: list[_Job], workers: _Workers) -> list[list[bytes]]:
"""The payloads of every chunk of every tensor of `jobs`, coded as `write_archive` codes them: the chunks of
different tensors together on the pool, or one tensor at a time with the copy `Codec.with_threads` returns.
"""
tasks = (
task
for k, j in enumerate(jobs)
for task in _encode_tasks(k, j.codec, j.record.meta, j.data, j.lengths, j.ref, workers, seal=False)
)
return _per_tensor(len(jobs), workers.ordered(tasks))
def _decode(
jobs: list[_Job], payloads: list[list[bytes]], crcs: list[list[int]], workers: _Workers
) -> list[list[_Decoded]]:
"""The decoded and checked chunks of every tensor of `jobs`, decoded as `Archive.read` decodes them."""
tasks = (
task
for k, (j, p, c) in enumerate(zip(jobs, payloads, crcs, strict=True))
for task in _decode_tasks(
k, j.codec, j.record.meta, zip(p, j.lengths, c, strict=True), j.ref, workers, j.record.meta.name
)
)
return _per_tensor(len(jobs), workers.ordered(tasks))
def _per_tensor(n: int, results: Iterator[tuple[int, list[T] | None]]) -> list[list[T]]:
out: list[list[T]] = [[] for _ in range(n)]
for k, chunks in results:
out[k] += chunks or []
return out
def _seal(jobs: list[_Job], payloads: list[list[bytes]], workers: _Workers) -> list[list[int]]:
return [
[crc for crc, _ in seal_chunks(j.codec, j.record.meta, j.data, j.lengths, p, j.ref, workers.pool)]
for j, p in zip(jobs, payloads, strict=True)
]
def _fingerprint(payloads: list[list[bytes]]) -> list[list[int]]:
return [[zlib.crc32(c) for c in p] for p in payloads]
def _warm_up(jobs: list[_Job], workers: _Workers) -> None:
"""Encode, seal, and decode a small slice once with each distinct codec, split over every pool thread, so that
no row pays for starting the pool's threads or for a codec's lazy imports (`zipnn/1` loads torch).
"""
warm: dict[tuple[str, str], _Job] = {}
for j in jobs:
itemsize = j.record.meta.itemsize
n = min(len(j.data), WARMUP_BYTES) // itemsize * itemsize
key = (j.codec.id, _params_json(j.codec))
if n and key not in warm:
lengths = _chunk_lengths(n, n // workers.threads, itemsize)
warm[key] = j._replace(data=j.data[:n], lengths=lengths, ref=j.ref[:n] if j.ref is not None else None)
for small in warm.values():
payloads = _encode([small], workers)
crcs = _seal([small], payloads, workers)
with suppress(ChecksumError): # the candidate's own row reports a failed decode
_decode([small], payloads, crcs, workers)
def _spin(seconds: float) -> None:
end = time.perf_counter() + seconds
while time.perf_counter() < end:
_spin_crc32(_SPIN_BUFFER)
def _load_threads(pool: ThreadPoolExecutor | None) -> None:
"""Keep every thread that can code the next pass busy for `SPIN_SECONDS`, all at once: each pool thread and the
calling thread, which runs a codec that has threads of its own. Without a pool only the calling thread spins, so
no thread is started where none can start (Pyodide).
"""
if pool is None:
_spin(SPIN_SECONDS)
return
# The barrier holds each task on its own pool thread until every pool thread and the caller has one. It needs
# every pool thread to exist: `compare` calls this first on its new, empty pool, where each submission starts a
# thread, and a ThreadPoolExecutor never stops one.
start = threading.Barrier(pool._max_workers + 1) # noqa: SLF001 - ThreadPoolExecutor gives its size only as _max_workers
def spin(_: int) -> None:
start.wait()
_spin(SPIN_SECONDS)
spinning: list[Future[None]] = []
try:
# Submitting is inside the `try`: a submission can raise (a refused thread, an interrupt) after earlier
# tasks already wait on the barrier, and the pool's shutdown would then wait for them forever.
spinning.extend(pool.submit(spin, i) for i in range(pool._max_workers)) # noqa: SLF001 - ThreadPoolExecutor gives its size only as _max_workers
start.wait()
except BaseException:
start.abort() # frees every task that waits on the barrier now, and fails every one that reaches it later
raise
_spin(SPIN_SECONDS)
for f in spinning:
f.result()
def _params_json(codec: Codec) -> str:
return json.dumps(codec.params.model_dump(mode="json"), sort_keys=True)
def _cpu_model() -> str | None:
system = platform.system()
try:
if system == "Darwin":
out = subprocess.run(
["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, check=True
)
return out.stdout.strip() or None
if system == "Linux":
with Path("/proc/cpuinfo").open(encoding="utf-8") as f:
for line in f:
if line.startswith("model name"):
return line.split(":", 1)[1].strip()
except (OSError, subprocess.CalledProcessError):
return None
return None
class _Run:
"""One candidate on one role while `_measure` takes its timings in rounds."""
def __init__(self, name: str, role: str, jobs: list[_Job], workers: _Workers) -> None:
self.name = name
self.role = role
self.jobs = jobs
payloads = _encode(jobs, workers)
self.crcs = _seal(jobs, payloads, workers)
self.fingerprint = _fingerprint(payloads)
self.stored_bytes = sum(len(c) for p in payloads for c in p)
self.encode_times: list[float] = []
self.decode_times: list[float] = []
self.decode_error: str | None = None
self.exact = False
self.max_err: float | None = None
def take_pass(self, workers: _Workers, *, timed: bool, judge: bool) -> None:
"""Encode, then decode the payloads that encode produced, and drop them, so that no candidate's payloads are
held while the others run. Only the encode and the decode are timed, and only when `timed`; each of them then
starts on threads that `_load_threads` has just kept busy.
"""
if timed:
_load_threads(workers.pool)
start = time.perf_counter()
payloads = _encode(self.jobs, workers)
encode_time = time.perf_counter() - start
if timed:
self.encode_times.append(encode_time)
if self.decode_error is not None:
return
fingerprint = _fingerprint(payloads)
if fingerprint != self.fingerprint: # a random encode: the checksums must come from these payloads
self.crcs = _seal(self.jobs, payloads, workers)
self.fingerprint = fingerprint
if timed:
_load_threads(workers.pool)
try:
start = time.perf_counter()
decoded = _decode(self.jobs, payloads, self.crcs, workers)
decode_time = time.perf_counter() - start
except ChecksumError as e:
self.decode_error = str(e)
return
if timed:
self.decode_times.append(decode_time)
if judge:
self.judge(decoded)
def judge(self, decoded: list[list[_Decoded]]) -> None:
outputs = [b"".join(parts) for parts in decoded]
self.exact = all(out == j.data for out, j in zip(outputs, self.jobs, strict=True))
self.max_err = max(
(_max_abs_diff(j.data, out, j.record.meta.dtype) for out, j in zip(outputs, self.jobs, strict=True)),
default=0.0,
)
def _measure(runs: list[_Run], workers: _Workers, repeats: int) -> None:
"""Take every run's timings round-robin: in each round every candidate in turn encodes and decodes once, so that
drift in the machine's speed is spread over all candidates instead of landing on whichever ran first or last.
The candidate order reverses on every other timed round, so a steady drift does not favour the same candidate.
"""
for k in range(WARMUP_PASSES + repeats):
timed = k >= WARMUP_PASSES
for run in runs[::-1] if timed and (k - WARMUP_PASSES) % 2 else runs:
run.take_pass(workers, timed=timed, judge=k == 0)
def _row(run: _Run) -> BenchRow:
jobs = run.jobs
failed = run.decode_error is not None
uses: Counter[tuple[str, str]] = Counter((j.codec.id, _params_json(j.codec)) for j in jobs)
return BenchRow(
candidate=run.name,
role=run.role,
codecs=[CodecUse(codec_id=i, params=json.loads(p), tensors=n) for (i, p), n in sorted(uses.items())],
raw_bytes=sum(len(j.data) for j in jobs),
stored_bytes=run.stored_bytes,
encode_seconds=min(run.encode_times),
encode_seconds_all=run.encode_times,
decode_seconds=None if failed else min(run.decode_times),
decode_seconds_all=None if failed else run.decode_times,
decode_error=run.decode_error,
lossless=all(j.codec.lossless for j in jobs),
needs_base=any(j.codec.needs_ref for j in jobs),
check_decode=not all(j.codec.lossless for j in jobs),
bit_exact=not failed and run.exact,
max_abs_err=None if failed else run.max_err,
fallback_tensors=sum(j.fell_back for j in jobs),
)
[ドキュメント]
def candidates_for(names: Sequence[str] | None = None, *, with_base: bool = False) -> dict[str, Assigner]:
"""Candidates keyed by codec id, each applied to float tensors with `UniformAssigner`.
Without `names`, every registered lossless codec that needs no base, plus the delta codecs if `with_base`,
except a codec whose optional package is missing (its encode of one float32 value raises
`MissingDependencyError`): that one is skipped with a `UserWarning` naming it. Named codecs are used as given,
lossy ones included, and a missing package raises when `compare` runs them. A delta codec stores a tensor the
base lacks with `bytegroup-zstd/1`.
"""
if names is not None:
chosen = list(names)
else:
chosen = []
for i in codec_ids():
codec = get_codec(i)
if not codec.lossless or (codec.needs_ref and not with_base):
continue
try:
codec.encode(memoryview(bytes(4)), _PROBE, memoryview(bytes(4)))
except MissingDependencyError as e:
warnings.warn(f"candidates_for skipped {i}: {e}", stacklevel=2)
continue
chosen.append(i)
fallback = CodecChoice(codec_id="bytegroup-zstd/1")
return {
i: UniformAssigner(CodecChoice(codec_id=i, fallback=fallback if get_codec(i).needs_ref else None))
for i in chosen
}
[ドキュメント]
def compare(
tensors: Sequence[TensorRecord],
candidates: Mapping[str, Assigner],
*,
base: Sequence[TensorRecord] | None = None,
threads: int | None = None,
repeats: int = 1,
) -> BenchReport:
"""Encode and decode `tensors` in memory with every candidate, one row per candidate and role.
Chunking, the thread pool, the delta reference slicing, and the decode checks are the container's own
functions (`encode_chunks`, `seal_chunks`, `decode_chunks`), so a row measures what `write_archive` and
`Archive.read` ask of the codec, without the file. See `BenchRow` for what the seconds include and exclude,
and `BenchEnvironment` for what is recorded about the run.
Before timing, each row does `WARMUP_PASSES` untimed passes, and the timed passes run round-robin across the
candidates of a role. Right before each timed encode and decode, the pool's threads and the calling thread
spin for `SPIN_SECONDS`, untimed. `bit_exact` and `max_abs_err` are
recomputed from the decoded bytes, never taken from a codec's claim. Lossy candidates run without any
opt-in; `base` holds the tensors that delta candidates refer to, and a delta tensor with no match in it
uses the choice's `fallback` or raises `MissingBaseError`. A candidate that chose a delta codec for some
tensors but found a reference for none of them raises `MissingBaseError` instead of reporting rows that
measure only its fallback.
"""
if repeats < 1:
raise ValueError(f"repeats must be at least 1, got {repeats}")
n_threads = _thread_count(threads)
by_role: dict[str, list[TensorRecord]] = defaultdict(list)
for record in tensors:
by_role[record.meta.role].append(record)
base_by_name = {r.meta.name: r for r in base} if base is not None else None
load = os.getloadavg()[0] if hasattr(os, "getloadavg") else None
jobs = {
name: {role: _jobs(records, assigner, base_by_name) for role, records in by_role.items()}
for name, assigner in candidates.items()
}
for name, by_candidate_role in jobs.items():
_check_reference(name, [j for role_jobs in by_candidate_role.values() for j in role_jobs])
with _Workers(n_threads) as workers:
if workers.pool is not None:
_load_threads(workers.pool) # starts every pool thread
_warm_up([j for c in jobs.values() for role_jobs in c.values() for j in role_jobs], workers)
runs = {}
for role in by_role:
role_runs = [
_Run(name, role, by_candidate_role[role], workers) for name, by_candidate_role in jobs.items()
]
_measure(role_runs, workers, repeats)
runs.update({(r.name, role): r for r in role_runs})
rows = [_row(runs[name, role]) for name in jobs for role in by_role]
env = BenchEnvironment(
jabara=__version__,
python=platform.python_version(),
platform=platform.platform(),
machine=platform.machine(),
cpu_model=_cpu_model(),
cpu_count=os.cpu_count(),
load_average_1m=load,
threads=n_threads,
repeats=repeats,
warmup_passes=WARMUP_PASSES,
spin_seconds=SPIN_SECONDS,
chunk_size=CHUNK_SIZE,
numpy=version("numpy"),
zstandard=version("zstandard"),
optional_packages={p: version(p) for p in OPTIONAL_PACKAGES if sys.modules.get(p) is not None},
)
return BenchReport(bench=1, environment=env, rows=rows)