diff --git a/aqpbm-cli/src/atomic_costs_cmd.rs b/aqpbm-cli/src/atomic_costs_cmd.rs index 47b8d724..9b9e47a0 100644 --- a/aqpbm-cli/src/atomic_costs_cmd.rs +++ b/aqpbm-cli/src/atomic_costs_cmd.rs @@ -9,7 +9,9 @@ use std::io::Read; use anyhow::{Context, Result}; use clap::Parser; -use aqpbm_core::{reduce_all, same_cell, MergedRecord}; +use std::collections::BTreeMap; + +use aqpbm_core::{reduce_all, MergedRecord}; #[derive(Parser, Debug)] pub struct AtomicCostsArgs { @@ -19,11 +21,21 @@ pub struct AtomicCostsArgs { /// Output path for the reduced table (JSON array). Defaults to stdout. #[arg(short, long)] output: Option, - /// `--flat` merge-accuracy rows (`--operations merge --metrics accuracy`), - /// one per cell and `--merge-shards`. Each lands in its cell's - /// `merge_accuracy`; one that matches no input row is an error. - #[arg(long)] - merge_accuracy: Option, + /// `VARIANT=METRIC`, once per variant: the `query_accuracy` key that is + /// that variant's `accuracy_metric`. A row whose variant has none, or + /// whose scores lack it, is skipped. + #[arg(long = "accuracy-metric", value_name = "VARIANT=METRIC", required = true, + value_parser = parse_accuracy_metric)] + accuracy_metrics: Vec<(String, String)>, +} + +fn parse_accuracy_metric(arg: &str) -> Result<(String, String), String> { + match arg.split_once('=') { + Some((variant, metric)) if !variant.is_empty() && !metric.is_empty() => { + Ok((variant.to_string(), metric.to_string())) + } + _ => Err(format!("expected VARIANT=METRIC, got {arg}")), + } } fn read_records(path: &str) -> Result> { @@ -46,25 +58,13 @@ fn read_records(path: &str) -> Result> { pub fn run(args: AtomicCostsArgs) -> Result<()> { let records = read_records(&args.input)?; - let merge_runs = match args.merge_accuracy.as_deref() { - Some(path) => read_records(path)?, - None => Vec::new(), - }; - if let Some(run) = merge_runs - .iter() - .find(|run| !records.iter().any(|record| same_cell(record, run))) - { - anyhow::bail!( - "merge-accuracy row {} {} matches no input row", - run.sketch, - run.sketch_config - .as_ref() - .map(|c| c.to_string()) - .unwrap_or_default() - ); + let mut accuracy_metrics = BTreeMap::new(); + for (variant, metric) in args.accuracy_metrics { + if let Some(earlier) = accuracy_metrics.insert(variant.clone(), metric.clone()) { + anyhow::bail!("--accuracy-metric gives {variant} twice ({earlier}, {metric})"); + } } - - let (table, skipped) = reduce_all(&records, &merge_runs); + let (table, skipped) = reduce_all(&records, &accuracy_metrics); for (i, reason) in &skipped { let record = &records[*i]; eprintln!( diff --git a/aqpbm-cli/tests/merge_accuracy.rs b/aqpbm-cli/tests/merge_accuracy.rs index 08506d00..6d814451 100644 --- a/aqpbm-cli/tests/merge_accuracy.rs +++ b/aqpbm-cli/tests/merge_accuracy.rs @@ -6,9 +6,18 @@ use std::process::Command; /// One `--flat` record measuring both the single sketch's and the merged /// sketch's accuracy over the same small fixed-seed stream. fn query_and_merge_accuracy(variant: &str, config: &str, dataset: &[&str]) -> serde_json::Value { + run_merge_accuracy(variant, "lib", &["--config", config], dataset) +} + +fn run_merge_accuracy( + variant: &str, + library: &str, + config: &[&str], + dataset: &[&str], +) -> serde_json::Value { let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) - .args(["sketchbench", "--variant", variant, "--library", "lib"]) - .args(["--config", config]) + .args(["sketchbench", "--variant", variant, "--library", library]) + .args(config) .args(["--operations", "query,merge", "--metrics", "accuracy"]) .args(["--merge-shards", "4", "--runs", "1", "--warmup-runs", "0"]) .args(["--size", "20000", "--seed", "7", "--flat"]) @@ -70,3 +79,36 @@ fn merged_kll_scores_finite() { .unwrap_or_else(|| panic!("no merged mean_rank_err in {r}")); assert!(err.is_finite(), "{err}"); } + +/// Exact accumulators merge without loss (the optimizer relies on it and no +/// longer measures merged accuracy per row, #174): every merged score is the +/// single accumulator's, and the worst group's error is 0. Increase reads +/// counters, so its shard boundaries split counter runs. +#[test] +fn merged_exact_accumulators_score_exactly_like_one() { + let spec = |name: &str| format!("{}/../configs/datagen/{name}", env!("CARGO_MANIFEST_DIR")); + for (variant, comparator, columns) in [ + ("exact-sum", "sum-or-count", "hydra_columns.yaml"), + ("exact-min", "min", "hydra_columns.yaml"), + ("exact-max", "max", "hydra_columns.yaml"), + ("exact-increase", "rate-or-increase", "counter_columns.yaml"), + ("exact-delta-set", "key-set", "hydra_columns.yaml"), + ] { + let path = spec(columns); + let r = run_merge_accuracy( + variant, + "exact", + &[], + &[ + "--comparator", + comparator, + "--spec", + &path, + "--dtype", + "i64", + ], + ); + assert_eq!(r["merge_accuracy"], r["query_accuracy"], "{variant}: {r}"); + assert_eq!(r["merge_accuracy"]["relative_error"], 0.0, "{variant}: {r}"); + } +} diff --git a/aqpbm-core/src/atomic_costs.rs b/aqpbm-core/src/atomic_costs.rs index a80b4136..fa5c8ee7 100644 --- a/aqpbm-core/src/atomic_costs.rs +++ b/aqpbm-core/src/atomic_costs.rs @@ -37,15 +37,19 @@ pub struct AtomicCostEntry { /// rank-error's `mean_rank_err`). No single scalar covers all of them, so /// this stays a map rather than picking one field to promote. pub query_accuracy: BTreeMap, - /// The same comparator's scores for the sketch left by folding `m` - /// shards, keyed by `m`: `MergedRecord::merge.accuracy` from the - /// merge-accuracy runs [`reduce_all`] is given. Empty when none were. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] - pub merge_accuracy: BTreeMap>, - /// The conditions the row was measured under. Optional so tables written - /// before it was added still load; [`reduce_one`] always fills it. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub measured_at: Option, + /// The `query_accuracy` key that is this row's accuracy, named by whoever + /// ran the export (the comparator doesn't say which of its scores is the + /// one). [`reduce_one`] refuses a record whose scores lack it. + pub accuracy_metric: String, + /// The conditions the row was measured under. + pub measured_at: MeasuredAt, +} + +impl AtomicCostEntry { + /// `query_accuracy[accuracy_metric]`; present in every reduced row. + pub fn accuracy(&self) -> Option { + self.query_accuracy.get(&self.accuracy_metric).copied() + } } /// What one benchmark instance saw. A consumer applying the row to an instance @@ -133,6 +137,9 @@ pub enum SkipReason { /// numbers) — a comparator/schema bug, not a run that simply didn't /// measure the field. InvalidField(&'static str), + /// The comparator's scores lack the row's `accuracy_metric`, e.g. DD + /// omits its error when every true quantile is 0. + MissingMetric(String), } impl std::fmt::Display for SkipReason { @@ -145,6 +152,7 @@ impl std::fmt::Display for SkipReason { write!(f, "{op} rate/elapsed/cpu_time sample counts disagree") } SkipReason::InvalidField(field) => write!(f, "{field} is not the expected shape"), + SkipReason::MissingMetric(metric) => write!(f, "query_accuracy has no {metric}"), } } } @@ -203,8 +211,25 @@ fn cpu_secs_per_op( /// measure insert+query+merge+memory in one invocation is expected to fail /// this — that's a driver bug (wrong `--operations`/`--metrics`), not a /// candidate to silently drop, so the caller should treat `SkipReason` as -/// worth logging even though it isn't fatal. -pub fn reduce_one(record: &MergedRecord) -> Result { +/// worth logging even though it isn't fatal. `accuracy_metric` names the +/// row's accuracy among the comparator's scores. +pub fn reduce_one( + record: &MergedRecord, + accuracy_metric: &str, +) -> Result { + let entry = reduce_scores(record)?; + if !entry.query_accuracy.contains_key(accuracy_metric) { + return Err(SkipReason::MissingMetric(accuracy_metric.to_string())); + } + Ok(AtomicCostEntry { + accuracy_metric: accuracy_metric.to_string(), + ..entry + }) +} + +/// [`reduce_one`] without naming the row's metric (`accuracy_metric` is +/// empty), for a consumer that keeps every score (ERP). +pub(crate) fn reduce_scores(record: &MergedRecord) -> Result { let mem_bytes_per_instance = record .memory_bytes .ok_or(SkipReason::MissingField("memory_bytes"))? as f64; @@ -250,9 +275,9 @@ pub fn reduce_one(record: &MergedRecord) -> Result insert_cpu_secs, merge_cpu_secs, query_cpu_secs, - measured_at: Some(measured_at(record, groups_measured)), + measured_at: measured_at(record, groups_measured), query_accuracy, - merge_accuracy: BTreeMap::new(), + accuracy_metric: String::new(), }) } @@ -320,65 +345,20 @@ fn accuracy_map( .ok_or(SkipReason::InvalidField(field)) } -/// Whether two rows measured the same cell: the identity `approxbench -/// flatten` groups by. It has no comparator, so a cell scored by two -/// comparators would collect both sets of merge rows and be skipped as a -/// duplicate count, loudly. -pub fn same_cell(a: &MergedRecord, b: &MergedRecord) -> bool { - a.sketch == b.sketch - && a.library == b.library - && a.sketch_config == b.sketch_config - && a.input_dataset == b.input_dataset -} - -/// `record`'s merge accuracy, keyed by merge count, from the `merge_runs` -/// of its cell. A merge run is one `--flat` invocation at one -/// `--merge-shards`, so each count is its own row; two at one count is a -/// duplicated export, refused rather than resolved. -fn merge_accuracy( - record: &MergedRecord, - merge_runs: &[MergedRecord], -) -> Result>, SkipReason> { - let mut out = BTreeMap::new(); - for run in merge_runs.iter().filter(|run| same_cell(record, run)) { - let shards = run - .merge - .merge_shards - .ok_or(SkipReason::MissingField("merge_shards"))?; - let scores = accuracy_map("merge_accuracy", run.merge.accuracy.as_ref())?; - if out.insert(shards as u64, scores).is_some() { - return Err(SkipReason::InvalidField("merge_accuracy")); - } - } - Ok(out) -} - /// Reduce every record that has what it takes, skipping (and reporting) the -/// rest. Order follows `records`. `merge_runs` are merge-accuracy rows; each -/// is attached to the record of its cell (see [`same_cell`]). A record -/// missing any merge count that appears in `merge_runs` is skipped, so a -/// partial grid can't pass as complete. +/// rest. Order follows `records`. `accuracy_metrics` maps each variant to its +/// accuracy key; a variant missing from it is skipped. pub fn reduce_all( records: &[MergedRecord], - merge_runs: &[MergedRecord], + accuracy_metrics: &BTreeMap, ) -> (AtomicCostTable, Vec<(usize, SkipReason)>) { - let grid_counts: std::collections::BTreeSet = merge_runs - .iter() - .filter_map(|run| run.merge.merge_shards.map(|m| m as u64)) - .collect(); let mut table = Vec::with_capacity(records.len()); let mut skipped = Vec::new(); for (i, record) in records.iter().enumerate() { - let entry = reduce_one(record).and_then(|mut entry| { - entry.merge_accuracy = merge_accuracy(record, merge_runs)?; - if !grid_counts - .iter() - .all(|m| entry.merge_accuracy.contains_key(m)) - { - return Err(SkipReason::MissingField("merge_accuracy")); - } - Ok(entry) - }); + let entry = accuracy_metrics + .get(&record.sketch) + .ok_or(SkipReason::MissingField("accuracy_metric")) + .and_then(|metric| reduce_one(record, metric)); match entry { Ok(entry) => table.push(entry), Err(reason) => skipped.push((i, reason)), @@ -396,6 +376,8 @@ mod tests { }; use aqpbm_datagen::TableDescription; + const METRIC: &str = "relative_error_mean"; + fn stats(mean: f64) -> RunStats { stats_n(mean, 5) } @@ -489,8 +471,8 @@ mod tests { fn grouped_records_are_priced_per_group() { let mut record = full_record(); record.query.accuracy = - Some(serde_json::json!({"relative_error": 0.0, "groups_per_instance": 4.0})); - let entry = reduce_one(&record).expect("fully populated record"); + Some(serde_json::json!({"relative_error_mean": 0.0, "groups_per_instance": 4.0})); + let entry = reduce_one(&record, METRIC).expect("fully populated record"); assert_eq!(entry.mem_bytes_per_instance, 12_288.0 / 4.0); assert!((entry.merge_cpu_secs - 10e-3 / 4.0).abs() < 1e-12); assert!((entry.insert_cpu_secs - 0.5e-6).abs() < 1e-12); @@ -503,8 +485,8 @@ mod tests { fn measured_at_reads_a_single_column_workload() { let mut record = full_record(); record.merge.merge_shards = Some(16); - let entry = reduce_one(&record).expect("fully populated record"); - let at = entry.measured_at.expect("always filled"); + let entry = reduce_one(&record, METRIC).expect("fully populated record"); + let at = entry.measured_at; assert_eq!(at.items_per_instance, 1_000_000); assert_eq!(at.keys_per_instance, Some(100_000)); assert_eq!(at.value_range, Some([0.0, 100_000.0])); @@ -535,14 +517,14 @@ mod tests { let mut record = full_record(); record.input_dataset = description.into(); - let at = reduce_one(&record).unwrap().measured_at.unwrap(); + let at = reduce_one(&record, METRIC).unwrap().measured_at; assert_eq!(at.keys_per_instance, Some(50_000)); assert_eq!(at.value_range, Some([10.0, 100_010.0])); assert_eq!(at.merge_operand_items, None); record.query.accuracy = - Some(serde_json::json!({"relative_error": 0.0, "groups_per_instance": 9_876.0})); - let at = reduce_one(&record).unwrap().measured_at.unwrap(); + Some(serde_json::json!({"relative_error_mean": 0.0, "groups_per_instance": 9_876.0})); + let at = reduce_one(&record, METRIC).unwrap().measured_at; assert_eq!(at.keys_per_instance, Some(9_876)); } @@ -554,44 +536,53 @@ mod tests { description.column_spec[0].special_rule = aqpbm_datagen::RULE_MONOTONIC_INCREASE; let mut record = full_record(); record.input_dataset = description.into(); - let at = reduce_one(&record).unwrap().measured_at.unwrap(); + let at = reduce_one(&record, METRIC).unwrap().measured_at; assert_eq!(at.value_range, None); assert_eq!(at.items_per_instance, 1_000_000); } - /// Tables written before `measured_at` existed still load. + /// A row without its metric is an error: tables are regenerated, not + /// migrated. #[test] - fn a_row_without_measured_at_still_loads() { + fn a_row_without_accuracy_metric_is_rejected() { let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{}}"#; - let entry: AtomicCostEntry = serde_json::from_str(json).unwrap(); - assert_eq!(entry.measured_at, None); + let err = serde_json::from_str::(json).unwrap_err(); + assert!(err.to_string().contains("accuracy_metric"), "{err}"); + } + + #[test] + fn a_record_without_its_metric_is_skipped() { + assert_eq!( + reduce_one(&full_record(), "mean_rank_err"), + Err(SkipReason::MissingMetric("mean_rank_err".into())) + ); } /// A misspelled or newer field is an error, not silently dropped data. #[test] fn a_row_with_an_unknown_field_is_rejected() { - let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"merge_acuracy":{}}"#; + let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"accuracy_metric":"x","merge_acuracy":{}}"#; let err = serde_json::from_str::(json).unwrap_err(); assert!(err.to_string().contains("merge_acuracy"), "{err}"); } #[test] fn measured_at_with_an_unknown_field_is_rejected() { - let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"measured_at":{"items_per_instance":1,"keys_per_instance":null,"value_rnage":null,"merge_operand_items":null,"distribution":null}}"#; + let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"accuracy_metric":"x","measured_at":{"items_per_instance":1,"keys_per_instance":null,"value_rnage":null,"merge_operand_items":null,"distribution":null}}"#; let err = serde_json::from_str::(json).unwrap_err(); assert!(err.to_string().contains("value_rnage"), "{err}"); } #[test] fn a_distribution_with_an_unknown_field_is_rejected() { - let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"measured_at":{"items_per_instance":1,"keys_per_instance":null,"value_range":null,"merge_operand_items":null,"distribution":{"kind":"zipf","skewnes":1.1,"skewness":1.1,"population_size":10,"seed":1}}}"#; + let json = r#"{"sketch":"cms","sketch_config":null,"mem_bytes_per_instance":1.0,"insert_cpu_secs":1.0,"merge_cpu_secs":1.0,"query_cpu_secs":1.0,"query_accuracy":{},"accuracy_metric":"x","measured_at":{"items_per_instance":1,"keys_per_instance":null,"value_range":null,"merge_operand_items":null,"distribution":{"kind":"zipf","skewnes":1.1,"skewness":1.1,"population_size":10,"seed":1}}}"#; let err = serde_json::from_str::(json).unwrap_err(); assert!(err.to_string().contains("skewnes"), "{err}"); } #[test] fn reduces_a_full_record_to_per_op_seconds() { - let entry = reduce_one(&full_record()).expect("fully populated record"); + let entry = reduce_one(&full_record(), METRIC).expect("fully populated record"); assert_eq!(entry.sketch, "cms"); assert_eq!(entry.mem_bytes_per_instance, 12_288.0); @@ -621,7 +612,7 @@ mod tests { let mut record = full_record(); record.query.accuracy = None; assert_eq!( - reduce_one(&record), + reduce_one(&record, METRIC), Err(SkipReason::MissingField("query_accuracy")) ); } @@ -634,7 +625,7 @@ mod tests { let mut record = full_record(); record.query.accuracy = Some(serde_json::json!({"relative_error_mean": "not a number"})); assert_eq!( - reduce_one(&record), + reduce_one(&record, METRIC), Err(SkipReason::InvalidField("query_accuracy")) ); } @@ -644,7 +635,7 @@ mod tests { let mut record = full_record(); record.memory_bytes = None; assert_eq!( - reduce_one(&record), + reduce_one(&record, METRIC), Err(SkipReason::MissingField("memory_bytes")) ); } @@ -657,7 +648,7 @@ mod tests { let mut record = full_record(); record.merge.cpu_time_ms = None; assert_eq!( - reduce_one(&record), + reduce_one(&record, METRIC), Err(SkipReason::MissingSubField("merge", "cpu_time")) ); } @@ -666,7 +657,10 @@ mod tests { fn zero_elapsed_time_is_skipped_not_divided() { let mut record = full_record(); record.insert.wall_time_ms = Some(stats(0.0)); - assert_eq!(reduce_one(&record), Err(SkipReason::ZeroWork("insert"))); + assert_eq!( + reduce_one(&record, METRIC), + Err(SkipReason::ZeroWork("insert")) + ); } #[test] @@ -679,7 +673,7 @@ mod tests { let mut record = full_record(); record.insert.throughput_items_per_sec = Some(stats_n(1_000_000.0, 4)); assert_eq!( - reduce_one(&record), + reduce_one(&record, METRIC), Err(SkipReason::MisalignedSamples("insert")) ); } @@ -690,9 +684,20 @@ mod tests { let mut bad = full_record(); bad.memory_bytes = None; - let (table, skipped) = reduce_all(&[good, bad], &[]); + let mut unnamed = full_record(); + unnamed.sketch = "hll".into(); + + let metrics = BTreeMap::from([("cms".to_string(), METRIC.to_string())]); + let (table, skipped) = reduce_all(&[good, bad, unnamed], &metrics); assert_eq!(table.len(), 1); - assert_eq!(skipped, vec![(1, SkipReason::MissingField("memory_bytes"))]); + assert_eq!(table[0].accuracy(), Some(0.01)); + assert_eq!( + skipped, + vec![ + (1, SkipReason::MissingField("memory_bytes")), + (2, SkipReason::MissingField("accuracy_metric")), + ] + ); } #[test] @@ -707,85 +712,19 @@ mod tests { merge_cpu_secs: 1e-2, query_cpu_secs: 4e-6, query_accuracy: BTreeMap::from([("relative_error_mean".to_string(), 0.01)]), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "relative_error_mean".into(), + measured_at: MeasuredAt { + items_per_instance: 1_000_000, + keys_per_instance: Some(10_000), + value_range: None, + merge_operand_items: None, + distribution: None, + }, }; let json = serde_json::to_string(&entry).unwrap(); assert_eq!( json, - r#"{"sketch":"cms","sketch_config":{"algorithm":"cms","params":{"cols":1024,"rows":3}},"mem_bytes_per_instance":12288.0,"insert_cpu_secs":5e-7,"merge_cpu_secs":0.01,"query_cpu_secs":4e-6,"query_accuracy":{"relative_error_mean":0.01}}"# - ); - } - - /// A `--flat` merge-accuracy row: only `merge_shards` and its scores. - fn merge_run(shards: usize, err: f64) -> MergedRecord { - let mut run = full_record(); - run.memory_bytes = None; - run.insert = InsertMetrics::default(); - run.query = QueryMetrics::default(); - run.merge = MergeMetrics { - merge_shards: Some(shards), - accuracy: Some(serde_json::json!({ "relative_error_mean": err })), - ..Default::default() - }; - run - } - - #[test] - fn merge_runs_attach_to_their_cell_by_merge_count() { - let mut other_cell = merge_run(4, 9.0); - other_cell.sketch_config = Some(serde_json::json!({"algorithm": "cms", "params": {}})); - let runs = [merge_run(64, 0.3), merge_run(4, 0.1), other_cell]; - let (table, skipped) = reduce_all(&[full_record()], &runs); - assert!(skipped.is_empty(), "{skipped:?}"); - let at = |m: u64| table[0].merge_accuracy[&m]["relative_error_mean"]; - assert_eq!(table[0].merge_accuracy.len(), 2); - assert_eq!(at(4), 0.1); - assert_eq!(at(64), 0.3); - } - - #[test] - fn a_row_missing_a_grid_merge_count_is_skipped() { - let mut other_cell = merge_run(16, 0.2); - other_cell.sketch_config = Some(serde_json::json!({"algorithm": "cms", "params": {}})); - let (table, skipped) = reduce_all(&[full_record()], &[merge_run(4, 0.1), other_cell]); - assert!(table.is_empty()); - assert_eq!( - skipped, - vec![(0, SkipReason::MissingField("merge_accuracy"))] - ); - } - - #[test] - fn two_merge_runs_at_one_count_skip_the_row() { - let (table, skipped) = - reduce_all(&[full_record()], &[merge_run(4, 0.1), merge_run(4, 0.2)]); - assert!(table.is_empty()); - assert_eq!( - skipped, - vec![(0, SkipReason::InvalidField("merge_accuracy"))] - ); - } - - #[test] - fn merge_accuracy_round_trips_and_is_omitted_when_empty() { - let (table, _) = reduce_all(&[full_record()], &[merge_run(16, 0.2)]); - let json = serde_json::to_string(&table[0]).unwrap(); - assert!( - json.contains(r#""merge_accuracy":{"16":{"relative_error_mean":0.2}}"#), - "{json}" - ); - assert_eq!( - serde_json::from_str::(&json).unwrap(), - table[0] - ); - - let (table, _) = reduce_all(&[full_record()], &[]); - let json = serde_json::to_string(&table[0]).unwrap(); - assert!(!json.contains("merge_accuracy"), "{json}"); - assert_eq!( - serde_json::from_str::(&json).unwrap(), - table[0] + r#"{"sketch":"cms","sketch_config":{"algorithm":"cms","params":{"cols":1024,"rows":3}},"mem_bytes_per_instance":12288.0,"insert_cpu_secs":5e-7,"merge_cpu_secs":0.01,"query_cpu_secs":4e-6,"query_accuracy":{"relative_error_mean":0.01},"accuracy_metric":"relative_error_mean","measured_at":{"items_per_instance":1000000,"keys_per_instance":10000,"value_range":null,"merge_operand_items":null,"distribution":null}}"# ); } } diff --git a/aqpbm-core/src/erp.rs b/aqpbm-core/src/erp.rs index 556fbb18..6a4e42c8 100644 --- a/aqpbm-core/src/erp.rs +++ b/aqpbm-core/src/erp.rs @@ -10,7 +10,8 @@ use serde::{Deserialize, Serialize}; use aqpbm_datagen::DataDistribution; -use crate::{reduce_one, MergedRecord, SkipReason, WorkloadDescription}; +use crate::atomic_costs::reduce_scores; +use crate::{MergedRecord, SkipReason, WorkloadDescription}; pub const ERP_SCHEMA_VERSION: u32 = 1; @@ -111,7 +112,7 @@ fn distribution_descriptor(workload: &WorkloadDescription) -> serde_json::Value /// row. The caller supplies an artifact-local ID and producer revision so an /// export remains auditable. pub fn erp_record(id: impl Into, record: &MergedRecord) -> Result { - let atomic = reduce_one(record)?; + let atomic = reduce_scores(record)?; Ok(ErpRecord { id: id.into(), sketch: atomic.sketch, diff --git a/aqpbm-core/src/lib.rs b/aqpbm-core/src/lib.rs index 7485576e..8792fc47 100644 --- a/aqpbm-core/src/lib.rs +++ b/aqpbm-core/src/lib.rs @@ -20,8 +20,7 @@ pub use aqpbm_datagen::{ ZipfParameter, RULE_MONOTONIC_INCREASE, RULE_NONE, }; pub use atomic_costs::{ - reduce_all, reduce_one, same_cell, AtomicCostEntry, AtomicCostTable, MeasuredAt, MeasuredShape, - SkipReason, + reduce_all, reduce_one, AtomicCostEntry, AtomicCostTable, MeasuredAt, MeasuredShape, SkipReason, }; pub use benchmark_result::{ BenchReport, BenchSection, CpuTime, ExternalWorkload, InsertMetrics, LatencySummary, diff --git a/configs/datagen/hydra_kll_disjoint_labels.yaml b/configs/datagen/hydra_kll_disjoint_labels.yaml index 0f3261e4..23392aee 100644 --- a/configs/datagen/hydra_kll_disjoint_labels.yaml +++ b/configs/datagen/hydra_kll_disjoint_labels.yaml @@ -2,7 +2,8 @@ # value can never render the same as a key2 value (#74). On the shared alphabet # a key1 query also picks up the matching key2 group, and that collision shows # up as rank error; here the `polars` baseline scores zero and any rank error -# is the sketch's. `export_rqe_optimizer_costs.sh` prices `hydra-kll` on it. +# is the sketch's. `export_rqe_optimizer_costs.sh` priced `hydra-kll` on it +# until #174; HydraKLL has no saturation curve, so nothing measures it now. column_num: 3 column_label: [key1, key2, value] diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index 9a6e81d0..abeb8e76 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -28,8 +28,9 @@ implemented, what is next, and what is intentionally deferred. counts, per-RQE eligibility, and the Cartesian mapping-space size. - Streaming mode reports periodic throughput and frontier-size progress, and can print initial example mappings. -- `scripts/export_rqe_optimizer_costs.sh` exports the 18-row measured cost - table used by `small_problem`, without changing ASAPQuery's exporter. +- `scripts/study_saturation.py --phase optimizer-cost` measures the cost + table used by `small_problem` (#174), without changing ASAPQuery's + exporter. - The MILP uses HiGHS to minimize `Objective::AUCCost { w_cpu, w_mem }`, `w_cpu × CPU + w_mem × memory GiB` (default `(1, 0)`), without enumerating mappings. It accepts optional per-RQE latency bounds and returns a normal diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index f3d3cfad..8e1f13ea 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -20,8 +20,9 @@ and per-RAQE latency. - **Configuration**: a family plus its parameters, such as KLL with `k = 200`. One row of the cost table. - **Cost table**: per configuration, measured memory per instance, CPU per - insert, merge and query, and accuracy. Exported by - [`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh). + insert, merge and query, and accuracy in its named `accuracy_metric`. + Measured by + [`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py). - **Window**: the interval `[k × y, k × y + x)` an instance covers; `x` is the window size and `y` the slide. - **Instance**: one sketch or accumulator object holding one group's samples @@ -66,16 +67,25 @@ lambda(metric) = card(metric.labels) / scrape_interval samples/second `validate_facts` reports every missing or inconsistent fact up front. -The cost table, exported by -[`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh) -from sketch-bench runs, gives for each configuration: +The cost table, measured by +[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py) +(#174), gives for each configuration: - memory per instance; - CPU per insert; - CPU per query of one instance; -- CPU per pairwise merge; and -- measured accuracy values, which only exact accumulators use (see - [eligibility](#candidate-deployments)). +- CPU per pairwise merge; +- the comparator's accuracy scores, and `accuracy_metric`, the one that is + the row's accuracy (only exact accumulators read it; see + [eligibility](#candidate-deployments)); and +- `measured_at`, the data it was measured on. + +The study measures every configuration once, serially, at one data shape: +Zipf θ = 1.1 over 1e4 keys (Pareto `a` = 2 for quantiles), 1e6 items, 5 runs +after 3 warm-ups. That is the dataset of the AutoSketch vs. ASAP evaluation +(ASAPQuery#777), so the evaluation's costs and the cost table are one +measurement. Cost is taken as independent of the data shape. The same study +measures the saturation curves, so the configurations in both are one grid. Each metric's facts also carry a fitted `data_shape` per grouping, which keys the saturation curves. @@ -204,11 +214,8 @@ An RAQE `r_i` is eligible for a candidate `D` when: 3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family (`family_properties`, which also gives the direction), clears `tol_i`. -Exact accumulators take that accuracy from the cost table, at both measured -merge counts bracketing the query's `S_i / D.x` windows (count 1 is the -single-instance accuracy; beyond the largest measured count, the largest). -Merge accuracy is not monotone in the count, so the worse bracket is used. -Sketches take it +Exact accumulators take that accuracy from the cost table; they merge without +loss, so the window size doesn't matter. Sketches take it from the saturation study's error-vs-N curves (`SaturationCurves`, #156), read at the number of items one group receives over the RAQE's whole lookback: series per group times scrapes per lookback. @@ -227,12 +234,14 @@ lookback: series per group times scrapes per lookback. The cost table's sketch accuracies are not read, but they are one point on each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto -`a`) is a grid point's key. `SaturationCurves::check_cost_table` reads the -curve there and reports every row that disagrees (beyond 3 seed standard -errors plus 5%), whose configuration is not in the grid, or whose table lacks -the curve's `error_metric`. Rows the study has no point for (KLL: the table -measures Zipf ranks, the study Pareto values) are reported as unchecked. -`small_problem` refuses to plan when any row disagrees. +`a`) is a grid point's key. `SaturationCurves::check_cost_table` reports every +row whose `accuracy_metric` is not its family's or not its curve's +`error_metric`, whose configuration is not in the grid, or whose accuracy +disagrees with the curve at `measured_at` (beyond 3 seed standard errors plus +5%). The study runs every configuration at the cost table's shape too, so +every sketch row has a grid point; a row without one (a study run with +`--no-cost-shape`) is reported as unchecked. `small_problem` refuses to plan +when any row disagrees. For lower-is-better metrics, passing means `measured <= tol_i`. For higher-is-better metrics, passing means `measured >= tol_i`. Direction is @@ -345,7 +354,7 @@ top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. ### Instance shape and size law Each row of the cost table (from -[`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh)) +[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py)) is measured on one instance, at whatever key count the benchmark fed it (`measured_keys`). A key is one distinct entry an instance stores exactly, such as one group's running sum in an exact accumulator. Turning a row into a diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 1c292820..25075a05 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -71,8 +71,16 @@ At the final N of each point one extra run (`--operations insert,query,merge --metrics throughput,cpu,memory --merge-shards 16 --runs 3 --warmup-runs 1 --flat`) records insert, merge and query CPU seconds (user + sys) and `memory_bytes`. `BENCH_WARMUP_SECS` -defaults to 0, so these costs are indicative; -`scripts/export_rqe_optimizer_costs.sh` remains the source of optimizer costs. +defaults to 0, so these costs are indicative. The optimizer's costs come +from `--phase optimizer-cost`: each configuration once, serially, at Zipf +θ = 1.1 over 1e4 keys (Pareto `a` = 2 for quantiles) and 1e6 items, with 5 +runs after 3 warm-ups and one accuracy pass, reduced by `approxbench +atomic-costs` to `rqe_atomic_costs.json` (#174). Put it under the curves' +directory as `optimizer_cost/`, where `rqe-optimizer` reads it. The accuracy +grid also runs every configuration at that shape (unless `--no-cost-shape`), +so each cost-table row is a point on a curve and the synthetic evaluation, +which uses the same data, reads an exact curve rather than the worse +neighbouring grid point. `--cost-rows 3` times only the rows=3 configs of CMS, CountSketch and CMS-heap top-k (all four cols); HLL, KLL and DDSketch are timed at every diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index e08050b8..bbabecdc 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -3,23 +3,22 @@ //! Pareto-optimal subset. Picking one mapping *off* the Pareto front is still //! the parked scalarization question (problem statement, "Open for later"). //! -//! Cost data is real, not fabricated: `scripts/export_rqe_optimizer_costs.sh` -//! measures it via `sketch-bench`/`aqpbm-cli` and writes -//! `DIR/rqe_atomic_costs.json`, an `AtomicCostTable` loaded here verbatim -- -//! no translation layer, since `rqe_optimizer::Deployment` embeds -//! `AtomicCostEntry` directly. +//! Cost data is real, not fabricated: `scripts/study_saturation.py --phase +//! optimizer-cost` measures it via `sketch-bench`/`aqpbm-cli` and writes +//! [`COST_TABLE`] under the saturation directory, an `AtomicCostTable` +//! loaded here verbatim -- no translation layer, since +//! `rqe_optimizer::Deployment` embeds `AtomicCostEntry` directly. //! //! Every other number this example uses (RAQE definitions, metric labels, //! cardinalities and scrape intervals) lives in the two tables below //! (`facts`, `raqes`) and nowhere else in this file. //! //! Sketch accuracy comes from the saturation study's curves, not the cost -//! table (#156): pass `--saturation-dir DIR` (required), the directory -//! holding `out_grid_1e7_cost/` and `out_1e9/` from -//! `scripts/study_saturation.py`. +//! table (#156). Pass `--saturation-dir DIR` (required), the directory +//! holding `out_grid_1e7_cost/`, `out_1e9/` and the cost table from +//! `scripts/study_saturation.py` (#174). //! -//! Run: `scripts/export_rqe_optimizer_costs.sh DIR` once, then pass -//! `--cost-dir DIR` (required) to this example. Do not run this example +//! Do not run this example //! with no mode flag on a large workload: eager mode retains every feasible //! mapping and can exhaust memory. Use `--milp`, `--candidates-only`, or //! `--sample-mappings N` instead. Add @@ -44,14 +43,12 @@ use rqe_optimizer::candidates::{ use rqe_optimizer::enumerate::{brute_force, for_each_mapping, for_each_mapping_while, unservable}; use rqe_optimizer::milp::{minimize, Objective}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; -use rqe_optimizer::saturation::{DataShape, SaturationCurves}; +use rqe_optimizer::saturation::{DataShape, SaturationCurves, COST_TABLE}; use rqe_optimizer::{ validate_facts, AtomicCostTable, Capability, Deployment, LabelSet, MetricFacts, Raqe, WorkloadFacts, }; -const COST_TABLE_FILE: &str = "rqe_atomic_costs.json"; - const REQUESTS: &str = "http_requests_total"; const DURATION: &str = "http_request_duration_seconds"; @@ -72,25 +69,25 @@ fn required_dir(flag: &str, what: &str) -> String { .unwrap_or_else(|| panic!("{flag} DIR is required ({what})")) } -fn load_saturation_curves() -> SaturationCurves { - let dir = required_dir( +fn saturation_dir() -> String { + required_dir( "--saturation-dir", - "holding out_grid_1e7_cost/ and out_1e9/ from scripts/study_saturation.py", - ); - SaturationCurves::load(std::path::Path::new(&dir)) + "holding out_grid_1e7_cost/, out_1e9/ and the cost table from scripts/study_saturation.py", + ) +} + +fn load_saturation_curves() -> SaturationCurves { + SaturationCurves::load(std::path::Path::new(&saturation_dir())) .unwrap_or_else(|e| panic!("couldn't load saturation curves: {e}")) } fn load_cost_table() -> AtomicCostTable { - let cost_dir = required_dir( - "--cost-dir", - "a directory written by scripts/export_rqe_optimizer_costs.sh", - ); - let path = std::path::Path::new(&cost_dir).join(COST_TABLE_FILE); + let path = std::path::Path::new(&saturation_dir()).join(COST_TABLE); let raw = std::fs::read_to_string(&path).unwrap_or_else(|e| { panic!( "couldn't read {} ({e}) -- run \ - `scripts/export_rqe_optimizer_costs.sh {cost_dir}` first to generate it", + `scripts/study_saturation.py --phase optimizer-cost --out DIR/optimizer_cost` \ + first to generate it", path.display() ) }); @@ -363,7 +360,6 @@ fn reject_unknown_args() { "--streaming", ]; const WITH_VALUE: &[&str] = &[ - "--cost-dir", "--latency-sla", "--print-candidates", "--print-first", diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index d819e0ff..207d2b3c 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -339,8 +339,8 @@ mod tests { use super::*; use crate::analytical_cost_model::{score, PhaseCost}; use crate::candidates::is_eligible; - use crate::test_support::{facts, METRIC}; - use crate::{table_accuracy_at, Capability, LabelSet}; + use crate::test_support::{facts, measured_at, METRIC}; + use crate::{row_accuracy, Capability, LabelSet}; use std::collections::BTreeSet; fn cms(rows: u64, cols: u64) -> AtomicCostEntry { @@ -359,8 +359,8 @@ mod tests { "precision_at_k".into(), 1.0 - 1.0 / (rows * cols) as f64, )]), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "precision_at_k".into(), + measured_at: measured_at(), } } @@ -386,7 +386,7 @@ mod tests { } fn table_accuracy(_: &Raqe, config: &AtomicCostEntry) -> Option { - Some(table_accuracy_at(config, 1)) + Some(row_accuracy(config)) } fn cheapest_feasible(raqe: &Raqe, costs: &[AtomicCostEntry]) -> usize { @@ -498,8 +498,8 @@ mod tests { merge_cpu_secs: 1e-6, query_cpu_secs: 1e-6, query_accuracy: BTreeMap::from([("mean_rank_err".into(), 1.0 / k as f64)]), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "mean_rank_err".into(), + measured_at: measured_at(), } } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 8dd3503f..e314e32d 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -371,7 +371,7 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A #[cfg(test)] mod tests { use super::*; - use crate::test_support::{facts, perfect_accuracy, METRIC}; + use crate::test_support::{facts, measured_at, metric_of, perfect_accuracy, METRIC}; use crate::{table_accuracy, LabelSet}; use std::collections::BTreeMap; fn raqe(id: &str, lookback: Millis, interval: Millis) -> Raqe { @@ -396,79 +396,11 @@ mod tests { merge_cpu_secs: 1.0, query_cpu_secs: 1.0, query_accuracy: perfect_accuracy(), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "precision_at_k".into(), + measured_at: measured_at(), } } #[test] - fn eligibility_checks_accuracy_at_the_queries_merge_count() { - let mut config = cost(); - let precision = |v: f64| BTreeMap::from([("precision_at_k".into(), v)]); - // Precision is not monotone in the count: 16 is worse than 4 and 64. - config.merge_accuracy = BTreeMap::from([ - (4, precision(0.8)), - (16, precision(0.1)), - (64, precision(0.7)), - ]); - let at_window = |window_ms| Deployment { - capability: Capability::TopKByValue, - metric: METRIC.into(), - spatial_filter: String::new(), - grouping_labels: LabelSet::new(), - config: config.clone(), - window_ms, - slide_ms: window_ms, - key_tracker: None, - }; - let r = raqe("a", 60_000, 60_000); - // One window reads query_accuracy; 2 reads 1 and 4; 4 reads 4 alone. - assert!(is_eligible( - &r, - &at_window(60_000), - &facts(1, 1), - &table_accuracy - )); - assert!(is_eligible( - &r, - &at_window(30_000), - &facts(1, 1), - &table_accuracy - )); - assert!(is_eligible( - &r, - &at_window(15_000), - &facts(1, 1), - &table_accuracy - )); - // 12 and 20 merges bracket the bad count 16 from either side; 60 - // reads 16 and 64, so it fails too even though 64 alone passes. - assert!(!is_eligible( - &r, - &at_window(5_000), - &facts(1, 1), - &table_accuracy - )); - assert!(!is_eligible( - &r, - &at_window(3_000), - &facts(1, 1), - &table_accuracy - )); - assert!(!is_eligible( - &r, - &at_window(1_000), - &facts(1, 1), - &table_accuracy - )); - // Past the largest count reads only 64. - assert!(is_eligible( - &r, - &at_window(500), - &facts(1, 1), - &table_accuracy - )); - } - #[test] fn shared_slide_comes_from_subset_gcd_not_all_divisors() { let raqes = vec![raqe("a", 60_000, 20_000), raqe("b", 60_000, 30_000)]; let candidates = @@ -527,6 +459,7 @@ mod tests { }; let named = |sketch: &str| AtomicCostEntry { sketch: sketch.into(), + accuracy_metric: metric_of(sketch), ..cost() }; let candidates = build_all_candidates( @@ -545,6 +478,7 @@ mod tests { let r = raqe("r", 60_000, 60_000); let named = |sketch: &str| AtomicCostEntry { sketch: sketch.into(), + accuracy_metric: metric_of(sketch), ..cost() }; let costs = [ diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index d7873381..ea44cfdb 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -127,9 +127,8 @@ pub fn for_each_mapping_while( mod tests { use super::*; use crate::candidates; - use crate::test_support::{facts, perfect_accuracy, METRIC}; + use crate::test_support::{facts, measured_at, perfect_accuracy, METRIC}; use crate::{table_accuracy, AtomicCostEntry, Capability, Deployment, LabelSet}; - use std::collections::BTreeMap; fn cost(sketch: &str) -> AtomicCostEntry { AtomicCostEntry { @@ -140,8 +139,8 @@ mod tests { merge_cpu_secs: 1.0, query_cpu_secs: 1.0, query_accuracy: perfect_accuracy(), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "precision_at_k".into(), + measured_at: measured_at(), } } diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 31e68f67..e5e811bb 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -66,7 +66,8 @@ impl Capability { /// `AtomicCostEntry.sketch` values serving this capability. These are /// sketch-bench *variant* strings, not algorithm names: fastpath and /// regularpath have different cost profiles, so `"cms"` would be - /// ambiguous. Lists only what `export_rqe_optimizer_costs.sh` measures; + /// ambiguous. Lists what `study_saturation.py --phase optimizer-cost` + /// measures, plus families it doesn't run yet; /// an unmeasured name here is harmless, it just matches no row. pub fn families(self) -> &'static [&'static str] { match self { @@ -148,8 +149,8 @@ pub struct FamilyProperties { } /// Panics on a variant with no entry: guessing would misprice it. -/// Accuracy keys mirror the comparator `export_rqe_optimizer_costs.sh` runs -/// per variant. +/// Accuracy keys are the metrics `study_saturation.py` records per variant, +/// which every cost-table row names as its `accuracy_metric`. pub fn family_properties(variant: &str) -> FamilyProperties { use AccuracyDirection::{HigherIsBetter, LowerIsBetter}; let one_sketch_per_group = |metric, direction| FamilyProperties { @@ -377,56 +378,28 @@ pub fn accuracy_key(sketch: &str) -> (&'static str, AccuracyDirection) { /// [`saturation::SaturationCurves::accuracy`]. pub type Accuracy<'a> = dyn Fn(&Raqe, &Deployment) -> Option + 'a; -/// The cost table's measured value after the query's `L / x` merges, which is -/// the exact accumulators' accuracy. -pub fn table_accuracy(raqe: &Raqe, deployment: &Deployment) -> Option { - Some(table_accuracy_at( - &deployment.config, - raqe.lookback_ms / deployment.window_ms, - )) +/// The cost table's measured value, which is the exact accumulators' +/// accuracy: they merge without loss, so the window size doesn't matter. +pub fn table_accuracy(_raqe: &Raqe, deployment: &Deployment) -> Option { + Some(row_accuracy(&deployment.config)) } -/// The worse of `config`'s scores at the two measured counts bracketing -/// `merges` (error is not monotone in the count), in its family's -/// [`accuracy_key`]. Panics when either lacks it: the family table names -/// the metric, so its absence means the cost export is broken. -pub fn table_accuracy_at(config: &AtomicCostEntry, merges: u64) -> f64 { - let (metric, direction) = accuracy_key(&config.sketch); - let [below, above] = accuracy_at(config, merges).map(|scores| { - *scores.get(metric).unwrap_or_else(|| { - panic!( - "{} {} has no {metric}; the cost export is broken \ - (dd omits it when every true quantile is 0 or unanswered)", - config.sketch, config.sketch_config - ) - }) - }); - match direction { - AccuracyDirection::LowerIsBetter => below.max(above), - AccuracyDirection::HigherIsBetter => below.min(above), - } -} - -/// `config`'s scores at the two measured merge counts bracketing `merges`: -/// the largest at or below it (count 1 is `query_accuracy`), and the smallest -/// at or above it, else the largest measured. One window, or a row with no -/// merge measurements, reads the single-instance scores for both. -pub fn accuracy_at(config: &AtomicCostEntry, merges: u64) -> [&BTreeMap; 2] { - let single = &config.query_accuracy; - if merges <= 1 { - return [single, single]; - } - let measured = &config.merge_accuracy; - let below = measured - .range(..=merges) - .next_back() - .map_or(single, |(_, scores)| scores); - let above = measured - .range(merges..) - .next() - .or_else(|| measured.last_key_value()) - .map_or(single, |(_, scores)| scores); - [below, above] +/// `config`'s accuracy: its `query_accuracy[accuracy_metric]`. Panics when +/// `accuracy_metric` isn't its family's [`accuracy_key`] or the score is +/// missing: either means the cost export is broken. +pub fn row_accuracy(config: &AtomicCostEntry) -> f64 { + let (metric, _) = accuracy_key(&config.sketch); + assert_eq!( + config.accuracy_metric, metric, + "{} {}: the row's accuracy_metric isn't its family's; the cost export is broken", + config.sketch, config.sketch_config + ); + config.accuracy().unwrap_or_else(|| { + panic!( + "{} {} has no {metric}; the cost export is broken", + config.sketch, config.sketch_config + ) + }) } /// A candidate deployment (§3): one configuration, one grouped stream, and a @@ -509,6 +482,22 @@ pub(crate) mod test_support { .collect() } + /// The accuracy metric a row of `sketch` names: its family's. + pub fn metric_of(sketch: &str) -> String { + accuracy_key(sketch).0.to_string() + } + + /// Where a fixture row was "measured": the cost table's canonical point. + pub fn measured_at() -> aqpbm_core::MeasuredAt { + aqpbm_core::MeasuredAt { + items_per_instance: 1_000_000, + keys_per_instance: Some(10_000), + value_range: None, + merge_operand_items: None, + distribution: None, + } + } + /// `groups` groups and `series` raw series scraped every second, so /// `λ = series`. Not validated: unit tests set `groups` freely. pub fn facts(groups: u64, series: u64) -> WorkloadFacts { @@ -561,8 +550,8 @@ pub(crate) mod test_support { merge_cpu_secs: merge, query_cpu_secs: query, query_accuracy: perfect_accuracy(), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: "precision_at_k".into(), + measured_at: measured_at(), }, window_ms, slide_ms, @@ -580,52 +569,6 @@ mod tests { names.iter().map(|s| s.to_string()).collect() } - #[test] - fn accuracy_at_reads_both_measured_merge_counts_bracketing_the_query() { - let mut config = deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config; - let scores = |v: f64| BTreeMap::from([("err".to_string(), v)]); - let at = |c: &AtomicCostEntry, merges| accuracy_at(c, merges).map(|s| s["err"]); - config.query_accuracy = scores(0.0); - // No merge measurements: every count reads the single instance. - assert_eq!(at(&config, 60), [0.0, 0.0]); - config.merge_accuracy = - BTreeMap::from([(4, scores(4.0)), (16, scores(16.0)), (64, scores(64.0))]); - assert_eq!(at(&config, 0), [0.0, 0.0]); - assert_eq!(at(&config, 1), [0.0, 0.0]); - // Below the smallest measured count, the lower bracket is count 1. - assert_eq!(at(&config, 2), [0.0, 4.0]); - assert_eq!(at(&config, 4), [4.0, 4.0]); - assert_eq!(at(&config, 5), [4.0, 16.0]); - assert_eq!(at(&config, 64), [64.0, 64.0]); - assert_eq!(at(&config, 1_000), [64.0, 64.0]); - } - - /// Both brackets must pass in the metric's own direction: top-k precision - /// is higher-is-better, and a bad count between two good ones fails. - #[test] - fn both_brackets_must_clear_a_higher_is_better_metric() { - let mut config = deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config; - let precision = |v: f64| BTreeMap::from([("precision_at_k".to_string(), v)]); - config.query_accuracy = precision(1.0); - config.merge_accuracy = BTreeMap::from([ - (4, precision(0.97)), - (16, precision(0.8)), - (64, precision(1.0)), - ]); - let r = Raqe { - accuracy_sla: 0.9, - ..raqe(60_000, 60_000) - }; - let ok = |merges| r.meets_sla(&config.sketch, Some(table_accuracy_at(&config, merges))); - assert!(ok(1)); - assert!(ok(4)); - assert!(!ok(8)); // [4, 16]: 16 fails - assert!(!ok(16)); - assert!(!ok(32)); // [16, 64] - assert!(ok(64)); - assert!(ok(5_000)); // beyond: [64, 64] - } - /// One quantile SLA: KLL is checked by rank error, DD by relative value /// error, each against the same number. #[test] @@ -638,9 +581,10 @@ mod tests { let row = |sketch: &str, metric: &str, value: f64| AtomicCostEntry { sketch: sketch.into(), query_accuracy: BTreeMap::from([(metric.to_string(), value)]), + accuracy_metric: metric.to_string(), ..deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config }; - let ok = |c: AtomicCostEntry| r.meets_sla(&c.sketch, Some(table_accuracy_at(&c, 1))); + let ok = |c: AtomicCostEntry| r.meets_sla(&c.sketch, Some(row_accuracy(&c))); assert!(ok(row("kll-percall", "mean_rank_err", 0.01))); assert!(!ok(row("kll-percall", "mean_rank_err", 0.1))); assert!(ok(row("dd", "mean_relative_value_error", 0.01))); @@ -655,9 +599,24 @@ mod tests { let config = AtomicCostEntry { sketch: "dd".into(), query_accuracy: BTreeMap::from([("mean_rank_err".to_string(), 0.0)]), + accuracy_metric: "mean_relative_value_error".into(), + ..deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config + }; + row_accuracy(&config); + } + + /// The row's declared metric is the one read, and it must be the + /// family's: a row naming another is a broken export, not a guess. + #[test] + #[should_panic(expected = "the row's accuracy_metric isn't its family's")] + fn a_row_naming_another_metric_panics() { + let config = AtomicCostEntry { + sketch: "kll-percall".into(), + query_accuracy: BTreeMap::from([("max_rank_err".to_string(), 0.0)]), + accuracy_metric: "max_rank_err".into(), ..deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config }; - table_accuracy_at(&config, 1); + row_accuracy(&config); } #[test] diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index cc986e8c..605b791d 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -337,6 +337,7 @@ mod tests { }); let costs = [AtomicCostEntry { sketch: sketch.into(), + accuracy_metric: crate::test_support::metric_of(sketch), ..deployment(1.0, 1.0, 1.0).config }]; let candidates = build_all_candidates(&raqes, &costs, &facts(1, 1), false, &table_accuracy); diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index beda553b..aafbf46a 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -10,7 +10,8 @@ //! //! The cost table's sketch accuracies are not read: each is one point on a //! curve, at the row's `measured_at`, and [`SaturationCurves::check_cost_table`] -//! checks that the two agree there (#171). +//! checks that the two agree there (#171). Both come from one study run +//! (`study_saturation.py --phase optimizer-cost`, #174). use std::collections::BTreeMap; use std::io; @@ -41,6 +42,10 @@ pub struct DataShape { /// both is taken whole from the later one. const RUN_DIRS: [&str; 2] = ["out_grid_1e7_cost", "out_1e9"]; +/// The cost table under the same directory, written by +/// `study_saturation.py --phase optimizer-cost --out DIR/optimizer_cost`. +pub const COST_TABLE: &str = "optimizer_cost/rqe_atomic_costs.json"; + /// One (sketch, config, data shape) point of the study. #[derive(Debug, Clone, PartialEq)] struct GridPoint { @@ -127,6 +132,13 @@ impl GridPoint { } } +/// Whether some capability plans `sketch`. +fn is_candidate(sketch: &str) -> bool { + Capability::ALL + .iter() + .any(|capability| capability.families().contains(&sketch)) +} + fn worse(a: f64, b: f64, direction: AccuracyDirection) -> f64 { match direction { AccuracyDirection::LowerIsBetter => a.max(b), @@ -182,10 +194,7 @@ impl SaturationCurves { curve: Vec::new(), }; let sketch = row["sketch"].as_str(); - let is_candidate = Capability::ALL - .iter() - .any(|capability| capability.families().contains(&sketch)); - if is_candidate && point.error_metric != accuracy_key(sketch).0 { + if is_candidate(sketch) && point.error_metric != accuracy_key(sketch).0 { return Err(invalid(format!( "{run}: {sketch} curve measured {}, but the optimizer reads {}; \ rerun the study", @@ -268,18 +277,31 @@ impl SaturationCurves { self.accuracy(raqe, &deployment, facts) } - /// Checks the cost table against the curves: a sketch row's - /// `query_accuracy` is the curve of its config and - /// `measured_at.data_shape()`, read at `measured_at.items_per_instance`. + /// Checks the cost table against the family table and the curves. A + /// candidate family's row must name the family's metric as its + /// `accuracy_metric`. A sketch row's accuracy is the curve of its config + /// and `measured_at.data_shape()`, read at `measured_at.items_per_instance`. /// Rows of sketches the study didn't run (exact accumulators among them) - /// are skipped. + /// skip the curve check. pub fn check_cost_table(&self, costs: &[AtomicCostEntry]) -> CostTableCheck { let mut check = CostTableCheck::default(); for row in costs { + let name = format!("{} {}", row.sketch, row.sketch_config["params"]); + let metric = &row.accuracy_metric; + if is_candidate(&row.sketch) { + if let Some((family_metric, _)) = family_properties(&row.sketch).accuracy { + if metric != family_metric { + check.mismatched.push(format!( + "{name}: accuracy_metric is {metric}, but the optimizer reads \ + {family_metric}" + )); + continue; + } + } + } let Some(points) = self.points_by_sketch.get(&row.sketch) else { continue; }; - let name = format!("{} {}", row.sketch, row.sketch_config["params"]); let params = config_params(row); let mut same_config = points .iter() @@ -291,25 +313,27 @@ impl SaturationCurves { .push(format!("{name}: config not in the saturation grid")); continue; } - let Some(measured_at) = &row.measured_at else { - check.unchecked.push(format!("{name}: no measured_at")); - continue; - }; - let shape = measured_at.data_shape(); + let shape = row.measured_at.data_shape(); let Some(point) = same_config.find(|point| Some(point.shape) == shape) else { check .unchecked .push(format!("{name}: no grid point at {shape:?}")); continue; }; - let metric = &point.error_metric; - let Some(&value) = row.query_accuracy.get(metric) else { + if &point.error_metric != metric { + check.mismatched.push(format!( + "{name}: accuracy_metric is {metric}, the curve's {}", + point.error_metric + )); + continue; + } + let Some(value) = row.accuracy() else { check .mismatched .push(format!("{name}: the table has no {metric}")); continue; }; - let n = measured_at.items_per_instance as f64; + let n = row.measured_at.items_per_instance as f64; match point.agrees_at(n, value) { None => check .unchecked @@ -520,8 +544,8 @@ mod tests { merge_cpu_secs: 1.0, query_cpu_secs: 1.0, query_accuracy: BTreeMap::from([("precision_at_k".into(), 1.0)]), - merge_accuracy: BTreeMap::new(), - measured_at: None, + accuracy_metric: crate::test_support::metric_of(sketch), + measured_at: crate::test_support::measured_at(), }, window_ms, slide_ms: window_ms, @@ -600,7 +624,7 @@ mod tests { AtomicCostEntry { sketch_config: serde_json::json!({"params": {"rows": 3, "cols": cols}}), query_accuracy: BTreeMap::from([("precision_at_k".into(), precision)]), - measured_at: Some(MeasuredAt { + measured_at: MeasuredAt { items_per_instance: items, keys_per_instance: Some(1_000), value_range: None, @@ -610,7 +634,7 @@ mod tests { population_size: 1_000, seed: 1, })), - }), + }, ..deployment(TOPK, 1).config } } @@ -639,18 +663,30 @@ mod tests { ); assert_eq!(check(&[measured_row(1024, 100, 0.95)]).unchecked.len(), 1); let mut pareto = measured_row(1024, 10_000, 0.95); - pareto.measured_at.as_mut().unwrap().distribution = None; + pareto.measured_at.distribution = None; assert_eq!(check(&[pareto]).unchecked.len(), 1); - // A table without the curve's metric is a mismatch. + // A row naming another metric than its family's is a mismatch. let mut other_metric = measured_row(1024, 10_000, 0.95); other_metric.query_accuracy = BTreeMap::from([("recall_at_k".into(), 0.95)]); + other_metric.accuracy_metric = "recall_at_k".into(); assert_eq!(check(&[other_metric]).mismatched.len(), 1); - // Sketches the study didn't run, exact ones among them, are skipped. + // Sketches the study didn't run, exact ones among them, skip the + // curve, but still name their family's metric. let exact = AtomicCostEntry { sketch: "exact-sum".into(), + query_accuracy: BTreeMap::from([("relative_error".into(), 0.0)]), + accuracy_metric: "relative_error".into(), ..measured_row(1024, 10_000, 0.0) }; - assert_eq!(check(&[exact]), CostTableCheck::default()); + assert_eq!( + check(std::slice::from_ref(&exact)), + CostTableCheck::default() + ); + let misnamed = AtomicCostEntry { + accuracy_metric: "relative_error_mean".into(), + ..exact + }; + assert_eq!(check(&[misnamed]).mismatched.len(), 1); } #[test] diff --git a/scripts/export_atomic_costs.sh b/scripts/export_atomic_costs.sh index 0b7b6672..1f0e3c1f 100755 --- a/scripts/export_atomic_costs.sh +++ b/scripts/export_atomic_costs.sh @@ -80,49 +80,39 @@ KLL_KS=(200 500) # comparator. Both write raw (non-`--flat`) records to the same file; `flatten` # below folds the two passes of one grid point back into one row. # -# Accuracy first, cost second — order matters. `BenchReport::from_runs` sets -# every square's own wall_time_ms/cpu_time_ms unconditionally, not just the -# metric that was asked for, and accuracy always runs exactly 1 sample -# (`aqpbm_core::runs_for`) regardless of `--runs`. `flatten_record`'s merge is -# last-square-wins per field, so whichever pass is written second decides -# query's wall_time_ms/cpu_time_ms. Cost must win that, since query_cpu_secs -# pairs them against query's throughput samples (`atomic_costs.rs`) — pairing -# them against accuracy's unrelated single-sample timing instead skips the row -# ("query rate/elapsed/cpu_time sample counts disagree"). query.accuracy -# itself is unaffected by the order: only the accuracy square ever sets it. +# Cost first, accuracy second — order matters. `BenchReport::from_runs` sets +# every square's own wall_time_ms/cpu_time_ms, not just the metric asked for, +# and `flatten_record` keeps the first value of each shared field. Cost must +# be first, since query_cpu_secs pairs those timings with query's throughput +# samples (`atomic_costs.rs`); the accuracy pass's single-sample timing would +# skip the row ("query rate/elapsed/cpu_time sample counts disagree"). +# Accuracy scores one run (`aqpbm_core::runs_for`), and warm-ups don't change +# it, so that pass runs once with none. point() { local algorithm=$1 config=$2 comparator=$3 echo " $algorithm ($config)" >&2 + local data=(--dataset uniform --size "$SIZE" --cardinality "$CARDINALITY" + --dtype i64 --seed "$SEED" --report "$RAW_JSONL") "$BINARY" sketchbench \ --variant "$algorithm" \ --library lib \ --config "$config" \ - --operations query \ - --metrics accuracy \ - --comparator "$comparator" \ + --operations insert,query,merge \ + --metrics throughput,cpu,memory \ + --merge-shards "$MERGE_SHARDS" \ --runs "$RUNS" \ --warmup-runs "$WARMUP" \ - --dataset uniform \ - --size "$SIZE" \ - --cardinality "$CARDINALITY" \ - --dtype i64 \ - --seed "$SEED" \ - --report "$RAW_JSONL" + "${data[@]}" "$BINARY" sketchbench \ --variant "$algorithm" \ --library lib \ --config "$config" \ - --operations insert,query,merge \ - --metrics throughput,cpu,memory \ - --merge-shards "$MERGE_SHARDS" \ - --runs "$RUNS" \ - --warmup-runs "$WARMUP" \ - --dataset uniform \ - --size "$SIZE" \ - --cardinality "$CARDINALITY" \ - --dtype i64 \ - --seed "$SEED" \ - --report "$RAW_JSONL" + --operations query \ + --metrics accuracy \ + --comparator "$comparator" \ + --runs 1 \ + --warmup-runs 0 \ + "${data[@]}" } echo "==> cms-fastpath-vector2d (CMS_DEPTHS x CMS_WIDTHS)" >&2 @@ -146,7 +136,18 @@ echo "==> Flattening cost + accuracy passes into one row per grid point..." >&2 "$BINARY" flatten "$RAW_JSONL" --output "$GRID_JSONL" echo "==> Reducing to atomic-cost table..." >&2 -"$BINARY" atomic-costs "$GRID_JSONL" --output "$TABLE_JSON" +# Each row names its accuracy: the metric the saturation study records for +# the variant (scripts/study_saturation.py SKETCHES). A skipped row is a +# failed measurement; fail rather than publish a short table. +summary=$("$BINARY" atomic-costs "$GRID_JSONL" --output "$TABLE_JSON" \ + --accuracy-metric cms-fastpath-vector2d=are_top100 \ + --accuracy-metric hll=relative_error \ + --accuracy-metric kll-percall=mean_rank_err \ + 2>&1 | tee /dev/stderr | tail -n 1) +if [[ "$summary" != *", 0 skipped" ]]; then + echo "ERROR: atomic-costs skipped rows; see the reasons above." >&2 + exit 1 +fi echo "" >&2 echo "Done. $TABLE_JSON" >&2 diff --git a/scripts/export_rqe_optimizer_costs.sh b/scripts/export_rqe_optimizer_costs.sh deleted file mode 100755 index 9d2cb55e..00000000 --- a/scripts/export_rqe_optimizer_costs.sh +++ /dev/null @@ -1,206 +0,0 @@ -#!/usr/bin/env bash -# Measure the small atomic-cost grid consumed by rqe-optimizer. -# -# This is intentionally separate from export_atomic_costs.sh: that script -# serves ASAPQuery's pinned grid, while this one covers the variants named by -# rqe_optimizer::Capability::families(). Only those also in -# DEPLOYABLE_FAMILIES become candidates; the rest are measured for when the -# engine gains them, and for research baselines. -# -# Usage: -# scripts/export_rqe_optimizer_costs.sh OUT_DIR -# scripts/export_rqe_optimizer_costs.sh OUT_DIR --no-build -# -# OUT_DIR must not exist yet, so a run never overwrites earlier measurements. - -set -euo pipefail - -BUILD=1 -OUT_DIR= -for arg in "$@"; do - case "$arg" in - --no-build) BUILD=0 ;; - -*) echo "ERROR: unknown flag $arg" >&2; exit 1 ;; - *) - [[ -z "$OUT_DIR" ]] || { echo "ERROR: more than one OUT_DIR given" >&2; exit 1; } - OUT_DIR=$arg - ;; - esac -done -if [[ -z "$OUT_DIR" ]]; then - echo "Usage: $0 OUT_DIR [--no-build]" >&2 - exit 1 -fi -if [[ -e "$OUT_DIR" ]]; then - echo "ERROR: $OUT_DIR already exists; pick a new directory." >&2 - exit 1 -fi - -RAW_JSONL="$OUT_DIR/rqe_atomic_costs_raw.jsonl" -GRID_JSONL="$OUT_DIR/rqe_atomic_costs_grid.jsonl" -MERGE_ACCURACY_JSONL="$OUT_DIR/rqe_merge_accuracy_grid.jsonl" -TABLE_JSON="$OUT_DIR/rqe_atomic_costs.json" -mkdir -p "$OUT_DIR" - -if [[ $BUILD -eq 1 ]]; then - echo "==> Building approxbench (release)..." >&2 - cargo build -p aqpbm-cli --release -fi - -BINARY=./target/release/approxbench -if [[ ! -x "$BINARY" ]]; then - echo "ERROR: $BINARY not found. Run without --no-build." >&2 - exit 1 -fi - -RUNS=5 -WARMUP=3 -SIZE=1000000 -CARDINALITY=100000 -SEED=42 -MERGE_SHARDS=16 -# Accuracy after folding m shards, for the optimizer's L/x windows per query. -# One shard is the accuracy pass's single instance. The same stream is split m -# ways (fixed total): for a fixed query L, choosing x splits the query's total -# over L/x windows. Beyond the largest count the optimizer reads the largest. -# Accuracy is scored once, so each merge pass runs once with no warm-up. On the -# 200k-row specs, 1024 shards of ceil(200000/1024) rows come out as 1021. -MERGE_ACCURACY_SHARDS=(4 16 64 256 1024) - -# The swept parameters, every one of them. Exact accumulators take none. -# Sketch configs are points of the saturation grid (scripts/study_saturation.py): -# the optimizer reads their accuracy from its curves, and a config with no -# curve is never eligible (#156). -HLL_PRECISIONS=(12 14) -KLL_KS=(200 800) -DD_ALPHAS=(0.01 0.02) -CMS_HEAP_ROWS=(3 5) -CMS_HEAP_COLS=(1024 4096) -UNIVMON_CONFIGS=( - "heap_size=1000 sketch_row=5 sketch_col=2048 layer_size=8" - "heap_size=500 sketch_row=3 sketch_col=1024 layer_size=6" -) -HYDRA_KLL_CONFIGS=( - "rows=3 cols=128 cell_k=200" - "rows=3 cols=256 cell_k=200" - "rows=3 cols=512 cell_k=200" - "rows=5 cols=256 cell_k=200" - "rows=3 cols=256 cell_k=500" -) - -# One row: a cost pass, an accuracy pass, then one merge-accuracy pass per -# merge count, over the same data. Arguments -# after the comparator name the data (`--dataset ...` or `--spec ...`, plus -# `--dtype`). An empty config omits `--config` (the exact accumulators). -measure() { - local variant=$1 library=$2 config=$3 comparator=$4 - shift 4 - local config_args=() - [[ -n "$config" ]] && config_args=(--config "$config") - echo " $variant${config:+ ($config)}" >&2 - - # Cost goes first. Secondary query timings accompany both passes, and - # flattening retains the first one; this preserves the five-sample cost - # timings that atomic-costs pairs with query throughput. - "$BINARY" sketchbench \ - --variant "$variant" --library "$library" "${config_args[@]}" \ - --operations insert,query,merge --metrics throughput,cpu,memory \ - --merge-shards "$MERGE_SHARDS" --runs "$RUNS" --warmup-runs "$WARMUP" \ - "$@" --seed "$SEED" --report "$RAW_JSONL" - "$BINARY" sketchbench \ - --variant "$variant" --library "$library" "${config_args[@]}" \ - --operations query --metrics accuracy --comparator "$comparator" \ - --runs "$RUNS" --warmup-runs "$WARMUP" \ - "$@" --seed "$SEED" --report "$RAW_JSONL" - # One `--flat` row per merge count: a cell's counts would collide in - # `flatten`, which keeps one merge slot per cell. atomic-costs joins them. - local m - for m in "${MERGE_ACCURACY_SHARDS[@]}"; do - "$BINARY" sketchbench \ - --variant "$variant" --library "$library" "${config_args[@]}" \ - --operations merge --metrics accuracy --comparator "$comparator" \ - --merge-shards "$m" --runs 1 --warmup-runs 0 \ - "$@" --seed "$SEED" --flat --report "$MERGE_ACCURACY_JSONL" - done -} - -# One-column sketches on inline data. Zipf is deliberate. Uniform data makes -# request-rate relative error meaningless in the rare-key tail and makes top-k -# accuracy degenerate. -point() { - local variant=$1 config=$2 comparator=$3 - measure "$variant" lib "$config" "$comparator" \ - --dataset zipf --zipf-s 1.1 --size "$SIZE" --cardinality "$CARDINALITY" \ - --dtype i64 -} - -# Rows that need a multi-column spec: grouped records for the exact -# accumulators and Hydra, key/value pairs for UnivMon cardinality. -point_spec() { - local variant=$1 library=$2 config=$3 comparator=$4 spec=$5 dtype=$6 - measure "$variant" "$library" "$config" "$comparator" --spec "$spec" --dtype "$dtype" -} - -# Exact accumulators live under library "exact" and take no config. Increase -# reads counters; the rest read grouped i64 records. -echo "==> Exact accumulators: sum, min, max, increase, delta set" >&2 -point_spec exact-sum exact "" sum-or-count configs/datagen/hydra_columns.yaml i64 -point_spec exact-min exact "" min configs/datagen/hydra_columns.yaml i64 -point_spec exact-max exact "" max configs/datagen/hydra_columns.yaml i64 -point_spec exact-increase exact "" rate-or-increase configs/datagen/counter_columns.yaml i64 -point_spec exact-delta-set exact "" key-set configs/datagen/hydra_columns.yaml i64 - -# HydraKLL rows are whole-sketch: one instance serves every group, and memory -# and merge cost are not divided per group (`subpop-rank-error` reports no -# `groups_per_instance`). The optimizer prices them as one shared fixed-size -# sketch, not card(G) instances, and plans them only up to the `subpopulations` -# they were measured at. The keys fan out to every label subset, unlike the -# single-key sketch the optimizer models (#165). The spec gives each label its -# own alphabet, so rank error is the sketch's, not label collisions' (#74). -echo "==> Quantiles: KLL, DDSketch, HydraKLL" >&2 -for k in "${KLL_KS[@]}"; do - point kll-percall "k=$k" rank-error -done -for alpha in "${DD_ALPHAS[@]}"; do - point dd "alpha=$alpha" relative-value-error -done -for config in "${HYDRA_KLL_CONFIGS[@]}"; do - point_spec hydra-kll lib "$config" subpop-rank-error \ - configs/datagen/hydra_kll_disjoint_labels.yaml f64 -done - -echo "==> Cardinality: HLL and UnivMon" >&2 -for lg_k in "${HLL_PRECISIONS[@]}"; do - point hll "lg_k=$lg_k" cardinality -done -for config in "${UNIVMON_CONFIGS[@]}"; do - point_spec univmon-cardinality lib "$config" keyed-cardinality \ - configs/datagen/univmon_columns.yaml u64 -done - -echo "==> Top-k: CMS heap, CountSketch heap, UnivMon" >&2 -for rows in "${CMS_HEAP_ROWS[@]}"; do - for cols in "${CMS_HEAP_COLS[@]}"; do - point cms-heap-topk-fastpath-vector2d "rows=$rows cols=$cols" topk - point countsketch-heap-topk-fastpath-vector2d "rows=$rows cols=$cols" topk - done -done -for config in "${UNIVMON_CONFIGS[@]}"; do - point univmon-topk "$config" topk -done - -echo "==> Flattening cost + accuracy passes..." >&2 -"$BINARY" flatten "$RAW_JSONL" --output "$GRID_JSONL" - -echo "==> Reducing to atomic-cost table (expect 24 row(s), 0 skipped)..." >&2 -# A skipped row is a failed measurement, e.g. an exact row that missed a group -# scores an infinite error, which JSON holds as null. Fail rather than publish -# a table that is silently short. -summary=$("$BINARY" atomic-costs "$GRID_JSONL" --merge-accuracy "$MERGE_ACCURACY_JSONL" \ - --output "$TABLE_JSON" 2>&1 | tee /dev/stderr | tail -n 1) -if [[ "$summary" != *", 0 skipped" ]]; then - echo "ERROR: atomic-costs skipped rows; see the reasons above." >&2 - exit 1 -fi - -echo "Done. $TABLE_JSON" >&2 diff --git a/scripts/study_saturation.py b/scripts/study_saturation.py index 0e3d0ec9..123cad49 100644 --- a/scripts/study_saturation.py +++ b/scripts/study_saturation.py @@ -11,12 +11,20 @@ Frequency, top-k and cardinality sketches run on Zipf(theta) over K keys; quantile sketches run on Pareto(alpha, scale 1000) floored to i64 (the exact quantile baseline is i64 only), which is unbounded, so K is blank. -`BENCH_WARMUP_SECS` defaults to 0 here: the cost numbers are indicative, and -scripts/export_rqe_optimizer_costs.sh stays the source of optimizer costs. +`BENCH_WARMUP_SECS` defaults to 0 here: the per-point cost numbers are +indicative. The optimizer's costs come from --phase optimizer-cost (#174). --phase accuracy runs only the (parallel) accuracy runs; --phase cost reads saturation_curve.csv from --out and runs only the serial cost runs, so CPU can be timed later on a quiet machine. Both take the same grid arguments. +--phase optimizer-cost measures each (sketch, config) of the families the +optimizer plans (OPTIMIZER_FAMILIES) once, serially, at one +shape (COST_*, the synthetic evaluation's dataset) with a cost and an +accuracy pass, plus the exact accumulators, and reduces them to +rqe_atomic_costs.json, the table rqe-optimizer loads; every row names its +accuracy_metric. It runs no curves and ignores the grid arguments. +The grid also holds every config at the optimizer-cost shape (Zipf 1.1 over +1e4 keys, Pareto a = 2) unless --no-cost-shape. --resume keeps the complete curves of an interrupted accuracy run; --cost-rows 3 times only the rows=3 Vector2D configs. @@ -32,6 +40,7 @@ saturation_merge_curve.csv with --merge-shards-list: seed-mean error per N of the sketch merged from m contiguous shards (m=1 is the plain single-sketch query) + rqe_atomic_costs.json (+ _raw, _grid .jsonl) --phase optimizer-cost only """ import argparse @@ -45,8 +54,8 @@ FREQ_CONFIGS = [f"rows={r} cols={c}" for r in (3, 5) for c in (256, 1024, 4096, 16384)] -# (family, variant, configs, comparator, error metric). Variants follow -# scripts/export_rqe_optimizer_costs.sh; configs step 4x in the size knob +# (family, variant, configs, comparator, error metric). The error metric is +# also the cost table's accuracy_metric; configs step 4x in the size knob # (asap HLL is compiled at lg_k 12, 14, 16 only, so it has no lg_k 10). SKETCHES = [ ("frequency", "cms-fastpath-vector2d", FREQ_CONFIGS, "frequency", "are_top100"), @@ -71,6 +80,32 @@ MERGE_SHARDS = 16 +# --phase optimizer-cost: the one data shape every sketch's cost is measured +# at, the synthetic evaluation's dataset (ProjectASAP/ASAPQuery#777): +# Zipf(1.1) over 1e4 keys, quantiles on Pareto(a = 2, scale 1000), 1e6 +# items. Cost is taken as independent of the shape (#174). +COST_THETA = 1.1 +COST_KEYS = 10_000 +COST_PARETO_ALPHA = 2.0 +COST_N = 1_000_000 +COST_RUNS, COST_WARMUP = 5, 3 +COST_SEED = 42 +COST_TABLE = "rqe_atomic_costs.json" +# Families some rqe-optimizer capability plans; frequency sketches serve none. +OPTIMIZER_FAMILIES = ("topk", "cardinality", "quantile") + +# Exact accumulators the optimizer plans, on grouped records (variant, +# comparator, datagen spec). Their error is 0 by construction; the accuracy +# pass checks it. They report the worst group's relative_error. +EXACT_COST_ROWS = [ + ("exact-sum", "sum-or-count", "configs/datagen/hydra_columns.yaml"), + ("exact-min", "min", "configs/datagen/hydra_columns.yaml"), + ("exact-max", "max", "configs/datagen/hydra_columns.yaml"), + ("exact-increase", "rate-or-increase", "configs/datagen/counter_columns.yaml"), + ("exact-delta-set", "key-set", "configs/datagen/hydra_columns.yaml"), +] +EXACT_METRIC = "relative_error" + SUMMARY_COLUMNS = [ "family", "sketch", "config", "dist", "param", "cardinality", "n_sat", "final_error", "error_metric", "insert_cpu_secs", "merge_cpu_secs", @@ -187,7 +222,9 @@ def read_curve(path, points, ns, tolerance, tail): curve = curves.get(point_key(p[1], p[2], *p[6:]), []) if [n for n, _, _ in curve] != ns: sys.exit(f"{path} has no curve over these sizes for {p[1]} ({p[2]}) " - f"{p[6]}={p[7]} K={p[8]}; pass the accuracy run's grid arguments") + f"{p[6]}={p[7]} K={p[8]}; pass the accuracy run's grid arguments " + "(an accuracy run without the optimizer-cost shape needs " + "--no-cost-shape)") means = [e for _, e, _ in curve] ses = [se for _, _, se in curve] results.append((p, n_saturation(ns, means, tolerance, tail, ses), means[-1])) @@ -240,6 +277,76 @@ def cpu_secs(record, op): return (cpu["user_ms"]["mean"] + cpu["sys_ms"]["mean"]) / 1000.0 +def cost_dataset(family): + """The approxbench data arguments of --phase optimizer-cost's shape.""" + if family == "quantile": + return ["--dataset", "pareto", "--pareto-alpha", str(COST_PARETO_ALPHA), + "--pareto-scale", "1000", "--cardinality", "1", "--dtype", "i64", + "--size", str(COST_N)] + return ["--dataset", "zipf", "--zipf-s", str(COST_THETA), "--cardinality", + str(COST_KEYS), "--dtype", "i64", "--size", str(COST_N)] + + +def optimizer_cost(args, families): + """The optimizer's cost table: one serial cost pass and one accuracy pass + per (sketch, config) at the COST_* shape, plus the exact accumulators, + reduced by `approxbench atomic-costs` to --out/COST_TABLE.""" + os.makedirs(args.out, exist_ok=True) + raw = os.path.join(args.out, "rqe_atomic_costs_raw.jsonl") + grid = os.path.join(args.out, "rqe_atomic_costs_grid.jsonl") + table = os.path.join(args.out, COST_TABLE) + for path in (raw, grid, table): + if os.path.exists(path): + sys.exit(f"{path} exists; pick a new --out") + + rows, metrics = [], {} + for family, variant, configs, comparator, metric in SKETCHES: + if family not in families or family not in OPTIMIZER_FAMILIES: + continue + metrics[variant] = metric + for config in configs[:1] if args.one_config else configs: + rows.append((variant, "lib", ["--config", config], comparator, + cost_dataset(family))) + for variant, comparator, spec in EXACT_COST_ROWS: + metrics[variant] = EXACT_METRIC + rows.append((variant, "exact", [], comparator, ["--spec", spec, "--dtype", "i64"])) + + def sketchbench(variant, library, config, data, passes): + subprocess.run( + [args.binary, "sketchbench", "--variant", variant, "--library", library] + + config + passes + data + ["--seed", str(COST_SEED), "--report", raw], + check=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) + + for variant, library, config, comparator, data in rows: + print(f" {variant} {' '.join(config[1:])}", file=sys.stderr) + # Cost first: flatten keeps the first pass's query timings. + sketchbench(variant, library, config, data, [ + "--operations", "insert,query,merge", "--metrics", "throughput,cpu,memory", + "--merge-shards", str(MERGE_SHARDS), "--runs", str(COST_RUNS), + "--warmup-runs", str(COST_WARMUP)]) + sketchbench(variant, library, config, data, [ + "--operations", "query", "--metrics", "accuracy", "--comparator", comparator, + "--runs", "1", "--warmup-runs", "0"]) + + subprocess.run([args.binary, "flatten", raw, "--output", grid], check=True) + reduce = subprocess.run( + [args.binary, "atomic-costs", grid, "--output", table] + + [arg for variant, metric in sorted(metrics.items()) + for arg in ("--accuracy-metric", f"{variant}={metric}")], + capture_output=True, text=True) + sys.stderr.write(reduce.stderr) + if reduce.returncode != 0: + sys.exit(f"atomic-costs failed (exit {reduce.returncode}); see above") + # A skipped row is a failed measurement; a short table must not pass. + lines = reduce.stderr.strip().splitlines() + summary = lines[-1] if lines else "" + expected = f"approxbench atomic-costs: {len(rows)} row(s), 0 skipped" + if summary != expected: + sys.exit(f"atomic-costs did not keep all {len(rows)} rows: {summary!r}") + print(f"Done. {table}", file=sys.stderr) + return 0 + + def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter @@ -252,6 +359,9 @@ def main(): parser.add_argument("--thetas", default="0,0.5,0.8,1.0,1.2,1.5,2.0") parser.add_argument("--cardinalities", default="1000,100000,10000000") parser.add_argument("--alphas", default="1.1,1.5,2,3") + parser.add_argument("--cost-shape", action=argparse.BooleanOptionalAction, default=True, + help="also run every config at --phase optimizer-cost's shape " + "(COST_*), so the cost table is a point on a curve") parser.add_argument("--n-min", type=float, default=1e3) parser.add_argument("--n-max", type=float, default=1e8) parser.add_argument("--per-decade", type=int, default=4) @@ -260,10 +370,13 @@ def main(): parser.add_argument("--plateau-tail", type=int, default=3) parser.add_argument("--jobs", type=int, default=1, help="parallel accuracy runs (cost runs are always serial)") - parser.add_argument("--phase", choices=["accuracy", "cost", "crossover", "all"], + parser.add_argument("--phase", + choices=["accuracy", "cost", "crossover", "all", "optimizer-cost"], default="all", help="cost reads saturation_curve.csv from --out; crossover " - "recomputes crossover.csv from the cost phase's JSONL in --out") + "recomputes crossover.csv from the cost phase's JSONL in --out; " + "optimizer-cost writes the optimizer's cost table to --out " + "(the grid's configs at one shape, no curves)") parser.add_argument("--points-from", help="CSV with sketch,config,dist,param,cardinality columns " "(e.g. a filtered saturation.csv): run only those points") @@ -285,6 +398,8 @@ def main(): ns = checkpoints(args.n_min, args.n_max, args.per_decade) seeds = list(range(1, args.seeds + 1)) shard_list = [int(m) for m in args.merge_shards_list.split(",") if m] + if args.phase == "optimizer-cost": + return optimizer_cost(args, families) os.environ.setdefault("BENCH_WARMUP_SECS", "0") os.makedirs(args.out, exist_ok=True) @@ -296,7 +411,8 @@ def main(): continue for config in configs[:1] if args.one_config else configs: if family == "quantile": - for alpha in alphas: + extra = args.cost_shape and COST_PARETO_ALPHA not in alphas + for alpha in alphas + [COST_PARETO_ALPHA] * extra: # --cardinality is required by the CLI but ignored for pareto. dataset = ["--dataset", "pareto", "--pareto-alpha", str(alpha), "--pareto-scale", "1000", "--cardinality", "1", @@ -304,12 +420,15 @@ def main(): points.append((family, variant, config, comparator, metric, dataset, "pareto", alpha, "")) continue - for theta in thetas: - for k in cardinalities: - dataset = ["--dataset", "zipf", "--zipf-s", str(theta), - "--cardinality", str(k), "--dtype", "i64"] - points.append((family, variant, config, comparator, metric, - dataset, "zipf", theta, k)) + # Plus the cost table's shape, so its rows are points on a curve. + shapes = [(t, k) for t in thetas for k in cardinalities] + if args.cost_shape and (COST_THETA, COST_KEYS) not in shapes: + shapes.append((COST_THETA, COST_KEYS)) + for theta, k in shapes: + dataset = ["--dataset", "zipf", "--zipf-s", str(theta), + "--cardinality", str(k), "--dtype", "i64"] + points.append((family, variant, config, comparator, metric, + dataset, "zipf", theta, k)) if args.points_from: with open(args.points_from, newline="") as f: wanted = {point_key(r["sketch"], r["config"], r["dist"], r["param"], @@ -446,7 +565,7 @@ def accuracy(point, n, seed, shards=1): merge_file.close() # Cost at the final N, one serial run per point with the merge setup of - # export_rqe_optimizer_costs.sh. --phase accuracy leaves these blank. + # --phase optimizer-cost. --phase accuracy leaves these blank. rows, records = [], [] cost = args.phase != "accuracy" rebuild = args.phase == "crossover" diff --git a/scripts/test_study_saturation.py b/scripts/test_study_saturation.py index b9b1d303..83263282 100644 --- a/scripts/test_study_saturation.py +++ b/scripts/test_study_saturation.py @@ -172,7 +172,7 @@ def run_study(self, d, points_csv): sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "accuracy", "--families", "cardinality", "--one-config", "--thetas", "0,1.0", "--cardinalities", "1000", "--n-max", "1e6", - "--per-decade", "1", "--seeds", "2", "--points-from", points_csv, + "--per-decade", "1", "--no-cost-shape", "--seeds", "2", "--points-from", points_csv, ], capture_output=True) def test_points_from_selects_points_and_cost_columns_stay_blank(self): @@ -203,7 +203,7 @@ def test_one_row_per_shard_count_and_one_is_the_plain_query(self): sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "accuracy", "--families", "cardinality", "--one-config", "--thetas", "1.0", "--cardinalities", "1000", "--n-max", "1e4", - "--per-decade", "1", "--seeds", "2", "--merge-shards-list", "4,1", + "--per-decade", "1", "--no-cost-shape", "--seeds", "2", "--merge-shards-list", "4,1", ], check=True, capture_output=True) with open(os.path.join(d, "saturation_merge_curve.csv"), newline="") as f: rows = list(csv.DictReader(f)) @@ -218,7 +218,7 @@ def test_without_the_flag_there_is_no_merge_curve(self): sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "accuracy", "--families", "cardinality", "--one-config", "--thetas", "1.0", "--cardinalities", "1000", "--n-max", "1e4", - "--per-decade", "1", "--seeds", "1", + "--per-decade", "1", "--no-cost-shape", "--seeds", "1", ], check=True, capture_output=True) self.assertFalse(os.path.exists(os.path.join(d, "saturation_merge_curve.csv"))) @@ -242,7 +242,7 @@ def test_keeps_complete_curves_and_reruns_the_rest(self): sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "accuracy", "--families", "cardinality", "--one-config", "--thetas", "0,1.0", "--cardinalities", "1000", "--n-max", "1e6", - "--per-decade", "1", "--seeds", "2", "--resume", + "--per-decade", "1", "--no-cost-shape", "--seeds", "2", "--resume", ], check=True, capture_output=True) with open(curve, newline="") as f: rows = list(csv.DictReader(f)) @@ -274,7 +274,7 @@ def test_a_point_without_its_merge_curve_is_rerun_without_duplicates(self): sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "accuracy", "--families", "cardinality", "--one-config", "--thetas", "0,1.0", "--cardinalities", "1000", "--n-max", "1e6", - "--per-decade", "1", "--seeds", "2", "--merge-shards-list", "1,4", + "--per-decade", "1", "--no-cost-shape", "--seeds", "2", "--merge-shards-list", "1,4", "--resume", ], check=True, capture_output=True) with open(os.path.join(d, "saturation_merge_curve.csv"), newline="") as f: @@ -300,7 +300,7 @@ def test_cost_rows_measures_only_that_rows_value(self): subprocess.run([ sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--phase", "cost", "--families", "frequency", "--thetas", "1.0", - "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1", + "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1", "--no-cost-shape", "--points-from", points, "--cost-rows", "3", ], check=True, capture_output=True) with open(os.path.join(d, "saturation.csv"), newline="") as f: @@ -321,7 +321,7 @@ def test_cost_phase_writes_crossover_from_an_existing_curve(self): subprocess.run([ sys.executable, SCRIPT, "--binary", binary, "--out", d, "--phase", "cost", "--families", "cardinality", "--one-config", "--thetas", "1.0", - "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1", + "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1", "--no-cost-shape", ], check=True, capture_output=True) with open(os.path.join(d, "crossover.csv"), newline="") as f: [row] = list(csv.DictReader(f)) @@ -347,7 +347,7 @@ def test_crossover_phase_rebuilds_from_saved_records(self): for n in ns]) args = [sys.executable, SCRIPT, "--binary", binary, "--out", d, "--families", "cardinality", "--one-config", "--thetas", "1.0", - "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1"] + "--cardinalities", "1000", "--n-max", "1e6", "--per-decade", "1", "--no-cost-shape"] subprocess.run(args + ["--phase", "cost"], check=True, capture_output=True) path = os.path.join(d, "crossover.csv") with open(path) as f: @@ -372,7 +372,7 @@ def test_crossover_phase_matches_saved_records_by_key(self): [["cms-fastpath-vector2d", c, "zipf", 1.0, 1000] for c in configs]) args = [sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, "--families", "frequency", "--thetas", "1.0", "--cardinalities", - "1000", "--n-max", "1e6", "--per-decade", "1", "--points-from", points] + "1000", "--n-max", "1e6", "--per-decade", "1", "--no-cost-shape", "--points-from", points] subprocess.run(args + ["--phase", "cost"], check=True, capture_output=True) # Tell the rows=5 record apart, and store it first. cost = os.path.join(d, "saturation_cost.jsonl") @@ -394,5 +394,73 @@ def test_crossover_phase_matches_saved_records_by_key(self): self.assertIn(b"has no record", missing.stderr) +class CostShapeTest(unittest.TestCase): + def test_the_grid_also_runs_the_optimizer_cost_shape(self): + with tempfile.TemporaryDirectory() as d: + subprocess.run([ + sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, + "--phase", "accuracy", "--families", "cardinality", "--one-config", + "--thetas", "1.0", "--cardinalities", "1000", "--n-max", "1e4", + "--per-decade", "1", "--seeds", "1", + ], check=True, capture_output=True) + with open(os.path.join(d, "saturation_curve.csv"), newline="") as f: + shapes = {(r["param"], r["cardinality"]) for r in csv.DictReader(f)} + self.assertEqual(shapes, {("1.0", "1000"), ("1.1", "10000")}) + + +# Logs every call; atomic-costs reports `--rows` rows kept, 0 skipped. +FAKE_COST_APPROXBENCH = textwrap.dedent("""\ + import json, os, sys + a = sys.argv + with open(os.environ["FAKE_LOG"], "a") as f: + f.write(json.dumps(a[1:]) + "\\n") + if a[1] == "atomic-costs": + kept = int(os.environ["FAKE_KEPT"]) + sys.stderr.write(f"approxbench atomic-costs: {kept} row(s), 0 skipped\\n") +""") + + +class OptimizerCostTest(unittest.TestCase): + def run_phase(self, d, kept): + binary = os.path.join(d, "approxbench") + with open(binary, "w") as f: + f.write("#!" + sys.executable + "\n" + FAKE_COST_APPROXBENCH) + os.chmod(binary, 0o755) + log = os.path.join(d, "log.jsonl") + result = subprocess.run([ + sys.executable, SCRIPT, "--binary", binary, "--out", os.path.join(d, "out"), + "--phase", "optimizer-cost", "--families", "topk,quantile", "--one-config", + ], capture_output=True, env={**os.environ, "FAKE_LOG": log, "FAKE_KEPT": str(kept)}) + with open(log) as f: + return result, [json.loads(line) for line in f] + + def test_one_cost_and_one_accuracy_pass_per_config_at_one_shape(self): + with tempfile.TemporaryDirectory() as d: + # topk and quantile (kll, dd) one config each, plus 5 exact. + result, calls = self.run_phase(d, 8) + self.assertEqual(result.returncode, 0, result.stderr) + bench = [c for c in calls if c[0] == "sketchbench"] + self.assertEqual(len(bench), 16) + value = lambda c, flag: c[c.index(flag) + 1] + topk, kll = bench[0], bench[2] + self.assertEqual((value(topk, "--zipf-s"), value(topk, "--cardinality"), + value(topk, "--size")), ("1.1", "10000", "1000000")) + self.assertEqual(value(kll, "--pareto-alpha"), "2.0") + self.assertEqual((value(topk, "--runs"), value(topk, "--warmup-runs")), ("5", "3")) + self.assertEqual(value(bench[1], "--metrics"), "accuracy") + self.assertEqual(value(bench[-1], "--library"), "exact") + [reduce] = [c for c in calls if c[0] == "atomic-costs"] + self.assertIn("cms-heap-topk-fastpath-vector2d=precision_at_k", reduce) + self.assertIn("kll-percall=mean_rank_err", reduce) + self.assertIn("exact-sum=relative_error", reduce) + self.assertNotIn("--merge-accuracy", reduce) + + def test_a_skipped_row_fails(self): + with tempfile.TemporaryDirectory() as d: + result, _ = self.run_phase(d, 7) + self.assertNotEqual(result.returncode, 0) + self.assertIn(b"did not keep all 8 rows", result.stderr) + + if __name__ == "__main__": unittest.main()