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..152e122a --- /dev/null +++ b/aqpbm-core/src/accuracy/subpopulation/sum.rs @@ -0,0 +1,210 @@ +//! 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)? { + // 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 => { + 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 + /// 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() { + 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..4b92fc5e 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,53 @@ 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); + // 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] fn kll_zero_cell_k_is_refused_by_name() { let bad = ParamSet::of(&HydraKllParams { @@ -119,3 +168,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 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; - 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 +132,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 +193,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 {