From fe5b16332cb3a0db13e7bfb07228e437017c1398 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:13:38 +0000 Subject: [PATCH 1/5] hydra: score any target grouping; per-group error output Every hydra-* row (lib and polars, all five variants and hydra-univmon's four statistics) takes `--group-columns J,K,...` (default `0`, today's behavior) in place of the hardcoded SCORED_LABEL_COLUMN. A subpopulation probe is now positioned (`Vec>`, Some at the grouped columns), so `hydra_shared::query` asks any non-empty subset of the key columns and the polars baselines look up `subset_key` with that subset's mask (`group_key`, generalizing `prefix_key`). Each grouped comparator reports its per-group error in its own metric (relative error; mean rank error for hydra-kll) and summarises it as err_mean, err_p50, err_p90, err_max, groups_scored, plus schema_width, records and fanned_mass. `--per-group-out PATH` writes the rows as `group_key,n_q,error`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- README.md | 6 + aqpbm-cli/src/cli.rs | 17 +++ aqpbm-cli/src/main.rs | 15 ++ aqpbm-cli/src/rows/hydra_univmon.rs | 12 +- aqpbm-cli/src/rows/mod.rs | 9 +- aqpbm-cli/src/rows/statistic.rs | 85 +++++++++-- aqpbm-cli/tests/hydra_grouping.rs | 137 ++++++++++++++++++ aqpbm-core/src/accuracy/mod.rs | 37 ++++- .../src/accuracy/subpopulation/cardinality.rs | 91 ++++++++---- .../src/accuracy/subpopulation/entropy.rs | 27 +++- .../src/accuracy/subpopulation/frequency.rs | 113 ++++++++++----- .../subpopulation/frequency_vector.rs | 77 +++++++--- .../src/accuracy/subpopulation/l1_norm.rs | 86 ++++++++++- .../src/accuracy/subpopulation/l2_norm.rs | 27 +++- aqpbm-core/src/accuracy/subpopulation/mod.rs | 82 ++++++++++- .../src/accuracy/subpopulation/rank_error.rs | 112 +++++++++----- configs/datagen/hydra_columns.yaml | 3 +- configs/datagen/hydra_columns_f64.yaml | 3 +- configs/datagen/hydra_columns_string.yaml | 3 +- configs/datagen/hydra_columns_u64.yaml | 3 +- .../datagen/hydra_kll_disjoint_labels.yaml | 3 +- configs/datagen/hydra_univmon_columns.yaml | 3 +- sketch-bench/src/request.rs | 4 + sketch-bench/src/wrappers/hydra_cms/mod.rs | 19 ++- sketch-bench/src/wrappers/hydra_cms/polars.rs | 4 +- .../src/wrappers/hydra_cms/sketchlib.rs | 10 +- sketch-bench/src/wrappers/hydra_cs/mod.rs | 15 +- sketch-bench/src/wrappers/hydra_cs/polars.rs | 4 +- .../src/wrappers/hydra_cs/sketchlib.rs | 10 +- sketch-bench/src/wrappers/hydra_hll/mod.rs | 6 +- sketch-bench/src/wrappers/hydra_hll/polars.rs | 4 +- .../src/wrappers/hydra_hll/sketchlib.rs | 6 +- sketch-bench/src/wrappers/hydra_kll/mod.rs | 6 +- sketch-bench/src/wrappers/hydra_kll/polars.rs | 6 +- .../src/wrappers/hydra_kll/sketchlib.rs | 6 +- sketch-bench/src/wrappers/hydra_shared.rs | 17 ++- .../src/wrappers/hydra_univmon/mod.rs | 19 ++- .../src/wrappers/hydra_univmon/polars.rs | 14 +- .../src/wrappers/hydra_univmon/sketchlib.rs | 28 ++-- sketch-bench/src/wrappers/polars_shared.rs | 38 +++-- 40 files changed, 885 insertions(+), 282 deletions(-) create mode 100644 aqpbm-cli/tests/hydra_grouping.rs diff --git a/README.md b/README.md index a0e3b1b8..f9414e41 100644 --- a/README.md +++ b/README.md @@ -449,6 +449,12 @@ The file can be found [under configs directory](./configs/datagen/hydra_columns. **`--flat`**: flatten record such that output data of multiple experiments is flatten into one json file. +**`--group-columns`** (Hydra rows only): which label columns the subpopulation is taken over, as comma-separated indices into the columns before the value column, e.g. `1` or `0,1`; default `0`. +Any non-empty subset works, since the grid stores every subset of a record's labels; it picks the one the `hydra-*` row (`lib` and `polars`) asks and scores. +With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). + +**`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per scored group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`). + #### General Explanation Most of the input and output is shared between this hydra example and the previous hll example. diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index bd14e42a..1667a45c 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -234,10 +234,27 @@ pub struct SketchbenchArgs { /// merge exactly, so a gap is a defect; for KLL it is the result. #[arg(long, default_value_t = 2, help_heading = "Measurement content")] pub merge_shards: usize, + /// Which label columns the `hydra-*` rows group by, comma-separated + /// indices into the columns before the value column: any non-empty subset + /// (`0`, `1`, `0,1`). The grid stores every subset, so this picks the one + /// asked and scored. Every other target ignores it. + #[arg( + long, + value_delimiter = ',', + default_value = "0", + help_heading = "Measurement content" + )] + pub group_columns: Vec, /// Path to append JSONL records to. `-` or omitted sends them to stdout. #[arg(long, help_heading = "Output")] pub report: Option, + /// Write a `hydra-*` row's per-group errors to this CSV, one row per scored + /// group: `group_key,n_q,error` (`n_q` is the group's record count, `error` + /// the row's own metric). The record's `err_*` fields summarise the same + /// rows. Takes one accuracy measurement: query or merge, not both. + #[arg(long, help_heading = "Output")] + pub per_group_out: Option, /// Write one line for the whole invocation instead of one per measurement, /// folding its records into a single flattened row: one slot per operation, /// one field per metric. One record per measurement is the default; this is the diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 8334d4dd..105035df 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -350,6 +350,19 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { None => ParamSet::empty(&variant), }; + let mut group_columns = args.group_columns.clone(); + group_columns.sort_unstable(); + group_columns.dedup(); + if args.per_group_out.is_some() { + if !variant.starts_with("hydra-") { + bail!("--per-group-out: only the hydra-* rows score groups, and {variant} is not one"); + } + if want.iter().filter(|(_, m)| *m == Metric::Accuracy).count() > 1 { + bail!( + "--per-group-out writes one accuracy measurement; ask for query or merge, not both" + ); + } + } let req = Requirement { variant: variant.clone(), library: library.clone(), @@ -357,6 +370,8 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { width, workers: args.workers.max(1), merge_shards: args.merge_shards, + group_columns, + per_group_out: args.per_group_out.as_ref().map(std::path::PathBuf::from), comparator: args.comparator.clone(), runs: args.runs, warmup_runs: args.warmup_runs, diff --git a/aqpbm-cli/src/rows/hydra_univmon.rs b/aqpbm-cli/src/rows/hydra_univmon.rs index eca3acd0..34320aa9 100644 --- a/aqpbm-cli/src/rows/hydra_univmon.rs +++ b/aqpbm-cli/src/rows/hydra_univmon.rs @@ -77,7 +77,7 @@ pub(crate) fn row_hydra_univmon_l1_norm_lib( table, want, SubpopL1NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -114,7 +114,7 @@ pub(crate) fn row_hydra_univmon_l1_norm_polars( table, want, SubpopL1NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_l1_norm::<$t>, @@ -147,7 +147,7 @@ pub(crate) fn row_hydra_univmon_l2_norm_lib( table, want, SubpopL2NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -184,7 +184,7 @@ pub(crate) fn row_hydra_univmon_l2_norm_polars( table, want, SubpopL2NormGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_l2_norm::<$t>, @@ -217,7 +217,7 @@ pub(crate) fn row_hydra_univmon_entropy_lib( table, want, SubpopEntropyGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hus::insert_hydra_univmon::<$t>, @@ -254,7 +254,7 @@ pub(crate) fn row_hydra_univmon_entropy_polars( table, want, SubpopEntropyGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, hup::insert_polars_subpop_entropy::<$t>, diff --git a/aqpbm-cli/src/rows/mod.rs b/aqpbm-cli/src/rows/mod.rs index e1f1c59c..66524a42 100644 --- a/aqpbm-cli/src/rows/mod.rs +++ b/aqpbm-cli/src/rows/mod.rs @@ -23,12 +23,12 @@ use aqpbm_core::accuracy::keyed::{ }; use aqpbm_core::accuracy::quantile::{RankErrorGT, RelativeValueErrorGT}; use aqpbm_core::accuracy::subpopulation::{ - SubpopCardinalityGT, SubpopEntropyGT, SubpopFrequencyGT, SubpopL1NormGT, SubpopL2NormGT, - SubpopRankErrorGT, + GroupKey, SubpopCardinalityGT, SubpopEntropyGT, SubpopFrequencyGT, SubpopL1NormGT, + SubpopL2NormGT, SubpopRankErrorGT, }; use aqpbm_core::accuracy::topk::TopkGT; use aqpbm_core::accuracy::Score; -use aqpbm_core::accuracy::{questions, CountedValue, GroundTruth}; +use aqpbm_core::accuracy::{questions, CountedValue, GroundTruth, PerGroup}; use aqpbm_core::error::RunError; use aqpbm_core::measure::{ record_calls, runs_for, Measurement, Pass as CorePass, Report, RunOutcome, MIN_MERGE_SHARDS, @@ -37,9 +37,6 @@ use aqpbm_core::metrics::{Metric, Operation}; use aqpbm_core::{ColumnItem, GeneratedTable, TableDescription}; use sketch_bench::wrappers::frequency_value::FrequencyValue; -/// The label column every subpopulation comparator scores over. -const SCORED_LABEL_COLUMN: usize = 0; - const KEYED_KEY_COLUMN: usize = 0; fn value_column(description: &TableDescription) -> usize { diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 3e6c0678..87a227aa 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -109,6 +109,28 @@ pub(super) fn topk_row( ) } +/// The label columns a grouped row asks and scores: `--group-columns`, which +/// must name at least one column, and only columns before the value column, +/// since those are the grid's key columns. +pub(super) fn group_columns( + req: &Requirement, + description: &TableDescription, +) -> Result, RunError> { + let labels = value_column(description); + if req.group_columns.is_empty() { + return Err(RunError::Sketch( + "--group-columns names no column; a group is taken over at least one".into(), + )); + } + if let Some(&column) = req.group_columns.iter().find(|&&c| c >= labels) { + return Err(RunError::Sketch(format!( + "--group-columns {column}: the label columns are 0..{labels}, the ones \ + before the value column" + ))); + } + Ok(req.group_columns.clone()) +} + /// A row answering **subpopulation frequency**: how often a value occurs inside /// a group. #[allow(clippy::too_many_arguments, clippy::type_complexity)] @@ -119,8 +141,8 @@ pub(super) fn subpop_frequency_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), (Vec, V), f64>, - merge: Option, V), f64>>, + query: QueryBody<(String, V), (GroupKey, V), f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -128,7 +150,10 @@ pub(super) fn subpop_frequency_row( description, table, want, - SubpopFrequencyGT::::over_columns(vec![SCORED_LABEL_COLUMN], value_column(description)), + SubpopFrequencyGT::::over_columns( + group_columns(req, description)?, + value_column(description), + ), peel_labeled::, insert, insert_step, @@ -148,8 +173,8 @@ pub(super) fn subpop_cardinality_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), Vec, f64>, - merge: Option, f64>>, + query: QueryBody<(String, V), GroupKey, f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -158,7 +183,7 @@ pub(super) fn subpop_cardinality_row( table, want, SubpopCardinalityGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, peel_labeled::, @@ -181,12 +206,12 @@ pub(super) fn subpop_vector_row( ground_truth: G, insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), Vec, f64>, - merge: Option, f64>>, + query: QueryBody<(String, V), GroupKey, f64>, + merge: Option>, prepare: Option>, ) -> Result where - G: GroundTruth, Answer = f64> + 'static, + G: GroundTruth + 'static, G::Truth: 'static, { scored_row( @@ -212,8 +237,8 @@ pub(super) fn subpop_quantile_row( want: &[(Operation, Metric)], insert: InsertBody<(String, V)>, insert_step: InsertStepBody<(String, V)>, - query: QueryBody<(String, V), (Vec, f64), f64>, - merge: Option, f64), f64>>, + query: QueryBody<(String, V), (GroupKey, f64), f64>, + merge: Option>, prepare: Option>, ) -> Result { scored_row( @@ -222,7 +247,7 @@ pub(super) fn subpop_quantile_row( table, want, SubpopRankErrorGT { - group_columns: vec![SCORED_LABEL_COLUMN], + group_columns: group_columns(req, description)?, value_column: value_column(description), }, peel_labeled::, @@ -348,7 +373,11 @@ where G::Probe: 'static, G::Answer: 'static, { - let (probes, score) = questions(ground_truth, &table)?; + let (probes, score, per_group) = questions(ground_truth, &table)?; + let score = match &req.per_group_out { + Some(path) => per_group_written(score, per_group, path)?, + None => score, + }; let items = materialise(description, table)?; let mut bodies = Vec::with_capacity(want.len()); for &(operation, metric) in want { @@ -399,6 +428,36 @@ where Ok(bodies) } +/// The scorer, also writing each scored group's error to `path` as +/// `group_key,n_q,error` whenever it scores. Every pass answers the same, so +/// each rewrites the same rows. The file is created here, so a path that +/// cannot be written fails before anything is measured. +fn per_group_written( + score: Score, + per_group: PerGroup, + path: &std::path::Path, +) -> Result, RunError> { + let fail = + |e: std::io::Error| RunError::Sketch(format!("--per-group-out {}: {e}", path.display())); + std::fs::File::create(path).map_err(fail)?; + let path = path.to_path_buf(); + Ok(Rc::new(move |answers: &[A]| { + let mut csv = String::from("group_key,n_q,error\n"); + for g in per_group(answers) { + // A label may hold a comma or a quote; CSV quotes the field then. + let key = if g.group.contains([',', '"', '\n']) { + format!("\"{}\"", g.group.replace('"', "\"\"")) + } else { + g.group + }; + csv.push_str(&format!("{key},{},{}\n", g.n_q, g.error)); + } + std::fs::write(&path, csv) + .unwrap_or_else(|e| panic!("--per-group-out {}: {e}", path.display())); + score(answers) + })) +} + /// A row that answers **nothing**: measured but not scored. The parallel-insert /// rows, whose worker sketches are dropped rather than asked, and whose ingest /// is one call over the whole stream rather than a loop over it. diff --git a/aqpbm-cli/tests/hydra_grouping.rs b/aqpbm-cli/tests/hydra_grouping.rs new file mode 100644 index 00000000..50464482 --- /dev/null +++ b/aqpbm-cli/tests/hydra_grouping.rs @@ -0,0 +1,137 @@ +//! `--group-columns`: a Hydra row asks and scores the label subset it names, +//! any non-empty one, not only column 0. On a grid large enough that no two of +//! the few subkeys share a column in most rows, the sketch answers each group +//! as the exact baseline does, so a group asked at the wrong columns shows up +//! as error. + +use std::process::Command; + +/// Two overlapping label columns (both render ranks over one alphabet, so +/// `b` is a value of each) over few values, and a value column at `dtype`. +fn spec(dtype: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "hydra_grouping_{}_{dtype}.yaml", + std::process::id() + )); + let yaml = format!( + "column_num: 3 +column_label: [key1, key2, value] +row_num: 5000 +column_spec: + - data_type: string + distribution: {{kind: uniform, lower_bound: 0.0, upper_bound: 4.0, seed: 1}} + - data_type: string + distribution: {{kind: zipf, skewness: 1.1, population_size: 3, seed: 2}} + - data_type: {dtype} + distribution: {{kind: zipf, skewness: 1.2, population_size: 40, seed: 3}} +" + ); + std::fs::write(&path, yaml).expect("the temp dir is writable"); + path +} + +/// The query accuracy record of one run, plus the per-group CSV it wrote. +fn scored( + variant: &str, + library: &str, + config: &str, + dtype: &str, + group_columns: &str, +) -> (serde_json::Value, String) { + let spec = spec(dtype); + let csv = spec.with_extension(format!("{variant}.{library}.{group_columns}.csv")); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", variant, "--library", library]) + .args(["--config", config, "--dtype", dtype]) + .args(["--spec", spec.to_str().expect("utf-8 path")]) + .args(["--group-columns", group_columns]) + .args(["--per-group-out", csv.to_str().expect("utf-8 path")]) + .args(["--operations", "query", "--metrics", "accuracy"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .env("BENCH_WARMUP_SECS", "0") + .output() + .expect("approxbench runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8(out.stdout).expect("utf-8"); + let record: serde_json::Value = + serde_json::from_str(stdout.lines().last().expect("one record")).expect("JSON"); + let csv = std::fs::read_to_string(&csv).expect("--per-group-out was written"); + (record["bench"]["accuracy"].clone(), csv) +} + +/// Every Hydra family, lib at a grid far larger than its 19 subkeys and the +/// polars baseline, grouped by column 1 alone and by both columns: both score +/// (about) zero, and the per-group file has one row per scored group, keyed by +/// the columns asked. +#[test] +fn any_label_subset_is_asked_where_it_was_inserted() { + let rows = [ + ("hydra-cms", "rows=3 cols=1024 cell_rows=3 cell_cols=256", "i64"), + ("hydra-cs", "rows=3 cols=1024 cell_rows=3 cell_cols=256", "i64"), + ("hydra-hll", "rows=3 cols=1024", "i64"), + ("hydra-kll", "rows=3 cols=1024 cell_k=4096", "f64"), + ( + "hydra-univmon-l1-norm", + "rows=3 cols=1024 cell_heap_size=64 cell_sketch_row=3 cell_sketch_col=256 cell_layer_size=4", + "i64", + ), + ]; + for (variant, config, dtype) in rows { + for group_columns in ["1", "0,1"] { + for (library, tolerance) in [("polars", 0.0), ("lib", 0.01)] { + let (acc, csv) = scored(variant, library, config, dtype, group_columns); + let at = format!("{variant}/{library} --group-columns {group_columns}: {acc}"); + assert!(acc["err_max"].as_f64().expect(&at) <= tolerance, "{at}"); + assert_eq!(acc["schema_width"], 2.0, "{at}"); + assert_eq!(acc["records"], 5000.0, "{at}"); + assert_eq!(acc["fanned_mass"], 15000.0, "{at}"); + + let mut lines = csv.lines(); + assert_eq!(lines.next(), Some("group_key,n_q,error"), "{at}"); + let rows: Vec<&str> = lines.collect(); + assert_eq!(rows.len() as f64, acc["groups_scored"].as_f64().expect(&at)); + let n_q: u64 = rows + .iter() + .map(|r| r.split(',').nth(1).and_then(|n| n.parse::().ok())) + .map(|n| n.expect("n_q is a count")) + .sum(); + assert_eq!(n_q, 5000, "every record is in exactly one group: {at}"); + let key = rows[0].split(',').next().expect("a key"); + match group_columns { + "1" => assert!(key.starts_with("label1:") && !key.contains(';'), "{key}"), + _ => assert!( + key.starts_with("label0:") && key.contains(";label1:"), + "{key}" + ), + } + } + } + } +} + +/// A grouping column has to be a label column: the value column is not a key +/// of the grid. +#[test] +fn a_group_column_past_the_labels_is_refused() { + let spec = spec("i64"); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", "hydra-cms", "--library", "lib"]) + .args([ + "--spec", + spec.to_str().expect("utf-8 path"), + "--dtype", + "i64", + ]) + .args(["--group-columns", "2"]) + .args(["--operations", "query", "--metrics", "accuracy"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .output() + .expect("approxbench runs"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("--group-columns 2"), "{err}"); +} diff --git a/aqpbm-core/src/accuracy/mod.rs b/aqpbm-core/src/accuracy/mod.rs index 1310d39d..698b38d0 100644 --- a/aqpbm-core/src/accuracy/mod.rs +++ b/aqpbm-core/src/accuracy/mod.rs @@ -102,6 +102,27 @@ pub trait GroundTruth { probes: &[Self::Probe], answers: &[Self::Answer], ) -> BTreeMap; + + /// ④ Each scored group's error, for a comparator whose population is + /// subpopulations; empty for every other. [`score`](Self::score) summarises + /// the same rows, and `--per-group-out` writes them. + fn per_group( + &self, + _truth: &Self::Truth, + _probes: &[Self::Probe], + _answers: &[Self::Answer], + ) -> Vec { + Vec::new() + } +} + +/// One scored subpopulation: its key, how many records it carried (`n_q`), and +/// its error in the comparator's own metric, lower is better. +#[derive(Clone, Debug, PartialEq)] +pub struct GroupError { + pub group: String, + pub n_q: u64, + pub error: f64, } /// How a row's answers turn into the named error metrics: the scorer @@ -109,14 +130,18 @@ pub trait GroundTruth { /// comparator type. pub type Score = Rc BTreeMap>; +/// The same answers, read back group by group: [`GroundTruth::per_group`]. +pub type PerGroup = Rc Vec>; + /// Draw the questions: the exact answer over the generated table, the probes -/// off it, and a scorer holding both. Run once per row, outside every clock, -/// so no comparator type reaches a measurement. +/// off it, and a scorer holding both (and the per-group reader beside it). Run +/// once per row, outside every clock, so no comparator type reaches a +/// measurement. #[allow(clippy::type_complexity)] pub fn questions( gt: G, table: &GeneratedTable, -) -> Result<(Rc>, Score), RunError> +) -> Result<(Rc>, Score, PerGroup), RunError> where G: GroundTruth + 'static, G::Truth: 'static, @@ -133,7 +158,11 @@ where let (gt, truth, probes) = (gt.clone(), truth.clone(), probes.clone()); Rc::new(move |answers: &[G::Answer]| gt.score(&truth, &probes, answers)) }; - Ok((probes, score)) + let per_group: PerGroup = { + let (gt, truth, probes) = (gt.clone(), truth.clone(), probes.clone()); + Rc::new(move |answers: &[G::Answer]| gt.per_group(&truth, &probes, answers)) + }; + Ok((probes, score, per_group)) } pub(crate) fn scalar_error(truth: f64, answers: &[f64]) -> BTreeMap { diff --git a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs index 69e990b5..c3128b81 100644 --- a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs +++ b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs @@ -7,8 +7,8 @@ use std::hash::Hash; use aqpbm_datagen::{ColumnData, DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::{curve, GroundTruth}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, GroundTruth, GroupError}; /// Ground truth for a grouped cardinality sketch: how many distinct values one /// subpopulation held. The population is the **subpopulation**, one entry per @@ -19,75 +19,91 @@ pub struct SubpopCardinalityGT { pub value_column: usize, } -/// Exact distinct-value counts per group, plus the ranking and the unfiltered -/// population. +/// Exact distinct-value counts per group, plus the ranking, the unfiltered +/// population, each group's record count and the stream's shape. pub struct SubpopCardTruth { - exact: HashMap, - ranked: Vec, - all: Vec, + exact: HashMap, + ranked: Vec, + all: Vec, + sizes: HashMap, + records: u64, + schema_width: usize, } /// One pass over the rows at whatever type the value column holds: a row /// contributes its value to exactly one group, and the group's truth is the -/// size of that set. +/// size of that set; the second number is how many records it carried. fn distinct_per_group( labels: &[&str], - width: usize, + columns: &[usize], values: &[V], -) -> HashMap { - let mut per_group: HashMap, HashSet<&V>> = HashMap::new(); - for (group, value) in labels.chunks(width).zip(values) { +) -> HashMap { + let mut per_group: HashMap, (HashSet<&V>, u64)> = HashMap::new(); + for (group, value) in labels.chunks(columns.len()).zip(values) { match per_group.get_mut(group) { - Some(seen) => { + Some((seen, records)) => { seen.insert(value); + *records += 1; } None => { - per_group.insert(group.to_vec(), HashSet::from([value])); + per_group.insert(group.to_vec(), (HashSet::from([value]), 1)); } } } per_group .into_iter() - .map(|(group, seen)| (owned(&group), seen.len() as u64)) + .map(|(group, (seen, records))| (owned(&group, columns), (seen.len() as u64, records))) .collect() } impl GroundTruth for SubpopCardinalityGT { type Truth = SubpopCardTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { let labels = group_labels(table, &self.group_columns)?; - let width = self.group_columns.len(); - let exact = match table.column(self.value_column)? { - ColumnData::Int64(v) => distinct_per_group(&labels, width, v), - ColumnData::Unsigned64(v) => distinct_per_group(&labels, width, v), - ColumnData::String(v) => distinct_per_group(&labels, width, v), + let columns = &self.group_columns; + let counted = match table.column(self.value_column)? { + ColumnData::Int64(v) => distinct_per_group(&labels, columns, v), + ColumnData::Unsigned64(v) => distinct_per_group(&labels, columns, v), + ColumnData::String(v) => distinct_per_group(&labels, columns, v), ColumnData::Float64(v) => { let bits: Vec = v.iter().map(|x| x.to_bits()).collect(); - distinct_per_group(&labels, width, &bits) + distinct_per_group(&labels, columns, &bits) } }; + let exact: HashMap = + counted.iter().map(|(g, (d, _))| (g.clone(), *d)).collect(); + let sizes = counted.into_iter().map(|(g, (_, n))| (g, n)).collect(); - let mut by_count: Vec<(Group, u64)> = exact.iter().map(|(g, c)| (g.clone(), *c)).collect(); + let mut by_count: Vec<(GroupKey, u64)> = + exact.iter().map(|(g, c)| (g.clone(), *c)).collect(); by_count.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); let all = curve::shuffled(&by_count); let ranked = by_count.into_iter().map(|(g, _)| g).collect(); - Ok(SubpopCardTruth { exact, ranked, all }) + Ok(SubpopCardTruth { + exact, + ranked, + all, + sizes, + records: table.row_num, + schema_width: self.value_column, + }) } - fn probes(&self, truth: &SubpopCardTruth) -> Vec { + fn probes(&self, truth: &SubpopCardTruth) -> Vec { curve::union_of(&truth.all, &truth.ranked, Clone::clone) } fn score( &self, truth: &SubpopCardTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { - let est: HashMap<&Group, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + let est: HashMap<&GroupKey, f64> = + probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); let mut metrics: BTreeMap = BTreeMap::new(); curve::error_curve( &truth.ranked, @@ -102,8 +118,25 @@ impl GroundTruth for SubpopCardinalityGT { ); metrics.insert("subpopulations".into(), truth.exact.len() as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + let groups = self.per_group(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } + + /// Relative error per group, as `are_all` averages it. + fn per_group( + &self, + truth: &SubpopCardTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + let est: HashMap<&GroupKey, f64> = + probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + group_errors(truth.exact.iter().filter(|(_, &d)| d > 0).map(|(g, &d)| { + let err = (est.get(g).copied().unwrap_or(0.0) - d as f64).abs() / d as f64; + (g.clone(), truth.sizes[g], err) + })) + } } #[cfg(test)] @@ -120,7 +153,7 @@ mod tests { let truth = gt .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["a".to_string()]], 2); - assert_eq!(truth.exact[&vec!["b".to_string()]], 1); + assert_eq!(truth.exact[&vec![Some("a".to_string())]], 2); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 1); } } diff --git a/aqpbm-core/src/accuracy/subpopulation/entropy.rs b/aqpbm-core/src/accuracy/subpopulation/entropy.rs index b768a08d..f96bb132 100644 --- a/aqpbm-core/src/accuracy/subpopulation/entropy.rs +++ b/aqpbm-core/src/accuracy/subpopulation/entropy.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopEntropyGT { /// Which label columns the subpopulation is taken over. @@ -29,25 +31,34 @@ pub fn entropy(counts: &[u64]) -> f64 { impl GroundTruth for SubpopEntropyGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, entropy) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -67,9 +78,9 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["b".to_string()]], 0.0); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 0.0); let expected = -(2.0 / 3.0 * (2.0f64 / 3.0).log2() + 1.0 / 3.0 * (1.0f64 / 3.0).log2()); - assert!((truth.exact[&vec!["a".to_string()]] - expected).abs() < 1e-12); + assert!((truth.exact[&vec![Some("a".to_string())]] - expected).abs() < 1e-12); } #[test] diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency.rs b/aqpbm-core/src/accuracy/subpopulation/frequency.rs index 381cacd2..75a8b2d1 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency.rs @@ -6,8 +6,8 @@ use std::marker::PhantomData; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::{curve, CountedValue, GroundTruth}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, CountedValue, GroundTruth, GroupError}; pub struct SubpopFrequencyGT { /// Which label columns the subpopulation is taken over. A grouped sketch @@ -28,19 +28,23 @@ impl SubpopFrequencyGT { } } -/// The exact per-(group, value) counts, the ranking, and the unfiltered -/// population. Owned: the truth outlives the borrow of the table. +/// The exact per-(group, value) counts, the ranking, the unfiltered +/// population, each group's record count and the stream's shape. Owned: the +/// truth outlives the borrow of the table. pub struct SubpopFreqTruth { - exact: HashMap<(Group, V::CountKey), u64>, - ranked: Vec<(Group, V)>, - all: Vec<(Group, V)>, + exact: HashMap<(GroupKey, V::CountKey), u64>, + ranked: Vec<(GroupKey, V)>, + all: Vec<(GroupKey, V)>, subpopulations: usize, + sizes: HashMap, + records: u64, + schema_width: usize, } type CountedByGroup<'a, V> = HashMap, HashMap<::CountKey, (u64, V)>>; -fn counted_key(pair: &(Group, V)) -> (Group, V::CountKey) { +fn counted_key(pair: &(GroupKey, V)) -> (GroupKey, V::CountKey) { (pair.0.clone(), pair.1.count_key()) } @@ -49,7 +53,7 @@ where V: CountedValue, { type Truth = SubpopFreqTruth; - type Probe = (Group, V); + type Probe = (GroupKey, V); type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result, DataGenError> { @@ -76,10 +80,12 @@ where } } let subpopulations = counted.len(); - let mut exact: HashMap<(Group, V::CountKey), u64> = HashMap::new(); - let mut by_count: Vec<((Group, V), u64)> = Vec::new(); + let mut exact: HashMap<(GroupKey, V::CountKey), u64> = HashMap::new(); + let mut by_count: Vec<((GroupKey, V), u64)> = Vec::new(); + let mut sizes: HashMap = HashMap::with_capacity(subpopulations); for (group, seen) in counted { - let group = owned(&group); + let group = owned(&group, &self.group_columns); + sizes.insert(group.clone(), seen.values().map(|(count, _)| count).sum()); for (key, (count, value)) in seen { exact.insert((group.clone(), key), count); by_count.push(((group.clone(), value), count)); @@ -99,20 +105,23 @@ where ranked, all, subpopulations, + sizes, + records: table.row_num, + schema_width: self.value_column, }) } - fn probes(&self, truth: &SubpopFreqTruth) -> Vec<(Group, V)> { + fn probes(&self, truth: &SubpopFreqTruth) -> Vec<(GroupKey, V)> { curve::union_of(&truth.all, &truth.ranked, counted_key) } fn score( &self, truth: &SubpopFreqTruth, - probes: &[(Group, V)], + probes: &[(GroupKey, V)], answers: &[f64], ) -> BTreeMap { - let est: HashMap<(Group, V::CountKey), f64> = probes + let est: HashMap<(GroupKey, V::CountKey), f64> = probes .iter() .zip(answers) .map(|(p, a)| (counted_key(p), *a)) @@ -136,8 +145,37 @@ where // be read. metrics.insert("subpopulations".into(), truth.subpopulations as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + let groups = self.per_group(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } + + /// A group's error is the relative error of its (group, value) pairs, + /// averaged over the group's pairs as `are_all` averages over every pair. + fn per_group( + &self, + truth: &SubpopFreqTruth, + probes: &[(GroupKey, V)], + answers: &[f64], + ) -> Vec { + let est: HashMap<(GroupKey, V::CountKey), f64> = probes + .iter() + .zip(answers) + .map(|(p, a)| (counted_key(p), *a)) + .collect(); + let mut per_group: HashMap<&GroupKey, (f64, usize)> = HashMap::new(); + for (key, &count) in &truth.exact { + let err = (est.get(key).copied().unwrap_or(0.0) - count as f64).abs() / count as f64; + let held = per_group.entry(&key.0).or_insert((0.0, 0)); + held.0 += err; + held.1 += 1; + } + group_errors( + per_group + .into_iter() + .map(|(g, (sum, pairs))| (g.clone(), truth.sizes[g], sum / pairs as f64)), + ) + } } #[cfg(test)] @@ -151,31 +189,17 @@ mod tests { /// and this double answers 0 whatever it was fed, so nothing needs to go /// into it. struct NullSubpop; - impl NullSubpop { - fn estimate_subpop_frequency(&self, _: &[&str], _: &i64) -> f64 { - 0.0 - } - } - fn query_null(s: &mut NullSubpop, p: &(Group, i64)) -> f64 { - s.estimate_subpop_frequency(&labels(&p.0), &p.1) - } - - fn labels(group: &Group) -> Vec<&str> { - group.iter().map(String::as_str).collect() + fn query_null(_: &mut NullSubpop, _: &(GroupKey, i64)) -> f64 { + 0.0 } /// The estimator that is exactly right, built from the same rows the /// comparator reads. Pins that the comparator's own truth is self-consistent. struct ExactSubpop { - counts: HashMap<(Group, i64), u64>, - } - impl ExactSubpop { - fn estimate_subpop_frequency(&self, group: &[&str], value: &i64) -> f64 { - *self.counts.get(&(owned(group), *value)).unwrap_or(&0) as f64 - } + counts: HashMap<(GroupKey, i64), u64>, } - fn query_exact(s: &mut ExactSubpop, p: &(Group, i64)) -> f64 { - s.estimate_subpop_frequency(&labels(&p.0), &p.1) + fn query_exact(s: &mut ExactSubpop, p: &(GroupKey, i64)) -> f64 { + *s.counts.get(p).unwrap_or(&0) as f64 } fn over(group_columns: Vec) -> SubpopFrequencyGT { @@ -258,6 +282,27 @@ mod tests { assert_eq!(cmp["group_columns"], 2.0); } + /// A group's error averages its own pairs: `a` holds (a,10) twice and + /// (a,20) once, so overcounting (a,10) by one misses that pair by 0.5 and + /// group `a` by 0.25, while `b` is exact. Over groups the mean is 0.125, + /// not `are_all`'s 0.5 / 3 over pairs. + #[test] + fn a_group_error_is_the_mean_over_its_pairs() { + let table = records(); + let gt = over(vec![0]); + let truth = gt.truth(&table).expect("the table has the named columns"); + let mut counts = truth.exact.clone(); + *counts + .get_mut(&(vec![Some("a".to_string())], 10)) + .expect("(a, 10) occurs") += 1; + let cmp = + crate::accuracy::score_with(>, &query_exact, &mut ExactSubpop { counts }, &table); + assert_eq!(cmp["err_mean"], 0.125); + assert_eq!(cmp["err_max"], 0.25); + assert_eq!(cmp["groups_scored"], 2.0); + assert!((cmp["are_all"] - 0.5 / 3.0).abs() < 1e-12); + } + #[test] fn a_grouping_column_that_is_not_text_is_refused() { let Err(err) = over(vec![2]).truth(&records()) else { diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs index 76f8b287..43d7b209 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs @@ -4,22 +4,25 @@ use std::hash::Hash; use aqpbm_datagen::{ColumnData, DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; -use crate::accuracy::curve; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; +use crate::accuracy::{curve, GroupError}; pub struct SubpopVectorTruth { - pub(super) exact: HashMap, - ranked: Vec, - all: Vec, + pub(super) exact: HashMap, + ranked: Vec, + all: Vec, + sizes: HashMap, + records: u64, + schema_width: usize, } fn histogram_per_group( labels: &[&str], - width: usize, + columns: &[usize], values: &[V], -) -> HashMap> { +) -> HashMap> { let mut per_group: HashMap, HashMap<&V, u64>> = HashMap::new(); - for (group, value) in labels.chunks(width).zip(values) { + for (group, value) in labels.chunks(columns.len()).zip(values) { match per_group.get_mut(group) { Some(seen) => *seen.entry(value).or_insert(0) += 1, None => { @@ -29,7 +32,7 @@ fn histogram_per_group( } per_group .into_iter() - .map(|(group, seen)| (owned(&group), seen.into_values().collect())) + .map(|(group, seen)| (owned(&group, columns), seen.into_values().collect())) .collect() } @@ -37,16 +40,16 @@ pub(super) fn counts_per_group( table: &GeneratedTable, group_columns: &[usize], value_column: usize, -) -> Result>, DataGenError> { +) -> Result>, DataGenError> { let labels = group_labels(table, group_columns)?; - let width = group_columns.len(); + let columns = group_columns; Ok(match table.column(value_column)? { - ColumnData::Int64(v) => histogram_per_group(&labels, width, v), - ColumnData::Unsigned64(v) => histogram_per_group(&labels, width, v), - ColumnData::String(v) => histogram_per_group(&labels, width, v), + ColumnData::Int64(v) => histogram_per_group(&labels, columns, v), + ColumnData::Unsigned64(v) => histogram_per_group(&labels, columns, v), + ColumnData::String(v) => histogram_per_group(&labels, columns, v), ColumnData::Float64(v) => { let bits: Vec = v.iter().map(|x| x.to_bits()).collect(); - histogram_per_group(&labels, width, &bits) + histogram_per_group(&labels, columns, &bits) } }) } @@ -58,14 +61,15 @@ pub(super) fn truth_over( fold: impl Fn(&[u64]) -> f64, ) -> Result { let counts = counts_per_group(table, group_columns, value_column)?; - let exact: HashMap = counts + let exact: HashMap = counts .iter() .map(|(group, counts)| (group.clone(), fold(counts))) .collect(); - let mut by_statistic: Vec<(Group, f64)> = exact.iter().map(|(g, v)| (g.clone(), *v)).collect(); + let mut by_statistic: Vec<(GroupKey, f64)> = + exact.iter().map(|(g, v)| (g.clone(), *v)).collect(); by_statistic.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); - let sized: Vec<(Group, u64)> = by_statistic + let sized: Vec<(GroupKey, u64)> = by_statistic .iter() .map(|(g, _)| { let size = counts.get(g).map(|c| c.iter().sum()).unwrap_or(0); @@ -73,21 +77,29 @@ pub(super) fn truth_over( }) .collect(); let all = curve::shuffled(&sized); + let sizes = sized.into_iter().collect(); let ranked = by_statistic.into_iter().map(|(g, _)| g).collect(); - Ok(SubpopVectorTruth { exact, ranked, all }) + Ok(SubpopVectorTruth { + exact, + ranked, + all, + sizes, + records: table.row_num, + schema_width: value_column, + }) } -pub(super) fn probes_over(truth: &SubpopVectorTruth) -> Vec { +pub(super) fn probes_over(truth: &SubpopVectorTruth) -> Vec { curve::union_of(&truth.all, &truth.ranked, Clone::clone) } pub(super) fn score_over( truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], group_columns: usize, ) -> BTreeMap { - let est: HashMap<&Group, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); let mut metrics: BTreeMap = BTreeMap::new(); curve::error_curve( &truth.ranked, @@ -102,16 +114,33 @@ pub(super) fn score_over( ); metrics.insert("subpopulations".into(), truth.exact.len() as f64); metrics.insert("group_columns".into(), group_columns as f64); + let groups = per_group_over(truth, probes, answers); + write_groups(&groups, truth.records, truth.schema_width, &mut metrics); metrics } +/// Relative error per group, as `are_all` averages it: a group whose true +/// statistic is zero (entropy over one value) has no relative error and is +/// not scored. +pub(super) fn per_group_over( + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], +) -> Vec { + let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); + group_errors(truth.exact.iter().filter(|(_, &v)| v > 0.0).map(|(g, &v)| { + let err = (est.get(g).copied().unwrap_or(0.0) - v).abs() / v; + (g.clone(), truth.sizes[g], err) + })) +} + #[cfg(test)] mod tests { use super::*; use crate::accuracy::subpopulation::records; - fn group(label: &str) -> Group { - vec![label.to_string()] + fn group(label: &str) -> GroupKey { + vec![Some(label.to_string())] } #[test] diff --git a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs index 9a9710ca..28ca38e2 100644 --- a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs +++ b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopL1NormGT { /// Which label columns the subpopulation is taken over. @@ -18,25 +20,34 @@ pub fn l1_norm(counts: &[u64]) -> f64 { impl GroundTruth for SubpopL1NormGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, l1_norm) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -56,8 +67,8 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert_eq!(truth.exact[&vec!["a".to_string()]], 3.0); - assert_eq!(truth.exact[&vec!["b".to_string()]], 3.0); + assert_eq!(truth.exact[&vec![Some("a".to_string())]], 3.0); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 3.0); } #[test] @@ -74,6 +85,65 @@ mod tests { assert_eq!(cmp["aae_all"], 0.0); } + /// The per-group summary on a fixed case. Over both columns the groups + /// carry 2, 1, 1 and 2 records; answering 2, 2, 1.5 and 3 misses them by + /// 0, 1, 0.5 and 0.5 relatively, so sorted `[0, 0.5, 0.5, 1]`: mean 0.5, + /// p50 (index round(1.5) = 2) 0.5, p90 (index round(2.7) = 3) 1, max 1. + #[test] + fn per_group_errors_are_summarised_over_groups() { + let gt = over(vec![0, 1]); + let table = records(); + let key = |a: &str, b: &str| vec![Some(a.to_string()), Some(b.to_string())]; + let mut answers = std::collections::HashMap::from([ + (key("a", "x"), 2.0), + (key("a", "y"), 2.0), + (key("b", "x"), 1.5), + (key("b", "y"), 3.0), + ]); + let ask = |held: &mut std::collections::HashMap, p: &GroupKey| held[p]; + let cmp = crate::accuracy::score_with(>, &ask, &mut answers, &table); + assert_eq!(cmp["err_mean"], 0.5); + assert_eq!(cmp["err_p50"], 0.5); + assert_eq!(cmp["err_p90"], 1.0); + assert_eq!(cmp["err_max"], 1.0); + assert_eq!(cmp["groups_scored"], 4.0); + assert_eq!(cmp["schema_width"], 2.0); + assert_eq!(cmp["records"], 6.0); + assert_eq!(cmp["fanned_mass"], 18.0); + + let truth = gt.truth(&table).expect("the table has the named columns"); + let probes = gt.probes(&truth); + let asked: Vec = probes.iter().map(|p| answers[p]).collect(); + let rows: Vec<(String, u64, f64)> = gt + .per_group(&truth, &probes, &asked) + .into_iter() + .map(|g| (g.group, g.n_q, g.error)) + .collect(); + assert_eq!( + rows, + vec![ + ("label0:a;label1:x".to_string(), 2, 0.0), + ("label0:b;label1:y".to_string(), 2, 0.5), + ("label0:a;label1:y".to_string(), 1, 1.0), + ("label0:b;label1:x".to_string(), 1, 0.5), + ] + ); + } + + /// Column 1 alone is asked with column 0 left open, and named by column 1. + #[test] + fn a_group_on_a_later_column_leaves_the_earlier_ones_open() { + let gt = over(vec![1]); + let truth = gt + .truth(&records()) + .expect("the table has the named columns"); + assert_eq!(truth.exact[&vec![None, Some("x".to_string())]], 3.0); + let probes = gt.probes(&truth); + let groups = gt.per_group(&truth, &probes, &vec![0.0; probes.len()]); + let keys: Vec<&str> = groups.iter().map(|g| g.group.as_str()).collect(); + assert_eq!(keys, ["label1:x", "label1:y"]); + } + #[test] fn a_different_grouping_is_a_different_population() { let cmp = null_over(&over(vec![0, 1]), &records()); diff --git a/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs b/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs index a2069e22..267da2da 100644 --- a/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs +++ b/aqpbm-core/src/accuracy/subpopulation/l2_norm.rs @@ -2,9 +2,11 @@ use std::collections::BTreeMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::frequency_vector::{probes_over, score_over, truth_over, SubpopVectorTruth}; -use super::Group; -use crate::accuracy::GroundTruth; +use super::frequency_vector::{ + per_group_over, probes_over, score_over, truth_over, SubpopVectorTruth, +}; +use super::GroupKey; +use crate::accuracy::{GroundTruth, GroupError}; pub struct SubpopL2NormGT { /// Which label columns the subpopulation is taken over. @@ -22,25 +24,34 @@ pub fn l2_norm(counts: &[u64]) -> f64 { impl GroundTruth for SubpopL2NormGT { type Truth = SubpopVectorTruth; - type Probe = Group; + type Probe = GroupKey; type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { truth_over(table, &self.group_columns, self.value_column, l2_norm) } - fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { probes_over(truth) } fn score( &self, truth: &SubpopVectorTruth, - probes: &[Group], + probes: &[GroupKey], answers: &[f64], ) -> BTreeMap { score_over(truth, probes, answers, self.group_columns.len()) } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } } #[cfg(test)] @@ -60,8 +71,8 @@ mod tests { let truth = over(vec![0]) .truth(&records()) .expect("the table has the named columns"); - assert!((truth.exact[&vec!["a".to_string()]] - 5.0f64.sqrt()).abs() < 1e-12); - assert_eq!(truth.exact[&vec!["b".to_string()]], 3.0); + assert!((truth.exact[&vec![Some("a".to_string())]] - 5.0f64.sqrt()).abs() < 1e-12); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 3.0); } #[test] diff --git a/aqpbm-core/src/accuracy/subpopulation/mod.rs b/aqpbm-core/src/accuracy/subpopulation/mod.rs index 76d7f1ad..2f16d227 100644 --- a/aqpbm-core/src/accuracy/subpopulation/mod.rs +++ b/aqpbm-core/src/accuracy/subpopulation/mod.rs @@ -17,10 +17,21 @@ pub use l1_norm::{l1_norm, SubpopL1NormGT}; pub use l2_norm::{l2_norm, SubpopL2NormGT}; pub use rank_error::{SubpopRankErrorGT, SubpopRankTruth}; +use std::collections::BTreeMap; + use aqpbm_datagen::{ColumnItem, DataGenError, GeneratedTable}; +use crate::accuracy::curve::percentile; +use crate::accuracy::GroupError; + pub type Group = Vec; +/// A subpopulation as a grid is asked for it: one slot per label column up to +/// the last one grouped on, `Some` at the grouped columns and `None` at the +/// rest. Grouping on column 1 alone asks `[None, Some(v)]`, which a wrapper +/// can tell apart from grouping on column 0. +pub type GroupKey = Vec>; + pub(crate) fn group_labels<'a>( table: &'a GeneratedTable, columns: &[usize], @@ -45,8 +56,67 @@ pub(crate) fn group_labels<'a>( Ok(flat) } -fn owned(group: &[&str]) -> Group { - group.iter().map(|label| (*label).to_string()).collect() +/// `group` holds one label per entry of `columns`, in that order. +fn owned(group: &[&str], columns: &[usize]) -> GroupKey { + let mut key = vec![None; columns.iter().max().map_or(0, |last| last + 1)]; + for (label, &column) in group.iter().zip(columns) { + key[column] = Some((*label).to_string()); + } + key +} + +/// How a group is named in `--per-group-out`: each grouped column's value +/// tagged with its column, as the grid's subkeys are (`label1:x`). +fn rendered(key: &GroupKey) -> String { + key.iter() + .enumerate() + .filter_map(|(j, label)| label.as_ref().map(|l| format!("label{j}:{l}"))) + .collect::>() + .join(";") +} + +/// One [`GroupError`] per group, heaviest first (ties on the key), so the +/// per-group file reads the same across runs. +fn group_errors(errors: impl Iterator) -> Vec { + let mut out: Vec = errors + .map(|(key, n_q, error)| GroupError { + group: rendered(&key), + n_q, + error, + }) + .collect(); + out.sort_by(|a, b| b.n_q.cmp(&a.n_q).then_with(|| a.group.cmp(&b.group))); + out +} + +/// The per-group summary every grouped comparator reports, in its own metric: +/// `err_mean` / `err_p50` / `err_p90` / `err_max` over the scored groups (none +/// written when no group was scored), `groups_scored`, and the stream's shape +/// against which a group's error is read: `schema_width` (`d`, the label +/// columns before the value), `records` (`N`) and `fanned_mass` +/// (`N·(2^d − 1)`, every subset a record is inserted into). +fn write_groups( + groups: &[GroupError], + records: u64, + schema_width: usize, + metrics: &mut BTreeMap, +) { + let mut errs: Vec = groups.iter().map(|g| g.error).collect(); + errs.sort_by(f64::total_cmp); + if let Some(&max) = errs.last() { + metrics.insert( + "err_mean".into(), + errs.iter().sum::() / errs.len() as f64, + ); + metrics.insert("err_p50".into(), percentile(&errs, 0.5)); + metrics.insert("err_p90".into(), percentile(&errs, 0.9)); + metrics.insert("err_max".into(), max); + } + metrics.insert("groups_scored".into(), errs.len() as f64); + metrics.insert("schema_width".into(), schema_width as f64); + metrics.insert("records".into(), records as f64); + let subsets = 2f64.powi(schema_width as i32) - 1.0; + metrics.insert("fanned_mass".into(), records as f64 * subsets); } /// key1 ∈ {a, b}, key2 ∈ {x, y}; the value column is what gets counted. @@ -76,15 +146,15 @@ fn records() -> GeneratedTable { #[cfg(test)] fn null_over(gt: &G, table: &GeneratedTable) -> std::collections::BTreeMap where - G: crate::accuracy::GroundTruth, + G: crate::accuracy::GroundTruth, { - crate::accuracy::score_with(gt, &|_: &mut (), _: &Group| 0.0, &mut (), table) + crate::accuracy::score_with(gt, &|_: &mut (), _: &GroupKey| 0.0, &mut (), table) } #[cfg(test)] fn exact_over(gt: &G, table: &GeneratedTable) -> std::collections::BTreeMap where - G: crate::accuracy::GroundTruth, + G: crate::accuracy::GroundTruth, { let mut exact = gt .truth(table) @@ -92,7 +162,7 @@ where .exact; crate::accuracy::score_with( gt, - &|held: &mut std::collections::HashMap, p: &Group| { + &|held: &mut std::collections::HashMap, p: &GroupKey| { held.get(p).copied().unwrap_or(0.0) }, &mut exact, diff --git a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs index 5364184c..4c2f65fa 100644 --- a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs +++ b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs @@ -5,9 +5,9 @@ use std::collections::HashMap; use aqpbm_datagen::{DataGenError, GeneratedTable}; -use super::{group_labels, owned, Group}; +use super::{group_errors, group_labels, owned, write_groups, GroupKey}; use crate::accuracy::quantile::rank_err; -use crate::accuracy::{curve, f64_values, GroundTruth}; +use crate::accuracy::{curve, f64_values, GroundTruth, GroupError}; /// Number of quantiles probed per group — the same grid the ungrouped /// comparator uses, named once in [`super::quantile`]. @@ -24,17 +24,18 @@ pub struct SubpopRankErrorGT { /// The ordered statistic inside each group, plus the groups worth probing. pub struct SubpopRankTruth { - per_group: HashMap>, + per_group: HashMap>, /// Every group, shuffled: probe order must not hand the baseline the /// locality the encounter order would. - probed: Vec, + probed: Vec, items: usize, + schema_width: usize, } impl GroundTruth for SubpopRankErrorGT { type Truth = SubpopRankTruth; /// One (group, fraction) question. - type Probe = (Group, f64); + type Probe = (GroupKey, f64); type Answer = f64; fn truth(&self, table: &GeneratedTable) -> Result { @@ -53,13 +54,13 @@ impl GroundTruth for SubpopRankErrorGT { } } } - let mut per_group: HashMap> = HashMap::with_capacity(borrowed.len()); + let mut per_group: HashMap> = HashMap::with_capacity(borrowed.len()); for (group, mut held) in borrowed { held.sort_by(f64::total_cmp); - per_group.insert(owned(&group), held); + per_group.insert(owned(&group, &self.group_columns), held); } - let mut by_size: Vec<(Group, u64)> = per_group + let mut by_size: Vec<(GroupKey, u64)> = per_group .iter() .map(|(g, v)| (g.clone(), v.len() as u64)) .collect(); @@ -69,10 +70,11 @@ impl GroundTruth for SubpopRankErrorGT { per_group, probed, items: table.row_num as usize, + schema_width: self.value_column, }) } - fn probes(&self, truth: &SubpopRankTruth) -> Vec<(Group, f64)> { + fn probes(&self, truth: &SubpopRankTruth) -> Vec<(GroupKey, f64)> { let mut out = Vec::with_capacity(truth.probed.len() * GROUP_GRID_POINTS); for group in &truth.probed { match truth.per_group.get(group) { @@ -89,41 +91,16 @@ impl GroundTruth for SubpopRankErrorGT { fn score( &self, truth: &SubpopRankTruth, - probes: &[(Group, f64)], + probes: &[(GroupKey, f64)], answers: &[f64], ) -> BTreeMap { - let mut sum_mean = 0.0f64; - let mut max_err = 0.0f64; - let mut scored_groups = 0usize; - - // The probe set is one contiguous grid per group, in order. - for (chunk_p, chunk_a) in probes - .chunks(GROUP_GRID_POINTS) - .zip(answers.chunks(GROUP_GRID_POINTS)) - { - let Some((group, _)) = chunk_p.first() else { - continue; - }; - let Some(sorted) = truth.per_group.get(group) else { - continue; - }; - let mut group_sum = 0.0f64; - for ((_, q), est) in chunk_p.iter().zip(chunk_a) { - let err = rank_err(sorted, *est, *q); - group_sum += err; - if err > max_err { - max_err = err; - } - } - sum_mean += group_sum / GROUP_GRID_POINTS as f64; - scored_groups += 1; - } - + let (groups, max_err) = rank_errors(truth, probes, answers); + let scored_groups = groups.len(); let mut metrics: BTreeMap = BTreeMap::new(); metrics.insert( "mean_rank_err".into(), if scored_groups > 0 { - sum_mean / scored_groups as f64 + groups.iter().map(|g| g.error).sum::() / scored_groups as f64 } else { 0.0 }, @@ -134,8 +111,63 @@ impl GroundTruth for SubpopRankErrorGT { metrics.insert("probes".into(), scored_groups as f64); metrics.insert("subpopulations".into(), truth.per_group.len() as f64); metrics.insert("group_columns".into(), self.group_columns.len() as f64); + write_groups( + &groups, + truth.items as u64, + truth.schema_width, + &mut metrics, + ); metrics } + + /// A group's error is its mean rank error over the grid, the number + /// `mean_rank_err` averages over groups. + fn per_group( + &self, + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], + ) -> Vec { + rank_errors(truth, probes, answers).0 + } +} + +/// Each group's mean rank error over its grid, plus the largest rank error any +/// single probe saw. +fn rank_errors( + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], +) -> (Vec, f64) { + let mut max_err = 0.0f64; + let mut groups = Vec::new(); + + // The probe set is one contiguous grid per group, in order. + for (chunk_p, chunk_a) in probes + .chunks(GROUP_GRID_POINTS) + .zip(answers.chunks(GROUP_GRID_POINTS)) + { + let Some((group, _)) = chunk_p.first() else { + continue; + }; + let Some(sorted) = truth.per_group.get(group) else { + continue; + }; + let mut group_sum = 0.0f64; + for ((_, q), est) in chunk_p.iter().zip(chunk_a) { + let err = rank_err(sorted, *est, *q); + group_sum += err; + if err > max_err { + max_err = err; + } + } + groups.push(( + group.clone(), + sorted.len() as u64, + group_sum / GROUP_GRID_POINTS as f64, + )); + } + (group_errors(groups.into_iter()), max_err) } #[cfg(test)] @@ -154,11 +186,11 @@ mod tests { .expect("the table has the named columns"); assert_eq!(truth.items, 6); assert_eq!( - truth.per_group[&vec!["a".to_string()]], + truth.per_group[&vec![Some("a".to_string())]], vec![10.0, 10.0, 20.0] ); assert_eq!( - truth.per_group[&vec!["b".to_string()]], + truth.per_group[&vec![Some("b".to_string())]], vec![30.0, 30.0, 30.0] ); } diff --git a/configs/datagen/hydra_columns.yaml b/configs/datagen/hydra_columns.yaml index 50cb4b5c..88b098f0 100644 --- a/configs/datagen/hydra_columns.yaml +++ b/configs/datagen/hydra_columns.yaml @@ -40,7 +40,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_f64.yaml b/configs/datagen/hydra_columns_f64.yaml index ac22d2a6..15b54921 100644 --- a/configs/datagen/hydra_columns_f64.yaml +++ b/configs/datagen/hydra_columns_f64.yaml @@ -21,7 +21,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_string.yaml b/configs/datagen/hydra_columns_string.yaml index 9997da4c..132e5c2c 100644 --- a/configs/datagen/hydra_columns_string.yaml +++ b/configs/datagen/hydra_columns_string.yaml @@ -23,7 +23,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_columns_u64.yaml b/configs/datagen/hydra_columns_u64.yaml index 11a04211..8e6b57d8 100644 --- a/configs/datagen/hydra_columns_u64.yaml +++ b/configs/datagen/hydra_columns_u64.yaml @@ -21,7 +21,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_kll_disjoint_labels.yaml b/configs/datagen/hydra_kll_disjoint_labels.yaml index cff3f56d..b98a7559 100644 --- a/configs/datagen/hydra_kll_disjoint_labels.yaml +++ b/configs/datagen/hydra_kll_disjoint_labels.yaml @@ -10,7 +10,8 @@ column_label: [key1, key2, value] row_num: 200000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/configs/datagen/hydra_univmon_columns.yaml b/configs/datagen/hydra_univmon_columns.yaml index ee4d1356..adad591e 100644 --- a/configs/datagen/hydra_univmon_columns.yaml +++ b/configs/datagen/hydra_univmon_columns.yaml @@ -25,7 +25,8 @@ column_label: [key1, key2, value] row_num: 20000 column_spec: - # key1: the column the comparator groups by. + # key1: the column the comparator groups by unless `--group-columns` names + # another subset (`1`, `0,1`). - data_type: string distribution: kind: uniform diff --git a/sketch-bench/src/request.rs b/sketch-bench/src/request.rs index 1a13d182..421990a7 100644 --- a/sketch-bench/src/request.rs +++ b/sketch-bench/src/request.rs @@ -118,6 +118,10 @@ pub struct Requirement { pub workers: usize, /// How many shards a merge measurement folds pub merge_shards: usize, + /// The label columns a grouped (`hydra-*`) row asks and scores, ascending + pub group_columns: Vec, + /// Where a grouped row writes each scored group's error, if anywhere + pub per_group_out: Option, /// A named comparator, or `None` for the row's default. pub comparator: Option, /// Measured runs, and the warm-ups run and discarded before them diff --git a/sketch-bench/src/wrappers/hydra_cms/mod.rs b/sketch-bench/src/wrappers/hydra_cms/mod.rs index 6a01f62c..a3eac34b 100644 --- a/sketch-bench/src/wrappers/hydra_cms/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cms/mod.rs @@ -60,11 +60,14 @@ mod tests { fed(&mut h, &r); } // (a, 10) occurs twice, under two different second labels. - assert_eq!(h.estimate_subpop_frequency(&["a"], &10i64), 2.0); - assert_eq!(h.estimate_subpop_frequency(&["a"], &20i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["b"], &30i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &10i64), 2.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &20i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("b")], &30i64), 1.0); // The full key is its own subpopulation and is stored too. - assert_eq!(h.estimate_subpop_frequency(&["a", "x"], &10i64), 1.0); + assert_eq!( + h.estimate_subpop_frequency(&[Some("a"), Some("x")], &10i64), + 1.0 + ); } /// A group that never occurred must estimate zero. This is the failure mode @@ -74,7 +77,7 @@ mod tests { fn an_absent_group_estimates_zero() { let mut h = built(); fed(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_frequency(&["zzz"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("zzz")], &10i64), 0.0); } /// Count-Min is linear and the grid is cell-wise, so folding two shards is @@ -91,7 +94,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); + assert_eq!(left.estimate_subpop_frequency(&[Some("a")], &10i64), 7.0); } /// The grid's key columns are fixed at construction: a record of another @@ -126,8 +129,8 @@ mod tests { fn an_empty_label_keeps_its_column() { let mut h = built(); fed(&mut h, &record(";x", 10)); - assert_eq!(h.estimate_subpop_frequency(&[""], &10i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["x"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("")], &10i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("x")], &10i64), 0.0); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_cms/polars.rs b/sketch-bench/src/wrappers/hydra_cms/polars.rs index 6bcacd40..706143dc 100644 --- a/sketch-bench/src/wrappers/hydra_cms/polars.rs +++ b/sketch-bench/src/wrappers/hydra_cms/polars.rs @@ -33,7 +33,7 @@ pub fn build_polars_subpop_frequency_cms( } impl PolarsSubpopFrequencyCms { - pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &T) -> f64 { + pub fn estimate_subpop_frequency(&self, labels: &[Option<&str>], value: &T) -> f64 { self.0.query(labels, value) } } @@ -92,7 +92,7 @@ pub fn insert_step_polars_subpop_frequency_cms( pub fn query_polars_subpop_frequency_cms( params: &ParamSet, items: Rc>, - probes: Rc, T)>>, + probes: Rc>, T)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs index dc3a629d..243ed3e4 100644 --- a/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cms/sketchlib.rs @@ -39,7 +39,11 @@ pub fn build_hydra_cms(config: &ParamSet, label_columns: usize) -> Result(&self, labels: &[&str], value: &V) -> f64 { + pub fn estimate_subpop_frequency( + &self, + labels: &[Option<&str>], + value: &V, + ) -> f64 { query( &self.inner, labels, @@ -106,7 +110,7 @@ pub fn insert_step_hydra_cms( pub fn query_hydra_cms( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_cms(params, items, probes, 1, passes) @@ -117,7 +121,7 @@ pub fn query_hydra_cms( pub fn merge_query_hydra_cms( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_cs/mod.rs b/sketch-bench/src/wrappers/hydra_cs/mod.rs index 6d49033b..270e903b 100644 --- a/sketch-bench/src/wrappers/hydra_cs/mod.rs +++ b/sketch-bench/src/wrappers/hydra_cs/mod.rs @@ -60,11 +60,14 @@ mod tests { fed(&mut h, &r); } // (a, 10) occurs twice, under two different second labels. - assert_eq!(h.estimate_subpop_frequency(&["a"], &10i64), 2.0); - assert_eq!(h.estimate_subpop_frequency(&["a"], &20i64), 1.0); - assert_eq!(h.estimate_subpop_frequency(&["b"], &30i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &10i64), 2.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("a")], &20i64), 1.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("b")], &30i64), 1.0); // The full key is its own subpopulation and is stored too. - assert_eq!(h.estimate_subpop_frequency(&["a", "x"], &10i64), 1.0); + assert_eq!( + h.estimate_subpop_frequency(&[Some("a"), Some("x")], &10i64), + 1.0 + ); } /// A group that never occurred must estimate zero. This is the failure mode @@ -74,7 +77,7 @@ mod tests { fn an_absent_group_estimates_zero() { let mut h = built(); fed(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_frequency(&["zzz"], &10i64), 0.0); + assert_eq!(h.estimate_subpop_frequency(&[Some("zzz")], &10i64), 0.0); } /// Count Sketch is linear and the grid is cell-wise, so folding two shards is @@ -91,7 +94,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - assert_eq!(left.estimate_subpop_frequency(&["a"], &10i64), 7.0); + assert_eq!(left.estimate_subpop_frequency(&[Some("a")], &10i64), 7.0); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_cs/polars.rs b/sketch-bench/src/wrappers/hydra_cs/polars.rs index 73e0ad8b..adab3d57 100644 --- a/sketch-bench/src/wrappers/hydra_cs/polars.rs +++ b/sketch-bench/src/wrappers/hydra_cs/polars.rs @@ -33,7 +33,7 @@ pub fn build_polars_subpop_frequency_cs( } impl PolarsSubpopFrequencyCs { - pub fn estimate_subpop_frequency(&self, labels: &[&str], value: &T) -> f64 { + pub fn estimate_subpop_frequency(&self, labels: &[Option<&str>], value: &T) -> f64 { self.0.query(labels, value) } } @@ -91,7 +91,7 @@ pub fn insert_step_polars_subpop_frequency_cs( pub fn query_polars_subpop_frequency_cs( params: &ParamSet, items: Rc>, - probes: Rc, T)>>, + probes: Rc>, T)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs index 554a3808..9c326e78 100644 --- a/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_cs/sketchlib.rs @@ -39,7 +39,11 @@ pub fn build_hydra_cs(config: &ParamSet, label_columns: usize) -> Result(&self, labels: &[&str], value: &V) -> f64 { + pub fn estimate_subpop_frequency( + &self, + labels: &[Option<&str>], + value: &V, + ) -> f64 { query( &self.inner, labels, @@ -106,7 +110,7 @@ pub fn insert_step_hydra_cs( pub fn query_hydra_cs( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_cs(params, items, probes, 1, passes) @@ -117,7 +121,7 @@ pub fn query_hydra_cs( pub fn merge_query_hydra_cs( params: &ParamSet, items: Rc>, - probes: Rc, V)>>, + probes: Rc>, V)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_hll/mod.rs b/sketch-bench/src/wrappers/hydra_hll/mod.rs index 52ef926f..29efabf5 100644 --- a/sketch-bench/src/wrappers/hydra_hll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_hll/mod.rs @@ -58,7 +58,7 @@ mod tests { } fed_hll(&mut h, &record("a;y", 20)); // Two distinct values under label `a`, seen four times. - let est = h.estimate_subpop_cardinality(&["a"]); + let est = h.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 2.0).abs() < 0.5, "two distinct values under `a`, estimated {est}" @@ -69,7 +69,7 @@ mod tests { fn hll_absent_group_estimates_zero() { let mut h = built_hll(); fed_hll(&mut h, &record("a;x", 10)); - assert_eq!(h.estimate_subpop_cardinality(&["zzz"]), 0.0); + assert_eq!(h.estimate_subpop_cardinality(&[Some("zzz")]), 0.0); } /// A HyperLogLog is register-wise mergeable, so two shards fold without @@ -84,7 +84,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - let est = left.estimate_subpop_cardinality(&["a"]); + let est = left.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 3.0).abs() < 0.5, "three distinct values across both shards, estimated {est}" diff --git a/sketch-bench/src/wrappers/hydra_hll/polars.rs b/sketch-bench/src/wrappers/hydra_hll/polars.rs index 272b99c1..822445b0 100644 --- a/sketch-bench/src/wrappers/hydra_hll/polars.rs +++ b/sketch-bench/src/wrappers/hydra_hll/polars.rs @@ -34,7 +34,7 @@ pub fn build_polars_subpop_cardinality( } impl PolarsSubpopCardinality { - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -92,7 +92,7 @@ pub fn insert_step_polars_subpop_cardinality( pub fn query_polars_subpop_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs index fc4815c4..bbd303a6 100644 --- a/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_hll/sketchlib.rs @@ -35,7 +35,7 @@ pub fn build_hydra_hll(config: &ParamSet, label_columns: usize) -> Result f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::Cardinality, "hydra-hll") } } @@ -96,7 +96,7 @@ pub fn insert_step_hydra_hll( pub fn query_hydra_hll( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_hll(params, items, probes, 1, passes) @@ -107,7 +107,7 @@ pub fn query_hydra_hll( pub fn merge_query_hydra_hll( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index e6758577..de6f74f6 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -64,7 +64,7 @@ mod tests { for _ in 0..500 { fed_kll(&mut h, &frecord("b;x", 10_000.0)); } - let median = h.estimate_subpop_quantile(&["a"], 0.5); + let median = h.estimate_subpop_quantile(&[Some("a")], 0.5); assert!( (1.0..=101.0).contains(&median), "group `a` spans 1..=101, median estimated {median}" @@ -80,8 +80,8 @@ mod tests { for v in 1..=101 { fed_kll(&mut h, &frecord("a;x", v as f64)); } - assert_eq!(h.estimate_subpop_quantile(&["a"], 0.0), 1.0); - assert_eq!(h.estimate_subpop_quantile(&["a"], 1.0), 101.0); + assert_eq!(h.estimate_subpop_quantile(&[Some("a")], 0.0), 1.0); + assert_eq!(h.estimate_subpop_quantile(&[Some("a")], 1.0), 101.0); } /// The library allocates a cell's retained slots once, so the footprint is diff --git a/sketch-bench/src/wrappers/hydra_kll/polars.rs b/sketch-bench/src/wrappers/hydra_kll/polars.rs index 44ecb2f4..11a6a268 100644 --- a/sketch-bench/src/wrappers/hydra_kll/polars.rs +++ b/sketch-bench/src/wrappers/hydra_kll/polars.rs @@ -46,8 +46,8 @@ impl PolarsSubpopQuantile { /// `floor(phi * n)`, clamped to the last index. That is the index whose /// rank interval contains `phi * n`, which is what the rank-error /// comparator scores against, so an exact answer scores zero. - pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { - let Some(values) = self.sorted.get(&prefix_key(labels)) else { + pub fn estimate_subpop_quantile(&self, labels: &[Option<&str>], phi: f64) -> f64 { + let Some(values) = self.sorted.get(&group_key(labels)) else { return f64::NAN; }; if values.is_empty() { @@ -157,7 +157,7 @@ pub fn insert_step_polars_subpop_quantile( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index 672de091..7f0ea176 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -46,7 +46,7 @@ impl HydraKll { /// at a rank, which is what rank error is defined over. The `Cdf` variant /// answers the inverse question. #[inline] - pub fn estimate_subpop_quantile(&self, labels: &[&str], phi: f64) -> f64 { + pub fn estimate_subpop_quantile(&self, labels: &[Option<&str>], phi: f64) -> f64 { query(&self.inner, labels, &HydraQuery::Quantile(phi), "hydra-kll") } } @@ -112,7 +112,7 @@ pub fn insert_step_hydra_kll( pub fn query_hydra_kll( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, passes: usize, ) -> Result>, BuildError> { merge_query_hydra_kll(params, items, probes, 1, passes) @@ -123,7 +123,7 @@ pub fn query_hydra_kll( pub fn merge_query_hydra_kll( params: &ParamSet, items: Rc>, - probes: Rc, f64)>>, + probes: Rc>, f64)>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 0521e338..1af9d7ef 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -6,8 +6,8 @@ use crate::wrappers::BuildError; use asap_sketchlib::input::{HydraCounter, HydraQuery}; use asap_sketchlib::{DataInput, Hydra}; -pub(crate) fn labels(group: &[String]) -> Vec<&str> { - group.iter().map(String::as_str).collect() +pub(crate) fn labels(group: &[Option]) -> Vec> { + group.iter().map(Option::as_deref).collect() } /// The label columns of a `;`-joined record stream, which every record must @@ -54,10 +54,11 @@ pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput, variant: &str) } } -/// Asks `query` of the subpopulation `group` constrains: its values are the -/// leading key columns' (the scored subpopulations group by column 0), the -/// rest unconstrained. A probe wider than the grid is refused. -pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery, variant: &str) -> f64 { +/// Asks `query` of the subpopulation `group` constrains: a value at each +/// grouped column, `None` (unconstrained) at the rest and past its end, so any +/// non-empty subset of the key columns can be asked. A probe wider than the +/// grid is refused. +pub(crate) fn query(h: &Hydra, group: &[Option<&str>], query: &HydraQuery, variant: &str) -> f64 { let width = h.schema().len(); if group.len() > width { panic!( @@ -65,7 +66,9 @@ pub(crate) fn query(h: &Hydra, group: &[&str], query: &HydraQuery, variant: &str group.len() ); } - let key: Vec> = (0..width).map(|i| group.get(i).copied()).collect(); + let key: Vec> = (0..width) + .map(|i| group.get(i).copied().flatten()) + .collect(); h.query_key(&key, query) .unwrap_or_else(|e| panic!("{variant}: probe {group:?}: {e}")) } diff --git a/sketch-bench/src/wrappers/hydra_univmon/mod.rs b/sketch-bench/src/wrappers/hydra_univmon/mod.rs index 181375ee..ab6073c8 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/mod.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/mod.rs @@ -59,7 +59,7 @@ mod tests { fed(&mut h, &record("a;x", 10)); } fed(&mut h, &record("a;y", 20)); - let est = h.estimate_subpop_l1_norm(&["a"]); + let est = h.estimate_subpop_l1_norm(&[Some("a")]); assert!( (est - 4.0).abs() < 0.5, "four records under `a`, estimated {est}" @@ -73,7 +73,7 @@ mod tests { fed(&mut h, &record("a;x", 10)); } fed(&mut h, &record("a;y", 20)); - let est = h.estimate_subpop_cardinality(&["a"]); + let est = h.estimate_subpop_cardinality(&[Some("a")]); assert!( (est - 2.0).abs() < 0.5, "two distinct values under `a`, estimated {est}" @@ -86,7 +86,7 @@ mod tests { for _ in 0..8 { fed(&mut h, &record("a;x", 10)); } - let est = h.estimate_subpop_entropy(&["a"]); + let est = h.estimate_subpop_entropy(&[Some("a")]); assert!( est.abs() < 0.1, "one value, so no uncertainty, estimated {est}" @@ -99,8 +99,8 @@ mod tests { for _ in 0..4 { fed(&mut h, &record("a;x", 10)); } - let l1 = h.estimate_subpop_l1_norm(&["a"]); - let l2 = h.estimate_subpop_l2_norm(&["a"]); + let l1 = h.estimate_subpop_l1_norm(&[Some("a")]); + let l2 = h.estimate_subpop_l2_norm(&[Some("a")]); assert!((l1 - l2).abs() < 0.5, "l1 {l1}, l2 {l2}"); } @@ -116,7 +116,7 @@ mod tests { left.inner .merge(&right.inner) .expect("both operands built from one ParamSet, so shapes match"); - let est = left.estimate_subpop_l1_norm(&["a"]); + let est = left.estimate_subpop_l1_norm(&[Some("a")]); assert!( (est - 7.0).abs() < 0.5, "seven records in all, estimated {est}" @@ -174,14 +174,17 @@ mod baseline_tests { type Asked = fn( &ParamSet, Rc>, - Rc>>, + Rc>>>, usize, ) -> Result>, crate::wrappers::BuildError>; fn answers_for(query: Asked) -> Vec { let params = ParamSet::of(&HydraUnivmonParams::canonical()); - let probes = Rc::new(vec![vec!["a".to_string()], vec!["b".to_string()]]); + let probes = Rc::new(vec![ + vec![Some("a".to_string())], + vec![Some("b".to_string())], + ]); let mut passes = query(¶ms, stream(), probes, 1).expect("baseline builds"); let pass = passes.pop().expect("one pass"); pass().0 diff --git a/sketch-bench/src/wrappers/hydra_univmon/polars.rs b/sketch-bench/src/wrappers/hydra_univmon/polars.rs index eb71f9f1..0e9dd152 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/polars.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/polars.rs @@ -39,7 +39,7 @@ impl Default for PolarsSubpopCardinalityUnivmon { } impl PolarsSubpopCardinalityUnivmon { - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -59,7 +59,7 @@ fn build_polars_subpop_vector( } impl PolarsSubpopUnivmon { - pub fn estimate_subpop_statistic(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_statistic(&self, labels: &[Option<&str>]) -> f64 { self.0.query(labels) } } @@ -116,7 +116,7 @@ pub fn insert_step_polars_subpop_cardinality_univmon( pub fn query_polars_subpop_cardinality_univmon( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); @@ -209,7 +209,7 @@ fn insert_step_polars_subpop_vector( fn query_polars_subpop_vector( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, fold: fn(&[u64]) -> f64, ) -> Result>, BuildError> { @@ -274,7 +274,7 @@ pub fn insert_step_polars_subpop_l1_norm( pub fn query_polars_subpop_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, l1_norm) @@ -307,7 +307,7 @@ pub fn insert_step_polars_subpop_l2_norm( pub fn query_polars_subpop_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, l2_norm) @@ -340,7 +340,7 @@ pub fn insert_step_polars_subpop_entropy( pub fn query_polars_subpop_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { query_polars_subpop_vector(params, items, probes, passes, entropy) diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index 11c689fa..e7465088 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -49,7 +49,7 @@ pub fn build_hydra_univmon( impl HydraUnivmon { #[inline] - pub fn estimate_subpop_cardinality(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_cardinality(&self, labels: &[Option<&str>]) -> f64 { query( &self.inner, labels, @@ -59,17 +59,17 @@ impl HydraUnivmon { } #[inline] - pub fn estimate_subpop_l1_norm(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_l1_norm(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::L1Norm, "hydra-univmon") } #[inline] - pub fn estimate_subpop_l2_norm(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_l2_norm(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::L2Norm, "hydra-univmon") } #[inline] - pub fn estimate_subpop_entropy(&self, labels: &[&str]) -> f64 { + pub fn estimate_subpop_entropy(&self, labels: &[Option<&str>]) -> f64 { query(&self.inner, labels, &HydraQuery::Entropy, "hydra-univmon") } } @@ -131,10 +131,10 @@ pub fn insert_step_hydra_univmon( fn asked_hydra_univmon( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, - estimate: fn(&HydraUnivmon, &[&str]) -> f64, + estimate: fn(&HydraUnivmon, &[Option<&str>]) -> f64, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -162,7 +162,7 @@ fn asked_hydra_univmon( pub fn query_hydra_univmon_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -180,7 +180,7 @@ pub fn query_hydra_univmon_cardinality( pub fn merge_query_hydra_univmon_cardinality( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -197,7 +197,7 @@ pub fn merge_query_hydra_univmon_cardinality( pub fn query_hydra_univmon_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -215,7 +215,7 @@ pub fn query_hydra_univmon_l1_norm( pub fn merge_query_hydra_univmon_l1_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -232,7 +232,7 @@ pub fn merge_query_hydra_univmon_l1_norm( pub fn query_hydra_univmon_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -250,7 +250,7 @@ pub fn query_hydra_univmon_l2_norm( pub fn merge_query_hydra_univmon_l2_norm( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { @@ -267,7 +267,7 @@ pub fn merge_query_hydra_univmon_l2_norm( pub fn query_hydra_univmon_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, passes: usize, ) -> Result>, BuildError> { asked_hydra_univmon( @@ -285,7 +285,7 @@ pub fn query_hydra_univmon_entropy( pub fn merge_query_hydra_univmon_entropy( params: &ParamSet, items: Rc>, - probes: Rc>>, + probes: Rc>>>, shards: usize, passes: usize, ) -> Result>, BuildError> { diff --git a/sketch-bench/src/wrappers/polars_shared.rs b/sketch-bench/src/wrappers/polars_shared.rs index d049a1b9..7e9e3c52 100644 --- a/sketch-bench/src/wrappers/polars_shared.rs +++ b/sketch-bench/src/wrappers/polars_shared.rs @@ -287,9 +287,17 @@ pub fn subset_key(parts: &[&str], mask: usize) -> String { out } -/// The key a probe of the leading label columns `labels` reads. -pub fn prefix_key(labels: &[&str]) -> String { - subset_key(labels, (1 << labels.len()) - 1) +/// The key a probe reads: `labels` holds a value at each grouped column and +/// `None` at the rest, so any subset of the columns is a group, not only a +/// prefix of them. +pub fn group_key(labels: &[Option<&str>]) -> String { + let parts: Vec<&str> = labels.iter().map(|l| l.unwrap_or("")).collect(); + let mask = labels + .iter() + .enumerate() + .filter(|(_, l)| l.is_some()) + .fold(0, |mask, (j, _)| mask | (1 << j)); + subset_key(&parts, mask) } /// Expand one record into `(subset_key, value)` rows, one per non-empty subset @@ -360,9 +368,9 @@ impl PolarsSubpopFrequencyCore { } } - pub fn query(&self, labels: &[&str], value: &T) -> f64 { + pub fn query(&self, labels: &[Option<&str>], value: &T) -> f64 { self.counts - .get(&(prefix_key(labels), value.count_key())) + .get(&(group_key(labels), value.count_key())) .copied() .unwrap_or(0) as f64 } @@ -426,8 +434,8 @@ impl PolarsSubpopCardinalityCore { } } - pub fn query(&self, labels: &[&str]) -> f64 { - self.distinct.get(&prefix_key(labels)).copied().unwrap_or(0) as f64 + pub fn query(&self, labels: &[Option<&str>]) -> f64 { + self.distinct.get(&group_key(labels)).copied().unwrap_or(0) as f64 } pub fn memory_bytes(&self) -> usize { @@ -495,8 +503,8 @@ impl PolarsSubpopVectorCore { .collect(); } - pub fn query(&self, labels: &[&str]) -> f64 { - self.exact.get(&prefix_key(labels)).copied().unwrap_or(0.0) + pub fn query(&self, labels: &[Option<&str>]) -> f64 { + self.exact.get(&group_key(labels)).copied().unwrap_or(0.0) } pub fn memory_bytes(&self) -> usize { @@ -542,7 +550,8 @@ mod tests { fn subset_keys_tag_each_value_with_its_column() { assert_eq!(subset_key(&["a", "b", "c"], 0b101), "label0:a;label2:c"); assert_eq!(subset_key(&["x:y;z", ""], 0b11), r"label0:x\:y\;z;label1:"); - assert_eq!(prefix_key(&["a", "b"]), "label0:a;label1:b"); + assert_eq!(group_key(&[Some("a"), Some("b")]), "label0:a;label1:b"); + assert_eq!(group_key(&[None, Some("b")]), "label1:b"); } /// #74: the column-0 group `a` holds 2 records (`a;a`, `a;b`). The old @@ -553,8 +562,11 @@ mod tests { core.update(&("a;a".to_string(), 7)); core.update(&("a;b".to_string(), 7)); core.finalize(); - assert_eq!(core.query(&["a"], &7), 2.0); - assert_eq!(core.query(&["a", "a"], &7), 1.0); - assert_eq!(core.query(&["b"], &7), 0.0); + assert_eq!(core.query(&[Some("a")], &7), 2.0); + assert_eq!(core.query(&[Some("a"), Some("a")], &7), 1.0); + assert_eq!(core.query(&[Some("b")], &7), 0.0); + // Column 1 alone: `a` once, `b` once, with column 0 unconstrained. + assert_eq!(core.query(&[None, Some("a")], &7), 1.0); + assert_eq!(core.query(&[None, Some("b")], &7), 1.0); } } From bc770e3b7af16c418609c2d40fb299921ebf4b4a Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:45:46 +0000 Subject: [PATCH 2/5] hydra: list every group in --per-group-out; escape keys; refuse no accuracy - Group keys escape `\`, `:` and `;` as polars_shared::subset_key does. - Groups that cannot be scored (zero true statistic, e.g. zero entropy) are written with an empty `error`, so n_q sums to the stream's records. - --per-group-out with no accuracy measurement is refused instead of writing an empty file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- README.md | 4 +- aqpbm-cli/src/cli.rs | 10 +++-- aqpbm-cli/src/main.rs | 8 ++-- aqpbm-cli/src/rows/statistic.rs | 7 ++-- aqpbm-cli/tests/hydra_grouping.rs | 32 +++++++++++++-- aqpbm-core/src/accuracy/mod.rs | 12 +++--- .../src/accuracy/subpopulation/cardinality.rs | 8 ++-- .../src/accuracy/subpopulation/entropy.rs | 28 +++++++++++++ .../src/accuracy/subpopulation/frequency.rs | 2 +- .../subpopulation/frequency_vector.rs | 8 ++-- .../src/accuracy/subpopulation/l1_norm.rs | 10 ++--- aqpbm-core/src/accuracy/subpopulation/mod.rs | 41 +++++++++++++++---- .../src/accuracy/subpopulation/rank_error.rs | 4 +- 13 files changed, 132 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index f9414e41..b4f28ebd 100644 --- a/README.md +++ b/README.md @@ -453,7 +453,9 @@ The file can be found [under configs directory](./configs/datagen/hydra_columns. Any non-empty subset works, since the grid stores every subset of a record's labels; it picks the one the `hydra-*` row (`lib` and `polars`) asks and scores. With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). -**`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per scored group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`). +**`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`, with `\`, `:` and `;` in a label escaped by `\`). +Every group is listed, so the `n_q` sum to the stream's records; a group that cannot be scored (its true statistic is zero, e.g. zero entropy) has an empty `error` and is left out of the `err_*` summary. +It takes exactly one accuracy measurement (query or merge). #### General Explanation diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index 1667a45c..65e02ee4 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -249,10 +249,12 @@ pub struct SketchbenchArgs { /// Path to append JSONL records to. `-` or omitted sends them to stdout. #[arg(long, help_heading = "Output")] pub report: Option, - /// Write a `hydra-*` row's per-group errors to this CSV, one row per scored - /// group: `group_key,n_q,error` (`n_q` is the group's record count, `error` - /// the row's own metric). The record's `err_*` fields summarise the same - /// rows. Takes one accuracy measurement: query or merge, not both. + /// Write a `hydra-*` row's per-group errors to this CSV, one row per group: + /// `group_key,n_q,error` (`n_q` is the group's record count, `error` the + /// row's own metric, empty for a group that cannot be scored, such as one + /// with zero entropy). The `n_q` sum to the stream's records; the record's + /// `err_*` fields summarise the scored rows. Takes exactly one accuracy + /// measurement: query or merge. #[arg(long, help_heading = "Output")] pub per_group_out: Option, /// Write one line for the whole invocation instead of one per measurement, diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 105035df..44edd0f9 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -357,10 +357,12 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { if !variant.starts_with("hydra-") { bail!("--per-group-out: only the hydra-* rows score groups, and {variant} is not one"); } - if want.iter().filter(|(_, m)| *m == Metric::Accuracy).count() > 1 { - bail!( + match want.iter().filter(|(_, m)| *m == Metric::Accuracy).count() { + 0 => bail!("--per-group-out writes an accuracy measurement, and none was asked for"), + 1 => {} + _ => bail!( "--per-group-out writes one accuracy measurement; ask for query or merge, not both" - ); + ), } } let req = Requirement { diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 87a227aa..7724a139 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -428,8 +428,8 @@ where Ok(bodies) } -/// The scorer, also writing each scored group's error to `path` as -/// `group_key,n_q,error` whenever it scores. Every pass answers the same, so +/// The scorer, also writing every group to `path` as `group_key,n_q,error` +/// whenever it scores; `error` is empty for a group that cannot be scored. Every pass answers the same, so /// each rewrites the same rows. The file is created here, so a path that /// cannot be written fails before anything is measured. fn per_group_written( @@ -450,7 +450,8 @@ fn per_group_written( } else { g.group }; - csv.push_str(&format!("{key},{},{}\n", g.n_q, g.error)); + let error = g.error.map_or(String::new(), |e| e.to_string()); + csv.push_str(&format!("{key},{},{error}\n", g.n_q)); } std::fs::write(&path, csv) .unwrap_or_else(|e| panic!("--per-group-out {}: {e}", path.display())); diff --git a/aqpbm-cli/tests/hydra_grouping.rs b/aqpbm-cli/tests/hydra_grouping.rs index 50464482..281ccec5 100644 --- a/aqpbm-cli/tests/hydra_grouping.rs +++ b/aqpbm-cli/tests/hydra_grouping.rs @@ -65,8 +65,8 @@ fn scored( /// Every Hydra family, lib at a grid far larger than its 19 subkeys and the /// polars baseline, grouped by column 1 alone and by both columns: both score -/// (about) zero, and the per-group file has one row per scored group, keyed by -/// the columns asked. +/// (about) zero, and the per-group file has one row per group, keyed by the +/// columns asked. #[test] fn any_label_subset_is_asked_where_it_was_inserted() { let rows = [ @@ -93,7 +93,8 @@ fn any_label_subset_is_asked_where_it_was_inserted() { let mut lines = csv.lines(); assert_eq!(lines.next(), Some("group_key,n_q,error"), "{at}"); let rows: Vec<&str> = lines.collect(); - assert_eq!(rows.len() as f64, acc["groups_scored"].as_f64().expect(&at)); + let scored = rows.iter().filter(|r| !r.ends_with(',')).count(); + assert_eq!(scored as f64, acc["groups_scored"].as_f64().expect(&at)); let n_q: u64 = rows .iter() .map(|r| r.split(',').nth(1).and_then(|n| n.parse::().ok())) @@ -135,3 +136,28 @@ fn a_group_column_past_the_labels_is_refused() { let err = String::from_utf8_lossy(&out.stderr); assert!(err.contains("--group-columns 2"), "{err}"); } + +/// `--per-group-out` writes an accuracy measurement, so a run that asks for +/// none is refused rather than leaving an empty file. +#[test] +fn per_group_out_without_accuracy_is_refused() { + let spec = spec("i64"); + let csv = spec.with_extension("no-accuracy.csv"); + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", "hydra-cms", "--library", "lib"]) + .args([ + "--spec", + spec.to_str().expect("utf-8 path"), + "--dtype", + "i64", + ]) + .args(["--per-group-out", csv.to_str().expect("utf-8 path")]) + .args(["--operations", "query", "--metrics", "throughput"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .output() + .expect("approxbench runs"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("none was asked for"), "{err}"); + assert!(!csv.exists(), "no file is left behind"); +} diff --git a/aqpbm-core/src/accuracy/mod.rs b/aqpbm-core/src/accuracy/mod.rs index 698b38d0..1ae393ed 100644 --- a/aqpbm-core/src/accuracy/mod.rs +++ b/aqpbm-core/src/accuracy/mod.rs @@ -103,9 +103,9 @@ pub trait GroundTruth { answers: &[Self::Answer], ) -> BTreeMap; - /// ④ Each scored group's error, for a comparator whose population is + /// ④ Every group with its error, for a comparator whose population is /// subpopulations; empty for every other. [`score`](Self::score) summarises - /// the same rows, and `--per-group-out` writes them. + /// the scored rows, and `--per-group-out` writes them all. fn per_group( &self, _truth: &Self::Truth, @@ -116,13 +116,15 @@ pub trait GroundTruth { } } -/// One scored subpopulation: its key, how many records it carried (`n_q`), and -/// its error in the comparator's own metric, lower is better. +/// One subpopulation: its key, how many records it carried (`n_q`), and its +/// error in the comparator's own metric, lower is better. `None` when the group +/// cannot be scored (its true statistic is zero, so it has no relative error); +/// it is still listed, so the groups' `n_q` sum to the stream's records. #[derive(Clone, Debug, PartialEq)] pub struct GroupError { pub group: String, pub n_q: u64, - pub error: f64, + pub error: Option, } /// How a row's answers turn into the named error metrics: the scorer diff --git a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs index c3128b81..3cf99df0 100644 --- a/aqpbm-core/src/accuracy/subpopulation/cardinality.rs +++ b/aqpbm-core/src/accuracy/subpopulation/cardinality.rs @@ -123,7 +123,8 @@ impl GroundTruth for SubpopCardinalityGT { metrics } - /// Relative error per group, as `are_all` averages it. + /// Relative error per group, as `are_all` averages it; a group with no + /// distinct value is listed unscored. fn per_group( &self, truth: &SubpopCardTruth, @@ -132,8 +133,9 @@ impl GroundTruth for SubpopCardinalityGT { ) -> Vec { let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); - group_errors(truth.exact.iter().filter(|(_, &d)| d > 0).map(|(g, &d)| { - let err = (est.get(g).copied().unwrap_or(0.0) - d as f64).abs() / d as f64; + group_errors(truth.exact.iter().map(|(g, &d)| { + let err = + (d > 0).then(|| (est.get(g).copied().unwrap_or(0.0) - d as f64).abs() / d as f64); (g.clone(), truth.sizes[g], err) })) } diff --git a/aqpbm-core/src/accuracy/subpopulation/entropy.rs b/aqpbm-core/src/accuracy/subpopulation/entropy.rs index f96bb132..4d2bdbb3 100644 --- a/aqpbm-core/src/accuracy/subpopulation/entropy.rs +++ b/aqpbm-core/src/accuracy/subpopulation/entropy.rs @@ -102,6 +102,34 @@ mod tests { assert_eq!(cmp["aae_all"], 0.0); } + /// Over both columns only (a, x) holds two values; the other groups have + /// zero entropy and no relative error, but are still listed, so `n_q` + /// sums to the stream's 6 records. + #[test] + fn a_zero_entropy_group_is_listed_unscored() { + let gt = over(vec![0, 1]); + let truth = gt + .truth(&records()) + .expect("the table has the named columns"); + let probes = gt.probes(&truth); + let rows: Vec<(String, u64, Option)> = gt + .per_group(&truth, &probes, &vec![0.0; probes.len()]) + .into_iter() + .map(|g| (g.group, g.n_q, g.error)) + .collect(); + assert_eq!( + rows, + vec![ + ("label0:a;label1:x".to_string(), 2, Some(1.0)), + ("label0:b;label1:y".to_string(), 2, None), + ("label0:a;label1:y".to_string(), 1, None), + ("label0:b;label1:x".to_string(), 1, None), + ] + ); + let cmp = null_over(>, &records()); + assert_eq!(cmp["groups_scored"], 1.0); + } + #[test] fn a_different_grouping_is_a_different_population() { let cmp = null_over(&over(vec![0, 1]), &records()); diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency.rs b/aqpbm-core/src/accuracy/subpopulation/frequency.rs index 75a8b2d1..588a286f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency.rs @@ -173,7 +173,7 @@ where group_errors( per_group .into_iter() - .map(|(g, (sum, pairs))| (g.clone(), truth.sizes[g], sum / pairs as f64)), + .map(|(g, (sum, pairs))| (g.clone(), truth.sizes[g], Some(sum / pairs as f64))), ) } } diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs index 43d7b209..08421ec4 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs @@ -120,16 +120,16 @@ pub(super) fn score_over( } /// Relative error per group, as `are_all` averages it: a group whose true -/// statistic is zero (entropy over one value) has no relative error and is -/// not scored. +/// statistic is zero (entropy over one value) has no relative error, so it is +/// listed unscored. pub(super) fn per_group_over( truth: &SubpopVectorTruth, probes: &[GroupKey], answers: &[f64], ) -> Vec { let est: HashMap<&GroupKey, f64> = probes.iter().zip(answers).map(|(p, a)| (p, *a)).collect(); - group_errors(truth.exact.iter().filter(|(_, &v)| v > 0.0).map(|(g, &v)| { - let err = (est.get(g).copied().unwrap_or(0.0) - v).abs() / v; + group_errors(truth.exact.iter().map(|(g, &v)| { + let err = (v > 0.0).then(|| (est.get(g).copied().unwrap_or(0.0) - v).abs() / v); (g.clone(), truth.sizes[g], err) })) } diff --git a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs index 28ca38e2..c32f9f5f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs +++ b/aqpbm-core/src/accuracy/subpopulation/l1_norm.rs @@ -114,7 +114,7 @@ mod tests { let truth = gt.truth(&table).expect("the table has the named columns"); let probes = gt.probes(&truth); let asked: Vec = probes.iter().map(|p| answers[p]).collect(); - let rows: Vec<(String, u64, f64)> = gt + let rows: Vec<(String, u64, Option)> = gt .per_group(&truth, &probes, &asked) .into_iter() .map(|g| (g.group, g.n_q, g.error)) @@ -122,10 +122,10 @@ mod tests { assert_eq!( rows, vec![ - ("label0:a;label1:x".to_string(), 2, 0.0), - ("label0:b;label1:y".to_string(), 2, 0.5), - ("label0:a;label1:y".to_string(), 1, 1.0), - ("label0:b;label1:x".to_string(), 1, 0.5), + ("label0:a;label1:x".to_string(), 2, Some(0.0)), + ("label0:b;label1:y".to_string(), 2, Some(0.5)), + ("label0:a;label1:y".to_string(), 1, Some(1.0)), + ("label0:b;label1:x".to_string(), 1, Some(0.5)), ] ); } diff --git a/aqpbm-core/src/accuracy/subpopulation/mod.rs b/aqpbm-core/src/accuracy/subpopulation/mod.rs index 2f16d227..0f92c223 100644 --- a/aqpbm-core/src/accuracy/subpopulation/mod.rs +++ b/aqpbm-core/src/accuracy/subpopulation/mod.rs @@ -66,18 +66,30 @@ fn owned(group: &[&str], columns: &[usize]) -> GroupKey { } /// How a group is named in `--per-group-out`: each grouped column's value -/// tagged with its column, as the grid's subkeys are (`label1:x`). +/// tagged with its column, as the grid's subkeys are (`label1:x`), with `\`, +/// `:` and `;` escaped. The same encoding as sketch-bench's +/// `polars_shared::subset_key`, which this crate cannot depend on. fn rendered(key: &GroupKey) -> String { - key.iter() - .enumerate() - .filter_map(|(j, label)| label.as_ref().map(|l| format!("label{j}:{l}"))) - .collect::>() - .join(";") + let mut out = String::new(); + for (j, label) in key.iter().enumerate() { + let Some(label) = label else { continue }; + if !out.is_empty() { + out.push(';'); + } + out.push_str(&format!("label{j}:")); + for ch in label.chars() { + if matches!(ch, '\\' | ':' | ';') { + out.push('\\'); + } + out.push(ch); + } + } + out } /// One [`GroupError`] per group, heaviest first (ties on the key), so the /// per-group file reads the same across runs. -fn group_errors(errors: impl Iterator) -> Vec { +fn group_errors(errors: impl Iterator)>) -> Vec { let mut out: Vec = errors .map(|(key, n_q, error)| GroupError { group: rendered(&key), @@ -101,7 +113,7 @@ fn write_groups( schema_width: usize, metrics: &mut BTreeMap, ) { - let mut errs: Vec = groups.iter().map(|g| g.error).collect(); + let mut errs: Vec = groups.iter().filter_map(|g| g.error).collect(); errs.sort_by(f64::total_cmp); if let Some(&max) = errs.last() { metrics.insert( @@ -169,3 +181,16 @@ where table, ) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A label holding the separators is escaped as the grid's subkeys are, + /// so it cannot be read as two columns. + #[test] + fn rendered_keys_escape_the_separators() { + let key = vec![None, Some(r"x:y;z\".to_string()), Some(String::new())]; + assert_eq!(rendered(&key), r"label1:x\:y\;z\\;label2:"); + } +} diff --git a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs index 4c2f65fa..01ec1259 100644 --- a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs +++ b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs @@ -100,7 +100,7 @@ impl GroundTruth for SubpopRankErrorGT { metrics.insert( "mean_rank_err".into(), if scored_groups > 0 { - groups.iter().map(|g| g.error).sum::() / scored_groups as f64 + groups.iter().filter_map(|g| g.error).sum::() / scored_groups as f64 } else { 0.0 }, @@ -164,7 +164,7 @@ fn rank_errors( groups.push(( group.clone(), sorted.len() as u64, - group_sum / GROUP_GRID_POINTS as f64, + Some(group_sum / GROUP_GRID_POINTS as f64), )); } (group_errors(groups.into_iter()), max_err) From b1a678ecd440911ea2bf9f5ad6c83cb455cec833 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:44:29 +0000 Subject: [PATCH 3/5] hydra: KLL CDF and UnivMon sum rows; KLL cell merge buffer - hydra-kll-cdf (lib, polars): asks the KLL grid HydraQuery::Cdf(x) at each group's own values at phi = 0.01..0.99, scored by absolute CDF error (SubpopCdfErrorGT, comparator subpop-cdf-error). The polars baseline is the exact share at or below x over the same sorted groups. - hydra-univmon-sum (lib, polars): each record inserted with count = value, so the UnivMon grid's L1 is the group's sum, scored by relative error against exact per-group sums (SubpopSumGT, comparator subpop-sum). Integer value dtypes only; f64/str and values outside [0, i32::MAX] are refused by name. - memory_hydra_kll counts each cell as kll_lib_bytes does, merge buffer of cell_k items included. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- README.md | 5 +- aqpbm-cli/src/rows/hydra.rs | 62 ++++++ aqpbm-cli/src/rows/hydra_univmon.rs | 80 ++++++++ aqpbm-cli/src/rows/mod.rs | 8 +- aqpbm-cli/src/rows/statistic.rs | 32 +++ aqpbm-cli/tests/hydra_grouping.rs | 29 +++ .../src/accuracy/subpopulation/cdf_error.rs | 193 ++++++++++++++++++ .../subpopulation/frequency_vector.rs | 29 ++- aqpbm-core/src/accuracy/subpopulation/mod.rs | 4 + .../src/accuracy/subpopulation/rank_error.rs | 8 +- aqpbm-core/src/accuracy/subpopulation/sum.rs | 182 +++++++++++++++++ configs/datagen/hydra_columns_f64.yaml | 6 +- configs/datagen/hydra_univmon_columns.yaml | 2 +- docs/concepts.md | 2 + sketch-bench/src/registry.rs | 66 ++++++ sketch-bench/src/request.rs | 4 + sketch-bench/src/wrappers/hydra_kll/mod.rs | 61 +++++- sketch-bench/src/wrappers/hydra_kll/polars.rs | 46 ++++- .../src/wrappers/hydra_kll/sketchlib.rs | 67 +++++- sketch-bench/src/wrappers/hydra_shared.rs | 14 +- .../src/wrappers/hydra_univmon/mod.rs | 55 +++++ .../src/wrappers/hydra_univmon/polars.rs | 144 +++++++++++++ .../src/wrappers/hydra_univmon/sketchlib.rs | 185 ++++++++++++++++- sketch-bench/src/wrappers/kll/mod.rs | 5 +- sketch-bench/src/wrappers/polars_shared.rs | 2 +- 25 files changed, 1245 insertions(+), 46 deletions(-) create mode 100644 aqpbm-core/src/accuracy/subpopulation/cdf_error.rs create mode 100644 aqpbm-core/src/accuracy/subpopulation/sum.rs diff --git a/README.md b/README.md index b4f28ebd..b4e58fc0 100644 --- a/README.md +++ b/README.md @@ -451,7 +451,10 @@ The file can be found [under configs directory](./configs/datagen/hydra_columns. **`--group-columns`** (Hydra rows only): which label columns the subpopulation is taken over, as comma-separated indices into the columns before the value column, e.g. `1` or `0,1`; default `0`. Any non-empty subset works, since the grid stores every subset of a record's labels; it picks the one the `hydra-*` row (`lib` and `polars`) asks and scores. -With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). +With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`; mean absolute CDF error for `hydra-kll-cdf`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). + +Two Hydra rows ask a second statistic of an existing cell: `hydra-kll-cdf` asks the KLL grid `Cdf(x)`, the share of a group at or below `x`, at each group's own values at `phi` = 0.01..0.99; `hydra-univmon-sum` inserts each value counted by itself (i64 or u64, within an `i32` count), so the UnivMon grid's L1 is the group's sum. +Both have a `polars` exact baseline. **`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`, with `\`, `:` and `;` in a label escaped by `\`). Every group is listed, so the `n_q` sum to the stream's records; a group that cannot be scored (its true statistic is zero, e.g. zero entropy) has an empty `error` and is left out of the `err_*` summary. diff --git a/aqpbm-cli/src/rows/hydra.rs b/aqpbm-cli/src/rows/hydra.rs index a1a60241..0c1cdbdf 100644 --- a/aqpbm-cli/src/rows/hydra.rs +++ b/aqpbm-cli/src/rows/hydra.rs @@ -253,3 +253,65 @@ pub(crate) fn row_hydra_kll_polars( other => Err(no_build_at(req, other)), } } + +pub(crate) fn row_hydra_kll_cdf_lib( + req: &Requirement, + description: &TableDescription, + table: GeneratedTable, + want: &[(Operation, Metric)], +) -> Result { + macro_rules! at { + ($t:ty) => { + subpop_cdf_row::<$t>( + req, + description, + table, + want, + hks::insert_hydra_kll::<$t>, + hks::insert_step_hydra_kll::<$t>, + hks::query_hydra_kll_cdf::<$t>, + Some(( + hks::merge_hydra_kll::<$t>, + hks::merge_step_hydra_kll::<$t>, + hks::merge_query_hydra_kll_cdf::<$t>, + )), + None, + ) + }; + } + match req.width { + Dtype::I64 => at!(i64), + Dtype::U64 => at!(u64), + Dtype::F64 => at!(f64), + other => Err(no_build_at(req, other)), + } +} + +pub(crate) fn row_hydra_kll_cdf_polars( + req: &Requirement, + description: &TableDescription, + table: GeneratedTable, + want: &[(Operation, Metric)], +) -> Result { + macro_rules! at { + ($t:ty) => { + subpop_cdf_row::<$t>( + req, + description, + table, + want, + hkp::insert_polars_subpop_quantile::<$t>, + hkp::insert_step_polars_subpop_quantile::<$t>, + hkp::query_polars_subpop_cdf::<$t>, + None, + Some(hkp::prepare_polars_subpop_quantile::<$t>), + ) + }; + } + match req.width { + Dtype::I64 => at!(i64), + Dtype::U64 => at!(u64), + Dtype::F64 => at!(f64), + other => Err(no_build_at(req, other)), + } +} diff --git a/aqpbm-cli/src/rows/hydra_univmon.rs b/aqpbm-cli/src/rows/hydra_univmon.rs index 34320aa9..cd3f283c 100644 --- a/aqpbm-cli/src/rows/hydra_univmon.rs +++ b/aqpbm-cli/src/rows/hydra_univmon.rs @@ -272,3 +272,83 @@ pub(crate) fn row_hydra_univmon_entropy_polars( Dtype::Str => at!(String), } } + +/// The sum rows insert each value as its own integer count, so they build at +/// the integer widths only. +fn no_sum_at(req: &Requirement, got: Dtype) -> RunError { + RunError::Sketch(format!( + "{}/{} counts each value by itself, an integer weight, so builds at i64 or u64; \ + --dtype {} is not an integer", + req.variant, + req.library, + got.name(), + )) +} + +pub(crate) fn row_hydra_univmon_sum_lib( + req: &Requirement, + description: &TableDescription, + table: GeneratedTable, + want: &[(Operation, Metric)], +) -> Result { + macro_rules! at { + ($t:ty) => { + subpop_vector_row::<$t, _>( + req, + description, + table, + want, + SubpopSumGT { + group_columns: group_columns(req, description)?, + value_column: value_column(description), + }, + hus::insert_hydra_univmon_sum::<$t>, + hus::insert_step_hydra_univmon_sum::<$t>, + hus::query_hydra_univmon_sum::<$t>, + Some(( + hus::merge_hydra_univmon_sum::<$t>, + hus::merge_step_hydra_univmon_sum::<$t>, + hus::merge_query_hydra_univmon_sum::<$t>, + )), + None, + ) + }; + } + match req.width { + Dtype::I64 => at!(i64), + Dtype::U64 => at!(u64), + other => Err(no_sum_at(req, other)), + } +} + +pub(crate) fn row_hydra_univmon_sum_polars( + req: &Requirement, + description: &TableDescription, + table: GeneratedTable, + want: &[(Operation, Metric)], +) -> Result { + macro_rules! at { + ($t:ty) => { + subpop_vector_row::<$t, _>( + req, + description, + table, + want, + SubpopSumGT { + group_columns: group_columns(req, description)?, + value_column: value_column(description), + }, + hup::insert_polars_subpop_sum::<$t>, + hup::insert_step_polars_subpop_sum::<$t>, + hup::query_polars_subpop_sum::<$t>, + None, + Some(hup::prepare_polars_subpop_sum::<$t>), + ) + }; + } + match req.width { + Dtype::I64 => at!(i64), + Dtype::U64 => at!(u64), + other => Err(no_sum_at(req, other)), + } +} diff --git a/aqpbm-cli/src/rows/mod.rs b/aqpbm-cli/src/rows/mod.rs index 66524a42..f1937bfc 100644 --- a/aqpbm-cli/src/rows/mod.rs +++ b/aqpbm-cli/src/rows/mod.rs @@ -23,8 +23,8 @@ use aqpbm_core::accuracy::keyed::{ }; use aqpbm_core::accuracy::quantile::{RankErrorGT, RelativeValueErrorGT}; use aqpbm_core::accuracy::subpopulation::{ - GroupKey, SubpopCardinalityGT, SubpopEntropyGT, SubpopFrequencyGT, SubpopL1NormGT, - SubpopL2NormGT, SubpopRankErrorGT, + GroupKey, SubpopCardinalityGT, SubpopCdfErrorGT, SubpopEntropyGT, SubpopFrequencyGT, + SubpopL1NormGT, SubpopL2NormGT, SubpopRankErrorGT, SubpopSumGT, }; use aqpbm_core::accuracy::topk::TopkGT; use aqpbm_core::accuracy::Score; @@ -127,6 +127,8 @@ fn binding(variant: &str, library: &str) -> Option { ("hydra-hll", "polars") => row_hydra_hll_polars, ("hydra-kll", "lib") => row_hydra_kll_lib, ("hydra-kll", "polars") => row_hydra_kll_polars, + ("hydra-kll-cdf", "lib") => row_hydra_kll_cdf_lib, + ("hydra-kll-cdf", "polars") => row_hydra_kll_cdf_polars, ("hydra-univmon-cardinality", "lib") => row_hydra_univmon_cardinality_lib, ("hydra-univmon-cardinality", "polars") => row_hydra_univmon_cardinality_polars, ("hydra-univmon-l1-norm", "lib") => row_hydra_univmon_l1_norm_lib, @@ -135,6 +137,8 @@ fn binding(variant: &str, library: &str) -> Option { ("hydra-univmon-l2-norm", "polars") => row_hydra_univmon_l2_norm_polars, ("hydra-univmon-entropy", "lib") => row_hydra_univmon_entropy_lib, ("hydra-univmon-entropy", "polars") => row_hydra_univmon_entropy_polars, + ("hydra-univmon-sum", "lib") => row_hydra_univmon_sum_lib, + ("hydra-univmon-sum", "polars") => row_hydra_univmon_sum_polars, ("univmon-cardinality", "lib") => row_univmon_cardinality_lib, ("univmon-l1-norm", "lib") => row_univmon_l1_norm_lib, ("univmon-l1-norm", "oxide") => row_univmon_l1_norm_oxide, diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 7724a139..232dfff0 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -259,6 +259,38 @@ pub(super) fn subpop_quantile_row( ) } +/// A row answering **subpopulation CDF**: the share of a group at or below a +/// value, scored in absolute CDF error. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] +pub(super) fn subpop_cdf_row( + req: &Requirement, + description: &TableDescription, + table: GeneratedTable, + want: &[(Operation, Metric)], + insert: InsertBody<(String, V)>, + insert_step: InsertStepBody<(String, V)>, + query: QueryBody<(String, V), (GroupKey, f64), f64>, + merge: Option>, + prepare: Option>, +) -> Result { + scored_row( + req, + description, + table, + want, + SubpopCdfErrorGT { + group_columns: group_columns(req, description)?, + value_column: value_column(description), + }, + peel_labeled::, + insert, + insert_step, + query, + merge, + prepare, + ) +} + #[allow(clippy::too_many_arguments)] pub(super) fn keyed_row( req: &Requirement, diff --git a/aqpbm-cli/tests/hydra_grouping.rs b/aqpbm-cli/tests/hydra_grouping.rs index 281ccec5..5050bfb5 100644 --- a/aqpbm-cli/tests/hydra_grouping.rs +++ b/aqpbm-cli/tests/hydra_grouping.rs @@ -74,11 +74,17 @@ fn any_label_subset_is_asked_where_it_was_inserted() { ("hydra-cs", "rows=3 cols=1024 cell_rows=3 cell_cols=256", "i64"), ("hydra-hll", "rows=3 cols=1024", "i64"), ("hydra-kll", "rows=3 cols=1024 cell_k=4096", "f64"), + ("hydra-kll-cdf", "rows=3 cols=1024 cell_k=4096", "f64"), ( "hydra-univmon-l1-norm", "rows=3 cols=1024 cell_heap_size=64 cell_sketch_row=3 cell_sketch_col=256 cell_layer_size=4", "i64", ), + ( + "hydra-univmon-sum", + "rows=3 cols=1024 cell_heap_size=64 cell_sketch_row=3 cell_sketch_col=256 cell_layer_size=4", + "i64", + ), ]; for (variant, config, dtype) in rows { for group_columns in ["1", "0,1"] { @@ -161,3 +167,26 @@ fn per_group_out_without_accuracy_is_refused() { assert!(err.contains("none was asked for"), "{err}"); assert!(!csv.exists(), "no file is left behind"); } + +/// The sum rows count each value by itself, an integer weight: an `f64` +/// value column is refused by name, at both libraries. +#[test] +fn a_float_sum_is_refused_by_name() { + let spec = spec("f64"); + for library in ["lib", "polars"] { + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", "hydra-univmon-sum"]) + .args(["--library", library, "--dtype", "f64"]) + .args(["--spec", spec.to_str().expect("utf-8 path")]) + .args(["--operations", "query", "--metrics", "accuracy"]) + .args(["--runs", "1", "--warmup-runs", "0"]) + .output() + .expect("approxbench runs"); + assert!(!out.status.success(), "{library}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!( + err.contains("f64") && err.contains("integer"), + "{library}: {err}" + ); + } +} diff --git a/aqpbm-core/src/accuracy/subpopulation/cdf_error.rs b/aqpbm-core/src/accuracy/subpopulation/cdf_error.rs new file mode 100644 index 00000000..9c734456 --- /dev/null +++ b/aqpbm-core/src/accuracy/subpopulation/cdf_error.rs @@ -0,0 +1,193 @@ +//! The CDF inside one subpopulation, in absolute CDF error: the inverse of the +//! rank-error question, asked at a value and answered with a fraction. + +use std::collections::BTreeMap; + +use aqpbm_datagen::{DataGenError, GeneratedTable}; + +use super::{group_errors, write_groups, GroupKey, SubpopRankErrorGT, SubpopRankTruth}; +use crate::accuracy::{GroundTruth, GroupError}; + +/// Thresholds probed per group: the group's own values at `phi` = 0.01..=0.99, +/// so every threshold sits inside the group's range whatever its scale. +const CDF_GRID_POINTS: usize = 99; + +/// Ground truth for a grouped CDF sketch: `F_q(x)`, the share of group `q`'s +/// values at or below `x`, scored as `|F̂_q(x) − F_q(x)|`. +pub struct SubpopCdfErrorGT { + /// Which label columns the subpopulation is taken over. + pub group_columns: Vec, + pub value_column: usize, +} + +/// `F(x)` over a sorted group: values at or below `x`, as a share. +fn cdf_at(sorted: &[f64], x: f64) -> f64 { + sorted.partition_point(|v| *v <= x) as f64 / sorted.len() as f64 +} + +impl GroundTruth for SubpopCdfErrorGT { + /// The same sorted values per group the rank-error comparator holds. + type Truth = SubpopRankTruth; + /// One (group, threshold) question. + type Probe = (GroupKey, f64); + type Answer = f64; + + fn truth(&self, table: &GeneratedTable) -> Result { + SubpopRankErrorGT { + group_columns: self.group_columns.clone(), + value_column: self.value_column, + } + .truth(table) + } + + /// The value at index `floor(phi * n)`, the index the exact quantile + /// baseline answers `phi` with. + fn probes(&self, truth: &SubpopRankTruth) -> Vec<(GroupKey, f64)> { + let mut out = Vec::with_capacity(truth.probed.len() * CDF_GRID_POINTS); + for group in &truth.probed { + let Some(sorted) = truth.per_group.get(group).filter(|s| !s.is_empty()) else { + continue; + }; + for i in 1..=CDF_GRID_POINTS { + let phi = i as f64 / 100.0; + let idx = ((phi * sorted.len() as f64).floor() as usize).min(sorted.len() - 1); + out.push((group.clone(), sorted[idx])); + } + } + out + } + + fn score( + &self, + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], + ) -> BTreeMap { + let (groups, max_err) = cdf_errors(truth, probes, answers); + let scored_groups = groups.len(); + let mut metrics: BTreeMap = BTreeMap::new(); + metrics.insert( + "mean_cdf_err".into(), + if scored_groups > 0 { + groups.iter().filter_map(|g| g.error).sum::() / scored_groups as f64 + } else { + 0.0 + }, + ); + metrics.insert("max_cdf_err".into(), max_err); + metrics.insert("grid_points".into(), CDF_GRID_POINTS as f64); + metrics.insert("items".into(), truth.items as f64); + metrics.insert("probes".into(), scored_groups as f64); + metrics.insert("subpopulations".into(), truth.per_group.len() as f64); + metrics.insert("group_columns".into(), self.group_columns.len() as f64); + write_groups( + &groups, + truth.items as u64, + truth.schema_width, + &mut metrics, + ); + metrics + } + + /// A group's error is its mean absolute CDF error over the grid, the + /// number `mean_cdf_err` averages over groups. Every group holds a record, + /// so every group is scored. + fn per_group( + &self, + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], + ) -> Vec { + cdf_errors(truth, probes, answers).0 + } +} + +/// Each group's mean absolute CDF error over its grid, plus the largest error +/// any single probe saw. +fn cdf_errors( + truth: &SubpopRankTruth, + probes: &[(GroupKey, f64)], + answers: &[f64], +) -> (Vec, f64) { + let mut max_err = 0.0f64; + let mut groups = Vec::new(); + // The probe set is one contiguous grid per group, in order. + for (chunk_p, chunk_a) in probes + .chunks(CDF_GRID_POINTS) + .zip(answers.chunks(CDF_GRID_POINTS)) + { + let Some((group, _)) = chunk_p.first() else { + continue; + }; + let Some(sorted) = truth.per_group.get(group) else { + continue; + }; + let mut group_sum = 0.0f64; + for ((_, x), est) in chunk_p.iter().zip(chunk_a) { + let err = (est - cdf_at(sorted, *x)).abs(); + group_sum += err; + max_err = max_err.max(err); + } + groups.push(( + group.clone(), + sorted.len() as u64, + Some(group_sum / CDF_GRID_POINTS as f64), + )); + } + (group_errors(groups.into_iter()), max_err) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::accuracy::subpopulation::records; + + fn over(group_columns: Vec) -> SubpopCdfErrorGT { + SubpopCdfErrorGT { + group_columns, + value_column: 2, + } + } + + /// Answering each threshold with its exact share scores zero, and the + /// thresholds are the group's own values: `a` holds 10, 10, 20, so + /// `F_a(10)` is 2/3 and `F_a(20)` is 1, at or below, ties included. + #[test] + fn the_exact_cdf_scores_zero() { + let gt = over(vec![0]); + let table = records(); + let mut truth = gt.truth(&table).expect("the table has the named columns"); + let probes = gt.probes(&truth); + assert_eq!(probes.len(), 2 * CDF_GRID_POINTS); + let a = vec![Some("a".to_string())]; + let sorted = truth.per_group[&a].clone(); + assert_eq!(cdf_at(&sorted, 10.0), 2.0 / 3.0); + assert_eq!(cdf_at(&sorted, 20.0), 1.0); + let cmp = crate::accuracy::score_with( + >, + &|t: &mut SubpopRankTruth, p: &(GroupKey, f64)| cdf_at(&t.per_group[&p.0], p.1), + &mut truth, + &table, + ); + assert_eq!(cmp["mean_cdf_err"], 0.0); + assert_eq!(cmp["err_max"], 0.0); + assert_eq!(cmp["groups_scored"], 2.0); + } + + /// Answering 0 everywhere misses each threshold by its whole share: over + /// `b`, which holds only 30, every threshold is 30 and `F_b(30)` is 1. + #[test] + fn a_zero_answer_misses_by_the_share() { + let gt = over(vec![0]); + let table = records(); + let truth = gt.truth(&table).expect("the table has the named columns"); + let probes = gt.probes(&truth); + let groups = gt.per_group(&truth, &probes, &vec![0.0; probes.len()]); + let b = groups + .iter() + .find(|g| g.group == "label0:b") + .expect("b is scored"); + assert_eq!(b.error, Some(1.0)); + assert_eq!(b.n_q, 3); + } +} diff --git a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs index 08421ec4..ae4790c6 100644 --- a/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs +++ b/aqpbm-core/src/accuracy/subpopulation/frequency_vector.rs @@ -61,32 +61,39 @@ pub(super) fn truth_over( fold: impl Fn(&[u64]) -> f64, ) -> Result { let counts = counts_per_group(table, group_columns, value_column)?; - let exact: HashMap = counts + let exact = counts.iter().map(|(g, c)| (g.clone(), fold(c))).collect(); + let sizes = counts .iter() - .map(|(group, counts)| (group.clone(), fold(counts))) + .map(|(g, c)| (g.clone(), c.iter().sum())) .collect(); + Ok(truth_of(exact, sizes, table.row_num, value_column)) +} +/// The truth over each group's exact statistic and record count, however the +/// statistic was taken. `schema_width` is the label columns before the value. +pub(super) fn truth_of( + exact: HashMap, + sizes: HashMap, + records: u64, + schema_width: usize, +) -> SubpopVectorTruth { let mut by_statistic: Vec<(GroupKey, f64)> = exact.iter().map(|(g, v)| (g.clone(), *v)).collect(); by_statistic.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); let sized: Vec<(GroupKey, u64)> = by_statistic .iter() - .map(|(g, _)| { - let size = counts.get(g).map(|c| c.iter().sum()).unwrap_or(0); - (g.clone(), size) - }) + .map(|(g, _)| (g.clone(), sizes.get(g).copied().unwrap_or(0))) .collect(); let all = curve::shuffled(&sized); - let sizes = sized.into_iter().collect(); let ranked = by_statistic.into_iter().map(|(g, _)| g).collect(); - Ok(SubpopVectorTruth { + SubpopVectorTruth { exact, ranked, all, sizes, - records: table.row_num, - schema_width: value_column, - }) + records, + schema_width, + } } pub(super) fn probes_over(truth: &SubpopVectorTruth) -> Vec { diff --git a/aqpbm-core/src/accuracy/subpopulation/mod.rs b/aqpbm-core/src/accuracy/subpopulation/mod.rs index 0f92c223..ce788a2f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/mod.rs +++ b/aqpbm-core/src/accuracy/subpopulation/mod.rs @@ -2,20 +2,24 @@ //! subpopulation, one comparator per statistic. mod cardinality; +mod cdf_error; mod entropy; mod frequency; mod frequency_vector; mod l1_norm; mod l2_norm; mod rank_error; +mod sum; pub use cardinality::{SubpopCardTruth, SubpopCardinalityGT}; +pub use cdf_error::SubpopCdfErrorGT; pub use entropy::{entropy, SubpopEntropyGT}; pub use frequency::{SubpopFreqTruth, SubpopFrequencyGT}; pub use frequency_vector::SubpopVectorTruth; pub use l1_norm::{l1_norm, SubpopL1NormGT}; pub use l2_norm::{l2_norm, SubpopL2NormGT}; pub use rank_error::{SubpopRankErrorGT, SubpopRankTruth}; +pub use sum::SubpopSumGT; use std::collections::BTreeMap; diff --git a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs index 01ec1259..5a3d612f 100644 --- a/aqpbm-core/src/accuracy/subpopulation/rank_error.rs +++ b/aqpbm-core/src/accuracy/subpopulation/rank_error.rs @@ -24,12 +24,12 @@ pub struct SubpopRankErrorGT { /// The ordered statistic inside each group, plus the groups worth probing. pub struct SubpopRankTruth { - per_group: HashMap>, + pub(super) per_group: HashMap>, /// Every group, shuffled: probe order must not hand the baseline the /// locality the encounter order would. - probed: Vec, - items: usize, - schema_width: usize, + pub(super) probed: Vec, + pub(super) items: usize, + pub(super) schema_width: usize, } impl GroundTruth for SubpopRankErrorGT { diff --git a/aqpbm-core/src/accuracy/subpopulation/sum.rs b/aqpbm-core/src/accuracy/subpopulation/sum.rs new file mode 100644 index 00000000..4c997eba --- /dev/null +++ b/aqpbm-core/src/accuracy/subpopulation/sum.rs @@ -0,0 +1,182 @@ +//! The sum of the values inside one subpopulation: the weighted L1 norm, each +//! value its own weight. + +use std::collections::BTreeMap; +use std::collections::HashMap; + +use aqpbm_datagen::{ColumnData, DataGenError, GeneratedTable}; + +use super::frequency_vector::{per_group_over, probes_over, score_over, truth_of}; +use super::{group_labels, owned, GroupKey, SubpopVectorTruth}; +use crate::accuracy::{GroundTruth, GroupError}; + +pub struct SubpopSumGT { + /// Which label columns the subpopulation is taken over. + pub group_columns: Vec, + pub value_column: usize, +} + +/// Each group's sum, over its record count. The value is an integer weight, +/// so an `f64` or text value column is refused by its type. +fn sums_per_group( + table: &GeneratedTable, + group_columns: &[usize], + value_column: usize, +) -> Result { + let labels = group_labels(table, group_columns)?; + let values: Vec = match table.column(value_column)? { + ColumnData::Int64(v) => v.iter().map(|&x| x as f64).collect(), + ColumnData::Unsigned64(v) => v.iter().map(|&x| x as f64).collect(), + other => { + return Err(DataGenError::TypeMismatch { + held: other.kind(), + wanted: "an integer value column (i64 or u64), the weights a sum adds", + }) + } + }; + let mut per_group: HashMap, (f64, u64)> = HashMap::new(); + for (group, value) in labels.chunks(group_columns.len()).zip(&values) { + match per_group.get_mut(group) { + Some((sum, n)) => { + *sum += value; + *n += 1; + } + None => { + per_group.insert(group.to_vec(), (*value, 1)); + } + } + } + let (mut sums, mut sizes) = (HashMap::new(), HashMap::new()); + for (group, (sum, n)) in per_group { + let key = owned(&group, group_columns); + sums.insert(key.clone(), sum); + sizes.insert(key, n); + } + Ok(truth_of(sums, sizes, table.row_num, value_column)) +} + +impl GroundTruth for SubpopSumGT { + type Truth = SubpopVectorTruth; + type Probe = GroupKey; + type Answer = f64; + + fn truth(&self, table: &GeneratedTable) -> Result { + sums_per_group(table, &self.group_columns, self.value_column) + } + + fn probes(&self, truth: &SubpopVectorTruth) -> Vec { + probes_over(truth) + } + + fn score( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> BTreeMap { + score_over(truth, probes, answers, self.group_columns.len()) + } + + fn per_group( + &self, + truth: &SubpopVectorTruth, + probes: &[GroupKey], + answers: &[f64], + ) -> Vec { + per_group_over(truth, probes, answers) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::accuracy::subpopulation::{exact_over, null_over, records}; + + fn over(group_columns: Vec) -> SubpopSumGT { + SubpopSumGT { + group_columns, + value_column: 2, + } + } + + /// `a` carries 10, 10 and 20; `b` 30 three times. Its L1 sibling would + /// answer 3 for both, the record count. + #[test] + fn the_sum_of_a_group_adds_its_values() { + let truth = over(vec![0]) + .truth(&records()) + .expect("the table has the named columns"); + assert_eq!(truth.exact[&vec![Some("a".to_string())]], 40.0); + assert_eq!(truth.exact[&vec![Some("b".to_string())]], 90.0); + let probes = over(vec![0]).probes(&truth); + let groups = over(vec![0]).per_group(&truth, &probes, &vec![0.0; probes.len()]); + let sizes: Vec = groups.iter().map(|g| g.n_q).collect(); + assert_eq!(sizes, [3, 3], "n_q is the group's records, not its sum"); + } + + #[test] + fn null_estimator_scores_exactly_one_on_are() { + let cmp = null_over(&over(vec![0]), &records()); + assert!((cmp["are_all"] - 1.0).abs() < 1e-12, "{}", cmp["are_all"]); + } + + #[test] + fn exact_estimator_scores_zero() { + let cmp = exact_over(&over(vec![0, 1]), &records()); + assert_eq!(cmp["are_all"], 0.0); + assert_eq!(cmp["err_max"], 0.0); + } + + /// A group whose values sum to zero has no relative error: it is listed + /// unscored, as a group with no distinct value is for cardinality. + #[test] + fn a_zero_sum_group_is_listed_unscored() { + use crate::accuracy::table_of; + let table = table_of( + &["key1", "value"], + vec![ + ColumnData::String(vec!["a".into(), "b".into(), "b".into()]), + ColumnData::Int64(vec![4, 0, 0]), + ], + ); + let gt = SubpopSumGT { + group_columns: vec![0], + value_column: 1, + }; + let truth = gt.truth(&table).expect("the table has the named columns"); + let probes = gt.probes(&truth); + let rows: Vec<(String, u64, Option)> = gt + .per_group(&truth, &probes, &vec![0.0; probes.len()]) + .into_iter() + .map(|g| (g.group, g.n_q, g.error)) + .collect(); + assert_eq!( + rows, + vec![ + ("label0:b".to_string(), 2, None), + ("label0:a".to_string(), 1, Some(1.0)), + ] + ); + } + + #[test] + fn a_float_value_column_is_refused_by_its_type() { + use crate::accuracy::table_of; + let table = table_of( + &["key1", "value"], + vec![ + ColumnData::String(vec!["a".into()]), + ColumnData::Float64(vec![1.5]), + ], + ); + let gt = SubpopSumGT { + group_columns: vec![0], + value_column: 1, + }; + let Err(err) = gt.truth(&table).map(|_| ()) else { + panic!("an f64 value column must be refused, not summed"); + }; + let err = err.to_string(); + assert!(err.contains("f64") && err.contains("integer"), "{err}"); + } +} diff --git a/configs/datagen/hydra_columns_f64.yaml b/configs/datagen/hydra_columns_f64.yaml index 15b54921..3e738c25 100644 --- a/configs/datagen/hydra_columns_f64.yaml +++ b/configs/datagen/hydra_columns_f64.yaml @@ -1,6 +1,6 @@ -# `hydra_columns.yaml` with an `f64` value column, for the record-ingesting row -# whose item is a float: `hydra-kll`, which orders its values rather than -# counting them. +# `hydra_columns.yaml` with an `f64` value column, for the record-ingesting rows +# whose item is a float: `hydra-kll` and `hydra-kll-cdf`, which order their +# values rather than count them. # # approxbench sketchbench --variant hydra-kll --library lib \ # --spec configs/datagen/hydra_columns_f64.yaml \ diff --git a/configs/datagen/hydra_univmon_columns.yaml b/configs/datagen/hydra_univmon_columns.yaml index adad591e..19eb3160 100644 --- a/configs/datagen/hydra_univmon_columns.yaml +++ b/configs/datagen/hydra_univmon_columns.yaml @@ -1,5 +1,5 @@ # `hydra_columns.yaml` at a row count the UnivMon-celled rows can run: -# `hydra-univmon-cardinality`, `-l1-norm`, `-l2-norm` and `-entropy`. The label +# `hydra-univmon-cardinality`, `-l1-norm`, `-l2-norm`, `-entropy` and `-sum`. The label # columns and every distribution parameter match that file exactly, so the # workload is the same shape read at a smaller size. # diff --git a/docs/concepts.md b/docs/concepts.md index 0c5d31cd..e864c618 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -58,9 +58,11 @@ heavy-hitter heavy items and how heavy subpop-cardinality cardinality, within the records carrying a set of labels subpop-frequency frequency, within the records carrying a set of labels subpop-quantile quantile, within the records carrying a set of labels +subpop-cdf share at or below a value, within the records carrying a set of labels subpop-l1-norm L1-norm of values, within the records carrying a set of labels subpop-l2-norm L2-norm of values, within the records carrying a set of labels subpop-entropy entropy of values, within the records carrying a set of labels +subpop-sum sum of values, within the records carrying a set of labels keyed-cardinality how many distinct items for a specific key keyed-entropy entropy of values for a specific key keyed-l1-norm L1-norm of values for a specific key diff --git a/sketch-bench/src/registry.rs b/sketch-bench/src/registry.rs index 05bcf08a..527e8cc0 100644 --- a/sketch-bench/src/registry.rs +++ b/sketch-bench/src/registry.rs @@ -678,6 +678,38 @@ pub const REGISTRY: &[SketchId] = &[ .union(MetricsMask::MEMORY) .union(MetricsMask::ACCURACY), }, + SketchId { + algorithm: "hydra-kll", + variant: "hydra-kll-cdf", + library: "lib", + description: "asap_sketchlib::Hydra over KLL cells: Cdf(x) per subpopulation", + capability: Capability::SubpopCdf, + comparator: Some("subpop-cdf-error"), + operations: OperationMask::INSERT + .union(OperationMask::QUERY) + .union(OperationMask::MERGE), + metrics: MetricsMask::THROUGHPUT + .union(MetricsMask::LATENCY) + .union(MetricsMask::CPU) + .union(MetricsMask::MEMORY) + .union(MetricsMask::ACCURACY), + }, + SketchId { + algorithm: "hydra-kll", + variant: "hydra-kll-cdf", + library: "polars", + description: "polars exact: sorted values per label subset, share at or below x", + capability: Capability::SubpopCdf, + comparator: Some("subpop-cdf-error"), + operations: OperationMask::INSERT + .union(OperationMask::QUERY) + .union(OperationMask::PREPARE), + metrics: MetricsMask::THROUGHPUT + .union(MetricsMask::LATENCY) + .union(MetricsMask::CPU) + .union(MetricsMask::MEMORY) + .union(MetricsMask::ACCURACY), + }, SketchId { algorithm: "hydra-univmon", variant: "hydra-univmon-cardinality", @@ -806,6 +838,38 @@ pub const REGISTRY: &[SketchId] = &[ .union(MetricsMask::MEMORY) .union(MetricsMask::ACCURACY), }, + SketchId { + algorithm: "hydra-univmon", + variant: "hydra-univmon-sum", + library: "lib", + description: "asap_sketchlib::Hydra over UnivMon cells, each value inserted with itself as count: calc_l1 per subpopulation", + capability: Capability::SubpopSum, + comparator: Some("subpop-sum"), + operations: OperationMask::INSERT + .union(OperationMask::QUERY) + .union(OperationMask::MERGE), + metrics: MetricsMask::THROUGHPUT + .union(MetricsMask::LATENCY) + .union(MetricsMask::CPU) + .union(MetricsMask::MEMORY) + .union(MetricsMask::ACCURACY), + }, + SketchId { + algorithm: "hydra-univmon", + variant: "hydra-univmon-sum", + library: "polars", + description: "polars exact: group_by(subset).agg(v.sum()) over every label subset", + capability: Capability::SubpopSum, + comparator: Some("subpop-sum"), + operations: OperationMask::INSERT + .union(OperationMask::QUERY) + .union(OperationMask::PREPARE), + metrics: MetricsMask::THROUGHPUT + .union(MetricsMask::LATENCY) + .union(MetricsMask::CPU) + .union(MetricsMask::MEMORY) + .union(MetricsMask::ACCURACY), + }, SketchId { algorithm: "univmon", variant: "univmon-cardinality", @@ -1360,9 +1424,11 @@ mod tests { "subpop-cardinality", "subpop-frequency", "subpop-rank-error", + "subpop-cdf-error", "subpop-l1-norm", "subpop-l2-norm", "subpop-entropy", + "subpop-sum", "keyed-cardinality", "keyed-l1-norm", "keyed-l2-norm", diff --git a/sketch-bench/src/request.rs b/sketch-bench/src/request.rs index 421990a7..478bfc1f 100644 --- a/sketch-bench/src/request.rs +++ b/sketch-bench/src/request.rs @@ -16,9 +16,11 @@ pub enum Capability { SubpopCardinality, SubpopFrequency, SubpopQuantile, + SubpopCdf, SubpopL1Norm, SubpopL2Norm, SubpopEntropy, + SubpopSum, KeyedCardinality, KeyedL1Norm, KeyedL2Norm, @@ -44,9 +46,11 @@ impl Capability { Capability::SubpopCardinality => "subpop-cardinality", Capability::SubpopFrequency => "subpop-frequency", Capability::SubpopQuantile => "subpop-quantile", + Capability::SubpopCdf => "subpop-cdf", Capability::SubpopL1Norm => "subpop-l1-norm", Capability::SubpopL2Norm => "subpop-l2-norm", Capability::SubpopEntropy => "subpop-entropy", + Capability::SubpopSum => "subpop-sum", Capability::KeyedCardinality => "keyed-cardinality", Capability::KeyedL1Norm => "keyed-l1-norm", Capability::KeyedL2Norm => "keyed-l2-norm", diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index de6f74f6..35f07656 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -11,9 +11,11 @@ pub(crate) use super::hydra_shared::{ check_grid, grid_overhead_bytes, label_columns, labels, new_hydra, query, update, }; -pub(crate) use crate::wrappers::kll::{kll_lib_slots as kll_cell_slots, KLL_LIB_MAX_LEVELS}; +pub(crate) use crate::wrappers::kll::kll_lib_bytes as kll_cell_bytes; #[cfg(test)] -use crate::wrappers::kll::{KLL_LIB_MAX_CACHEABLE_K, KLL_LIB_MIN_LEVEL}; +use crate::wrappers::kll::{ + kll_lib_slots as kll_cell_slots, KLL_LIB_MAX_CACHEABLE_K, KLL_LIB_MAX_LEVELS, KLL_LIB_MIN_LEVEL, +}; #[cfg(test)] mod tests { @@ -103,6 +105,34 @@ mod tests { ); } + /// A cell is a whole `KLL`, merge buffer included, as the `kll-*` lib rows + /// count it. Hand-derived: at `k = 200`, 1004 retained slots (above) plus + /// 200 buffer items, 8 bytes each, plus 62 level offsets. + #[test] + fn kll_footprint_counts_each_cells_merge_buffer() { + let per_cell = (1004 + 200) * 8 + 62 * std::mem::size_of::(); + assert_eq!( + memory_hydra_kll(&built_kll()), + 3 * 64 * per_cell + grid_overhead_bytes(3, 64) + ); + } + + /// Below `k` the cell keeps every value, so `Cdf(x)` is the exact share at + /// or below `x`, inside the group only. + #[test] + fn kll_cdf_is_the_share_at_or_below_inside_the_group() { + let mut h = built_kll(); + for v in 1..=100 { + fed_kll(&mut h, &frecord("a;x", v as f64)); + } + for _ in 0..300 { + fed_kll(&mut h, &frecord("b;x", 0.5)); + } + assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 25.0), 0.25); + assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 100.0), 1.0); + assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 0.9), 0.0); + } + #[test] fn kll_zero_cell_k_is_refused_by_name() { let bad = ParamSet::of(&HydraKllParams { @@ -119,3 +149,30 @@ mod tests { ); } } + +#[cfg(test)] +mod baseline_tests { + use super::polars::*; + use crate::params::{ParamSet, SketchParams}; + use crate::wrappers::hydra_kll::HydraKllParams; + use std::rc::Rc; + + /// `a` holds 10, 10, 20: `F_a(10)` counts both tens, `F_a(15)` too, and + /// `F_a(5)` nothing. A group never seen answers NaN, not a share. + #[test] + fn the_cdf_baseline_answers_the_share_at_or_below() { + let stream = Rc::new(vec![ + ("a;x".to_string(), 10.0), + ("a;y".to_string(), 10.0), + ("a;x".to_string(), 20.0), + ("b;x".to_string(), 30.0), + ]); + let a = || vec![Some("a".to_string())]; + let probes = Rc::new(vec![(a(), 10.0), (a(), 15.0), (a(), 5.0), (a(), 20.0)]); + let params = ParamSet::of(&HydraKllParams::canonical()); + let mut passes = + query_polars_subpop_cdf::(¶ms, stream, probes, 1).expect("baseline builds"); + let answers = passes.pop().expect("one pass")().0; + assert_eq!(answers, vec![2.0 / 3.0, 2.0 / 3.0, 0.0, 1.0]); + } +} diff --git a/sketch-bench/src/wrappers/hydra_kll/polars.rs b/sketch-bench/src/wrappers/hydra_kll/polars.rs index 11a6a268..57094c5b 100644 --- a/sketch-bench/src/wrappers/hydra_kll/polars.rs +++ b/sketch-bench/src/wrappers/hydra_kll/polars.rs @@ -56,6 +56,18 @@ impl PolarsSubpopQuantile { let idx = ((phi * values.len() as f64).floor() as usize).min(values.len() - 1); values[idx] } + + /// The share of the group at or below `x`: exact, so the CDF-error + /// comparator scores it zero. + pub fn estimate_subpop_cdf(&self, labels: &[Option<&str>], x: f64) -> f64 { + let Some(values) = self.sorted.get(&group_key(labels)) else { + return f64::NAN; + }; + if values.is_empty() { + return f64::NAN; + } + values.partition_point(|v| *v <= x) as f64 / values.len() as f64 + } } pub fn memory_polars_subpop_quantile( @@ -159,6 +171,38 @@ pub fn query_polars_subpop_quantile>, probes: Rc>, f64)>>, passes: usize, +) -> Result>, BuildError> { + asked_polars_subpop( + params, + items, + probes, + passes, + PolarsSubpopQuantile::estimate_subpop_quantile, + ) +} + +/// The `hydra-kll-cdf` baseline: the same sorted groups, asked at a value. +pub fn query_polars_subpop_cdf( + params: &ParamSet, + items: Rc>, + probes: Rc>, f64)>>, + passes: usize, +) -> Result>, BuildError> { + asked_polars_subpop( + params, + items, + probes, + passes, + PolarsSubpopQuantile::estimate_subpop_cdf, + ) +} + +fn asked_polars_subpop( + params: &ParamSet, + items: Rc>, + probes: Rc>, f64)>>, + passes: usize, + estimate: fn(&PolarsSubpopQuantile, &[Option<&str>], f64) -> f64, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -172,7 +216,7 @@ pub fn query_polars_subpop_quantile], phi: f64) -> f64 { query(&self.inner, labels, &HydraQuery::Quantile(phi), "hydra-kll") } + + /// `HydraQuery::Cdf`: the share of the group at or below `x`, the question + /// the `hydra-kll-cdf` row asks. + #[inline] + pub fn estimate_subpop_cdf(&self, labels: &[Option<&str>], x: f64) -> f64 { + query(&self.inner, labels, &HydraQuery::Cdf(x), "hydra-kll") + } } -/// Retained slots per cell times the grid area, plus the level index every -/// cell carries. Analytic because the cell allocates once — see -/// `kll_lib_slots` in this crate's `kll` module for the per-cell count. Unlike -/// the `kll-percall` lib rows (`kll_lib_bytes`), each cell's merge buffer of -/// `cell_k` items is not counted. +/// One `asap_sketchlib::KLL` per cell times the grid area: its retained +/// slots, level index and merge buffer of `cell_k` items, as the `kll-*` lib +/// rows count them (`kll_lib_bytes`). Analytic because the cell allocates once. pub fn memory_hydra_kll(sketch: &HydraKll) -> usize { let p = &sketch.params; - let per_cell = kll_cell_slots(p.cell_k) * std::mem::size_of::() - + (KLL_LIB_MAX_LEVELS + 1) * std::mem::size_of::(); - p.rows * p.cols * per_cell + grid_overhead_bytes(p.rows, p.cols) + p.rows * p.cols * kll_cell_bytes::(p.cell_k) + grid_overhead_bytes(p.rows, p.cols) } pub fn insert_hydra_kll( @@ -126,6 +129,52 @@ pub fn merge_query_hydra_kll( probes: Rc>, f64)>>, shards: usize, passes: usize, +) -> Result>, BuildError> { + asked_hydra_kll( + params, + items, + probes, + shards, + passes, + HydraKll::estimate_subpop_quantile, + ) +} + +pub fn query_hydra_kll_cdf( + params: &ParamSet, + items: Rc>, + probes: Rc>, f64)>>, + passes: usize, +) -> Result>, BuildError> { + merge_query_hydra_kll_cdf(params, items, probes, 1, passes) +} + +/// The query, asked of the sketch a fold over `shards` shards leaves. One +/// shard is the plain query. +pub fn merge_query_hydra_kll_cdf( + params: &ParamSet, + items: Rc>, + probes: Rc>, f64)>>, + shards: usize, + passes: usize, +) -> Result>, BuildError> { + asked_hydra_kll( + params, + items, + probes, + shards, + passes, + HydraKll::estimate_subpop_cdf, + ) +} + +fn asked_hydra_kll( + params: &ParamSet, + items: Rc>, + probes: Rc>, f64)>>, + shards: usize, + passes: usize, + estimate: fn(&HydraKll, &[Option<&str>], f64) -> f64, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -141,7 +190,7 @@ pub fn merge_query_hydra_kll( out.push(Box::new(move || { let mut answers = Vec::with_capacity(probes.len()); for p in probes.iter() { - answers.push(sketch.estimate_subpop_quantile(&labels(&p.0), p.1)); + answers.push(estimate(&sketch, &labels(&p.0), p.1)); } let footprint = memory_hydra_kll(&sketch); (answers, footprint) diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 1af9d7ef..5f1c3d47 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -44,8 +44,20 @@ pub(crate) fn new_hydra( /// Records one `;`-joined record, one value per key column in place. The /// build already refused a stream of mixed widths; this is the backstop. pub(crate) fn update(h: &mut Hydra, key: &str, value: &DataInput, variant: &str) { + update_counted(h, key, value, None, variant) +} + +/// [`update`], the value counted `count` times in each cell it reaches +/// (`None` is once): the library's integer weight. +pub(crate) fn update_counted( + h: &mut Hydra, + key: &str, + value: &DataInput, + count: Option, + variant: &str, +) { let parts: Vec<&str> = key.split(';').collect(); - if let Err(e) = h.update(&parts, value, None) { + if let Err(e) = h.update(&parts, value, count) { panic!( "{variant}: record {key:?} has {} label(s), the grid {}: {e}", parts.len(), diff --git a/sketch-bench/src/wrappers/hydra_univmon/mod.rs b/sketch-bench/src/wrappers/hydra_univmon/mod.rs index ab6073c8..8ff87bc2 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/mod.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/mod.rs @@ -123,6 +123,52 @@ mod tests { ); } + /// Each record counted by its own value makes the group's L1 its sum. At + /// a grid far wider than the four subkeys, every cell holds one group. + #[test] + fn weighted_l1_of_a_group_is_its_sum() { + let params = ParamSet::of(&HydraUnivmonParams { + rows: 3, + cols: 1024, + cell_heap_size: 32, + cell_sketch_row: 5, + cell_sketch_col: 256, + cell_layer_size: 4, + }); + let stream = std::rc::Rc::new(vec![ + record("a;x", 10), + record("a;y", 10), + record("a;x", 25), + record("b;x", 7), + ]); + let probes = std::rc::Rc::new(vec![ + vec![Some("a".to_string())], + vec![Some("b".to_string())], + vec![None, Some("x".to_string())], + ]); + let mut passes = query_hydra_univmon_sum(¶ms, stream, probes, 1).expect("builds"); + let answers = passes.pop().expect("one pass")().0; + assert_eq!(answers, vec![45.0, 7.0, 42.0]); + } + + /// The library's weight is an `i32` count: a value it cannot carry is + /// refused by name, not truncated into a different sum. + #[test] + fn a_value_past_an_i32_count_is_refused_by_name() { + let params = ParamSet::of(&HydraUnivmonParams::canonical()); + for bad in [i64::from(i32::MAX) + 1, -1] { + let stream = std::rc::Rc::new(vec![record("a;x", 1), record("a;x", bad)]); + let Err(err) = insert_hydra_univmon_sum(¶ms, stream, 1) else { + panic!("{bad} must be refused, not inserted"); + }; + let err = err.to_string(); + assert!( + err.contains("hydra-univmon-sum") && err.contains(&bad.to_string()), + "{err}" + ); + } + } + #[test] fn zero_dimensions_are_refused_by_name() { let bad = ParamSet::of(&HydraUnivmonParams { @@ -198,6 +244,15 @@ mod baseline_tests { ); } + /// `a` holds 10, 10, 20; its L1 sibling answers 3 for it. + #[test] + fn the_sum_baseline_answers_the_group_sum() { + assert_eq!( + answers_for(query_polars_subpop_sum::), + vec![40.0, 30.0] + ); + } + #[test] fn the_cardinality_baseline_answers_distinct_values() { assert_eq!( diff --git a/sketch-bench/src/wrappers/hydra_univmon/polars.rs b/sketch-bench/src/wrappers/hydra_univmon/polars.rs index 0e9dd152..a4f32f46 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/polars.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/polars.rs @@ -8,8 +8,10 @@ use crate::params::ParamSet; use crate::wrappers::hll::CardinalityValue; use crate::wrappers::polars_shared::*; use crate::wrappers::{BuildError, Pass, QueryPass, Shared, StepPass}; +use ::polars::prelude::*; use aqpbm_core::accuracy::subpopulation::{entropy, l1_norm, l2_norm}; use std::cell::RefCell; +use std::collections::HashMap; use std::rc::Rc; pub struct PolarsSubpopUnivmon(PolarsSubpopVectorCore); @@ -353,3 +355,145 @@ pub fn prepare_polars_subpop_entropy( ) -> Result, BuildError> { prepare_polars_subpop_vector(params, items, passes, entropy) } + +/// `hydra-univmon-sum/polars` — the exact sum of each label subset's values. +pub struct PolarsSubpopSum { + buf: Vec<(String, T)>, + exact: HashMap, +} + +// Hand-written rather than derived, for the reason the cardinality baseline's is. +impl Default for PolarsSubpopSum { + fn default() -> Self { + Self { + buf: Vec::new(), + exact: HashMap::new(), + } + } +} + +pub fn build_polars_subpop_sum( + config: &ParamSet, +) -> Result, BuildError> { + // Parsed and discarded, as the other baselines here do. + let _p: HydraUnivmonParams = config.parse()?; + Ok(PolarsSubpopSum::default()) +} + +impl PolarsSubpopSum { + /// The exact answer, over the stream as buffered. Its own step because the + /// runner times it as `prepare`: this row's cost is the pass, not the ask. + fn finalize(&mut self) { + let Some(result) = grouped_values(&self.buf, |lazy| { + lazy.group_by([col("g")]).agg([col("v").sum().alias("sum")]) + }) else { + return; + }; + let groups = result.column("g").expect("g column"); + let groups = groups.str().expect("str groups"); + let sums = result + .column("sum") + .expect("sum column") + .cast(&DataType::Float64) + .expect("cast to f64"); + let sums = sums.f64().expect("f64 sums"); + self.exact = groups + .into_iter() + .zip(sums) + .filter_map(|(g, s)| Some((g?.to_string(), s?))) + .collect(); + } + + pub fn estimate_subpop_sum(&self, labels: &[Option<&str>]) -> f64 { + self.exact.get(&group_key(labels)).copied().unwrap_or(0.0) + } +} + +pub fn memory_polars_subpop_sum(sketch: &PolarsSubpopSum) -> usize { + let held: usize = sketch.buf.iter().map(|(g, _)| g.capacity()).sum(); + sketch.buf.capacity() * std::mem::size_of::<(String, T)>() + + held + + sketch.exact.capacity() * (std::mem::size_of::() + std::mem::size_of::()) +} + +pub fn insert_polars_subpop_sum( + params: &ParamSet, + items: Rc>, + passes: usize, +) -> Result, BuildError> { + let mut out = Vec::with_capacity(passes); + for _ in 0..passes { + // Built here, so calling the closure is the insert and nothing else. + let mut sketch = build_polars_subpop_sum::(params)?; + let items = items.clone(); + out.push(Box::new(move || { + for v in items.iter() { + sketch.buf.push(v.clone()); + } + memory_polars_subpop_sum(&sketch) + }) as Pass); + } + Ok(out) +} + +pub fn insert_step_polars_subpop_sum( + params: &ParamSet, + items: Rc>, + passes: usize, +) -> Result, BuildError> { + let mut out = Vec::with_capacity(passes); + for _ in 0..passes { + let sketch: Shared<_> = Rc::new(RefCell::new(build_polars_subpop_sum::(params)?)); + let (driven, read) = (sketch.clone(), sketch); + let stream = items.clone(); + out.push(StepPass { + steps: items.len(), + step: Box::new(move |i| driven.borrow_mut().buf.push(stream[i].clone())), + footprint: Box::new(move || memory_polars_subpop_sum(&read.borrow())), + }); + } + Ok(out) +} + +pub fn query_polars_subpop_sum( + params: &ParamSet, + items: Rc>, + probes: Rc>>>, + passes: usize, +) -> Result>, BuildError> { + let mut out = Vec::with_capacity(passes); + for _ in 0..passes { + // Built and fed here: the closure below asks, and only asks. + let mut sketch = build_polars_subpop_sum::(params)?; + sketch.buf.extend(items.iter().cloned()); + sketch.finalize(); + let probes = probes.clone(); + out.push(Box::new(move || { + let mut answers = Vec::with_capacity(probes.len()); + for p in probes.iter() { + answers.push(sketch.estimate_subpop_sum(&labels(p))); + } + let footprint = memory_polars_subpop_sum(&sketch); + (answers, footprint) + }) as QueryPass); + } + Ok(out) +} + +pub fn prepare_polars_subpop_sum( + params: &ParamSet, + items: Rc>, + passes: usize, +) -> Result, BuildError> { + let mut out = Vec::with_capacity(passes); + for _ in 0..passes { + // Fed here: the closure below is the step that makes it ready to answer. + let mut sketch = build_polars_subpop_sum::(params)?; + sketch.buf.extend(items.iter().cloned()); + out.push(Box::new(move || { + sketch.finalize(); + memory_polars_subpop_sum(&sketch) + }) as Pass); + } + Ok(out) +} diff --git a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs index e7465088..d9760048 100644 --- a/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_univmon/sketchlib.rs @@ -6,6 +6,7 @@ use super::*; use crate::params::ParamSet; use crate::wrappers::hll::CardinalityValue; +use crate::wrappers::hydra_shared::update_counted; use crate::wrappers::partition; use crate::wrappers::{BuildError, Pass, QueryPass, Shared, StepPass}; use asap_sketchlib::input::{HHItem, HydraCounter, HydraQuery}; @@ -82,10 +83,80 @@ pub fn memory_hydra_univmon(sketch: &HydraUnivmon) -> usize { p.rows * p.cols * p.cell_layer_size * (counters + heap) + grid_overhead_bytes(p.rows, p.cols) } +/// A value the `-sum` row inserts as its own count, the library's integer +/// weight: `None` for one an `i32` weight cannot carry, or a negative one. +pub trait WeightValue: CardinalityValue { + fn weight(&self) -> Option; +} + +impl WeightValue for i64 { + fn weight(&self) -> Option { + i32::try_from(*self).ok().filter(|w| *w >= 0) + } +} + +impl WeightValue for u64 { + fn weight(&self) -> Option { + i32::try_from(*self).ok() + } +} + +/// How one record enters the grid: its value as the key, counted once +/// ([`counted`]) or counted by itself ([`weighted`]). +type Feed = fn(&mut HydraUnivmon, &(String, V)); + +fn counted(sketch: &mut HydraUnivmon, r: &(String, V)) { + update(&mut sketch.inner, &r.0, &r.1.data_input(), "hydra-univmon"); +} + +/// Weighted L1 is the group's sum. Every weight was checked by [`weights`] +/// before the grid was built. +fn weighted(sketch: &mut HydraUnivmon, r: &(String, V)) { + let count = r.1.weight().expect("weights() checked every value"); + update_counted( + &mut sketch.inner, + &r.0, + &r.1.data_input(), + Some(count), + "hydra-univmon-sum", + ); +} + +/// Refuses a stream with a value [`WeightValue::weight`] cannot carry, naming +/// it, so no sum is built over a truncated weight. +fn weights(items: &[(String, V)]) -> Result<(), BuildError> { + match items.iter().find(|r| r.1.weight().is_none()) { + Some(r) => Err(BuildError(format!( + "hydra-univmon-sum: value {:?} is not a count in [0, {}], the library's i32 weight", + r.1, + i32::MAX + ))), + None => Ok(()), + } +} + pub fn insert_hydra_univmon( params: &ParamSet, items: Rc>, passes: usize, +) -> Result, BuildError> { + inserted(params, items, passes, counted::) +} + +pub fn insert_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + passes: usize, +) -> Result, BuildError> { + weights(&items)?; + inserted(params, items, passes, weighted::) +} + +fn inserted( + params: &ParamSet, + items: Rc>, + passes: usize, + feed: Feed, ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -94,7 +165,7 @@ pub fn insert_hydra_univmon( let items = items.clone(); out.push(Box::new(move || { for v in items.iter() { - update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); + feed(&mut sketch, v); } memory_hydra_univmon(&sketch) }) as Pass); @@ -106,6 +177,24 @@ pub fn insert_step_hydra_univmon( params: &ParamSet, items: Rc>, passes: usize, +) -> Result, BuildError> { + inserted_step(params, items, passes, counted::) +} + +pub fn insert_step_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + passes: usize, +) -> Result, BuildError> { + weights(&items)?; + inserted_step(params, items, passes, weighted::) +} + +fn inserted_step( + params: &ParamSet, + items: Rc>, + passes: usize, + feed: Feed, ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { @@ -118,9 +207,7 @@ pub fn insert_step_hydra_univmon( out.push(StepPass { steps: items.len(), step: Box::new(move |i| { - let sketch = &mut *driven.borrow_mut(); - let v = &stream[i]; - update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); + feed(&mut driven.borrow_mut(), &stream[i]); }), footprint: Box::new(move || memory_hydra_univmon(&read.borrow())), }); @@ -134,12 +221,13 @@ fn asked_hydra_univmon( probes: Rc>>>, shards: usize, passes: usize, + feed: Feed, estimate: fn(&HydraUnivmon, &[Option<&str>]) -> f64, ) -> Result>, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { // Built, fed and folded here: the closure below asks, and only asks. - let (mut sketch, rest) = hydra_univmon_shards(params, &items, shards)?; + let (mut sketch, rest) = hydra_univmon_shards(params, &items, shards, feed)?; for other in rest.iter() { sketch .inner @@ -171,6 +259,7 @@ pub fn query_hydra_univmon_cardinality( probes, 1, passes, + counted::, HydraUnivmon::estimate_subpop_cardinality, ) } @@ -190,6 +279,7 @@ pub fn merge_query_hydra_univmon_cardinality( probes, shards, passes, + counted::, HydraUnivmon::estimate_subpop_cardinality, ) } @@ -206,6 +296,7 @@ pub fn query_hydra_univmon_l1_norm( probes, 1, passes, + counted::, HydraUnivmon::estimate_subpop_l1_norm, ) } @@ -225,6 +316,7 @@ pub fn merge_query_hydra_univmon_l1_norm( probes, shards, passes, + counted::, HydraUnivmon::estimate_subpop_l1_norm, ) } @@ -241,6 +333,7 @@ pub fn query_hydra_univmon_l2_norm( probes, 1, passes, + counted::, HydraUnivmon::estimate_subpop_l2_norm, ) } @@ -260,6 +353,7 @@ pub fn merge_query_hydra_univmon_l2_norm( probes, shards, passes, + counted::, HydraUnivmon::estimate_subpop_l2_norm, ) } @@ -276,6 +370,7 @@ pub fn query_hydra_univmon_entropy( probes, 1, passes, + counted::, HydraUnivmon::estimate_subpop_entropy, ) } @@ -295,19 +390,72 @@ pub fn merge_query_hydra_univmon_entropy( probes, shards, passes, + counted::, HydraUnivmon::estimate_subpop_entropy, ) } +/// The group's sum: the L1 norm of a grid whose records were each counted by +/// their own value. +pub fn query_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + probes: Rc>>>, + passes: usize, +) -> Result>, BuildError> { + merge_query_hydra_univmon_sum(params, items, probes, 1, passes) +} + +/// The query, asked of the sketch a fold over `shards` shards leaves. One +/// shard is the plain query. +pub fn merge_query_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + probes: Rc>>>, + shards: usize, + passes: usize, +) -> Result>, BuildError> { + weights(&items)?; + asked_hydra_univmon( + params, + items, + probes, + shards, + passes, + weighted::, + HydraUnivmon::estimate_subpop_l1_norm, + ) +} + pub fn merge_hydra_univmon( params: &ParamSet, items: Rc>, shards: usize, passes: usize, +) -> Result, BuildError> { + merged(params, items, shards, passes, counted::) +} + +pub fn merge_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + shards: usize, + passes: usize, +) -> Result, BuildError> { + weights(&items)?; + merged(params, items, shards, passes, weighted::) +} + +fn merged( + params: &ParamSet, + items: Rc>, + shards: usize, + passes: usize, + feed: Feed, ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let (mut acc, rest) = hydra_univmon_shards(params, &items, shards)?; + let (mut acc, rest) = hydra_univmon_shards(params, &items, shards, feed)?; out.push(Box::new(move || { for other in rest.iter() { acc.inner @@ -325,10 +473,30 @@ pub fn merge_step_hydra_univmon( items: Rc>, shards: usize, passes: usize, +) -> Result, BuildError> { + merged_step(params, items, shards, passes, counted::) +} + +pub fn merge_step_hydra_univmon_sum( + params: &ParamSet, + items: Rc>, + shards: usize, + passes: usize, +) -> Result, BuildError> { + weights(&items)?; + merged_step(params, items, shards, passes, weighted::) +} + +fn merged_step( + params: &ParamSet, + items: Rc>, + shards: usize, + passes: usize, + feed: Feed, ) -> Result, BuildError> { let mut out = Vec::with_capacity(passes); for _ in 0..passes { - let (acc, rest) = hydra_univmon_shards(params, &items, shards)?; + let (acc, rest) = hydra_univmon_shards(params, &items, shards, feed)?; let acc: Shared<_> = Rc::new(RefCell::new(acc)); let (driven, read) = (acc.clone(), acc); out.push(StepPass { @@ -353,12 +521,13 @@ fn hydra_univmon_shards( params: &ParamSet, items: &[(String, V)], shards: usize, + feed: Feed, ) -> Result<(HydraUnivmon, Vec), BuildError> { let mut parts: Vec = Vec::new(); for shard in partition(items, shards) { let mut sketch = build_hydra_univmon(params, label_columns(items, "hydra-univmon")?)?; for v in shard { - update(&mut sketch.inner, &v.0, &v.1.data_input(), "hydra-univmon"); + feed(&mut sketch, v); } parts.push(sketch); } diff --git a/sketch-bench/src/wrappers/kll/mod.rs b/sketch-bench/src/wrappers/kll/mod.rs index 92521c08..00e2d9b0 100644 --- a/sketch-bench/src/wrappers/kll/mod.rs +++ b/sketch-bench/src/wrappers/kll/mod.rs @@ -65,8 +65,9 @@ pub(crate) fn kll_lib_slots(k: u32) -> usize { /// and the merge buffer's capacity of `k` items. Independent of the item count, /// so a window's sketch costs the same however many values it sees. The /// sketch's own allocation only: the cdf row's prepared CDF table, built for -/// queries, is not counted (nor is the oxide cdf row's). -fn kll_lib_bytes(k: u32) -> usize { +/// queries, is not counted (nor is the oxide cdf row's). Each `hydra-kll` +/// cell is one of these. +pub(crate) fn kll_lib_bytes(k: u32) -> usize { kll_lib_slots(k) * std::mem::size_of::() + (KLL_LIB_MAX_LEVELS + 1) * std::mem::size_of::() + kll_lib_k(k) * std::mem::size_of::() diff --git a/sketch-bench/src/wrappers/polars_shared.rs b/sketch-bench/src/wrappers/polars_shared.rs index 7e9e3c52..7cc7f02b 100644 --- a/sketch-bench/src/wrappers/polars_shared.rs +++ b/sketch-bench/src/wrappers/polars_shared.rs @@ -519,7 +519,7 @@ impl PolarsSubpopVectorCore { } } -fn grouped_values( +pub(crate) fn grouped_values( buf: &[(String, T)], aggregate: impl Fn(LazyFrame) -> LazyFrame, ) -> Option { From 52f889c6d48b7e95f0b16a25ab55c3c6e1b17eaf Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 05:04:20 +0000 Subject: [PATCH 4/5] hydra-kll: the footprint's merge buffer is the steady state; tie tests The grid clones its cells from one template, and a cloned Vec keeps no capacity, so a cell's merge buffer is empty at build and grows to about cell_k items at its first compaction. Say the footprint counts it at that bound. The CDF test now asks a group of ties (at or below) and a mixed-tie group on a grid wide enough that it shares no cell. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- sketch-bench/src/wrappers/hydra_kll/mod.rs | 19 +++++++++++++++++++ .../src/wrappers/hydra_kll/sketchlib.rs | 7 +++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/sketch-bench/src/wrappers/hydra_kll/mod.rs b/sketch-bench/src/wrappers/hydra_kll/mod.rs index 35f07656..4b92fc5e 100644 --- a/sketch-bench/src/wrappers/hydra_kll/mod.rs +++ b/sketch-bench/src/wrappers/hydra_kll/mod.rs @@ -131,6 +131,25 @@ mod tests { assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 25.0), 0.25); assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 100.0), 1.0); assert_eq!(h.estimate_subpop_cdf(&[Some("a")], 0.9), 0.0); + // Ties count as at or below: every one of b's values is 0.5. + assert_eq!(h.estimate_subpop_cdf(&[Some("b")], 0.5), 1.0); + + // Mixed ties, on a grid wide enough that `c` shares no cell: its 2s + // are three of its five values. + let mut wide = build_hydra_kll( + &ParamSet::of(&HydraKllParams { + rows: 3, + cols: 4096, + cell_k: 200, + }), + 2, + ) + .expect("canonical dimensions build"); + for v in [1.0, 2.0, 2.0, 2.0, 3.0] { + fed_kll(&mut wide, &frecord("c;y", v)); + } + assert_eq!(wide.estimate_subpop_cdf(&[Some("c")], 2.0), 0.8); + assert_eq!(wide.estimate_subpop_cdf(&[Some("c")], 1.0), 0.2); } #[test] diff --git a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs index 97a5bfd1..c1af9097 100644 --- a/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs +++ b/sketch-bench/src/wrappers/hydra_kll/sketchlib.rs @@ -59,8 +59,11 @@ impl HydraKll { } /// One `asap_sketchlib::KLL` per cell times the grid area: its retained -/// slots, level index and merge buffer of `cell_k` items, as the `kll-*` lib -/// rows count them (`kll_lib_bytes`). Analytic because the cell allocates once. +/// slots and level index, allocated with the grid, plus its merge buffer at +/// its `cell_k`-item bound (`kll_lib_bytes`). The grid clones its cells from +/// one template and a cloned `Vec` keeps no capacity, so a cell's buffer is +/// empty at build and grows to about `cell_k` items once its level 0 first +/// compacts: this is the steady-state footprint, not the one at build. pub fn memory_hydra_kll(sketch: &HydraKll) -> usize { let p = &sketch.params; p.rows * p.cols * kll_cell_bytes::(p.cell_k) + grid_overhead_bytes(p.rows, p.cols) From 62536983bde6a4676f2020965ee32b76417629bb Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 05:49:38 +0000 Subject: [PATCH 5/5] hydra-univmon-sum: the ground truth refuses negative values too The lib row inserts each value as a UnivMon count and refuses negatives; the truth (and so the polars baseline) accepted them, so a spec with negatives ran on polars and failed on lib. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- aqpbm-core/src/accuracy/subpopulation/sum.rs | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/aqpbm-core/src/accuracy/subpopulation/sum.rs b/aqpbm-core/src/accuracy/subpopulation/sum.rs index 4c997eba..152e122a 100644 --- a/aqpbm-core/src/accuracy/subpopulation/sum.rs +++ b/aqpbm-core/src/accuracy/subpopulation/sum.rs @@ -25,6 +25,13 @@ fn sums_per_group( ) -> Result { let labels = group_labels(table, group_columns)?; let values: Vec = match table.column(value_column)? { + // The lib row inserts each value as a UnivMon count, which can't be + // negative, so the truth refuses negatives too. + ColumnData::Int64(v) if v.iter().any(|&x| x < 0) => { + return Err(DataGenError::BadParam( + "a sum's values are UnivMon counts, so they can't be negative".into(), + )) + } ColumnData::Int64(v) => v.iter().map(|&x| x as f64).collect(), ColumnData::Unsigned64(v) => v.iter().map(|&x| x as f64).collect(), other => { @@ -128,6 +135,27 @@ mod tests { } /// A group whose values sum to zero has no relative error: it is listed + /// Negative values are refused, as the lib row refuses them. + #[test] + fn a_negative_value_is_refused() { + use crate::accuracy::table_of; + let table = table_of( + &["key1", "value"], + vec![ + ColumnData::String(vec!["a".into()]), + ColumnData::Int64(vec![-1]), + ], + ); + let gt = SubpopSumGT { + group_columns: vec![0], + value_column: 1, + }; + let Err(err) = gt.truth(&table) else { + panic!("a negative value must be refused"); + }; + assert!(err.to_string().contains("negative"), "{err}"); + } + /// unscored, as a group with no distinct value is for cardinality. #[test] fn a_zero_sum_group_is_listed_unscored() {