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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions aqpbm-cli/src/rows/statistic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,8 @@ pub(super) fn cardinality_row<T: ColumnItem>(

/// 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<T: CountedValue>(
req: &Requirement,
Expand All @@ -100,7 +99,7 @@ pub(super) fn topk_row<T: CountedValue>(
description,
table,
want,
TopkGT::<T>::over_column(chl::CMS_HEAP_TOP_K, value_column(description)),
TopkGT::<T>::over_column(chl::TOPK_K, value_column(description)),
peel::<T>,
insert,
insert_step,
Expand Down
12 changes: 11 additions & 1 deletion docs/rqe_sketch_deployment_v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion docs/saturation_study.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
9 changes: 4 additions & 5 deletions rqe-optimizer/src/analytical_cost_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 13 additions & 1 deletion rqe-optimizer/src/autosketch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,22 @@ struct Grid {

impl Grid {
fn new(variant: &str, costs: &[AtomicCostEntry]) -> Option<Grid> {
// 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::<Vec<_>>(),
);
let rows: Vec<(usize, BTreeMap<String, f64>)> = 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() {
Expand Down
206 changes: 198 additions & 8 deletions rqe-optimizer/src/candidates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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))
Expand All @@ -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<u64> = group
.iter()
.filter_map(|r| heap_needed(r.lookback_ms, window_ms))
.collect();
let configs: Vec<AtomicCostEntry> = 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<u64, AtomicCostEntry> = 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 {
Expand Down Expand Up @@ -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<u64, &'a AtomicCostEntry>> {
let mut out: BTreeMap<_, BTreeMap<u64, &AtomicCostEntry>> = 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<u64, &AtomicCostEntry>, heap: u64) -> Option<AtomicCostEntry> {
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],
Expand Down Expand Up @@ -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))
}

Expand All @@ -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,
Expand All @@ -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::<BTreeSet<_>>()
};
// 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)];
Expand Down
3 changes: 2 additions & 1 deletion rqe-optimizer/src/enumerate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading