From e4751e229b48c83b4c79da39b0698fbe48726730 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 3 Dec 2026 22:55:51 +0000 Subject: [PATCH 1/2] feat(studies): HLL and UnivMon per-value tail error for ASAPPlanner's measured accuracy table study_saturation.py --phase hll-tail runs hll-tail-study (a standalone crate pinning the asap_sketchlib commit the planner's executor runs) over lg_k 12..18, distinct counts 1..1e6 (10 per decade) and states merged from 1, 6, 60 and 360 panes, 2,000 trials per point. It measures HyperLogLogSparse, read as the executor reads it, and writes the error not exceeded except with probability delta, worst over counts and panes, as ASAPPlanner's MeasuredSketchAccuracy JSON. --phase univmon-tail does the same for the planner's UnivMon shapes (distinct count and entropy) with univmon-tail. Co-Authored-By: Claude Opus 5.5 --- docs/saturation_study.md | 127 ++++++- hll-tail-study/Cargo.lock | 429 +++++++++++++++++++++++ hll-tail-study/Cargo.toml | 29 ++ hll-tail-study/src/bin/univmon-tail.rs | 217 ++++++++++++ hll-tail-study/src/main.rs | 248 +++++++++++++ scripts/studies/study_saturation.py | 291 ++++++++++++++- scripts/studies/test_study_saturation.py | 71 +++- 7 files changed, 1407 insertions(+), 5 deletions(-) create mode 100644 hll-tail-study/Cargo.lock create mode 100644 hll-tail-study/Cargo.toml create mode 100644 hll-tail-study/src/bin/univmon-tail.rs create mode 100644 hll-tail-study/src/main.rs diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 07ab33e3..725917e5 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -6,8 +6,9 @@ records the cost of the sketch at the largest N measured, and finds the stream length N* past which an exact answer costs 10x (100x) more than the sketch. The study is `scripts/studies/study_saturation.py`, in phases: `accuracy`, -`cost`, `crossover`, `hydra` (Hydra grids, below) and `optimizer-cost` (the -cost table the optimizer in ASAPQuery reads). Around it, +`cost`, `crossover`, `hydra` (Hydra grids, below), `optimizer-cost` (the +cost table the optimizer in ASAPQuery reads) and `hll-tail` (the per-value +tail error of HLL for ASAPPlanner's measured accuracy table, below). Around it, `scripts/studies/merge_study_parts.py` joins the outputs of runs split across machines, `scripts/studies/recommend_config.py` turns data parameters into a configuration, and four scripts draw the figures: @@ -356,6 +357,128 @@ per grid; `measured_at` names the `dataset` and `schema_width`. Their accuracy column is one pass's `err_max` at the default grouping; the optimizer reads Hydra accuracy from `hydra_saturation.csv`. +## HLL per-value tail error (`--phase hll-tail`) + +ASAPPlanner keeps a distinct count per group in an HLL state, merged over +the panes of a window, and needs a guarantee in the form "each value is +within relative error ε except with probability δ" (accuracy scope +`per_value`). HLL's analysis gives only a standard error (no failure +probability), so this phase measures the tail instead, on the exact state +the planner's executor builds, and writes it as the planner's measured +accuracy table (ASAPPlanner `MeasuredSketchAccuracy`, +`crates/accuracy/src/measured.rs`). + +The trials run in `hll-tail-study/`, a separate crate (its own workspace) that +pins the `asap_sketchlib` commit the executor runs and builds the same type: +`HyperLogLogImpl` read with `estimate()` (an integer, +as the executor reads it), or with `--features sparse` the sparse-then-dense +`HyperLogLogSparse` once the executor keeps that. A point is +(precision `lg_k`, distinct count `n`, pane count `m`). A trial makes `n` +distinct 64-bit items, puts each in a uniformly random pane and, with +probability 1/2, also in a second random pane (one item seen in several +windows), builds one state per non-empty pane, merges them in pane order +into one state and records `|estimate − n| / n`. A trial's items do not depend +on `m` or `lg_k`, so every pane count and precision reads the same streams; +for a state whose merge equals the build of the union (both HLL states), every +`m` gives the same errors, which the study checks rather than assumes. + +For each point the binary prints, per requested δ, the error exceeded in at +most `floor(δ · trials)` trials. The reduction takes, per precision and δ, the +worst over every count and pane count (`hll_tail_worst`) and writes: + +- `hll_tail.jsonl` (raw, one line per point) and `hll_tail.csv`; +- `hll_tail_ranges.csv`: per count range, the worst error at + `--hll-target-delta` per precision and the least precision within + `--hll-target`; +- `hll_measured_accuracy.json`: one entry per precision, `statistic` + `Cardinality`, `accuracy_metric` `relative`, `trials`, and `error_at` for + every δ ≥ 3 / trials (the planner's validity rule). + +Defaults: `lg_k` 12..18, counts 1..1e6 at 10 per decade (58 counts). Small +counts are included because below `1/ε` one register collision is already an +error above ε; counts go to 1e6 because the worst error sits where the +estimator switches from linear counting to the harmonic mean, near +`2.5 · 2^lg_k` (655,360 at `lg_k` 18); +panes 1, 6, 60, 360 (one 10 s pane, 1 min, 10 min and 1 h of 10 s panes), +2,000 trials per point, δ ∈ {0.005, 0.01, 0.02, 0.05, 0.1}, seed 1. + +```sh +cargo build --release --manifest-path hll-tail-study/Cargo.toml # add --features sparse +python3 scripts/studies/study_saturation.py --phase hll-tail --hll-threads 32 --out out_hll +# Re-reduce hll_tail.jsonl (e.g. another --hll-target) without rerunning: +python3 scripts/studies/study_saturation.py --phase hll-tail --hll-reduce-only --out out_hll +``` + +Results (2026-12-03, `HyperLogLogSparse` at sketchlib `d28d5a6`, the +defaults above, 1,624 points of 2,000 trials each). In every one of the 406 +(lg_k, n) pairs, all pane counts give the same errors, as the merge-equals-union +property predicts. Below `m/8` items the state is sparse and every error is 0. +Worst relative error per value (the table's entries): + +| lg_k | δ 0.005 | δ 0.01 | δ 0.02 | δ 0.05 | δ 0.1 | worst at (δ 0.05) | +|---|---|---|---|---|---|---| +| 12 | 0.0587 | 0.0568 | 0.0527 | 0.0477 | 0.0428 | n = 10,000 | +| 13 | 0.0504 | 0.0478 | 0.0460 | 0.0421 | 0.0384 | n = 19,953 | +| 14 | 0.0428 | 0.0404 | 0.0395 | 0.0369 | 0.0346 | n = 39,811 | +| 15 | 0.0379 | 0.0372 | 0.0360 | 0.0342 | 0.0327 | n = 79,433 | +| 16 | 0.0353 | 0.0345 | 0.0163 | 0.0150 | 0.0137 | n = 199,526 | +| 17 | 0.0159 | 0.0154 | 0.0147 | 0.0136 | 0.0127 | n = 398,107 | +| 18 | 0.0140 | 0.0138 | 0.0132 | 0.0126 | 0.0119 | n = 794,328 | + +Each worst case sits at the classic estimator's switch from linear counting to +the harmonic mean (about `2.5 · 2^lg_k`). For relative error 0.05 at δ 0.05 per +value, the least passing precision is 12 in every count range (1–10, …, +1e5–1e6, `hll_tail_ranges.csv`). For 0.05 at δ 0.005 it is 14 (13 misses: +0.0504). + +### UnivMon (`--phase univmon-tail`) + +The same measurement for the UnivMon shapes ASAPPlanner lists (its +`UNIVMON_PARAMETERS`, reproduced in `univmon_shapes`), read for the distinct +count (`Cardinality`, relative error) and the frequency entropy +(`FrequencyEntropy`, absolute error in bits). The planner states no +theoretical bound for either. The total (`estimate_l1`) is the exact row +count, so it is not measured. `univmon-tail` (same crate) updates +`asap_sketchlib::UnivMon` as the executor does (one unit-weight update of the +sample's f64 bits per row). A trial streams `4n` rows over exactly `n` keys: +every key once, then `3n` more rows drawn uniformly (`uniform`) or from +Zipf(1.1) (`zipf1.1`). Each row goes to a random pane, and the pane states +are merged in pane order. Each entry is the worst over counts, panes and +both distributions. Defaults: counts 1..1e5 at 5 per decade, panes 1 and 6, +200 trials, δ ∈ {0.02, 0.05, 0.1}. Shapes whose state exceeds +`--um-max-state-mb` (64 MB, `univmon_state_bytes`) are left out and listed +on stderr. Outputs: `univmon_tail.jsonl`, `univmon_tail.csv` and +`univmon_measured_accuracy.json`. + +```sh +python3 scripts/studies/study_saturation.py --phase univmon-tail --hll-threads 16 --out out_um +``` + +Results (2026-12-03, sketchlib `d28d5a6`, the defaults above; 16 of the 40 +listed shapes fit 64 MB). Worst error per value at δ 0.05 (entropy in bits, +distinct count relative): + +| shape (heap × rows × cols × layers) | entropy | distinct | +|---|---|---| +| 1 × 5 × {624 … 1,409,067} × 1 (L2 shapes) | 5.21 | 1.0 | +| 256 × 5 × 1,024 × 16 | 0.283 | 0.135 | +| 13,500 × 1 × 1 × 19 | 306 | 0.0085 | +| 54,000 × 1 × 1 × 19 | 261 | 0.0036 | +| 13,500 × 5 × 624 × 19 | 0.453 | 0.0087 | +| 13,500 × 5 × 2,367 × 19 | 0.227 | 0.0121 | +| 13,500 × 5 × 14,349 × 19 | 0.046 | 0.0108 | +| 13,500 × 5 × 56,817 × 19 | 0.020 | 0.0105 | +| 54,000 × 5 × 624 × 19 | 0.512 | 0.0023 | +| 54,000 × 5 × 2,367 × 19 | 0.231 | 0.0063 | +| 54,000 × 5 × 14,349 × 19 | 0.039 | 0.0051 | + +The L2 shapes (one layer, heap 1) and the distinct shapes (one counter per +layer) are not built for entropy, and the table records that. Entropy within +0.1 bits at δ 0.05 per value needs 14,349 columns or more at 19 layers. The +worst cases often sit at the largest count (1e5), so the entries hold for +counts up to 1e5. Larger counts, more panes and the 24 shapes above 64 MB +are not measured. + ## Results (config grid, N up to 1e7) `--phase accuracy --n-max 1e7 --seeds 3 --jobs 16 --out out_grid_1e7`: 595 diff --git a/hll-tail-study/Cargo.lock b/hll-tail-study/Cargo.lock new file mode 100644 index 00000000..b898e192 --- /dev/null +++ b/hll-tail-study/Cargo.lock @@ -0,0 +1,429 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "asap_sketchlib" +version = "0.4.0" +source = "git+https://github.com/ProjectASAP/asap_sketchlib?rev=d28d5a65cede6486aa32f778c5edebad123f463d#d28d5a65cede6486aa32f778c5edebad123f463d" +dependencies = [ + "rand 0.9.5", + "rmp-serde", + "serde", + "serde_bytes", + "smallvec", + "twox-hash", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "hll-tail-study" +version = "0.1.0" +dependencies = [ + "asap_sketchlib", + "rand 0.9.5", + "rand_distr", + "rand_xoshiro", + "rayon", + "serde_json", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_distr" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463" +dependencies = [ + "num-traits", + "rand 0.9.5", +] + +[[package]] +name = "rand_xoshiro" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41" +dependencies = [ + "rand_core 0.9.5", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" +dependencies = [ + "rand 0.10.4", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/hll-tail-study/Cargo.toml b/hll-tail-study/Cargo.toml new file mode 100644 index 00000000..ca246b32 --- /dev/null +++ b/hll-tail-study/Cargo.toml @@ -0,0 +1,29 @@ +# Per-value tail error of the HLL state the ASAPPlanner executor keeps +# (study_saturation.py --phase hll-tail). Its own workspace: it pins the +# asap_sketchlib commit the executor runs, not the benchmark's pin. +[workspace] + +[package] +name = "hll-tail-study" +version = "0.1.0" +edition = "2021" +license = "MIT" + +[features] +# Measure the classic dense registers (`HyperLogLogImpl`, the +# executor's state before the sparse phase) instead of `HyperLogLogSparse`. +dense = [] + +[dependencies] +# The commit the executor pins (its `HllRegisters`); move with it. +asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = "d28d5a65cede6486aa32f778c5edebad123f463d" } +rand = "0.9" +rand_distr = "0.5" +rand_xoshiro = "0.7" +rayon = "1" +serde_json = "1" + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 diff --git a/hll-tail-study/src/bin/univmon-tail.rs b/hll-tail-study/src/bin/univmon-tail.rs new file mode 100644 index 00000000..57a10a77 --- /dev/null +++ b/hll-tail-study/src/bin/univmon-tail.rs @@ -0,0 +1,217 @@ +//! Per-value tail error of the executor's UnivMon state +//! (`asap_sketchlib::UnivMon`, updated as the executor's +//! `UnivMonAccumulator::insert_sample` does: one unit-weight update of the +//! sample's f64 bits per row) for its distinct count (relative error) and +//! frequency entropy (absolute error, bits). Its total (`estimate_l1`) is the +//! exact row count, so it is not measured. +//! +//! A point is (shape, distribution, distinct count `n`, panes `m`). A trial +//! makes a stream of `4 n` rows over exactly `n` keys: every key once, then +//! `3 n` more rows, each key drawn uniformly (`uniform`) or from Zipf(1.1) +//! over the `n` keys (`zipf1.1`). Each row goes to a uniformly random pane; +//! one state per non-empty pane is built and merged in pane order, as a +//! window chain merges its panes. The errors are against the stream's exact +//! distinct count and entropy. One JSON line per (point, statistic), as +//! `hll-tail-study` prints them, plus the shape and distribution. +//! +//! Usage: univmon-tail --shapes 256:5:1024:16,13500:1:1:19 --counts 1,10,100 +//! --panes 1,6 --trials 200 --deltas 0.02,0.05 [--seed 1] [--threads 32] + +use asap_sketchlib::{DataInput, UnivMon}; +use rand::{Rng, SeedableRng}; +use rand_distr::{Distribution, Zipf}; +use rand_xoshiro::Xoshiro256PlusPlus; +use rayon::prelude::*; + +#[derive(Clone, Copy)] +struct Shape { + heap_size: usize, + rows: usize, + cols: usize, + layers: usize, +} + +const DISTRIBUTIONS: [&str; 2] = ["uniform", "zipf1.1"]; +const ROWS_PER_KEY: u64 = 4; + +struct Job { + shape: Shape, + distribution: &'static str, + n: u64, + panes: usize, + trials: u32, + seed: u64, + deltas: Vec, +} + +fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +fn error_at(sorted: &[f64], delta: f64) -> f64 { + let allowed = (delta * sorted.len() as f64).floor() as usize; + sorted[sorted.len() - 1 - allowed.min(sorted.len() - 1)] +} + +/// One trial's (relative distinct-count error, absolute entropy error). +fn trial(job: &Job, trial: u32) -> (f64, f64) { + let distribution_index = DISTRIBUTIONS + .iter() + .position(|d| *d == job.distribution) + .unwrap(); + let key = mix(job.seed ^ mix(job.n ^ mix(u64::from(trial) ^ mix(distribution_index as u64)))); + let mut rng = Xoshiro256PlusPlus::seed_from_u64(key); + let zipf = Zipf::new(job.n as f64, 1.1).unwrap(); + let mut counts = vec![1u64; job.n as usize]; + let mut rows: Vec = (0..job.n).collect(); + for _ in 0..(ROWS_PER_KEY - 1) * job.n { + let k = match distribution_index { + 0 => rng.random_range(0..job.n), + _ => zipf.sample(&mut rng) as u64 - 1, + }; + counts[k as usize] += 1; + rows.push(k); + } + let mut panes: Vec> = vec![Vec::new(); job.panes]; + for k in rows { + panes[rng.random_range(0..job.panes)].push(k); + } + let s = job.shape; + let mut merged: Option = None; + for pane in panes.iter().filter(|pane| !pane.is_empty()) { + let mut state = UnivMon::new(s.heap_size, s.rows, s.cols, s.layers); + for &k in pane { + // The executor's sample identity: the value's f64 bits (key ids + // are distinct non-zero samples). + let value = (k + 1) as f64; + state.update_weighted(&DataInput::U64(value.to_bits()), 1); + } + match merged.as_mut() { + None => merged = Some(state), + Some(acc) => acc.merge(&state), + } + } + let state = merged.unwrap(); + let total = (ROWS_PER_KEY * job.n) as f64; + let entropy = total.log2() + - counts + .iter() + .map(|&c| c as f64 * (c as f64).log2()) + .sum::() + / total; + let cardinality_error = (state.estimate_cardinality() - job.n as f64).abs() / job.n as f64; + let entropy_error = (state.estimate_entropy() - entropy).abs(); + (cardinality_error, entropy_error) +} + +fn list(text: &str, flag: &str) -> Vec { + text.split(',') + .filter(|s| !s.is_empty()) + .map(|s| { + s.parse() + .unwrap_or_else(|_| panic!("{flag}: cannot parse {s:?}")) + }) + .collect() +} + +fn main() { + let mut shapes = Vec::new(); + let mut counts: Vec = vec![1, 10, 100, 1_000]; + let mut panes: Vec = vec![1]; + let mut deltas: Vec = vec![0.05]; + let (mut trials, mut seed, mut threads) = (200u32, 1u64, 0usize); + let args: Vec = std::env::args().skip(1).collect(); + for pair in args.chunks(2) { + let [flag, value] = pair else { + panic!("{} needs a value", pair[0]) + }; + match flag.as_str() { + "--shapes" => { + shapes = value + .split(',') + .map(|shape| { + let v: Vec = list(&shape.replace(':', ","), flag); + let [heap_size, rows, cols, layers] = v[..] else { + panic!("--shapes: heap:rows:cols:layers, not {shape}") + }; + UnivMon::check_shape(heap_size, rows, cols, layers) + .unwrap_or_else(|e| panic!("{shape}: {e:?}")); + Shape { + heap_size, + rows, + cols, + layers, + } + }) + .collect() + } + "--counts" => counts = list(value, flag), + "--panes" => panes = list(value, flag), + "--deltas" => deltas = list(value, flag), + "--trials" => trials = value.parse().expect("--trials"), + "--seed" => seed = value.parse().expect("--seed"), + "--threads" => threads = value.parse().expect("--threads"), + other => panic!("unknown flag {other}"), + } + } + assert!(!shapes.is_empty(), "--shapes is required"); + rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build_global() + .unwrap(); + let mut jobs = Vec::new(); + for &shape in &shapes { + for distribution in DISTRIBUTIONS { + for &n in &counts { + for &m in &panes { + let deltas = deltas.clone(); + jobs.push(Job { + shape, + distribution, + n, + panes: m, + trials, + seed, + deltas, + }); + } + } + } + } + let stdout = std::sync::Mutex::new(std::io::stdout()); + jobs.par_iter().for_each(|job| { + let (mut cardinality, mut entropy): (Vec, Vec) = + (0..job.trials).map(|t| trial(job, t)).unzip(); + cardinality.sort_by(f64::total_cmp); + entropy.sort_by(f64::total_cmp); + let s = job.shape; + let mut out = stdout.lock().unwrap(); + for (statistic, metric, errors) in [ + ("Cardinality", "relative", &cardinality), + ("FrequencyEntropy", "absolute", &entropy), + ] { + let line = serde_json::json!({ + "shape": {"heap_size": s.heap_size, "sketch_rows": s.rows, + "sketch_cols": s.cols, "layers": s.layers}, + "statistic": statistic, + "accuracy_metric": metric, + "distribution": job.distribution, + "n": job.n, + "panes": job.panes, + "trials": job.trials, + "seed": job.seed, + "deltas": job.deltas, + "errors_at": job.deltas.iter().map(|&d| error_at(errors, d)).collect::>(), + "max_error": errors.last().unwrap(), + "mean_error": errors.iter().sum::() / errors.len() as f64, + }); + use std::io::Write; + writeln!(out, "{line}").unwrap(); + } + use std::io::Write; + out.flush().unwrap(); + }); +} diff --git a/hll-tail-study/src/main.rs b/hll-tail-study/src/main.rs new file mode 100644 index 00000000..be33e64b --- /dev/null +++ b/hll-tail-study/src/main.rs @@ -0,0 +1,248 @@ +//! Per-value tail error of the executor's HLL state: `HyperLogLogSparse` +//! (an exact hash set up to m/8 hashes, then the classic registers and +//! estimate), or with `--features dense` the classic registers alone. +//! +//! For every point (precision `lg_k`, distinct count `n`, panes `m`) it runs +//! `trials` independent trials. A trial makes `n` distinct items, puts each +//! in a uniformly random pane and, with probability 1/2, again in a second +//! random pane (the same item seen in several windows), builds one state per +//! non-empty pane, merges them in pane order into one state (as a window +//! chain merges its panes) and reads the distinct count the way the executor +//! does. Its error is `|estimate - n| / n`. A trial's items are the same at +//! every pane count and precision (common random numbers). +//! +//! One JSON line per point: the error not exceeded except in at most +//! `floor(delta * trials)` trials, for each requested `delta`, plus the +//! largest and mean error. +//! +//! Usage: hll-tail-study --lg-ks 12,13 --counts 1,10,100 --panes 1,6 +//! --trials 1000 --deltas 0.01,0.05 [--seed 1] [--threads 32] + +use asap_sketchlib::DataInput; +use rand::{Rng, SeedableRng}; +use rand_xoshiro::Xoshiro256PlusPlus; +use rayon::prelude::*; + +/// The state a window keeps, as the executor builds, merges and reads it. +trait HllState: Sized { + const STATE: &'static str; + fn new() -> Self; + fn update(&mut self, item: &DataInput); + fn merge(&mut self, other: &Self); + fn estimate(&self) -> f64; +} + +macro_rules! states { + ($($storage:ident = $precision:literal),* $(,)?) => { + $(asap_sketchlib::impl_hll_registers!($storage, $precision, 1_usize << $precision);)* + + #[cfg(feature = "dense")] + mod state { + use super::*; + use asap_sketchlib::sketches::hll::HyperLogLogImpl; + use asap_sketchlib::Classic; + $(impl HllState for HyperLogLogImpl { + const STATE: &'static str = "dense"; + fn new() -> Self { HyperLogLogImpl::::new() } + fn update(&mut self, item: &DataInput) { HyperLogLogImpl::::update(self, item) } + fn merge(&mut self, other: &Self) { HyperLogLogImpl::::merge(self, other) } + // The executor's readout: the library's integer estimate. + fn estimate(&self) -> f64 { HyperLogLogImpl::::estimate(self) as f64 } + })* + pub fn point(lg_k: u32, job: &super::Job) -> Option { + match lg_k { + $($precision => Some(super::run_point::>(job)),)* + _ => None, + } + } + } + + #[cfg(not(feature = "dense"))] + mod state { + use super::*; + use asap_sketchlib::sketches::hll::HyperLogLogSparse; + $(impl HllState for HyperLogLogSparse<$storage> { + const STATE: &'static str = "sparse"; + fn new() -> Self { HyperLogLogSparse::<$storage>::new() } + fn update(&mut self, item: &DataInput) { HyperLogLogSparse::<$storage>::update(self, item) } + fn merge(&mut self, other: &Self) { HyperLogLogSparse::<$storage>::merge(self, other) } + // The executor's readout (`HllRegisters::estimate`): the + // library's estimate rounded down to an integer. + fn estimate(&self) -> f64 { (HyperLogLogSparse::<$storage>::estimate(self) as usize) as f64 } + })* + pub fn point(lg_k: u32, job: &super::Job) -> Option { + match lg_k { + $($precision => Some(super::run_point::>(job)),)* + _ => None, + } + } + } + }; +} + +states!( + RegistersP4 = 4, + RegistersP6 = 6, + RegistersP8 = 8, + RegistersP10 = 10, + RegistersP12 = 12, + RegistersP13 = 13, + RegistersP14 = 14, + RegistersP15 = 15, + RegistersP16 = 16, + RegistersP17 = 17, + RegistersP18 = 18, +); + +pub struct Job { + lg_k: u32, + n: u64, + panes: usize, + trials: u32, + seed: u64, + deltas: Vec, +} + +pub struct PointResult { + state: &'static str, + errors_at: Vec, + max_error: f64, + mean_error: f64, +} + +/// SplitMix64's finalizer: a bijection on u64, so distinct inputs give +/// distinct items. +fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// The error not exceeded in more than `floor(delta * errors.len())` of the +/// sorted `errors`. +fn error_at(sorted: &[f64], delta: f64) -> f64 { + let allowed = (delta * sorted.len() as f64).floor() as usize; + sorted[sorted.len() - 1 - allowed.min(sorted.len() - 1)] +} + +/// One trial's relative error. +fn trial(job: &Job, trial: u32) -> f64 { + // The items depend on (seed, n, trial) only, so the same stream is + // measured whole and split into panes: for a state whose merge equals + // the build of the union, every pane count reads the same estimate. + let key = mix(job.seed ^ mix(job.n ^ mix(u64::from(trial)))); + let mut rng = Xoshiro256PlusPlus::seed_from_u64(mix(key ^ job.panes as u64)); + let mut panes: Vec> = vec![Vec::new(); job.panes]; + for i in 0..job.n { + let item = mix(key.wrapping_add(i)) as i64; + panes[rng.random_range(0..job.panes)].push(item); + if rng.random_bool(0.5) { + panes[rng.random_range(0..job.panes)].push(item); + } + } + let mut merged: Option = None; + for pane in panes.iter().filter(|pane| !pane.is_empty()) { + let mut state = S::new(); + for &item in pane { + state.update(&DataInput::I64(item)); + } + match merged.as_mut() { + None => merged = Some(state), + Some(acc) => acc.merge(&state), + } + } + let estimate = merged.map_or(0.0, |state| state.estimate()); + (estimate - job.n as f64).abs() / job.n as f64 +} + +fn run_point(job: &Job) -> PointResult { + let mut errors: Vec = (0..job.trials).map(|t| trial::(job, t)).collect(); + errors.sort_by(f64::total_cmp); + PointResult { + state: S::STATE, + errors_at: job.deltas.iter().map(|&d| error_at(&errors, d)).collect(), + max_error: *errors.last().unwrap(), + mean_error: errors.iter().sum::() / errors.len() as f64, + } +} + +fn list(text: &str, flag: &str) -> Vec { + text.split(',') + .filter(|s| !s.is_empty()) + .map(|s| { + s.parse() + .unwrap_or_else(|_| panic!("{flag}: cannot parse {s:?}")) + }) + .collect() +} + +fn main() { + let mut lg_ks: Vec = (12..=18).collect(); + let mut counts: Vec = vec![1, 10, 100, 1_000, 10_000, 100_000]; + let mut panes: Vec = vec![1]; + let mut deltas: Vec = vec![0.05]; + let (mut trials, mut seed, mut threads) = (1000u32, 1u64, 0usize); + let args: Vec = std::env::args().skip(1).collect(); + for pair in args.chunks(2) { + let [flag, value] = pair else { + panic!("{} needs a value", pair[0]) + }; + match flag.as_str() { + "--lg-ks" => lg_ks = list(value, flag), + "--counts" => counts = list(value, flag), + "--panes" => panes = list(value, flag), + "--deltas" => deltas = list(value, flag), + "--trials" => trials = value.parse().expect("--trials"), + "--seed" => seed = value.parse().expect("--seed"), + "--threads" => threads = value.parse().expect("--threads"), + other => panic!("unknown flag {other}"), + } + } + assert!(trials > 0 && counts.iter().all(|&n| n > 0) && panes.iter().all(|&m| m > 0)); + rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build_global() + .unwrap(); + // Largest points first, so the long ones do not finish last. + let mut jobs = Vec::new(); + for &lg_k in &lg_ks { + for &n in &counts { + for &m in &panes { + let deltas = deltas.clone(); + jobs.push(Job { + lg_k, + n, + panes: m, + trials, + seed, + deltas, + }); + } + } + } + jobs.sort_by_key(|job| { + std::cmp::Reverse(job.n * (1u64 << job.lg_k.min(18)) / 1024 + job.panes as u64) + }); + let stdout = std::sync::Mutex::new(std::io::stdout()); + jobs.par_iter().for_each(|job| { + let result = state::point(job.lg_k, job) + .unwrap_or_else(|| panic!("lg_k {} is not built (4..=18 even, 12..=18)", job.lg_k)); + let line = serde_json::json!({ + "lg_k": job.lg_k, + "n": job.n, + "panes": job.panes, + "trials": job.trials, + "seed": job.seed, + "state": result.state, + "deltas": job.deltas, + "errors_at": result.errors_at, + "max_error": result.max_error, + "mean_error": result.mean_error, + }); + use std::io::Write; + let mut out = stdout.lock().unwrap(); + writeln!(out, "{line}").unwrap(); + out.flush().unwrap(); + }); +} diff --git a/scripts/studies/study_saturation.py b/scripts/studies/study_saturation.py index 358371bb..de50a026 100644 --- a/scripts/studies/study_saturation.py +++ b/scripts/studies/study_saturation.py @@ -32,6 +32,9 @@ row and column, so the grid stays a full cross) and a = 2 joins --alphas. --phase hydra measures Hydra's per-group error on the eval's datasets and a generic hierarchy (HYDRA_SWEEPS) into hydra_saturation.csv; see `hydra`. +--phase hll-tail measures the per-value tail error of the HLL state the +ASAPPlanner executor keeps (hll-tail-study) into the planner's measured +accuracy table; see `hll_tail`. --resume keeps the complete curves of an interrupted accuracy run; --cost-rows 3 times only the rows=3 Vector2D configs. @@ -50,6 +53,8 @@ rqe_atomic_costs.json (+ _raw, _grid .jsonl) --phase optimizer-cost only hydra_saturation.csv (+ hydra_accuracy.jsonl) --phase hydra only: one row per run, HYDRA_COLUMNS + hll_tail.jsonl, hll_tail.csv, hll_tail_ranges.csv, + hll_measured_accuracy.json --phase hll-tail only """ import argparse @@ -831,6 +836,255 @@ def measure(i, job): return 0 +# --phase hll-tail: the per-value tail error of the HLL state the ASAPPlanner +# executor keeps, for its measured accuracy table. A point is (lg_k, distinct +# count n, panes m); hll-tail-study runs HLL_TAIL_TRIALS trials of each (see +# its main.rs: n distinct items, half of them also in a second pane, one +# state per pane merged in pane order) and reports the error not exceeded in +# more than floor(δ · trials) trials. Panes 6, 60, 360: a 1 min, 10 min and +# 1 h window of 10 s panes. +HLL_TAIL_BINARY = "./hll-tail-study/target/release/hll-tail-study" +HLL_TAIL_LG_KS = tuple(range(12, 19)) +# Counts up to 1e6: the worst error sits where the estimator switches from +# linear counting to the harmonic mean, near 2.5 · 2^lg_k (655,360 at +# lg_k 18), so a smaller top count misses it for the large precisions. +HLL_TAIL_N_MAX = 1e6 +HLL_TAIL_PANES = (1, 6, 60, 360) +HLL_TAIL_TRIALS = 2000 +HLL_TAIL_DELTAS = (0.005, 0.01, 0.02, 0.05, 0.1) +# Count ranges the summary names the least passing lg_k for: [lo, hi). +HLL_TAIL_RANGES = ((1, 10), (10, 100), (100, 1_000), (1_000, 10_000), (10_000, 100_001), + (100_001, 1_000_001)) +HLL_TAIL_TABLE = "hll_measured_accuracy.json" + + +def hll_tail_errors(record): + """{δ: error} of one hll-tail-study record.""" + return dict(zip(record["deltas"], record["errors_at"])) + + +def hll_tail_worst(records, deltas): + """{lg_k: (trials, {δ: (error, n, panes)})}: per precision and δ, the + largest error over every count and pane count measured, with where it + was found. trials is the fewest any point ran.""" + worst = {} + for record in records: + entry = worst.setdefault(record["lg_k"], [record["trials"], {}]) + entry[0] = min(entry[0], record["trials"]) + at = entry[1] + errors = hll_tail_errors(record) + for delta in deltas: + error = errors[delta] + if delta not in at or error > at[delta][0]: + at[delta] = (error, record["n"], record["panes"]) + return {lg_k: (trials, at) for lg_k, (trials, at) in worst.items()} + + +def measured_accuracy_table(worst, deltas): + """The planner's MeasuredSketchAccuracy JSON (ASAPPlanner + crates/accuracy/src/measured.rs): one entry per precision, HLL read for + its distinct count, relative error, at every δ the trials can record + (δ ≥ 3 / trials); each error is the worst over the counts and pane counts + measured. Errors are made non-increasing in δ (a larger δ never records + a larger error, which a max over points already gives).""" + entries = [] + for lg_k in sorted(worst): + trials, at = worst[lg_k] + points, floor = [], math.inf + for delta in sorted(deltas): + if delta < 3 / trials: + continue + floor = min(floor, at[delta][0]) + points.append({"failure_probability": delta, "error": floor}) + entries.append({"sketch": {"Hll": {"precision": lg_k}}, "statistic": "Cardinality", + "accuracy_metric": "relative", "trials": trials, "error_at": points}) + return {"entries": entries} + + +def hll_tail_ranges(records, delta, target, ranges=HLL_TAIL_RANGES): + """Per count range [lo, hi): (lo, hi, {lg_k: worst error at δ over the + range's counts and every pane count}, least lg_k whose worst error is at + most target, or None).""" + rows = [] + for lo, hi in ranges: + per_lg_k = {} + for record in records: + if lo <= record["n"] < hi: + error = hll_tail_errors(record)[delta] + per_lg_k[record["lg_k"]] = max(per_lg_k.get(record["lg_k"], 0.0), error) + passing = [lg_k for lg_k, error in per_lg_k.items() if error <= target] + rows.append((lo, hi, per_lg_k, min(passing) if passing else None)) + return rows + + +def read_hll_tail(path): + """hll-tail-study's records in `path`, one per (lg_k, n, panes) (a point + rerun after an interruption is the same deterministic record), sorted; a + line cut off mid-write is skipped.""" + records = {} + with open(path) as f: + for line in f: + try: + record = json.loads(line) + except json.JSONDecodeError: + continue + records.setdefault((record["lg_k"], record["n"], record["panes"]), record) + return [records[key] for key in sorted(records)] + + +def hll_tail(args): + """--phase hll-tail: run hll-tail-study over the grid into + --out/hll_tail.jsonl, then write hll_tail.csv (one row per point), + hll_tail_ranges.csv (least passing lg_k per count range at + --hll-target, --hll-target-delta) and hll_measured_accuracy.json.""" + os.makedirs(args.out, exist_ok=True) + deltas = [float(d) for d in args.hll_deltas.split(",")] + counts = checkpoints(1, args.hll_n_max, args.hll_per_decade) + raw = os.path.join(args.out, "hll_tail.jsonl") + command = [args.hll_binary, "--lg-ks", args.hll_lg_ks, "--counts", ",".join(map(str, counts)), + "--panes", args.hll_panes, "--trials", str(args.hll_trials), "--deltas", + ",".join(map(str, deltas)), "--seed", str(args.hll_seed), "--threads", + str(args.hll_threads)] + if not args.hll_reduce_only: + print(" ".join(command), file=sys.stderr) + with open(raw, "w") as f: + subprocess.run(command, check=True, stdout=f, stdin=subprocess.DEVNULL) + records = read_hll_tail(raw) + with open(os.path.join(args.out, "hll_tail.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(["lg_k", "n", "panes", "trials", "state", "max_error", "mean_error"] + + [f"error_at_{d}" for d in deltas]) + for r in records: + errors = hll_tail_errors(r) + w.writerow([r["lg_k"], r["n"], r["panes"], r["trials"], r["state"], r["max_error"], + r["mean_error"]] + [errors[d] for d in deltas]) + lg_ks = sorted({r["lg_k"] for r in records}) + with open(os.path.join(args.out, "hll_tail_ranges.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(["n_from", "n_below", "delta", "target"] + [f"lg_k_{k}" for k in lg_ks] + + ["least_passing_lg_k"]) + for lo, hi, per_lg_k, least in hll_tail_ranges(records, args.hll_target_delta, + args.hll_target): + w.writerow([lo, hi, args.hll_target_delta, args.hll_target] + + [per_lg_k.get(k, "") for k in lg_ks] + ["" if least is None else least]) + worst = hll_tail_worst(records, deltas) + with open(os.path.join(args.out, HLL_TAIL_TABLE), "w") as f: + json.dump(measured_accuracy_table(worst, deltas), f, indent=2) + f.write("\n") + for lg_k in sorted(worst): + trials, at = worst[lg_k] + print(f"lg_k {lg_k}: " + ", ".join( + f"δ {d}: {at[d][0]:.4f} (n {at[d][1]}, panes {at[d][2]})" for d in deltas), + file=sys.stderr) + + +# --phase univmon-tail: the same per-value tail error for the UnivMon shapes +# ASAPPlanner lists (its parameter_lists UNIVMON_PARAMETERS: L2 shapes +# 1 x 5 x cols x 1, distinct shapes heap x 1 x 1 x 19, each L2 cols x each +# distinct heap at 5 rows and 19 layers, and 256 x 5 x 1024 x 16), read for +# the distinct count (relative error) and the frequency entropy (absolute, +# bits); see univmon-tail.rs. The total (estimate_l1) is the exact row +# count and is not measured. A shape whose state exceeds --um-max-state-mb +# (UNIVMON_STATE_BYTES) is left out and reported. +UNIVMON_L2_COLUMNS = (624, 2_367, 14_349, 56_817, 226_130, 1_409_067, 5_630_630) +UNIVMON_DISTINCT_HEAP_SIZES = (13_500, 54_000, 337_500, 1_350_000) +UNIVMON_TAIL_BINARY = "./hll-tail-study/target/release/univmon-tail" +UNIVMON_TAIL_PANES = (1, 6) +UNIVMON_TAIL_TRIALS = 200 +UNIVMON_TAIL_DELTAS = (0.02, 0.05, 0.1) +UNIVMON_TAIL_TABLE = "univmon_measured_accuracy.json" + + +def univmon_shapes(): + """The planner's UnivMon list, as (heap_size, rows, cols, layers).""" + return ([(1, 5, cols, 1) for cols in UNIVMON_L2_COLUMNS] + + [(heap, 1, 1, 19) for heap in UNIVMON_DISTINCT_HEAP_SIZES] + + [(heap, 5, cols, 19) for cols in UNIVMON_L2_COLUMNS + for heap in UNIVMON_DISTINCT_HEAP_SIZES] + + [(256, 5, 1024, 16)]) + + +def univmon_state_bytes(shape): + """A UnivMon state's bytes, roughly: per layer an i64 Count Sketch + (rows x cols) and a full heap (about 24 bytes a slot).""" + heap, rows, cols, layers = shape + return layers * (8 * rows * cols + 24 * heap) + + +def univmon_tail_worst(records, deltas): + """{(shape, statistic, metric): (trials, {δ: (error, n, panes, dist)})}: + the largest error over every count, pane count and distribution.""" + worst = {} + for r in records: + shape = tuple(r["shape"][k] for k in ("heap_size", "sketch_rows", "sketch_cols", "layers")) + entry = worst.setdefault((shape, r["statistic"], r["accuracy_metric"]), [r["trials"], {}]) + entry[0] = min(entry[0], r["trials"]) + errors = hll_tail_errors(r) + for delta in deltas: + if delta not in entry[1] or errors[delta] > entry[1][delta][0]: + entry[1][delta] = (errors[delta], r["n"], r["panes"], r["distribution"]) + return {key: (trials, at) for key, (trials, at) in worst.items()} + + +def univmon_measured_accuracy_table(worst, deltas): + """The planner's MeasuredSketchAccuracy JSON for `univmon_tail_worst`.""" + entries = [] + for (shape, statistic, metric) in sorted(worst): + trials, at = worst[(shape, statistic, metric)] + points, floor = [], math.inf + for delta in sorted(deltas): + if delta < 3 / trials: + continue + floor = min(floor, at[delta][0]) + points.append({"failure_probability": delta, "error": floor}) + heap, rows, cols, layers = shape + entries.append({"sketch": {"UnivMon": {"heap_size": heap, "sketch_rows": rows, + "sketch_cols": cols, "layers": layers}}, + "statistic": statistic, "accuracy_metric": metric, "trials": trials, + "error_at": points}) + return {"entries": entries} + + +def univmon_tail(args): + """--phase univmon-tail: run univmon-tail over the planner's UnivMon + shapes that fit --um-max-state-mb into --out/univmon_tail.jsonl, then + write univmon_tail.csv (worst per shape and statistic) and + univmon_measured_accuracy.json.""" + os.makedirs(args.out, exist_ok=True) + deltas = [float(d) for d in args.um_deltas.split(",")] + shapes = [s for s in univmon_shapes() + if univmon_state_bytes(s) <= args.um_max_state_mb * 2**20] + for s in univmon_shapes(): + if s not in shapes: + print(f"univmon-tail: shape {s} left out: about " + f"{univmon_state_bytes(s) / 2**20:.0f} MB a state", file=sys.stderr) + counts = checkpoints(1, args.um_n_max, args.um_per_decade) + raw = os.path.join(args.out, "univmon_tail.jsonl") + command = [args.um_binary, "--shapes", ",".join(":".join(map(str, s)) for s in shapes), + "--counts", ",".join(map(str, counts)), "--panes", args.um_panes, + "--trials", str(args.um_trials), "--deltas", ",".join(map(str, deltas)), + "--seed", str(args.hll_seed), "--threads", str(args.hll_threads)] + if not args.hll_reduce_only: + print(" ".join(command), file=sys.stderr) + with open(raw, "w") as f: + subprocess.run(command, check=True, stdout=f, stdin=subprocess.DEVNULL) + with open(raw) as f: + records = [json.loads(line) for line in f if line.strip()] + worst = univmon_tail_worst(records, deltas) + with open(os.path.join(args.out, "univmon_tail.csv"), "w", newline="") as f: + w = csv.writer(f) + w.writerow(["heap_size", "sketch_rows", "sketch_cols", "layers", "statistic", + "accuracy_metric", "trials"] + + [c for d in deltas for c in (f"error_at_{d}", f"worst_n_at_{d}", + f"worst_dist_at_{d}")]) + for (shape, statistic, metric), (trials, at) in sorted(worst.items()): + w.writerow(list(shape) + [statistic, metric, trials] + + [x for d in deltas for x in (at[d][0], at[d][1], at[d][3])]) + with open(os.path.join(args.out, UNIVMON_TAIL_TABLE), "w") as f: + json.dump(univmon_measured_accuracy_table(worst, deltas), f, indent=2) + f.write("\n") + + def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter @@ -865,13 +1119,14 @@ def main(): help="parallel accuracy runs (cost runs are always serial)") parser.add_argument("--phase", choices=["accuracy", "cost", "crossover", "all", "optimizer-cost", - "hydra"], + "hydra", "hll-tail", "univmon-tail"], default="all", help="cost reads saturation_curve.csv from --out; crossover " "recomputes crossover.csv from the cost phase's JSONL in --out; " "optimizer-cost writes the optimizer's cost table to --out " "(the grid's configs at one shape, no curves); hydra writes " - "hydra_saturation.csv (HYDRA_SWEEPS, its own grid)") + "hydra_saturation.csv (HYDRA_SWEEPS, its own grid); hll-tail " + "writes the HLL per-value tail-error table (its own grid)") parser.add_argument("--points-from", help="CSV with sketch,config,dist,param,cardinality columns " "(e.g. a filtered saturation.csv): run only those points") @@ -903,8 +1158,40 @@ def main(): parser.add_argument("--hydra-groupings", help="hydra: only these groupings, ';'-separated, labels by name " "joined by ',' in schema order") + parser.add_argument("--hll-binary", default=HLL_TAIL_BINARY, help="hll-tail: hll-tail-study") + parser.add_argument("--hll-lg-ks", default=",".join(map(str, HLL_TAIL_LG_KS)), + help="hll-tail: precisions") + parser.add_argument("--hll-n-max", type=float, default=HLL_TAIL_N_MAX, + help="hll-tail: distinct counts 1..this, log-spaced") + parser.add_argument("--hll-per-decade", type=int, default=10) + parser.add_argument("--hll-panes", default=",".join(map(str, HLL_TAIL_PANES)), + help="hll-tail: pane counts a state is merged from") + parser.add_argument("--hll-trials", type=int, default=HLL_TAIL_TRIALS) + parser.add_argument("--hll-deltas", default=",".join(map(str, HLL_TAIL_DELTAS)), + help="hll-tail: failure probabilities to record") + parser.add_argument("--hll-seed", type=int, default=1) + parser.add_argument("--hll-threads", type=int, default=32) + parser.add_argument("--hll-target", type=float, default=0.05, + help="hll-tail: relative error hll_tail_ranges.csv checks") + parser.add_argument("--hll-target-delta", type=float, default=0.05) + parser.add_argument("--hll-reduce-only", action="store_true", + help="hll-tail: reduce --out/hll_tail.jsonl without running") + parser.add_argument("--um-binary", default=UNIVMON_TAIL_BINARY, + help="univmon-tail: univmon-tail") + parser.add_argument("--um-n-max", type=float, default=1e5, + help="univmon-tail: distinct counts 1..this, log-spaced") + parser.add_argument("--um-per-decade", type=int, default=5) + parser.add_argument("--um-panes", default=",".join(map(str, UNIVMON_TAIL_PANES))) + parser.add_argument("--um-trials", type=int, default=UNIVMON_TAIL_TRIALS) + parser.add_argument("--um-deltas", default=",".join(map(str, UNIVMON_TAIL_DELTAS))) + parser.add_argument("--um-max-state-mb", type=float, default=64, + help="univmon-tail: leave out shapes with larger states") args = parser.parse_args() check_filters(args) + if args.phase == "hll-tail": + return hll_tail(args) + if args.phase == "univmon-tail": + return univmon_tail(args) if args.phase == "hydra": return hydra(args) diff --git a/scripts/studies/test_study_saturation.py b/scripts/studies/test_study_saturation.py index caee71c8..f383cc8d 100644 --- a/scripts/studies/test_study_saturation.py +++ b/scripts/studies/test_study_saturation.py @@ -19,7 +19,8 @@ from study_saturation import ( # noqa: E402 HYDRA_COLUMNS, HYDRA_DATAGEN, HYDRA_SWEEPS, check_filters, checkpoints, covered_max, - filtered_configs, hydra_groupings, + filtered_configs, hll_tail_ranges, hll_tail_worst, hydra_groupings, measured_accuracy_table, + univmon_measured_accuracy_table, univmon_shapes, univmon_tail_worst, hydra_jobs, hydra_labels, hydra_spec, n_saturation, n_star, read_curve, read_per_group) SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "study_saturation.py") @@ -858,5 +859,73 @@ def test_a_misspelled_sketch_or_config_exits(self): check_filters(self.args(None, "k=26")) +def hll_record(lg_k, n, panes, errors, trials=1000, deltas=(0.01, 0.05)): + return {"lg_k": lg_k, "n": n, "panes": panes, "trials": trials, "deltas": list(deltas), + "errors_at": list(errors), "max_error": max(errors), "mean_error": 0.0, + "state": "dense"} + + +class HllTailTest(unittest.TestCase): + RECORDS = [ + hll_record(12, 10, 1, [0.1, 0.0]), + hll_record(12, 10_000, 1, [0.06, 0.045]), + hll_record(12, 10_000, 360, [0.05, 0.048]), + hll_record(14, 10, 1, [0.0, 0.0]), + hll_record(14, 10_000, 60, [0.015, 0.012], trials=500), + ] + + def test_worst_is_over_counts_and_panes(self): + worst = hll_tail_worst(self.RECORDS, [0.01, 0.05]) + self.assertEqual(worst[12], (1000, {0.01: (0.1, 10, 1), 0.05: (0.048, 10_000, 360)})) + self.assertEqual(worst[14][0], 500) # the fewest trials any point ran + + def test_table_is_the_planners_format(self): + table = measured_accuracy_table(hll_tail_worst(self.RECORDS, [0.01, 0.05]), [0.01, 0.05]) + self.assertEqual(table["entries"][0], { + "sketch": {"Hll": {"precision": 12}}, "statistic": "Cardinality", + "accuracy_metric": "relative", "trials": 1000, + "error_at": [{"failure_probability": 0.01, "error": 0.1}, + {"failure_probability": 0.05, "error": 0.048}]}) + + def test_table_drops_deltas_below_three_over_trials(self): + # 500 trials record δ >= 0.006 only. + records = [hll_record(14, 10, 1, [0.02, 0.01], trials=500, deltas=(0.005, 0.01))] + table = measured_accuracy_table(hll_tail_worst(records, [0.005, 0.01]), [0.005, 0.01]) + self.assertEqual(table["entries"][0]["error_at"], + [{"failure_probability": 0.01, "error": 0.01}]) + + def test_table_error_never_grows_with_delta(self): + records = [hll_record(12, 10, 1, [0.02, 0.03])] + table = measured_accuracy_table(hll_tail_worst(records, [0.01, 0.05]), [0.01, 0.05]) + self.assertEqual([p["error"] for p in table["entries"][0]["error_at"]], [0.02, 0.02]) + + def test_ranges_name_the_least_passing_precision(self): + rows = hll_tail_ranges(self.RECORDS, 0.05, 0.047, ranges=((1, 100), (100, 100_001))) + self.assertEqual(rows[0], (1, 100, {12: 0.0, 14: 0.0}, 12)) + self.assertEqual(rows[1], (100, 100_001, {12: 0.048, 14: 0.012}, 14)) + + +class UnivMonTailTest(unittest.TestCase): + def test_shapes_are_the_planners_forty(self): + shapes = univmon_shapes() + self.assertEqual(len(shapes), 40) + self.assertEqual(shapes[0], (1, 5, 624, 1)) + self.assertEqual(shapes[-1], (256, 5, 1024, 16)) + + def test_table_entry_is_worst_over_distributions(self): + shape = {"heap_size": 256, "sketch_rows": 5, "sketch_cols": 1024, "layers": 16} + records = [dict(hll_record(0, n, 1, errors), shape=shape, statistic="FrequencyEntropy", + accuracy_metric="absolute", distribution=dist) + for n, errors, dist in [(10, [0.2, 0.05], "uniform"), + (1000, [0.1, 0.08], "zipf1.1")]] + table = univmon_measured_accuracy_table(univmon_tail_worst(records, [0.01, 0.05]), + [0.01, 0.05]) + self.assertEqual(table["entries"], [{ + "sketch": {"UnivMon": shape}, "statistic": "FrequencyEntropy", + "accuracy_metric": "absolute", "trials": 1000, + "error_at": [{"failure_probability": 0.01, "error": 0.2}, + {"failure_probability": 0.05, "error": 0.08}]}]) + + if __name__ == "__main__": unittest.main() From 87f3ce2584c5f3ff3dc11891642ef6eeead7f46d Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 4 Dec 2026 02:03:33 +0000 Subject: [PATCH 2/2] fix(studies): measure HLL's linear-counting/harmonic-mean switch band The 10-per-decade count grid stepped over the error spike near n = 2.4 * 2^lg_k (the estimate crosses 2.5 * 2^lg_k and switches estimators), so the table understated the worst error by up to 2x (p16 0.0150 vs 0.0319). --phase hll-tail now also runs, per precision, counts at 0.01 m steps over [2.25, 2.6] m and 0.05 m over [2.0, 3.2] m (one pane: merging changes no state; 1,000 trials). New worst at delta 0.05: p12 0.0507 ... p18 0.0297; the least precision meeting rel 0.05 is 13. Co-Authored-By: Claude Opus 5.5 --- docs/saturation_study.md | 41 +++++++++++++----------- scripts/studies/study_saturation.py | 29 +++++++++++++++++ scripts/studies/test_study_saturation.py | 11 ++++++- 3 files changed, 62 insertions(+), 19 deletions(-) diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 725917e5..f133c25a 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -394,7 +394,9 @@ worst over every count and pane count (`hll_tail_worst`) and writes: `Cardinality`, `accuracy_metric` `relative`, `trials`, and `error_at` for every δ ≥ 3 / trials (the planner's validity rule). -Defaults: `lg_k` 12..18, counts 1..1e6 at 10 per decade (58 counts). Small +Defaults: `lg_k` 12..18, counts 1..1e6 at 10 per decade (58 counts) plus +the switch band per precision (`hll_switch_counts`: steps of `0.01 m` over +`[2.25, 2.6] m` and `0.05 m` over `[2.0, 3.2] m`, one pane, 1,000 trials). Small counts are included because below `1/ε` one register collision is already an error above ε; counts go to 1e6 because the worst error sits where the estimator switches from linear counting to the harmonic mean, near @@ -409,27 +411,30 @@ python3 scripts/studies/study_saturation.py --phase hll-tail --hll-threads 32 -- python3 scripts/studies/study_saturation.py --phase hll-tail --hll-reduce-only --out out_hll ``` -Results (2026-12-03, `HyperLogLogSparse` at sketchlib `d28d5a6`, the -defaults above, 1,624 points of 2,000 trials each). In every one of the 406 -(lg_k, n) pairs, all pane counts give the same errors, as the merge-equals-union +Results (2026-12-04, `HyperLogLogSparse` at sketchlib `d28d5a6`). The decade +grid (1,624 points, 2,000 trials each) plus the switch band (53 counts per +precision at one pane, 1,000 trials each). In all 406 (lg_k, n) pairs of the +decade grid, every pane count gives the same errors, as the merge-equals-union property predicts. Below `m/8` items the state is sparse and every error is 0. -Worst relative error per value (the table's entries): +Worst relative error per value (the table's entries, `trials` = 1,000): | lg_k | δ 0.005 | δ 0.01 | δ 0.02 | δ 0.05 | δ 0.1 | worst at (δ 0.05) | |---|---|---|---|---|---|---| -| 12 | 0.0587 | 0.0568 | 0.0527 | 0.0477 | 0.0428 | n = 10,000 | -| 13 | 0.0504 | 0.0478 | 0.0460 | 0.0421 | 0.0384 | n = 19,953 | -| 14 | 0.0428 | 0.0404 | 0.0395 | 0.0369 | 0.0346 | n = 39,811 | -| 15 | 0.0379 | 0.0372 | 0.0360 | 0.0342 | 0.0327 | n = 79,433 | -| 16 | 0.0353 | 0.0345 | 0.0163 | 0.0150 | 0.0137 | n = 199,526 | -| 17 | 0.0159 | 0.0154 | 0.0147 | 0.0136 | 0.0127 | n = 398,107 | -| 18 | 0.0140 | 0.0138 | 0.0132 | 0.0126 | 0.0119 | n = 794,328 | - -Each worst case sits at the classic estimator's switch from linear counting to -the harmonic mean (about `2.5 · 2^lg_k`). For relative error 0.05 at δ 0.05 per -value, the least passing precision is 12 in every count range (1–10, …, -1e5–1e6, `hll_tail_ranges.csv`). For 0.05 at δ 0.005 it is 14 (13 misses: -0.0504). +| 12 | 0.0635 | 0.0599 | 0.0556 | 0.0507 | 0.0449 | n = 9,789 (2.39 m) | +| 13 | 0.0508 | 0.0492 | 0.0464 | 0.0426 | 0.0388 | n = 19,743 (2.41 m) | +| 14 | 0.0437 | 0.0422 | 0.0399 | 0.0375 | 0.0353 | n = 39,649 (2.42 m) | +| 15 | 0.0390 | 0.0384 | 0.0376 | 0.0342 | 0.0327 | n = 79,299 (2.42 m) | +| 16 | 0.0356 | 0.0345 | 0.0334 | 0.0319 | 0.0309 | n = 159,252 (2.43 m) | +| 17 | 0.0331 | 0.0321 | 0.0317 | 0.0308 | 0.0301 | n = 318,505 (2.43 m) | +| 18 | 0.0310 | 0.0306 | 0.0303 | 0.0297 | 0.0291 | n = 637,010 (2.43 m) | + +Every worst case sits in the switch band, about `0.05 m` wide, where the +estimate crosses `2.5 m` and jumps from linear counting to the harmonic mean. +The decade grid alone stepped over it and understated the error by up to 2× +(p16 0.0150, p18 0.0126), which is why the band is part of the default run. +For relative error 0.05 at δ 0.05 per value, the least passing precision is +13: p12 misses (0.0507), in the 1e3–1e4 range (`hll_tail_ranges.csv`). For +0.05 at δ 0.005 it is 14. ### UnivMon (`--phase univmon-tail`) diff --git a/scripts/studies/study_saturation.py b/scripts/studies/study_saturation.py index de50a026..d7507ff1 100644 --- a/scripts/studies/study_saturation.py +++ b/scripts/studies/study_saturation.py @@ -849,6 +849,14 @@ def measure(i, job): # linear counting to the harmonic mean, near 2.5 · 2^lg_k (655,360 at # lg_k 18), so a smaller top count misses it for the large precisions. HLL_TAIL_N_MAX = 1e6 +# The switch band: near n = 2.4 · 2^lg_k the error spikes over a band about +# 0.05 · 2^lg_k wide (the estimate crosses 2.5 · 2^lg_k and jumps from linear +# counting to the harmonic mean), which a 10-per-decade grid steps over. Per +# precision the band adds counts at 0.01 · 2^lg_k steps over [2.25, 2.6] · +# 2^lg_k and 0.05 · 2^lg_k steps over [2.0, 3.2] · 2^lg_k, at one pane +# (merging changes no state: every pane count gives the same errors) and +# HLL_TAIL_SWITCH_TRIALS trials. +HLL_TAIL_SWITCH_TRIALS = 1000 HLL_TAIL_PANES = (1, 6, 60, 360) HLL_TAIL_TRIALS = 2000 HLL_TAIL_DELTAS = (0.005, 0.01, 0.02, 0.05, 0.1) @@ -917,6 +925,14 @@ def hll_tail_ranges(records, delta, target, ranges=HLL_TAIL_RANGES): return rows +def hll_switch_counts(lg_k): + """The switch band's counts for `lg_k` (see HLL_TAIL_N_MAX).""" + m = 2 ** lg_k + fine = [round(m * (2.25 + 0.01 * i)) for i in range(36)] + coarse = [round(m * (2.0 + 0.05 * i)) for i in range(25)] + return sorted(set(fine + coarse)) + + def read_hll_tail(path): """hll-tail-study's records in `path`, one per (lg_k, n, panes) (a point rerun after an interruption is the same deterministic record), sorted; a @@ -949,6 +965,16 @@ def hll_tail(args): print(" ".join(command), file=sys.stderr) with open(raw, "w") as f: subprocess.run(command, check=True, stdout=f, stdin=subprocess.DEVNULL) + if not args.hll_reduce_only and args.hll_switch_band: + for lg_k in args.hll_lg_ks.split(","): + band = [n for n in hll_switch_counts(int(lg_k)) if n <= args.hll_n_max] + band_command = command[:] + for flag, value in (("--lg-ks", lg_k), ("--counts", ",".join(map(str, band))), + ("--panes", "1"), ("--trials", str(args.hll_switch_trials))): + band_command[band_command.index(flag) + 1] = value + print(" ".join(band_command), file=sys.stderr) + with open(raw, "a") as f: + subprocess.run(band_command, check=True, stdout=f, stdin=subprocess.DEVNULL) records = read_hll_tail(raw) with open(os.path.join(args.out, "hll_tail.csv"), "w", newline="") as f: w = csv.writer(f) @@ -1174,6 +1200,9 @@ def main(): parser.add_argument("--hll-target", type=float, default=0.05, help="hll-tail: relative error hll_tail_ranges.csv checks") parser.add_argument("--hll-target-delta", type=float, default=0.05) + parser.add_argument("--hll-switch-band", action=argparse.BooleanOptionalAction, + default=True, help="hll-tail: also run hll_switch_counts per precision") + parser.add_argument("--hll-switch-trials", type=int, default=HLL_TAIL_SWITCH_TRIALS) parser.add_argument("--hll-reduce-only", action="store_true", help="hll-tail: reduce --out/hll_tail.jsonl without running") parser.add_argument("--um-binary", default=UNIVMON_TAIL_BINARY, diff --git a/scripts/studies/test_study_saturation.py b/scripts/studies/test_study_saturation.py index f383cc8d..5f31cc59 100644 --- a/scripts/studies/test_study_saturation.py +++ b/scripts/studies/test_study_saturation.py @@ -19,7 +19,7 @@ from study_saturation import ( # noqa: E402 HYDRA_COLUMNS, HYDRA_DATAGEN, HYDRA_SWEEPS, check_filters, checkpoints, covered_max, - filtered_configs, hll_tail_ranges, hll_tail_worst, hydra_groupings, measured_accuracy_table, + filtered_configs, hll_switch_counts, hll_tail_ranges, hll_tail_worst, hydra_groupings, measured_accuracy_table, univmon_measured_accuracy_table, univmon_shapes, univmon_tail_worst, hydra_jobs, hydra_labels, hydra_spec, n_saturation, n_star, read_curve, read_per_group) @@ -905,6 +905,15 @@ def test_ranges_name_the_least_passing_precision(self): self.assertEqual(rows[1], (100, 100_001, {12: 0.048, 14: 0.012}, 14)) +class HllSwitchBandTest(unittest.TestCase): + def test_band_covers_the_switch_finely(self): + counts = hll_switch_counts(12) + self.assertEqual((counts[0], counts[-1]), (8192, 13107)) + self.assertIn(9748, counts) # 2.38 * 4096, where p12's worst sits + fine = [n for n in counts if 2.25 * 4096 <= n <= 2.6 * 4096] + self.assertTrue(all(b - a <= 41 for a, b in zip(fine, fine[1:]))) + + class UnivMonTailTest(unittest.TestCase): def test_shapes_are_the_planners_forty(self): shapes = univmon_shapes()