diff --git a/.github/workflows/pyamplicol.yml b/.github/workflows/pyamplicol.yml index 4acb06495a..7a36625a7f 100644 --- a/.github/workflows/pyamplicol.yml +++ b/.github/workflows/pyamplicol.yml @@ -449,13 +449,14 @@ jobs: # in source-contracts: they are loop tests, which skip without a # Symbolica that accepts the package key, and source-contracts installs # no Symbolica. - # The stability display, wide magnitudes and tracked-precision files - # are the fast new one-loop tests of the lane-rescue / runtime-options - # import (about 20 s together). test_loop_v2_process_history.py is not - # listed: its child process uses Symbolica directly, which is refused - # without a personal licence once pytest holds the restricted thread. - # The last seven files are the fastest of the restored one-loop engine - # tests (about 70 s together). + # Two groups are listed for their speed (measured locally, one pytest + # process per group): the stability-display, wide-magnitude and + # tracked-precision files of the lane-rescue / runtime-options import + # (about 20 s), and the last seven files, the fastest of the restored + # one-loop engine tests (about 30 s). test_loop_v2_process_history.py + # is not listed: its child process uses Symbolica directly, which is + # refused without a personal licence once pytest holds the restricted + # thread. - name: Run the light one-loop tests without SYMBOLICA_LICENSE (30 GiB RSS limit) env: PYAMPLICOL_REQUIRE_SYMBOLICA_LICENSE: "1" @@ -886,6 +887,10 @@ jobs: name: pyamplicol-retained-sdist path: pyamplicol/.artifacts/retained - name: Build and deploy-test in manylinux_2_28 x86_64 + # The wheel is built from the retained sdist only (--skip-checkout-wheel), + # as the macOS wheels are. A second wheel from this checkout cannot be + # built here: its prepared models are not committed (only the sdist has + # them), and umami.h is a symlink into madspace/, outside the mount. run: | docker run --rm \ -v "$PWD:/io" \ @@ -910,6 +915,7 @@ jobs: "$PY311" tools/ci/memory_watchdog.py --limit-gib 30 -- \ "$PY311" tools/release/build_release_artifacts.py \ --retained-sdist .artifacts/retained/pyamplicol-*.tar.gz \ + --skip-checkout-wheel \ --output-dir .artifacts/platform "$PY311" tools/ci/memory_watchdog.py --limit-gib 30 -- \ "$PY311" tools/release/test_deployment.py \ diff --git a/pyamplicol/docs/user/command-line-interface.md b/pyamplicol/docs/user/command-line-interface.md index 22290c57e3..ed8afff850 100644 --- a/pyamplicol/docs/user/command-line-interface.md +++ b/pyamplicol/docs/user/command-line-interface.md @@ -1147,6 +1147,92 @@ best-effort counts with the binary64 time, without the truth-based columns; the header says `none (estimates only)` and the JSON's `ground_truth` `{"arithmetic": "none", "label": "none"}`. +**Measured precisions.** `--measured-precisions` (`benchmark.measured_precisions`, +a list; on the command line space- or comma-separated, +`--measured-precisions double dd arb:60`) names the precisions whose +stability the stability run measures, each its own pair of tables in the +order given; the default is `binary64` alone (today's tables). An entry is +`binary64` (`double`, `b64`) or what `--ground-truth` accepts +(`double-double`/`dd`, `arbitrary`/`arb`, `arbitrary:DIGITS`/`arb:DIGITS`). +Each entry's points are evaluated as binary64's are, in its arithmetic: the +default checks (one default rotation; on TIRust's points also the rescaled +reduction-direction check), a refused point served best-effort, lane rescue +as that arithmetic has it (`--no-lane-rescue` turns it off). An entry below +the ground truth is read against it ("Stable digits of double-double vs +arb(60)"): its true and estimated digits capped to its own range +(double-double -log10(2^-106) = 31.91, arbitrary precision its digits) and +to what the ground truth certifies (its range; an arbitrary-precision truth +its cross-check's 2^-106, or on a point where the backends' references agree +closer the agreement they reach), the title adding "capped at what the ground +truth certifies (at least D digits)" when that is the lower. The ground truth's own precision +has its estimates-only tables ("Estimated digits of arb(60) (the ground +truth)" and "Default checks, estimates only, arb(60)"): its points are +evaluated in it once, with the default checks, and that evaluation is also +the reference of the lower precisions (its unrotated value is the plain +reference evaluation's bit for bit, verified on g g > g g g in +double-double and arb(60); a best-effort or failed point has no reference, +as before; the certification of an arbitrary-precision truth is unchanged; +with one backend and an arbitrary-precision truth its references stay the +checked evaluations). A ground truth not listed gets no table and no checks +beyond its certification above (with an arbitrary-precision truth the +cross-check between the backends and the checked re-run of a reference it +does not certify; with one backend one checked evaluation per point). An +entry above the ground truth (or listed twice) is refused before any work; +with `--ground-truth none` every entry is estimates-only. A precision not +listed is not evaluated: without binary64 in the list the stability run has +no binary64 stream (`stability` is then empty in `--json`) and the runtime +no binary64 calls, except binary64's runtime worker when another listed +precision's table shows the ground truth's multiplier and the truth itself +is not listed (the multiplier pass runs in that worker); binary64's counts +are still the start of the other precisions' calls. Each precision's +failure causes are under its own tables. The precisions given are +honoured; the stability plan and its ETA count each extra stream at a lower +bound of its point (a checked binary64 point below the ground truth, the +plain reference point for the ground truth's own) until the run measures it, +and the default budget's deadline admits points at the measured costs of +every stream. The scope rules (A and B above) count them by lower bounds +too: binary64's calls only when listed, every other precision's stream at +least two binary64 points in the runtime timing (its measuring call and +one timed call) and one binary64 point per stability point, a listed +ground truth as the reference it is (in the runtime timing its stream runs +after binary64's rows, so until then rule A sees it at one binary64 point +per call and rarely leaves a backend out for it, more output than asked, +never less); the stability plan prices a listed ground truth's stream at +its checks' evaluations per point (the point and each rotation of a plain +reference point); the whole command's ETA counts each +precision's runtime calls (its measuring point and its budget) until they +run, and `--completion-time` keeps their estimates out of binary64's share +and gives each the time left when it starts. With `--runtime`, every entry other than binary64 also gets +its own "Runtime per reduction backend, " and "Time per point and +stage, " tables, in the order given (the +ground truth's own precision too: timing needs no truth; with a list given, +binary64's runtime and checks tables are titled ", binary64" as well): per backend the +same optimistic pass as binary64's in that arithmetic, in a process of its +own (one core, or `--runtime-threads`), its stage groups from the native +stage reports of those calls and its peak RAM. It starts from binary64's +counts and budget for that backend (`--target-runtime` is each backend's +timed budget per measured precision); its one-point warm-up call (untimed) +measures its cost, and its batch falls to the largest power of two that +its calls fit in that budget, down to one point, that call its warm-up (a +`--batch-size` given is honoured: every call holds that many points). A +wider carrier's time per point depends on the points per call +(double-double on g g > g g g, NinjaRS: 0.69 s at one point, 0.57 s at +two, 0.45 s at 16), so it compares with the multiplier pass's (one point +per call where it is dear) at the same batch. Its time carries the ground +truth's multiplier against it, `(arb(60) x1.1)`, none on the ground truth's +own table. When the ground truth is listed its stream is timed once: it is +the multiplier of binary64's table and of the others (no separate +multiplier pass), and rule B leaves it in (a precision given). In `--json` its rows are `runtime_measured` (each its +`precision` record and `runtime` rows as `runtime`), absent by default. In +`--json` the other precisions' rows are under `stability_setup.measured_precisions` +(each entry its precision, `estimates_only`, `digits_cap`, +`capped_by_truth` and `stability`, the same rows as `stability`; binary64's +entry `stability: null`, its rows where they always are); the key is absent +with the default. The per-sample records (`--json`, `--samples-output`: its +`measured_precisions`) of a wider precision hold its value and sectors as +the exact decimal text of its carrier's value; every precision's records +also carry `estimate_digits_uncapped` and `true_digits_uncapped`. + **Stability.** Over N flat points (`benchmark.stability_points` / `--stability-points`; by default as many as one minute per worker affords, at least five; with `--completion-time` what is left of it; drawn with @@ -1199,15 +1285,19 @@ reference failed has an unknown truth and is left out (shown as "no ref."). The measured points (N in what follows) are all others. The measured points are sorted by true digits from worst to best. At the -percentiles 1 per mil, 1 %, 10 % and 50 % the table shows the true digits of -the point of rank floor(p N) (1-based; the 50 % row is the median, the lower -middle point for an even N), and over the class of points of rank -floor(p' N) < rank <= floor(p N) (p' the previous percentile, 0 for the -first) the point count (with its failed points), the min, median and max of -|estimated - true| and the median of estimated - true (positive: the -estimate is optimistic), both over the class's points with an estimate. At +percentiles 1 per mil, 1 %, 10 %, 50 % and 100 % the table shows the true +digits of the point of rank floor(p N) (1-based; the 50 % row is the median, +the lower middle point for an even N; the 100 % row the best point), and +over the class of points of rank floor(p' N) < rank <= floor(p N) (p' the +previous percentile, 0 for the first; the classes add up to N) the min, +median and max of |estimated - true| and the median of estimated - true +(positive: the estimate is optimistic), both over the class's points with +an estimate. A class holds floor(p N) - floor(p' N) points, so the table +shows no count (`--json` keeps each class's `count` and `failed`); a class +with points without a value says so after its digits, `0.00 (2 failed)`. At small N a class can be empty (`-`; the table prints the N a populated class -needs: 1000 measured points for the 1 per mil class, 2 for the median). +needs: 1000 measured points for the 1 per mil class, 2 for the median, 1 +for the 100 % row). A second table compares the default checks with the truth, per backend: the measured points, those served best-effort / without a value in binary64, the points flagged unstable diff --git a/pyamplicol/docs/user/configuration.md b/pyamplicol/docs/user/configuration.md index 217b6afa10..4f1816456d 100644 --- a/pyamplicol/docs/user/configuration.md +++ b/pyamplicol/docs/user/configuration.md @@ -906,7 +906,7 @@ rescaled = true | Interface | The TOML | One setting | | --- | --- | --- | | CLI | `pyamplicol evaluate ARTIFACT --card options.toml` (the run card) | its flag (table below) | -| Python | `Runtime.load(artifact, options=...)`: a path, a TOML text or a parsed mapping | its keyword | +| Python | `Runtime.load(artifact, options=...)`: a path, a TOML text or a parsed mapping (a one-line string is a path when it names an existing file, else TOML; neither: refused naming both) | its keyword | | C SDK | `rusticol_virtual_set_options(handle, toml_text)`; `rusticol_virtual_open_with_options(path, process, parameters_json, r2_strategy, toml_text, &handle)` | its setter | | C++ / Fortran / Rust SDK | `VirtualRuntime::set_options` / `set_options_file` / `with_options`; `runtime%set_options`, `runtime%load(..., options_toml=)`; `Runtime::set_options` / `set_options_file` / `open_with_options` | its setter | diff --git a/pyamplicol/docs/user/profiling-and-benchmarking.md b/pyamplicol/docs/user/profiling-and-benchmarking.md index 230e8782db..ff5bd37a46 100644 --- a/pyamplicol/docs/user/profiling-and-benchmarking.md +++ b/pyamplicol/docs/user/profiling-and-benchmarking.md @@ -236,7 +236,9 @@ group) with the ratio between the backends (the faster highlighted), and the stable digits of pure binary64 against a re-run in the reference precision (`--ground-truth`: double-double by default, or arbitrary precision) over flat points at the percentiles 1 per mil, -1 %, 10 % and 50 % (a point a backend refuses in binary64 measured with its +1 %, 10 %, 50 % and 100 % (other precisions too with `--measured-precisions`, +each its own tables, e.g. `--measured-precisions double dd --ground-truth +arb:60`; a point a backend refuses in binary64 measured with its best-effort value at its true digits; only a point with no binary64 value ranked at 0 digits), with the accuracy of the default estimate against that truth (one default rotation on NinjaRS's points; one default rotation and diff --git a/pyamplicol/docs/user/python-api.md b/pyamplicol/docs/user/python-api.md index 6619f3d701..f1cadf61fe 100644 --- a/pyamplicol/docs/user/python-api.md +++ b/pyamplicol/docs/user/python-api.md @@ -297,8 +297,9 @@ effect by its run-card name, as plain data (the stability checks as "cross_backend"}` or None, as the SDKs' `options_json`); `threads` is the effective count and `threads_requested` the requested one when it was clamped. A tree runtime refuses, at load, every virtual option the TOML -names. A one-line `options` string without `=` is a path (a mistyped path -says that no such file exists). +names. A one-line `options` string that names an existing file is a path, +else a TOML text (`"[evaluation]"`: an empty table, no option set); one that +is neither (a mistyped path) is refused naming both readings. `threads=N` bounds every native thread pool of the runtime, its load and every evaluation in every carrier, to `N` workers (clamped to the cores the diff --git a/pyamplicol/examples/all_options.toml b/pyamplicol/examples/all_options.toml index 5a221158b8..cc2e7f452a 100644 --- a/pyamplicol/examples/all_options.toml +++ b/pyamplicol/examples/all_options.toml @@ -574,6 +574,14 @@ n_core = 10 # the runtime timing then times its multiplier even when its minimal counts # exceed the budget. ground_truth = "double-double" +# benchmark.measured_precisions: Loop artifacts: the precisions whose +# stability the stability run measures (`--measured-precisions`), each its +# own pair of tables in this order: "binary64" ("double", "b64"; the default +# ["binary64"]), "double-double" ("dd"), "arbitrary[:DIGITS]" ("arb"), each +# strictly below ground_truth (true digits against it) or ground_truth itself +# (its estimates only, with the default checks); with ground_truth "none" +# every entry is estimates only. +measured_precisions = ["binary64"] # benchmark.checked: Loop artifacts: time the checked mode (`--checked`): the # backends' own acceptance checks, a refused point served best-effort, the # default backend as auto. Default false: one fully optimistic binary64 pass diff --git a/pyamplicol/rust/crates/rusticol-core/src/loop_v2/plan/binary.rs b/pyamplicol/rust/crates/rusticol-core/src/loop_v2/plan/binary.rs index 1dbd29aa22..4a804c02de 100644 --- a/pyamplicol/rust/crates/rusticol-core/src/loop_v2/plan/binary.rs +++ b/pyamplicol/rust/crates/rusticol-core/src/loop_v2/plan/binary.rs @@ -1882,11 +1882,7 @@ thread_local! { static SEQUENTIAL: std::cell::Cell = const { std::cell::Cell::new(false) }; } -/// [`read_binary_with`] within the caller's thread bound: under a load's -/// bound (`plan::with_load_threads`) with the threads its work uses, inside a -/// pool's worker on that pool's threads, else sequentially on the calling -/// thread, never starting rayon's global pool (whose workers would outlive -/// the call). +/// [`read_binary_with`] within the caller's thread bound (`read_bounded`). /// The loader's read of a stored member (`LoopProgramV4::load_with`): an /// executor or runtime built with a thread bound starts no other threads /// (M-FINAL MF-8G-1 item 5; the JSON load is sequential too). The model and @@ -1895,8 +1891,11 @@ pub fn read_binary_bounded(member: &[u8], policy: FormPolicy) -> RusticolResult< read_bounded(|| read_binary_with(member, policy)) } -/// `read` (a read of a binary member) within the caller's thread bound -/// ([`read_binary_bounded`]). +/// `read` (a read of a binary member) within the caller's thread bound: +/// under a load's bound (`plan::with_load_threads`) with the threads its work +/// uses, inside a pool's worker on that pool's threads, else sequentially on +/// the calling thread, never starting rayon's global pool (whose workers +/// would outlive the call). pub(super) fn read_bounded(read: impl FnOnce() -> RusticolResult) -> RusticolResult { if rayon::current_thread_index().is_some() || super::load_bound().is_some() { return read(); @@ -1934,13 +1933,13 @@ pub fn read_pool() -> Option { /// else the bound of a load on this thread (`plan::with_load_threads`: each /// list then decodes on the load's pool with the threads it uses, /// [`Reader::list_threads`]); else inside a pool's worker that pool's, else -/// the global pool's, started first. rayon starts the global pool lazily at its first use and panics -/// there when a worker cannot be spawned, and never starts it after a failed -/// start (any later use panics too): the reader starts it itself, and a -/// pool that cannot start, or whose start failed before (outside this -/// reader, revealed by one caught use), makes every read of the process -/// decode on one thread, never a refusal or rayon's panic. A pool another -/// component started first is used as it is. +/// the global pool's, started first. rayon starts the global pool lazily at +/// its first use and panics there when a worker cannot be spawned, and never +/// starts it after a failed start (any later use panics too): the reader +/// starts it itself, and a pool that cannot start, or whose start failed +/// before (outside this reader, revealed by one caught use), makes every +/// read of the process decode on one thread, never a refusal or rayon's +/// panic. A pool another component started first is used as it is. fn read_threads() -> usize { if allocations_can_fail() || SEQUENTIAL.with(std::cell::Cell::get) { return 1; diff --git a/pyamplicol/rust/loop-reduction/src/runtime/fast.rs b/pyamplicol/rust/loop-reduction/src/runtime/fast.rs index 3b4731c221..1e6d7e1a8d 100644 --- a/pyamplicol/rust/loop-reduction/src/runtime/fast.rs +++ b/pyamplicol/rust/loop-reduction/src/runtime/fast.rs @@ -158,6 +158,10 @@ impl FastReductions { for (index, sector) in self.sectors.iter_mut().enumerate() { if self.active[index] { results.push(sector.evaluate(ids, input, parameters)?); + // Taken after a successful evaluation only, which suffices: + // NinjaRS's `FastAmplitude::evaluate` forgets the thread's + // earlier records on entry (`clear_instabilities`), so those + // of a failed evaluation never reach the next one. records.push(super::lane_status::fast_instabilities(ids.len())); } else { records.push(vec![None; ids.len()]); diff --git a/pyamplicol/rust/loop-reduction/src/runtime/reduction.rs b/pyamplicol/rust/loop-reduction/src/runtime/reduction.rs index d901fa3c21..4f53939a0a 100644 --- a/pyamplicol/rust/loop-reduction/src/runtime/reduction.rs +++ b/pyamplicol/rust/loop-reduction/src/runtime/reduction.rs @@ -208,6 +208,11 @@ where ) .map_err(error)?, ); + // Taken after a successful evaluation only, which suffices: + // NinjaRS's `Amplitude::evaluate_batch_with_inputs` (every + // `evaluate_batch*` goes through it) forgets the thread's earlier + // box-Gram refusals on entry (`clear_box_gram_refusals`), so those + // of a failed evaluation never reach the next one. refusals.push(super::lane_status::generic_refusals()); } let mut sectors = results.into_iter(); diff --git a/pyamplicol/rust/loop-reduction/src/runtime/v2_reduce.rs b/pyamplicol/rust/loop-reduction/src/runtime/v2_reduce.rs index f26ab825e4..83cbbd454d 100644 --- a/pyamplicol/rust/loop-reduction/src/runtime/v2_reduce.rs +++ b/pyamplicol/rust/loop-reduction/src/runtime/v2_reduce.rs @@ -714,6 +714,10 @@ impl FastEngine { &mut self.statuses, ) .map_err(error)?; + // Taken after a successful evaluation only, which suffices: NinjaRS's + // `FastAmplitude::evaluate` forgets the thread's earlier records on + // entry (`clear_instabilities`), so those of a failed evaluation + // never reach the next one. let records = super::lane_status::fast_instabilities(lanes); Ok(self .statuses diff --git a/pyamplicol/src/pyamplicol/benchmarking.py b/pyamplicol/src/pyamplicol/benchmarking.py index edd390c9d4..0a10cfaa18 100644 --- a/pyamplicol/src/pyamplicol/benchmarking.py +++ b/pyamplicol/src/pyamplicol/benchmarking.py @@ -3047,6 +3047,7 @@ def profile_virtual( optimistic: bool = False, monitor: Callable[[str, Mapping[str, Any]], None] | None = None, warm_entry: bool = False, + precision: Mapping[str, Any] | None = None, ) -> VirtualProfileResult: """Profile a loop artifact path or a loaded virtual :class:`Runtime` (``VirtualProfileResult``) on ``points`` (default: the distinct flat @@ -3130,6 +3131,13 @@ def profile_virtual( ) initial = sum(1 for leg in physics.external_particles if leg.state == "incoming") options = {"poles": "none", "on_failure": on_failure} + # A measured precision other than binary64 (``loop_profile. + # MeasuredPrecision.options``): the same calls in its arithmetic, its + # batch fitted to its cost (``_fitted_calls``) unless ``fit`` is false + # (a --batch-size given). + carrier = dict(precision or {}) + fit = bool(carrier.pop("fit", True)) and bool(carrier) + options.update(carrier) if reduction is not None: options["reduction"] = reduction if optimistic: @@ -3186,6 +3194,9 @@ def report( if prepared is None else replace(bench, warmup_runs=bench.warmup_runs - 1) ) + if fit: + calls = _fitted_calls(runtime, batches, calls, options, scales) + size = calls.batch_size profile = _profile_virtual_calls( runtime, batches, calls, options, scales, report ) @@ -3230,6 +3241,35 @@ def drops(reference_point: float | None = None, entry: float | None = None) -> b ) +def _fitted_calls( + runtime: Any, + batches: Any, + bench: BenchmarkConfig, + options: Mapping[str, Any], + scales: Callable[[Momenta], Any], +) -> BenchmarkConfig: + """A measured precision's calls (``profile_virtual(precision=)``): its + one-point warm-up call measures its cost per point (untimed; after the + warm entry the same call, a first measured point), and the batch falls + to what ``target_runtime`` affords for ``minimum_samples`` calls, a + power of two of at most ``batch_size`` points, at least one; the + measuring call is its warm-up (no other: a carrier's first call at a + new batch size costs no more than its next, measured on gg_ggg in + double-double). A cheap precision keeps the batch given.""" + + batch = batches(0, 1) + begin = time.perf_counter() + runtime.evaluate(batch, mu_r2=scales(batch), **options) + per_point = time.perf_counter() - begin + calls = max(int(bench.minimum_samples), 1) + affordable = float(bench.target_runtime) / max(calls * per_point, 1e-12) + size = 1 + while size * 2 <= min(int(bench.batch_size), affordable): + size *= 2 + size = max(min(size, int(bench.batch_size)), 1) + return replace(bench, batch_size=size, warmup_runs=0) + + def _scope_drops( profile: VirtualProfileResult, scope: Mapping[str, Any], @@ -3727,7 +3767,10 @@ def _profile_virtual_calls( def call(k: int) -> float: nonlocal failed, served, rescued - batch = batches(k) + # The first ``batch_size`` points of call k's batch: a measured + # precision's fitted batch (``_fitted_calls``) is smaller than the + # batches' own, which ``batches(k)`` alone would return whole. + batch = batches(k, bench.batch_size) mu_r2 = scales(batch) if k < warmup: # One point first: when a full call would cost more than diff --git a/pyamplicol/src/pyamplicol/cli/profile_options.py b/pyamplicol/src/pyamplicol/cli/profile_options.py index 3c8bd3630c..f35eed9570 100644 --- a/pyamplicol/src/pyamplicol/cli/profile_options.py +++ b/pyamplicol/src/pyamplicol/cli/profile_options.py @@ -88,6 +88,23 @@ def add_profile_mode_options(parser: argparse.ArgumentParser) -> None: "at its minimal counts; --no-all-backends: the default only)" ), ) + parser.add_argument( + "--measured-precisions", + dest="benchmark.measured_precisions", + action="extend", + nargs="+", + default=argparse.SUPPRESS, + metavar="PRECISION", + help=( + "loop artifacts: the precisions whose stability --stability " + "measures (benchmark.measured_precisions), each its own pair of " + "tables in the order given: binary64 (double, b64; the default), " + "double-double (dd), arbitrary (arb) or arbitrary:DIGITS, at most " + "the --ground-truth precision (that one: its estimates only, with " + "the default checks); with --runtime each also its own runtime " + "tables (--target-runtime per precision); space- or comma-separated" + ), + ) parser.add_argument( "--ground-truth", dest="benchmark.ground_truth", diff --git a/pyamplicol/src/pyamplicol/config/models.py b/pyamplicol/src/pyamplicol/config/models.py index 457dfc0ac9..46a6e8a000 100644 --- a/pyamplicol/src/pyamplicol/config/models.py +++ b/pyamplicol/src/pyamplicol/config/models.py @@ -542,6 +542,62 @@ def _ground_truth(value: object) -> str: ) +# The precisions a loop profile's stability run measures by default +# (``benchmark.measured_precisions``, ``--measured-precisions``): this one +# line sets the default. +DEFAULT_MEASURED_PRECISIONS: tuple[str, ...] = ("binary64",) + + +def _measured_precision(value: object) -> str: + """A ``benchmark.measured_precisions`` entry in its canonical spelling: + "binary64" (also "double", "b64"), or a reference precision as + ``_ground_truth`` spells it ("double-double", "arbitrary", + "arbitrary:DIGITS"; "none" is no precision).""" + + text = value.strip().lower() if isinstance(value, str) else "" + if text in ("binary64", "double", "b64"): + return "binary64" + try: + canonical = _ground_truth(text) + except ConfigurationError: + canonical = "none" + if canonical == "none": + raise ConfigurationError( + "benchmark.measured_precisions entries must be binary64 (double, " + "b64), double-double (dd), arbitrary (arb) or arbitrary:DIGITS " + f"(arb:DIGITS); got {value!r}" + ) + return canonical + + +def _measured_precisions(value: object) -> tuple[str, ...]: + """``benchmark.measured_precisions`` canonical, in the order given: at + least one entry, no duplicate.""" + + if isinstance(value, str): + value = [value] + if isinstance(value, (list, tuple)): + # An entry may hold several, comma-separated (``--measured-precisions + # b64,dd``). + value = [ + part + for entry in value + for part in (entry.split(",") if isinstance(entry, str) else [entry]) + if not isinstance(part, str) or part.strip() + ] + if not isinstance(value, (list, tuple)) or not value: + raise ConfigurationError( + "benchmark.measured_precisions must be a non-empty list of precisions" + ) + canonical = tuple(_measured_precision(entry) for entry in value) + for position, entry in enumerate(canonical): + if entry in canonical[:position]: + raise ConfigurationError( + f"benchmark.measured_precisions lists {entry} twice" + ) + return canonical + + def _finite_float( value: float, name: str, *, minimum: float, exclusive: bool = False ) -> float: @@ -1816,6 +1872,15 @@ class BenchmarkConfig: ground_truth: str = field( default=DefaultStr("double-double"), metadata=_setting("str") ) + # The precisions whose stability the stability run measures + # (``--measured-precisions``), each its own pair of tables in this + # order: binary64 (the default, ``DEFAULT_MEASURED_PRECISIONS``) and + # the reference precisions up to the ground truth's (the ground truth's + # own: its estimates only); "dd", "arb[:DIGITS]", "double", "b64" + # accepted. + measured_precisions: tuple[str, ...] = field( + default=DEFAULT_MEASURED_PRECISIONS, metadata=_setting("list_str") + ) # The runtime timing of a loop profile in the checked mode (``--checked``): # the backends' own acceptance checks, a refused point served best-effort # and the default backend as "auto". False (the default): one fully @@ -1867,6 +1932,11 @@ def __post_init__(self) -> None: "ground_truth", DefaultStr(truth) if isinstance(self.ground_truth, DefaultStr) else truth, ) + object.__setattr__( + self, + "measured_precisions", + _measured_precisions(self.measured_precisions), + ) if self.all_backends is not None and type(self.all_backends) is not bool: raise ConfigurationError("benchmark.all_backends must be a boolean") if self.completion_time is not None: diff --git a/pyamplicol/src/pyamplicol/config/runtime_options.py b/pyamplicol/src/pyamplicol/config/runtime_options.py index d97c52fbaf..aa6ec8ec95 100644 --- a/pyamplicol/src/pyamplicol/config/runtime_options.py +++ b/pyamplicol/src/pyamplicol/config/runtime_options.py @@ -84,9 +84,9 @@ def _document(source: RuntimeOptionsSource) -> Mapping[str, object]: def _parse(source: os.PathLike[str] | str) -> Mapping[str, object]: """The TOML of ``source``: a PathLike is a path; a one-line string is a - path when it names an existing file or has no "=" (a mistyped path then - says "no such file"), else a TOML text; a one-line string with "=" that - is neither an existing file nor valid TOML is refused naming both + path when it names an existing file, else a TOML text (``[evaluation]`` + is an empty table: no option); a one-line string that is neither an + existing file nor valid TOML (a mistyped path) is refused naming both readings.""" if isinstance(source, os.PathLike): @@ -94,7 +94,7 @@ def _parse(source: os.PathLike[str] | str) -> Mapping[str, object]: if not isinstance(source, str): raise TypeError("options takes a TOML path, a TOML text or a mapping") one_line = bool(source.strip()) and "\n" not in source - if one_line and (Path(source).expanduser().is_file() or "=" not in source): + if one_line and Path(source).expanduser().is_file(): return _read(Path(source)) try: return tomllib.loads(source) diff --git a/pyamplicol/src/pyamplicol/loop_profile.py b/pyamplicol/src/pyamplicol/loop_profile.py index b096f44889..880ae93029 100644 --- a/pyamplicol/src/pyamplicol/loop_profile.py +++ b/pyamplicol/src/pyamplicol/loop_profile.py @@ -46,21 +46,23 @@ Both are read on the finite part of the total (the sum over the squared-order sectors; the poles are not computed) and capped to binary64's range [0, -log10(2^-53)] (``stable_digits``). The MEASURED points are those -whose reference exists and those that failed in binary64 (no -value, whatever the reference); a binary64 value without a reference leaves -the truth unknown and is counted apart. They are sorted by true digits from -worst to best; at each percentile p of ``PERCENTILES`` the true digits of -the point of rank floor(p N) (1-based, N measured points; 50 %: the lower -middle point) are reported, with the deviation |estimated - true| (min, -median, max) and the signed median (estimated - true: positive when the -estimate is optimistic) over the points with an estimate in the class of the -points of rank floor(p' N) < rank <= floor(p N), p' the previous percentile -(0 for the first). A class may be empty at small N (``needed_points``). The -default checks flag a point unstable when its estimate exceeds the default -target (the relative metric of the rescue, per sector) or when it failed in -binary64 (a failure is reported, so detected); a point is truly inaccurate -when its true relative error exceeds the same target or it has no binary64 -value. +whose reference exists and those that failed in binary64 (no value, whatever +the reference); a binary64 value without a reference leaves the truth +unknown and is counted apart. They are sorted by true digits from worst to +best; at each percentile p of ``PERCENTILES`` the true digits of the point +of rank floor(p N) (1-based, N measured points; 50 %: the lower middle +point; 100 %: the best point) are reported, with the deviation |estimated - +true| (min, median, max) and the signed median (estimated - true: positive +when the estimate is optimistic) over the points with an estimate in the +class of the points of rank floor(p' N) < rank <= floor(p N), p' the +previous percentile (0 for the first); the classes add up to N. The +--measured-precisions other than binary64 are read the same way at their own +precision (``MeasuredPrecision``). A class may be empty at small N +(``needed_points``). The default checks flag a point unstable when its +estimate exceeds the default target (the relative metric of the rescue, per +sector) or when it failed in binary64 (a failure is reported, so detected); +a point is truly inaccurate when its true relative error exceeds the same +target or it has no binary64 value. Every evaluation goes through the public ``Runtime.evaluate`` with explicit ``reduction=``; a backend that refuses the process (``ReductionUnavailable``) @@ -92,8 +94,15 @@ # with the stability run asked for sets its points). STABILITY_FALLBACK = 5 # The percentiles of the sorted true digits (worst first): 1 per mil, 1 %, -# 10 % and 50 % (the median). -PERCENTILES = (Fraction(1, 1000), Fraction(1, 100), Fraction(1, 10), Fraction(1, 2)) +# 10 %, 50 % (the median) and 100 % (the best point); their classes add up +# to every measured point. +PERCENTILES = ( + Fraction(1, 1000), + Fraction(1, 100), + Fraction(1, 10), + Fraction(1, 2), + Fraction(1, 1), +) # binary64's range of stable digits: -log10 of its unit roundoff. BINARY64_DIGITS = 53 * math.log10(2.0) @@ -178,19 +187,153 @@ def ground_truth(text: str) -> GroundTruth: return GroundTruth("arbitrary", default_arbitrary_digits()) -def stable_digits(relative_error: float) -> float: - """-log10(relative error), capped to [0, ``BINARY64_DIGITS``]: an exact - agreement (or one below binary64's roundoff) counts all of binary64's - digits, an error of 100 % or more (or a non-finite one) none.""" +# The stream key prefix of a measured precision other than binary64 +# (``MeasuredPrecision.stream``): "measured: