Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,14 @@ 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 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

Most of the input and output is shared between this hydra example and the previous hll example.
Expand Down
19 changes: 19 additions & 0 deletions aqpbm-cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,29 @@ 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<usize>,

/// Path to append JSONL records to. `-` or omitted sends them to stdout.
#[arg(long, help_heading = "Output")]
pub report: Option<String>,
/// 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<String>,
/// 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
Expand Down
17 changes: 17 additions & 0 deletions aqpbm-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,13 +350,30 @@ 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");
}
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 {
variant: variant.clone(),
library: library.clone(),
params: params.clone(),
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,
Expand Down
12 changes: 6 additions & 6 deletions aqpbm-cli/src/rows/hydra_univmon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>,
Expand Down Expand Up @@ -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>,
Expand Down Expand Up @@ -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>,
Expand Down Expand Up @@ -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>,
Expand Down Expand Up @@ -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>,
Expand Down Expand Up @@ -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>,
Expand Down
9 changes: 3 additions & 6 deletions aqpbm-cli/src/rows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down
86 changes: 73 additions & 13 deletions aqpbm-cli/src/rows/statistic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,28 @@ pub(super) fn topk_row<T: CountedValue>(
)
}

/// 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<Vec<usize>, 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)]
Expand All @@ -119,16 +141,19 @@ pub(super) fn subpop_frequency_row<V: CountedValue + 'static>(
want: &[(Operation, Metric)],
insert: InsertBody<(String, V)>,
insert_step: InsertStepBody<(String, V)>,
query: QueryBody<(String, V), (Vec<String>, V), f64>,
merge: Option<Folds<(String, V), (Vec<String>, V), f64>>,
query: QueryBody<(String, V), (GroupKey, V), f64>,
merge: Option<Folds<(String, V), (GroupKey, V), f64>>,
prepare: Option<PrepareBody<(String, V)>>,
) -> Result<Measurements, RunError> {
scored_row(
req,
description,
table,
want,
SubpopFrequencyGT::<V>::over_columns(vec![SCORED_LABEL_COLUMN], value_column(description)),
SubpopFrequencyGT::<V>::over_columns(
group_columns(req, description)?,
value_column(description),
),
peel_labeled::<V>,
insert,
insert_step,
Expand All @@ -148,8 +173,8 @@ pub(super) fn subpop_cardinality_row<V: ColumnItem + 'static>(
want: &[(Operation, Metric)],
insert: InsertBody<(String, V)>,
insert_step: InsertStepBody<(String, V)>,
query: QueryBody<(String, V), Vec<String>, f64>,
merge: Option<Folds<(String, V), Vec<String>, f64>>,
query: QueryBody<(String, V), GroupKey, f64>,
merge: Option<Folds<(String, V), GroupKey, f64>>,
prepare: Option<PrepareBody<(String, V)>>,
) -> Result<Measurements, RunError> {
scored_row(
Expand All @@ -158,7 +183,7 @@ pub(super) fn subpop_cardinality_row<V: ColumnItem + 'static>(
table,
want,
SubpopCardinalityGT {
group_columns: vec![SCORED_LABEL_COLUMN],
group_columns: group_columns(req, description)?,
value_column: value_column(description),
},
peel_labeled::<V>,
Expand All @@ -181,12 +206,12 @@ pub(super) fn subpop_vector_row<V: ColumnItem + 'static, G>(
ground_truth: G,
insert: InsertBody<(String, V)>,
insert_step: InsertStepBody<(String, V)>,
query: QueryBody<(String, V), Vec<String>, f64>,
merge: Option<Folds<(String, V), Vec<String>, f64>>,
query: QueryBody<(String, V), GroupKey, f64>,
merge: Option<Folds<(String, V), GroupKey, f64>>,
prepare: Option<PrepareBody<(String, V)>>,
) -> Result<Measurements, RunError>
where
G: GroundTruth<Probe = Vec<String>, Answer = f64> + 'static,
G: GroundTruth<Probe = GroupKey, Answer = f64> + 'static,
G::Truth: 'static,
{
scored_row(
Expand All @@ -212,8 +237,8 @@ pub(super) fn subpop_quantile_row<V: ColumnItem + 'static>(
want: &[(Operation, Metric)],
insert: InsertBody<(String, V)>,
insert_step: InsertStepBody<(String, V)>,
query: QueryBody<(String, V), (Vec<String>, f64), f64>,
merge: Option<Folds<(String, V), (Vec<String>, f64), f64>>,
query: QueryBody<(String, V), (GroupKey, f64), f64>,
merge: Option<Folds<(String, V), (GroupKey, f64), f64>>,
prepare: Option<PrepareBody<(String, V)>>,
) -> Result<Measurements, RunError> {
scored_row(
Expand All @@ -222,7 +247,7 @@ pub(super) fn subpop_quantile_row<V: ColumnItem + 'static>(
table,
want,
SubpopRankErrorGT {
group_columns: vec![SCORED_LABEL_COLUMN],
group_columns: group_columns(req, description)?,
value_column: value_column(description),
},
peel_labeled::<V>,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -399,6 +428,37 @@ where
Ok(bodies)
}

/// 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<A: 'static>(
score: Score<A>,
per_group: PerGroup<A>,
path: &std::path::Path,
) -> Result<Score<A>, 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
};
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()));
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.
Expand Down
Loading