diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 6ceba69b..a1e1f879 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -81,9 +81,8 @@ pub(super) fn cardinality_row( /// A row answering **top-k**: the heaviest `k` keys, ranked. The probe is /// `()` — one question, the whole list, asked repeatedly for timing — and `k` is -/// `chl::CMS_HEAP_TOP_K`, the same compile-time constant the sketch was built -/// with, so the heap's capacity and the truth it's graded against can never -/// silently disagree (see #95's design-decision comment on the registry entry). +/// `chl::TOPK_K`, the `k` every top-k row answers whatever its heap's capacity +/// (`heap=`): a larger heap answers its heaviest `k`. #[allow(clippy::too_many_arguments)] pub(super) fn topk_row( req: &Requirement, @@ -100,7 +99,7 @@ pub(super) fn topk_row( description, table, want, - TopkGT::::over_column(chl::CMS_HEAP_TOP_K, value_column(description)), + TopkGT::::over_column(chl::TOPK_K, value_column(description)), peel::, insert, insert_step, diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 3e2408a6..7fb1dc66 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -239,7 +239,17 @@ lookback: series per group times scrapes per lookback. (`--merge-shards-list`) up to the N it reads at: past the merge curve's last N, the merged answer has no accuracy either (#158). `SaturationCurves::load` refuses a study with no merge curves for a - candidate KLL or top-k sketch. + candidate KLL sketch. +- Heap top-k (CMS-heap, CountSketch-heap) keeps a heap of `m · k` in a + deployment answering from `m = S_i / D.x` merged windows (`k = 32`, the + answered and graded `k`; `m = 1` gives `k`). Candidates carry one heap per + distinct `m` among the RAQEs on a window, and a RAQE is eligible only where + the heap holds its `m · k`. Such a merged answer reads as one sketch: the + plain curve, then the guarantee fallback. It assumes the merged heaps still + hold the true top `k`; it is not a guarantee. So heap top-k needs no merge + curves. Costs come from the cost table's rows at heaps 32, 128, 512 and + 2048 (`heap=`), linear in the heap between them and past them. Curves are + measured at a heap of `k`, and larger heaps read the same curve. - Where the study measured nothing for a bracketing point at or above its first N (past an unsaturated curve, past the measured merge counts or N, or with no merge curve), the accuracy falls back to the algorithm's diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 25075a05..02a072cc 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -75,7 +75,10 @@ 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' +atomic-costs` to `rqe_atomic_costs.json` (#174). Top-k configs are measured at heaps 32, 128, 512 and +2048 (`TOPK_HEAPS`, `heap=`): a deployment merging `m` windows keeps `m · k` +and rqe-optimizer interpolates between them. The accuracy grid measures top-k +at the default heap, `k = 32`. 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, diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 0eba2c9d..83d4d8cf 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -26,11 +26,10 @@ pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; pub const OUTPUT_BYTES_PER_VALUE: f64 = 8.0; /// Query output per top-k entry: a 64-bit key hash and a count. pub const OUTPUT_BYTES_PER_TOPK_ENTRY: f64 = 16.0; -/// Top-k entries per group: the heap size every top-k cost row was measured -/// at (sketch-bench's `CMS_HEAP_TOP_K`). -// ponytail: fixed k. A large k needs `k` on the RAQE and a benchmark that -// varies the heap. -pub const TOPK_ENTRIES: f64 = 32.0; +/// Top-k entries one query outputs per group: the `k` it answers +/// ([`crate::TOPK_K`]), whatever the heap's capacity. +// ponytail: fixed k. A large k needs `k` on the RAQE. +pub const TOPK_ENTRIES: f64 = crate::TOPK_K as f64; /// Bytes per DDSketch bucket: one `u64` count, as sketch-bench's /// `dd_footprint` counts them. pub const DD_BYTES_PER_BUCKET: f64 = 8.0; diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index 207d2b3c..5291c641 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -207,10 +207,22 @@ struct Grid { impl Grid { fn new(variant: &str, costs: &[AtomicCostEntry]) -> Option { + // Two rows at one heap (no heap and heap=k) would be two grid points + // for one config; the candidates' check refuses them. + crate::candidates::heap_rows_by_shape( + &costs + .iter() + .filter(|c| c.sketch == variant) + .collect::>(), + ); let rows: Vec<(usize, BTreeMap)> = costs .iter() .enumerate() - .filter(|(_, c)| c.sketch == variant) + // AutoSketch never merges (x = S), so a heap of k serves it; the + // larger heaps only cost more and aren't a search axis. + .filter(|(_, c)| { + c.sketch == variant && crate::heap_capacity(c).is_none_or(|h| h <= crate::TOPK_K) + }) .map(|(i, c)| (i, numeric_params(&c.sketch_config))) .collect(); if rows.is_empty() { diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index e314e32d..da84af71 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -2,8 +2,8 @@ use crate::analytical_cost_model; use crate::{ - Accuracy, AtomicCostEntry, Capability, Deployment, LabelSet, MetricFacts, Millis, Raqe, - WorkloadFacts, KEY_TRACKER_FAMILY, + has_heap, heap_capacity, heap_needed, Accuracy, AtomicCostEntry, Capability, Deployment, + LabelSet, MetricFacts, Millis, Raqe, WorkloadFacts, KEY_TRACKER_FAMILY, }; use std::collections::{BTreeMap, BTreeSet}; @@ -83,6 +83,15 @@ fn candidate_deployments( tracker_rows.len() ); let tracker_row = tracker_rows.first().copied(); + let family_rows: Vec<&AtomicCostEntry> = costs + .iter() + .filter(|c| { + capability + .candidate_families(allow_undeployable_families) + .any(|family| family == c.sketch) + }) + .collect(); + let heap_rows = heap_rows_by_shape(&family_rows); let windows = group .iter() .flat_map(|r| divisors(r.lookback_ms / scrape_interval_ms)) @@ -99,11 +108,28 @@ fn candidate_deployments( .filter(|r| r.lookback_ms % window_ms == 0) .map(|r| gcd(window_ms, r.interval_ms)), ); - for config in costs.iter().filter(|c| { - capability - .candidate_families(allow_undeployable_families) - .any(|family| family == c.sketch) - }) { + // A heap family keeps one candidate per heap a RAQE on this window + // needs, m · k for its m = L / x merged windows, priced by + // interpolating the measured heap sizes. Other rows are used as they are. + let heaps: BTreeSet = group + .iter() + .filter_map(|r| heap_needed(r.lookback_ms, window_ms)) + .collect(); + let configs: Vec = family_rows + .iter() + .filter(|c| !has_heap(&c.sketch)) + .map(|c| (*c).clone()) + .chain(heap_rows.values().flat_map(|rows| { + // Needs that one measured row serves collapse onto it. + let by_heap: BTreeMap = heaps + .iter() + .filter_map(|&heap| at_heap(rows, heap)) + .filter_map(|entry| Some((heap_capacity(&entry)?, entry))) + .collect(); + by_heap.into_values() + })) + .collect(); + for config in &configs { let key_tracker = if crate::family_properties(&config.sketch).needs_delta_set_key_tracker { match tracker_row { @@ -132,6 +158,86 @@ fn candidate_deployments( deployments } +/// A heap family's rows, by family and counter shape (every param but +/// `heap`), then by heap capacity. +pub(crate) fn heap_rows_by_shape<'a>( + rows: &[&'a AtomicCostEntry], +) -> BTreeMap<(String, String), BTreeMap> { + let mut out: BTreeMap<_, BTreeMap> = BTreeMap::new(); + for &row in rows { + let Some(heap) = heap_capacity(row) else { + continue; + }; + let mut shape = row.sketch_config["params"].clone(); + if let Some(params) = shape.as_object_mut() { + params.remove("heap"); + } + let shape = shape.to_string(); + if out + .entry((row.sketch.clone(), shape.clone())) + .or_default() + .insert(heap, row) + .is_some() + { + panic!( + "two {} {shape} cost rows at heap {heap} (e.g. no heap and heap={heap}); \ + keep one", + row.sketch + ); + } + } + out +} + +/// `rows` (one family and counter shape, by heap) priced at `heap`: each +/// per-op cost linear in the heap between the measured sizes around it, and +/// extended from the two nearest past them. With one measured size, the +/// smallest row holding at least `heap` serves at its own size and cost. +/// The accuracy fields are the smallest heap's: curves are measured at +/// `TOPK_K`. Panics when one measured heap is smaller than `heap`: the +/// table needs the heap sizes measured. +fn at_heap(rows: &BTreeMap, heap: u64) -> Option { + let (_, &base) = rows.first_key_value()?; + // A measured heap's costs, with the base's accuracy like every other. + let measured = |row: &AtomicCostEntry| AtomicCostEntry { + query_accuracy: base.query_accuracy.clone(), + ..row.clone() + }; + if let Some(row) = rows.get(&heap) { + return Some(measured(row)); + } + if rows.len() < 2 { + let Some((_, row)) = rows.range(heap..).next() else { + panic!( + "{} {} is priced at one heap only, smaller than the heap {heap} a \ + candidate needs; rerun study_saturation.py --phase optimizer-cost to \ + measure the top-k heap sizes", + base.sketch, base.sketch_config["params"] + ); + }; + return Some(measured(row)); + } + let mut below = rows.range(..heap).rev(); + let mut above = rows.range(heap..); + let ((h0, a), (h1, b)) = match (below.next(), above.next()) { + (Some(lo), Some(hi)) => (lo, hi), + (Some(hi), None) => (below.next()?, hi), + (None, Some(lo)) => (lo, above.next()?), + (None, None) => return None, + }; + let t = (heap as f64 - *h0 as f64) / (*h1 as f64 - *h0 as f64); + let line = |x: f64, y: f64| (x + t * (y - x)).max(0.0); + let mut entry = AtomicCostEntry { + mem_bytes_per_instance: line(a.mem_bytes_per_instance, b.mem_bytes_per_instance), + insert_cpu_secs: line(a.insert_cpu_secs, b.insert_cpu_secs), + merge_cpu_secs: line(a.merge_cpu_secs, b.merge_cpu_secs), + query_cpu_secs: line(a.query_cpu_secs, b.query_cpu_secs), + ..(*base).clone() + }; + entry.sketch_config["params"]["heap"] = heap.into(); + Some(entry) +} + /// Configurations come from [`Capability::candidate_families`]. pub fn build_all_candidates( raqes: &[Raqe], @@ -365,6 +471,10 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A && properties.needs_delta_set_key_tracker == d.key_tracker.is_some() && (!properties.one_fixed_size_sketch_for_all_groups || measured_at_group_count(&d.config, facts[&d.metric].cardinality[&d.grouping_labels])) + && heap_capacity(&d.config).is_none_or(|heap| { + d.heap_needed(r.lookback_ms) + .is_some_and(|need| heap >= need) + }) && r.meets_sla(&d.config.sketch, accuracy(r, d)) } @@ -390,7 +500,8 @@ mod tests { fn cost() -> AtomicCostEntry { AtomicCostEntry { sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), + // A heap that holds any merge, so heap top-k fixtures merge freely. + sketch_config: serde_json::json!({"params": {"heap": 1u64 << 40}}), mem_bytes_per_instance: 1.0, insert_cpu_secs: 1.0, merge_cpu_secs: 1.0, @@ -400,6 +511,85 @@ mod tests { measured_at: measured_at(), } } + /// A heap top-k row measured at `heap`, its costs `heap` per op. + fn heap_row(heap: u64) -> AtomicCostEntry { + let h = heap as f64; + AtomicCostEntry { + sketch_config: serde_json::json!({"params": {"rows": 3, "cols": 256, "heap": heap}}), + mem_bytes_per_instance: 1000.0 + h, + insert_cpu_secs: h, + merge_cpu_secs: 2.0 * h, + query_cpu_secs: 3.0 * h, + ..cost() + } + } + + #[test] + fn heap_costs_are_linear_between_and_past_the_measured_sizes() { + let (a, b, c) = (heap_row(32), heap_row(128), heap_row(512)); + let rows = BTreeMap::from([(32, &a), (128, &b), (512, &c)]); + let at = |heap| at_heap(&rows, heap).unwrap(); + assert_eq!(at(128), b); + let between = at(64); + assert_eq!(between.mem_bytes_per_instance, 1064.0); + assert_eq!(between.merge_cpu_secs, 128.0); + assert_eq!(heap_capacity(&between), Some(64)); + // Past the largest: the line through the two largest. + assert_eq!(at(2048).query_cpu_secs, 3.0 * 2048.0); + // One measured size: the smallest row holding the heap serves as is. + let single = BTreeMap::from([(128, &b)]); + assert_eq!(at_heap(&single, 64), Some(b.clone())); + } + + /// A table priced at one heap can't price a larger one: planning stops + /// and names the rerun, rather than dropping the candidate. + #[test] + #[should_panic(expected = "rerun study_saturation.py --phase optimizer-cost")] + fn one_measured_heap_cannot_price_a_larger_one() { + let b = heap_row(128); + at_heap(&BTreeMap::from([(128, &b)]), 256); + } + + /// No heap and heap = k are one heap: two such rows would overwrite each + /// other. + #[test] + #[should_panic(expected = "cost rows at heap 32")] + fn two_rows_at_one_heap_are_refused() { + let explicit = heap_row(32); + let mut implicit = heap_row(32); + implicit.sketch_config["params"] + .as_object_mut() + .unwrap() + .remove("heap"); + heap_rows_by_shape(&[&explicit, &implicit]); + } + + /// Each window gets the heaps its RAQEs need, m · k for m = L / x, and a + /// RAQE is eligible only where the heap holds its m · k. + #[test] + fn a_heap_candidate_holds_m_times_k_for_its_merges() { + let raqes = vec![raqe("a", 60_000, 60_000), raqe("b", 240_000, 60_000)]; + let rows = [heap_row(32), heap_row(128), heap_row(512)]; + let candidates = build_all_candidates_unpruned(&raqes, &rows, &facts(1, 1), false); + let heaps_at = |window_ms: Millis| { + candidates + .iter() + .filter(|d| d.window_ms == window_ms) + .filter_map(|d| heap_capacity(&d.config)) + .collect::>() + }; + // x = 60 s: a merges 1 (32), b merges 4 (128). + assert_eq!(heaps_at(60_000), BTreeSet::from([32, 128])); + // x = 30 s: a merges 2 (64, interpolated), b merges 8 (256). + assert_eq!(heaps_at(30_000), BTreeSet::from([64, 256])); + let d = candidates + .iter() + .find(|d| d.window_ms == 60_000 && heap_capacity(&d.config) == Some(32)) + .unwrap(); + assert!(is_eligible(&raqes[0], d, &facts(1, 1), &table_accuracy)); + assert!(!is_eligible(&raqes[1], d, &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)]; diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index ea44cfdb..0d264790 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -133,7 +133,8 @@ mod tests { fn cost(sketch: &str) -> AtomicCostEntry { AtomicCostEntry { sketch: sketch.to_string(), - sketch_config: serde_json::json!(null), + // A heap that holds any merge, so heap top-k fixtures merge freely. + sketch_config: serde_json::json!({"params": {"heap": 1u64 << 40}}), mem_bytes_per_instance: 1.0, insert_cpu_secs: 1.0, merge_cpu_secs: 1.0, diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index f29d7a19..1286c248 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -128,6 +128,41 @@ pub const DEPLOYABLE_FAMILIES: &[&str] = &[ /// deployment pays for alongside its sketch. Never a candidate on its own. pub const KEY_TRACKER_FAMILY: &str = "exact-delta-set"; +/// The `k` every top-k RAQE asks for, and the heap capacity of a row that +/// sets no `heap` (sketch-bench's `TOPK_K`). +pub const TOPK_K: u64 = 32; + +/// Top-k families whose heap capacity is a config knob (sketch-bench's +/// `heap=`). A deployment answering from `m` merged windows keeps a heap of +/// `m · TOPK_K`, so the merged heaps still hold the true top `k` +/// (approximately: a working assumption, not a guarantee). +pub fn has_heap(sketch: &str) -> bool { + matches!( + sketch, + "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" + ) +} + +/// The heap a heap top-k deployment with `window_ms` windows needs to serve +/// `lookback_ms`: `m · k` for its `m` merged windows, or `None` when the +/// lookback isn't whole windows. [`Deployment::heap_needed`] for a built one. +pub fn heap_needed(lookback_ms: Millis, window_ms: Millis) -> Option { + if window_ms == 0 || !lookback_ms.is_multiple_of(window_ms) { + return None; + } + Some(lookback_ms / window_ms * TOPK_K) +} + +/// A heap family's capacity: its `heap` param, else [`TOPK_K`]. `None` for +/// other families. +pub fn heap_capacity(config: &AtomicCostEntry) -> Option { + has_heap(&config.sketch).then(|| { + let heap = &config.sketch_config["params"]["heap"]; + // A number in any JSON form (128, 128.0); absent is k. + heap.as_f64().map_or(TOPK_K, |h| h.round() as u64) + }) +} + /// What a variant's algorithm can do, as opposed to what it measured. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FamilyProperties { @@ -445,6 +480,13 @@ impl Deployment { Some(lookback_ms / self.window_ms) } + /// The heap a heap top-k deployment needs to serve `lookback_ms`: `m · k` + /// for its `m` merged windows. `None` when the lookback isn't whole + /// windows. + pub fn heap_needed(&self, lookback_ms: Millis) -> Option { + heap_needed(lookback_ms, self.window_ms) + } + /// Closed instances kept to serve a lookback: those wholly inside it, /// which start in `[now − L, now − x]`, so `(L − x) / y + 1`. pub fn closed_instance_count(&self, lookback_ms: Millis) -> Option { @@ -545,7 +587,8 @@ pub(crate) mod test_support { grouping_labels: LabelSet::new(), config: AtomicCostEntry { sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), + // A heap that holds any merge, so heap top-k fixtures merge freely. + sketch_config: serde_json::json!({"params": {"heap": 1u64 << 40}}), mem_bytes_per_instance: memory, insert_cpu_secs: insert, merge_cpu_secs: merge, @@ -595,7 +638,7 @@ mod tests { /// DD omits its metric when every true quantile is 0; a row without it /// must not pass, nor be skipped silently. #[test] - #[should_panic(expected = "dd null has no mean_relative_value_error")] + #[should_panic(expected = "has no mean_relative_value_error")] fn a_row_missing_its_familys_metric_panics() { let config = AtomicCostEntry { sketch: "dd".into(), diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index e242fb8a..a499ec04 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -14,15 +14,15 @@ //! 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::collections::{BTreeMap, BTreeSet}; use std::io; use std::path::Path; use crate::autosketch::window_adapter; use crate::theory; use crate::{ - accuracy_key, family_properties, table_accuracy, AccuracyDirection, AtomicCostEntry, - Capability, Deployment, LabelSet, MetricFacts, Raqe, WorkloadFacts, + accuracy_key, family_properties, has_heap, heap_capacity, table_accuracy, AccuracyDirection, + AtomicCostEntry, Capability, Deployment, LabelSet, MetricFacts, Raqe, WorkloadFacts, TOPK_K, }; use aqpbm_core::MeasuredShape; @@ -361,7 +361,9 @@ impl SaturationCurves { // accuracy. let mut lossy: BTreeMap<&str, bool> = BTreeMap::new(); for (sketch, point) in points.values() { - if is_candidate(sketch) && merges_lossily(sketch) { + // Heap top-k merges as one sketch when sized m · k, so only KLL + // needs the curves. + if is_candidate(sketch) && merges_lossily(sketch) && !has_heap(sketch) { *lossy.entry(sketch).or_default() |= !point.merged.is_empty(); } } @@ -419,7 +421,16 @@ impl SaturationCurves { let covered = items_per_group(metric_facts, grouping, raqe.lookback_ms); let (_, direction) = accuracy_key(&deployment.config.sketch); let merges = if merges_lossily(&deployment.config.sketch) { - deployment.query_instance_count(raqe.lookback_ms)? + let merges = deployment.query_instance_count(raqe.lookback_ms)?; + // A heap of m · k merged from m windows reads as one sketch: the + // merged heaps are taken to still hold the true top k. + match ( + heap_capacity(&deployment.config), + deployment.heap_needed(raqe.lookback_ms), + ) { + (Some(heap), Some(need)) if heap >= need => 1, + _ => merges, + } } else { 1 }; @@ -494,6 +505,10 @@ impl SaturationCurves { let Some(points) = self.points_by_sketch.get(&row.sketch) else { continue; }; + // Curves are measured at a heap of k; larger heaps are cost-only. + if heap_capacity(row).is_some_and(|heap| heap != TOPK_K) { + continue; + } let params = config_params(row); let mut same_config = points .iter() @@ -537,6 +552,23 @@ impl SaturationCurves { Some(true) => {} } } + // A heap top-k config priced at one heap only can't serve any heap + // above it: every merged top-k candidate would quietly vanish. + let mut heaps: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + for row in costs.iter().filter(|row| is_candidate(&row.sketch)) { + if let Some(heap) = heap_capacity(row) { + let key = (row.sketch.clone(), format!("{:?}", config_params(row))); + heaps.entry(key).or_default().insert(heap); + } + } + for ((sketch, params), measured) in heaps { + if measured.len() < 2 { + check.mismatched.push(format!( + "{sketch} {params}: priced at heap {measured:?} only; rerun \ + study_saturation.py --phase optimizer-cost for the heap sizes" + )); + } + } check } @@ -601,11 +633,14 @@ fn bracket(values: impl Iterator, target: f64) -> Option> { (above > 0 && above < values.len()).then(|| vec![values[above - 1], values[above]]) } -/// `{"params": {"rows": 3, "cols": 1024}}` → `{rows: 3, cols: 1024}`. +/// `config`'s params, less a top-k `heap`: `{"params": {"rows": 3, "cols": +/// 1024, "heap": 128}}` → `{rows: 3, cols: 1024}`. Curves are measured at a +/// heap of `TOPK_K`, and a larger heap reads the same curve. fn config_params(config: &AtomicCostEntry) -> Option> { config.sketch_config["params"] .as_object()? .iter() + .filter(|(name, _)| *name != "heap") .map(|(name, value)| Some((name.clone(), value.as_f64()?))) .collect() } @@ -807,6 +842,42 @@ mod tests { assert_eq!(at(100_000), None); } + /// A heap of m · k merged from m windows reads as one sketch: the plain + /// curve, not the merge curve, and no merge curve is needed. + #[test] + fn a_heap_of_m_times_k_reads_the_plain_curve() { + let facts = workload(10, shape(1.2, 1e3)); + let r = topk_raqe(10_000_000); + let with_heap = |window_ms, heap: u64| { + let mut d = deployment(TOPK, window_ms); + d.config.sketch_config["params"]["heap"] = heap.into(); + d + }; + let mut plain_only = curves(); + for point in plain_only.points_by_sketch.get_mut(TOPK).unwrap() { + point.merged.clear(); + } + // 4 windows: a heap of 4k reads the plain curve; 2k doesn't, and + // without a merge curve has no accuracy. + assert_eq!( + plain_only.accuracy(&r, &with_heap(2_500_000, 4 * TOPK_K), &facts), + Some(0.9) + ); + assert_eq!( + plain_only.accuracy(&r, &with_heap(2_500_000, 2 * TOPK_K), &facts), + None + ); + // With merge curves, a small heap still reads them. + assert!( + (curves() + .accuracy(&r, &with_heap(2_500_000, TOPK_K), &facts) + .unwrap() + - 0.88) + .abs() + < 1e-12 + ); + } + /// Past a merge curve's last checkpoint the merged answer is unknown, /// even when the plain curve saturated: nothing shows the merged sketch /// stopped changing. @@ -965,7 +1036,31 @@ mod tests { #[test] fn the_cost_table_is_a_point_on_the_curve() { - let check = |rows: &[AtomicCostEntry]| curves().check_cost_table(rows); + // Each top-k row also priced at a large heap, as the study does. + let check = |rows: &[AtomicCostEntry]| { + let mut all = rows.to_vec(); + for row in rows.iter().filter(|row| heap_capacity(row).is_some()) { + let mut large = row.clone(); + large.sketch_config["params"]["heap"] = (64 * TOPK_K).into(); + all.push(large); + } + curves().check_cost_table(&all) + }; + // Priced at one heap only: no merged top-k candidate could be built. + let lone = curves().check_cost_table(&[measured_row(1024, 10_000, 0.93)]); + assert_eq!(lone.mismatched.len(), 1, "{lone:?}"); + assert!(lone.mismatched[0].contains("priced at heap"), "{lone:?}"); + // A heap of k is checked like no heap; a larger heap is cost-only. + let with_heap = |heap: u64, precision| { + let mut row = measured_row(1024, 10_000, precision); + row.sketch_config["params"]["heap"] = heap.into(); + row + }; + assert_eq!(check(&[with_heap(TOPK_K, 0.8)]).mismatched.len(), 1); + assert_eq!( + check(&[with_heap(4 * TOPK_K, 0.8)]), + CostTableCheck::default() + ); // θ = 1.2, K = 1e3 reads 0.95 ± 3 × 0.01 + 5% at N = 1e4. assert_eq!( check(&[measured_row(1024, 10_000, 0.93)]), @@ -993,7 +1088,12 @@ mod tests { 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); + // (Its large-heap copy names the same wrong metric.) + let wrong = check(&[other_metric]).mismatched; + assert!( + !wrong.is_empty() && wrong.iter().all(|m| m.contains("recall_at_k")), + "{wrong:?}" + ); // Sketches the study didn't run, exact ones among them, skip the // curve, but still name their family's metric. let exact = AtomicCostEntry { @@ -1051,6 +1151,33 @@ mod tests { assert_eq!(points[0].params, BTreeMap::from([("k".to_string(), 200.0)])); } + /// Top-k merges as one sketch when its heap holds m · k, so a study needs + /// no merge curves for it. + #[test] + fn load_needs_no_merge_curves_for_heap_topk() { + let dir = std::env::temp_dir().join(format!("rqe-topk-nomerge-{}", std::process::id())); + let header = "family,sketch,config,dist,param,cardinality"; + let point = format!("topk,{TOPK},rows=3 cols=1024,zipf,1.2,1000"); + for run in RUN_DIRS { + std::fs::create_dir_all(dir.join(run)).unwrap(); + std::fs::write( + dir.join(run).join("saturation.csv"), + format!( + "{header},n_sat,final_error,error_metric\n{point},1000,0.9,precision_at_k\n" + ), + ) + .unwrap(); + std::fs::write( + dir.join(run).join("saturation_curve.csv"), + format!("{header},n,seed_mean_error,seed_se\n{point},1000,0.9,0\n"), + ) + .unwrap(); + } + let loaded = SaturationCurves::load(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(loaded.is_ok(), "{:?}", loaded.err()); + } + /// A curve for another metric than the family's, such as DD's max error /// before #175, is a stale study: refused at load, whatever the lookback. #[test] diff --git a/scripts/study_saturation.py b/scripts/study_saturation.py index 123cad49..8727d8b8 100644 --- a/scripts/study_saturation.py +++ b/scripts/study_saturation.py @@ -93,6 +93,11 @@ COST_TABLE = "rqe_atomic_costs.json" # Families some rqe-optimizer capability plans; frequency sketches serve none. OPTIMIZER_FAMILIES = ("topk", "cardinality", "quantile") +# Heap capacities the cost table measures each top-k config at. A deployment +# merging m windows keeps a heap of m · k (k = 32, the graded and answered +# k); rqe-optimizer interpolates costs between these. Accuracy curves are +# measured at the default heap, k. +TOPK_HEAPS = (32, 128, 512, 2048) # Exact accumulators the optimizer plans, on grouped records (variant, # comparator, datagen spec). Their error is 0 by construction; the accuracy @@ -290,7 +295,11 @@ def cost_dataset(family): 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.""" + reduced by `approxbench atomic-costs` to --out/COST_TABLE. Each sketch + row's accuracy is then the mean over seeds 1..--seeds at COST_N, the + same measurement as the curve's point there when --seeds matches the + accuracy run's, so check_cost_table compares like with like. Exact rows + keep their 0.""" 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") @@ -305,8 +314,10 @@ def optimizer_cost(args, 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))) + heaps = [f" heap={h}" for h in TOPK_HEAPS] if family == "topk" else [""] + for heap in heaps: + rows.append((variant, "lib", ["--config", config + heap], 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"])) @@ -343,10 +354,41 @@ def sketchbench(variant, library, config, data, passes): 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}") + seed_mean_accuracy(args, table, rows, metrics) print(f"Done. {table}", file=sys.stderr) return 0 +def seed_mean_accuracy(args, table, rows, metrics): + """Rewrite each sketch row's accuracy in `table` as the mean over seeds + 1..--seeds of one accuracy run at COST_N: the run the curves make at that + N. Top-k at heaps above k keep the base's: curves are measured at k.""" + def params(config): + return {k: float(v) for k, v in (kv.split("=") for kv in config.split())} + + means = {} + for variant, library, config, comparator, data in rows: + if library == "exact" or float(params(config[1]).get("heap", TOPK_HEAPS[0])) != \ + TOPK_HEAPS[0]: + continue + errors = [error(run(args.binary, [ + "--variant", variant, "--library", library, *config, + "--operations", "query", "--metrics", "accuracy", "--comparator", comparator, + "--runs", "1", "--warmup-runs", "0", "--seed", str(seed)] + data), + metrics[variant]) for seed in range(1, args.seeds + 1)] + base = {k: v for k, v in params(config[1]).items() if k != "heap"} + means[(variant, tuple(sorted(base.items())))] = sum(errors) / len(errors) + with open(table) as f: + entries = json.load(f) + for entry in entries: + p = {k: float(v) for k, v in entry["sketch_config"]["params"].items() if k != "heap"} + mean = means.get((entry["sketch"], tuple(sorted(p.items())))) + if mean is not None: + entry["query_accuracy"][entry["accuracy_metric"]] = mean + with open(table, "w") as f: + json.dump(entries, f, indent=2) + + def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter @@ -603,10 +645,23 @@ def accuracy(point, n, seed, shards=1): cost_raw.close() if not rebuild: - with open(os.path.join(args.out, "saturation.csv"), "w", newline="") as f: + summary_path = os.path.join(args.out, "saturation.csv") + # --resume over a narrower grid keeps the other points' rows, as the + # curve files keep their curves. + kept_summary = [] + # Accuracy phase only: a cost phase truncates saturation_cost.jsonl, + # so other points' cost columns would outlive their records. + if args.resume and args.phase == "accuracy" and os.path.exists(summary_path): + grid = {point_key(p[1], p[2], *p[6:]) for p in points} + with open(summary_path, newline="") as f: + kept_summary = [[r.get(c, "") for c in SUMMARY_COLUMNS] + for r in csv.DictReader(f) + if point_key(r["sketch"], r["config"], r["dist"], r["param"], + r["cardinality"]) not in grid] + with open(summary_path, "w", newline="") as f: writer = csv.writer(f) writer.writerow(SUMMARY_COLUMNS) - writer.writerows(rows) + writer.writerows(kept_summary + rows) print(f"Done. {os.path.join(args.out, 'saturation.csv')}", file=sys.stderr) if not cost: return 0 diff --git a/scripts/test_study_saturation.py b/scripts/test_study_saturation.py index 83263282..6df75564 100644 --- a/scripts/test_study_saturation.py +++ b/scripts/test_study_saturation.py @@ -394,6 +394,23 @@ def test_crossover_phase_matches_saved_records_by_key(self): self.assertIn(b"has no record", missing.stderr) +class ResumeSummaryTest(unittest.TestCase): + def test_a_narrower_resume_keeps_the_other_points_summary_rows(self): + with tempfile.TemporaryDirectory() as d: + base = [sys.executable, SCRIPT, "--binary", fake_binary(d), "--out", d, + "--phase", "accuracy", "--one-config", "--thetas", "1.0", + "--cardinalities", "1000", "--n-max", "1e4", "--per-decade", "1", + "--seeds", "1", "--no-cost-shape"] + subprocess.run(base + ["--families", "cardinality,frequency"], check=True, + capture_output=True) + subprocess.run(base + ["--families", "cardinality", "--resume"], check=True, + capture_output=True) + with open(os.path.join(d, "saturation.csv"), newline="") as f: + sketches = sorted(r["sketch"] for r in csv.DictReader(f)) + self.assertEqual(sketches, ["cms-fastpath-vector2d", "countsketch-fastpath-vector2d", + "hll"]) + + class CostShapeTest(unittest.TestCase): def test_the_grid_also_runs_the_optimizer_cost_shape(self): with tempfile.TemporaryDirectory() as d: @@ -412,11 +429,29 @@ def test_the_grid_also_runs_the_optimizer_cost_shape(self): FAKE_COST_APPROXBENCH = textwrap.dedent("""\ import json, os, sys a = sys.argv + value = lambda flag: a[a.index(flag) + 1] if flag in a else None with open(os.environ["FAKE_LOG"], "a") as f: f.write(json.dumps(a[1:]) + "\\n") if a[1] == "atomic-costs": + # One row per logged accuracy pass, scoring 0.5 in its metric. + metrics = dict(m.split("=") for m in a[3:] if "=" in m and "/" not in m) + rows = [] + for line in open(os.environ["FAKE_LOG"]): + c = json.loads(line) + if c[0] == "sketchbench" and "--report" in c and "accuracy" in c: + v = c[c.index("--variant") + 1] + cfg = c[c.index("--config") + 1] if "--config" in c else "" + params = {k: float(x) for k, x in (kv.split("=") for kv in cfg.split())} + rows.append({"sketch": v, "sketch_config": {"params": params}, + "query_accuracy": {metrics[v]: 0.5}, "accuracy_metric": metrics[v]}) + json.dump(rows, open(value("--output"), "w")) kept = int(os.environ["FAKE_KEPT"]) sys.stderr.write(f"approxbench atomic-costs: {kept} row(s), 0 skipped\\n") + elif a[1] == "sketchbench" and "--report" not in a: + # A seed run: error = seed / 100 in every metric. + e = int(value("--seed")) / 100 + print(json.dumps({"bench": {"accuracy": {m: e for m in ( + "precision_at_k", "mean_rank_err", "mean_relative_value_error")}}})) """) @@ -430,19 +465,23 @@ def run_phase(self, d, kept): result = subprocess.run([ sys.executable, SCRIPT, "--binary", binary, "--out", os.path.join(d, "out"), "--phase", "optimizer-cost", "--families", "topk,quantile", "--one-config", + "--seeds", "3", ], 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) + # topk one config at 4 heaps, quantile (kll, dd) one config + # each, plus 5 exact. + result, calls = self.run_phase(d, 11) self.assertEqual(result.returncode, 0, result.stderr) - bench = [c for c in calls if c[0] == "sketchbench"] - self.assertEqual(len(bench), 16) + bench = [c for c in calls if c[0] == "sketchbench" and "--report" in c] + self.assertEqual(len(bench), 22) value = lambda c, flag: c[c.index(flag) + 1] - topk, kll = bench[0], bench[2] + topk, kll = bench[0], bench[8] + self.assertEqual([value(c, "--config") for c in bench[0:8:2]], + [f"rows=3 cols=256 heap={h}" for h in (32, 128, 512, 2048)]) self.assertEqual((value(topk, "--zipf-s"), value(topk, "--cardinality"), value(topk, "--size")), ("1.1", "10000", "1000000")) self.assertEqual(value(kll, "--pareto-alpha"), "2.0") @@ -454,12 +493,34 @@ def test_one_cost_and_one_accuracy_pass_per_config_at_one_shape(self): self.assertIn("kll-percall=mean_rank_err", reduce) self.assertIn("exact-sum=relative_error", reduce) self.assertNotIn("--merge-accuracy", reduce) + # Then 3 seed runs per sketch config at heap k: top-k, KLL, DD. + seeds = [c for c in calls if c[0] == "sketchbench" and "--report" not in c] + self.assertEqual(len(seeds), 9) + self.assertEqual({c[c.index("--seed") + 1] for c in seeds}, {"1", "2", "3"}) + self.assertTrue(all("heap=32" in c[c.index("--config") + 1] for c in seeds + if "topk" in c[c.index("--variant") + 1])) + + def test_sketch_rows_take_the_seed_mean_accuracy(self): + with tempfile.TemporaryDirectory() as d: + result, _ = self.run_phase(d, 11) + with open(os.path.join(d, "out", "rqe_atomic_costs.json")) as f: + rows = json.load(f) + self.assertEqual(result.returncode, 0, result.stderr) + # Seeds 1..3 score 0.01, 0.02, 0.03: every sketch row (every heap) + # reads their mean; exact rows keep the accuracy pass's. + sketches = [r for r in rows if not r["sketch"].startswith("exact-")] + self.assertEqual(len(sketches), 6) + for row in sketches: + self.assertAlmostEqual(row["query_accuracy"][row["accuracy_metric"]], 0.02) + for row in rows: + if row["sketch"].startswith("exact-"): + self.assertEqual(row["query_accuracy"][row["accuracy_metric"]], 0.5) def test_a_skipped_row_fails(self): with tempfile.TemporaryDirectory() as d: - result, _ = self.run_phase(d, 7) + result, _ = self.run_phase(d, 10) self.assertNotEqual(result.returncode, 0) - self.assertIn(b"did not keep all 8 rows", result.stderr) + self.assertIn(b"did not keep all 11 rows", result.stderr) if __name__ == "__main__": diff --git a/sketch-bench/src/params.rs b/sketch-bench/src/params.rs index 41fa74cb..21dc6987 100644 --- a/sketch-bench/src/params.rs +++ b/sketch-bench/src/params.rs @@ -398,36 +398,63 @@ sketch_params!( pub struct CmsHeapParams { pub rows: usize, pub cols: usize, + /// The heap's capacity. Absent means `TOPK_K`, the `k` every top-k row + /// answers and is graded at (`wrappers::cms_heap::sketchlib`); a larger + /// heap still answers its heaviest `TOPK_K`. Fewer than `TOPK_K` is + /// refused at build. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub heap: Option, } -// No `top_k` field: the heap's capacity and the TopK comparator's grading `k` -// are the same compile-time constant (`CMS_HEAP_TOP_K` in -// `wrappers::cms_heap::sketchlib`), so there is nothing here for them to -// silently disagree about. `deny_unknown_fields` turns a `--config` that -// tries to set `top_k` anyway into a named error rather than ignoring it. sketch_params!( CmsHeapParams, "cms-heap", CmsHeapParams { rows: 3, - cols: 1024 + cols: 1024, + heap: None } ); +/// CountSketch + heap: CountSketch's knobs plus the heap's capacity, as +/// [`CmsHeapParams`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct CountSketchParams { +pub struct CsHeapParams { pub rows: usize, pub cols: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub heap: Option, } sketch_params!( - CountSketchParams, - "countsketch", - CountSketchParams { + CsHeapParams, + "countsketch-heap", + CsHeapParams { rows: 3, - cols: 1024 + cols: 1024, + heap: None } ); +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CountSketchParams { + pub rows: usize, + pub cols: usize, +} +impl SketchParams for CountSketchParams { + const ALGORITHM: &'static str = "countsketch"; + /// Not `countsketch-heap-*`: those take [`CsHeapParams`]. + fn owns(variant: &str) -> bool { + in_algorithm(variant, Self::ALGORITHM) && !in_algorithm(variant, "countsketch-heap") + } + fn canonical() -> Self { + CountSketchParams { + rows: 3, + cols: 1024, + } + } +} + // ---------- Hydra, one algorithm per cell type ---------- // The cell type is on the algorithm axis because each cell answers a different // statistic under a different comparator, and each keeps `deny_unknown_fields`. @@ -633,6 +660,8 @@ mod tests { check::(); check::(); check::(); + check::(); + check::(); check::(); check::(); check::(); @@ -656,6 +685,13 @@ mod tests { assert!(CountSketchParams::owns("countsketch-fastpath-vector2d")); assert!(!CountSketchParams::owns("cms")); + assert!(!CountSketchParams::owns( + "countsketch-heap-topk-fastpath-vector2d" + )); + assert!(CsHeapParams::owns( + "countsketch-heap-topk-fastpath-vector2d" + )); + assert!(!CsHeapParams::owns("countsketch-fastpath-vector2d")); assert!(HllParams::owns("hll")); assert!(HllParams::owns("hll-hip")); diff --git a/sketch-bench/src/registry.rs b/sketch-bench/src/registry.rs index f6280fe1..f8a5e328 100644 --- a/sketch-bench/src/registry.rs +++ b/sketch-bench/src/registry.rs @@ -143,8 +143,8 @@ pub const REGISTRY: &[SketchId] = &[ .union(MetricsMask::MEMORY), }, // -------- CMS + heap (frequency, and top-k) -------- - // A separate algorithm from `cms`: `CmsHeapParams` has no `top_k` (it's a - // compile-time constant, see wrappers::cms_heap::sketchlib::CMS_HEAP_TOP_K), + // A separate algorithm from `cms`: `CmsHeapParams` adds the heap's + // capacity (`heap`; the answered k is wrappers::cms_heap::sketchlib::TOPK_K), // so it's a different knob set, and `CMSHeap` answers two different // questions (per-key frequency, and top-k), so it gets two rows per // backend instead of one. Only `Vector2D` x {FastPath, RegularPath}: no diff --git a/sketch-bench/src/wrappers/cms_heap/mod.rs b/sketch-bench/src/wrappers/cms_heap/mod.rs index 84f0b6b3..e61736f5 100644 --- a/sketch-bench/src/wrappers/cms_heap/mod.rs +++ b/sketch-bench/src/wrappers/cms_heap/mod.rs @@ -1,6 +1,6 @@ //! `asap_sketchlib::CMSHeap` wrappers — a Count-Min sketch paired with a -//! fixed-capacity top-k heap. A separate algorithm from `cms`: it takes a -//! different knob set (no `top_k` in `--config`, see `sketchlib::CMS_HEAP_TOP_K`) +//! top-k heap. A separate algorithm from `cms`: it takes a different knob set +//! (`heap`, the heap's capacity; the answered `k` is `sketchlib::TOPK_K`) //! and answers two different questions (per-key frequency, and top-k), so it //! gets two registry rows per backend rather than one. @@ -13,9 +13,8 @@ mod tests { use std::collections::HashMap; use std::rc::Rc; - /// `deny_unknown_fields` is what turns a stray `top_k` in `--config` into a - /// named error rather than silently ignoring it or building at the wrong - /// capacity — the guarantee the whole compile-time-`k` design rests on. + /// `deny_unknown_fields` turns a stray `top_k` in `--config` into a named + /// error: the answered `k` is `TOPK_K`, not a knob. #[test] fn top_k_is_not_a_config_field() { let bad = ParamSet { @@ -37,6 +36,7 @@ mod tests { let params = ParamSet::of(&CmsHeapParams { rows: 5, cols: 4096, + heap: None, }); let items = Rc::new(vec![1i64, 1, 1, 2, 2, 3]); let probes = Rc::new(vec![()]); @@ -53,7 +53,11 @@ mod tests { #[test] fn degenerate_shapes_are_refused_by_name() { for (rows, cols) in [(0usize, 256usize), (3, 0), (0, 0)] { - let p = ParamSet::of(&CmsHeapParams { rows, cols }); + let p = ParamSet::of(&CmsHeapParams { + rows, + cols, + heap: None, + }); assert!( build_cms_heap_lib_vector2d_fast(&p).is_err(), "fastpath {rows}x{cols}" @@ -66,14 +70,15 @@ mod tests { } /// Footprint is `rows * cols` counters at the real width plus a full heap - /// of `CMS_HEAP_TOP_K` `HHItem`s, as UnivMon counts its heaps (#146). + /// of `heap` `HHItem`s, as UnivMon counts its heaps (#146). #[test] fn footprint_is_counters_plus_heap() { let p = ParamSet::of(&CmsHeapParams { rows: 5, cols: 2048, + heap: Some(128), }); - let heap = CMS_HEAP_TOP_K * std::mem::size_of::(); + let heap = 128 * std::mem::size_of::(); let fast = build_cms_heap_lib_vector2d_fast(&p).expect("5x2048 is a valid shape"); assert_eq!( memory_cms_heap_lib_vector2d_fast(&fast), @@ -85,4 +90,38 @@ mod tests { 5 * 2048 * std::mem::size_of::() + heap ); } + + /// A heap smaller than the `k` it answers can't answer, and is refused. + #[test] + fn a_heap_below_k_is_refused() { + let p = ParamSet::of(&CmsHeapParams { + rows: 3, + cols: 256, + heap: Some(TOPK_K - 1), + }); + let err = build_cms_heap_lib_vector2d_fast(&p).err().expect("refused"); + assert!(err.to_string().contains("heap="), "{err}"); + } + + /// A heap larger than `k` still answers its heaviest `TOPK_K`. + #[test] + fn a_larger_heap_answers_its_heaviest_k() { + let params = ParamSet::of(&CmsHeapParams { + rows: 5, + cols: 4096, + heap: Some(4 * TOPK_K), + }); + // Key i appears i times, for 2k keys: the heaviest k are k+1..=2k. + let keys = 2 * TOPK_K as i64; + let stream: Vec = (1..=keys) + .flat_map(|i| std::iter::repeat_n(i, i as usize)) + .collect(); + let mut passes = + query_cms_heap_lib_vector2d_fast_topk(¶ms, Rc::new(stream), Rc::new(vec![()]), 1) + .expect("builds"); + let (answers, _) = passes.remove(0)(); + let mut answered: Vec = answers[0].iter().map(|&(k, _)| k).collect(); + answered.sort_unstable(); + assert_eq!(answered, (TOPK_K as i64 + 1..=keys).collect::>()); + } } diff --git a/sketch-bench/src/wrappers/cms_heap/sketchlib.rs b/sketch-bench/src/wrappers/cms_heap/sketchlib.rs index 761178f4..7d29d951 100644 --- a/sketch-bench/src/wrappers/cms_heap/sketchlib.rs +++ b/sketch-bench/src/wrappers/cms_heap/sketchlib.rs @@ -11,14 +11,39 @@ use std::rc::Rc; use asap_sketchlib::input::HHItem; use asap_sketchlib::{heap_item_to_sketch_input, CMSHeap, FastPath, RegularPath, Vector2D}; -/// The heap's fixed capacity, and the `k` every TopK-capability row grades -/// against. The two are the same constant on purpose (see #95's design-decision -/// comment): a `CMSHeap` cannot answer a `k` bigger than its own capacity, so -/// letting grading `k` and construction capacity diverge — whether by a -/// `--config` field or a second constant — would let them silently disagree. -/// Changing this means editing it and rebuilding, not a config sweep; the -/// follow-up issue tracks loosening that. -pub const CMS_HEAP_TOP_K: usize = 32; +/// The `k` every TopK-capability row answers and is graded against, and the +/// heap's capacity when `--config` sets no `heap`. A larger heap (`heap=`) +/// keeps more candidates, so a merge of `m` heaps of `m · k` loses fewer of +/// the true top `k`; the answer is still its heaviest `k`. A heap smaller +/// than `k` couldn't answer, and is refused at build. +pub const TOPK_K: usize = 32; + +/// The heap capacity `heap` asks for: `TOPK_K` when absent, at least +/// `TOPK_K`. +pub fn heap_capacity(name: &str, heap: Option) -> Result { + let heap = heap.unwrap_or(TOPK_K); + if heap < TOPK_K { + return Err(BuildError(format!( + "{name}: heap={heap} is smaller than the k={TOPK_K} it answers" + ))); + } + Ok(heap) +} + +/// A heap's contents, heaviest first, cut to the `TOPK_K` a top-k query +/// answers. +pub fn top_k<'a>(items: impl Iterator) -> Vec<&'a HHItem> { + let mut items: Vec<&HHItem> = items.collect(); + let heaviest = |item: &&HHItem| std::cmp::Reverse(item.count); + // Select the heaviest k without sorting the rest: the query's cost is + // what's benchmarked. + if items.len() > TOPK_K { + items.select_nth_unstable_by_key(TOPK_K, heaviest); + items.truncate(TOPK_K); + } + items.sort_unstable_by_key(heaviest); + items +} /// One key read off the heap, paired with its estimated count. `TopkGT` /// scores a `Vec` of these against the exact top-k. @@ -33,6 +58,7 @@ pub struct CmsHeapLibVector2dFast { inner: CMSHeap, FastPath>, rows: usize, cols: usize, + heap: usize, } pub fn build_cms_heap_lib_vector2d_fast( @@ -41,18 +67,20 @@ pub fn build_cms_heap_lib_vector2d_fast( let p: CmsHeapParams = config.parse()?; require_positive("asap CMSHeap Vector2D FastPath", "rows", p.rows)?; require_positive("asap CMSHeap Vector2D FastPath", "cols", p.cols)?; + let heap = heap_capacity("asap CMSHeap Vector2D FastPath", p.heap)?; Ok(CmsHeapLibVector2dFast { - inner: CMSHeap::, FastPath>::new(p.rows, p.cols, CMS_HEAP_TOP_K), + inner: CMSHeap::, FastPath>::new(p.rows, p.cols, heap), rows: p.rows, cols: p.cols, + heap, }) } -/// The counter matrix plus a full heap of `CMS_HEAP_TOP_K` `HHItem`s, counted -/// the way UnivMon counts its heaps so the TopK rows compare like for like. +/// The counter matrix plus a full heap of `heap` `HHItem`s, counted the way +/// UnivMon counts its heaps so the TopK rows compare like for like. pub fn memory_cms_heap_lib_vector2d_fast(sketch: &CmsHeapLibVector2dFast) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + CMS_HEAP_TOP_K * std::mem::size_of::() + + sketch.heap * std::mem::size_of::() } // ---------- asap_sketchlib: Vector2D + RegularPath ---------- @@ -60,6 +88,7 @@ pub struct CmsHeapLibVector2dRegular { inner: CMSHeap, RegularPath>, rows: usize, cols: usize, + heap: usize, } pub fn build_cms_heap_lib_vector2d_regular( @@ -68,17 +97,19 @@ pub fn build_cms_heap_lib_vector2d_regular( let p: CmsHeapParams = config.parse()?; require_positive("asap CMSHeap Vector2D RegularPath", "rows", p.rows)?; require_positive("asap CMSHeap Vector2D RegularPath", "cols", p.cols)?; + let heap = heap_capacity("asap CMSHeap Vector2D RegularPath", p.heap)?; Ok(CmsHeapLibVector2dRegular { - inner: CMSHeap::, RegularPath>::new(p.rows, p.cols, CMS_HEAP_TOP_K), + inner: CMSHeap::, RegularPath>::new(p.rows, p.cols, heap), rows: p.rows, cols: p.cols, + heap, }) } /// As [`memory_cms_heap_lib_vector2d_fast`]. pub fn memory_cms_heap_lib_vector2d_regular(sketch: &CmsHeapLibVector2dRegular) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + CMS_HEAP_TOP_K * std::mem::size_of::() + + sketch.heap * std::mem::size_of::() } // ---------- insert / insert_step (FastPath) ---------- @@ -282,11 +313,8 @@ pub fn merge_query_cms_heap_lib_vector2d_fast_topk( out.push(Box::new(move || { let mut answers = Vec::with_capacity(probes.len()); for _p in probes.iter() { - let ranked: TopkAnswer = sketch - .inner - .heap() - .heap() - .iter() + let ranked: TopkAnswer = top_k(sketch.inner.heap().heap().iter()) + .into_iter() .map(|item| { ( T::from_data_input(&heap_item_to_sketch_input(&item.key)), @@ -332,11 +360,8 @@ pub fn merge_query_cms_heap_lib_vector2d_regular_topk( out.push(Box::new(move || { let mut answers = Vec::with_capacity(probes.len()); for _p in probes.iter() { - let ranked: TopkAnswer = sketch - .inner - .heap() - .heap() - .iter() + let ranked: TopkAnswer = top_k(sketch.inner.heap().heap().iter()) + .into_iter() .map(|item| { ( T::from_data_input(&heap_item_to_sketch_input(&item.key)), @@ -357,7 +382,7 @@ pub fn merge_query_cms_heap_lib_vector2d_regular_topk( // // Heavier than plain CMS's merge: after folding the counter matrices, // `CMSHeap::merge` re-estimates every heap candidate from both sides (up to -// 2 * CMS_HEAP_TOP_K `estimate()` calls) to rebuild the merged heap. Not a +// 2 * heap `estimate()` calls) to rebuild the merged heap. Not a // pure cell-fold the way plain CMS merge is — see the registry description. pub fn merge_cms_heap_lib_vector2d_fast( diff --git a/sketch-bench/src/wrappers/cs_heap.rs b/sketch-bench/src/wrappers/cs_heap.rs index 7a8225dd..2a0df763 100644 --- a/sketch-bench/src/wrappers/cs_heap.rs +++ b/sketch-bench/src/wrappers/cs_heap.rs @@ -1,11 +1,12 @@ //! `asap_sketchlib::CSHeap` — a Count Sketch paired with a top-k heap. The //! CountSketch counterpart of `cms_heap`'s top-k row, and graded the same way: -//! heap capacity is `CMS_HEAP_TOP_K`, the `k` `TopkGT` grades against. +//! the heap holds `heap` items (default `TOPK_K`) and the answer is its +//! heaviest `TOPK_K`, the `k` `TopkGT` grades against. // ponytail: Vector2D + FastPath top-k only, the one the optimizer prices; add // RegularPath / per-key estimate rows when something asks for them. -use crate::params::{CountSketchParams, ParamSet}; -use crate::wrappers::cms_heap::sketchlib::{TopkAnswer, CMS_HEAP_TOP_K}; +use crate::params::{CsHeapParams, ParamSet}; +use crate::wrappers::cms_heap::sketchlib::{heap_capacity, top_k, TopkAnswer}; use crate::wrappers::frequency_value::FrequencyValue; use crate::wrappers::{require_positive, BuildError, Pass, QueryPass, Shared, StepPass}; use asap_sketchlib::input::HHItem; @@ -17,25 +18,28 @@ pub struct CsHeapLibVector2dFast { inner: CSHeap, FastPath>, rows: usize, cols: usize, + heap: usize, } pub fn build_cs_heap_lib_vector2d_fast( config: &ParamSet, ) -> Result { - let p: CountSketchParams = config.parse()?; + let p: CsHeapParams = config.parse()?; require_positive("asap CSHeap Vector2D FastPath", "rows", p.rows)?; require_positive("asap CSHeap Vector2D FastPath", "cols", p.cols)?; + let heap = heap_capacity("asap CSHeap Vector2D FastPath", p.heap)?; Ok(CsHeapLibVector2dFast { - inner: CSHeap::, FastPath>::new(p.rows, p.cols, CMS_HEAP_TOP_K), + inner: CSHeap::, FastPath>::new(p.rows, p.cols, heap), rows: p.rows, cols: p.cols, + heap, }) } /// Counter matrix plus a full heap, as `cms_heap` counts it. pub fn memory_cs_heap_lib_vector2d_fast(sketch: &CsHeapLibVector2dFast) -> usize { sketch.rows * sketch.cols * std::mem::size_of::() - + CMS_HEAP_TOP_K * std::mem::size_of::() + + sketch.heap * std::mem::size_of::() } pub fn insert_cs_heap_lib_vector2d_fast( @@ -102,11 +106,8 @@ pub fn merge_query_cs_heap_lib_vector2d_fast_topk( out.push(Box::new(move || { let mut answers = Vec::with_capacity(probes.len()); for _p in probes.iter() { - let ranked: TopkAnswer = sketch - .inner - .heap() - .heap() - .iter() + let ranked: TopkAnswer = top_k(sketch.inner.heap().heap().iter()) + .into_iter() .map(|item| { ( T::from_data_input(&heap_item_to_sketch_input(&item.key)), diff --git a/sketch-bench/src/wrappers/univmon/sketchlib.rs b/sketch-bench/src/wrappers/univmon/sketchlib.rs index c8ca577b..0a8d44ab 100644 --- a/sketch-bench/src/wrappers/univmon/sketchlib.rs +++ b/sketch-bench/src/wrappers/univmon/sketchlib.rs @@ -326,9 +326,9 @@ fn univmon_lib_shards( // // Fed the same one-column stream the CMS/CS heap rows are, so `TopkGT` grades // all three alike. The answer is layer 0's heap -- the layer every item -// reaches -- cut to the `CMS_HEAP_TOP_K` heaviest. +// reaches -- cut to the `TOPK_K` heaviest. -use crate::wrappers::cms_heap::sketchlib::{TopkAnswer, CMS_HEAP_TOP_K}; +use crate::wrappers::cms_heap::sketchlib::{top_k, TopkAnswer}; use asap_sketchlib::heap_item_to_sketch_input; fn univmon_lib_item_shards( @@ -415,11 +415,8 @@ pub fn merge_query_univmon_lib_topk( out.push(Box::new(move || { let mut answers = Vec::with_capacity(probes.len()); for _p in probes.iter() { - let mut heap: Vec<_> = sketch.inner.hh_layers[0].heap().iter().collect(); - heap.sort_unstable_by_key(|item| std::cmp::Reverse(item.count)); - let ranked: TopkAnswer = heap + let ranked: TopkAnswer = top_k(sketch.inner.hh_layers[0].heap().iter()) .into_iter() - .take(CMS_HEAP_TOP_K) .map(|item| { ( T::from_data_input(&heap_item_to_sketch_input(&item.key)),