diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 7fb1dc66..63efa770 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -277,9 +277,13 @@ each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto 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 +5%). The study adds the cost table's shape to the grid as a full row and +column (θ = 1.1 at every K, K = 1e4 at every θ), so every sketch row has a +grid point and the grid stays a full cross. `SaturationCurves::load` +refuses curves whose Zipf grid isn't a full cross of its θ and K values and +names the missing points: a hole would leave every shape around it without +accuracy (for example, curves from `--points-from` or a narrowed `--resume`). A row without a grid point (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 diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 02a072cc..c7743d47 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -80,10 +80,11 @@ atomic-costs` to `rqe_atomic_costs.json` (#174). Top-k configs are measured at h 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, -which uses the same data, reads an exact curve rather than the worse -neighbouring grid point. +grid also covers that shape (unless `--no-cost-shape`): θ = 1.1 and K = 1e4 +join the grid as a full row and column (a = 2 joins the Pareto values), so +the grid stays a full cross, 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/src/saturation.rs b/rqe-optimizer/src/saturation.rs index a499ec04..6ac729bc 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -380,6 +380,36 @@ impl SaturationCurves { } points_by_sketch.entry(sketch).or_default().push(point); } + // The optimizer brackets a shape between grid points, so each + // config's Zipf grid must be a full cross of its θ and K values: a + // hole would quietly leave every shape around it without accuracy. + for (sketch, points) in &points_by_sketch { + let mut by_config: BTreeMap> = BTreeMap::new(); + for point in points { + if let MeasuredShape::Zipf { skew, keys } = point.shape { + by_config + .entry(format!("{:?}", point.params)) + .or_default() + .insert((skew.to_bits(), keys.to_bits())); + } + } + for (config, shapes) in by_config { + let thetas: BTreeSet = shapes.iter().map(|&(t, _)| t).collect(); + let keys: BTreeSet = shapes.iter().map(|&(_, k)| k).collect(); + let missing: Vec<(f64, f64)> = thetas + .iter() + .flat_map(|&t| keys.iter().map(move |&k| (t, k))) + .filter(|shape| !shapes.contains(shape)) + .map(|(t, k)| (f64::from_bits(t), f64::from_bits(k))) + .collect(); + if !missing.is_empty() { + return Err(invalid(format!( + "{sketch} {config}: the grid isn't a full cross of θ and K; \ + missing (θ, K) {missing:?}. Rerun the study's accuracy grid for them" + ))); + } + } + } Ok(Self { points_by_sketch }) } @@ -810,6 +840,34 @@ mod tests { ); } + /// A hole in the grid (a bracketing point the study didn't measure) + /// leaves the shape unknown rather than bridging to farther points: + /// accuracy needn't be monotone in K. + #[test] + fn a_hole_in_the_grid_has_no_accuracy() { + let mut curves = curves(); + // Drop θ = 1.2, K = 1e3. + let hole = MeasuredShape::Zipf { + skew: 1.2, + keys: 1e3, + }; + curves + .points_by_sketch + .get_mut(TOPK) + .unwrap() + .retain(|p| p.shape != hole); + let r = topk_raqe(1_000_000); + let d = deployment(TOPK, 1_000_000); + assert_eq!( + curves.accuracy(&r, &d, &workload(10, shape(1.1, 1e3))), + None + ); + // θ = 1.0 at K = 1e3 is still measured. + assert!(curves + .accuracy(&r, &d, &workload(10, shape(1.0, 1e3))) + .is_some()); + } + #[test] fn a_shape_outside_the_grid_or_without_a_fit_has_no_accuracy() { let r = topk_raqe(1_000_000); @@ -1113,6 +1171,39 @@ mod tests { assert_eq!(check(&[misnamed]).mismatched.len(), 1); } + #[test] + fn load_refuses_a_grid_that_isnt_a_full_cross() { + let dir = std::env::temp_dir().join(format!("rqe-cross-{}", std::process::id())); + let header = "family,sketch,config,dist,param,cardinality"; + let points = ["1.0,1000", "1.2,1000", "1.0,100000"] + .map(|shape| format!("topk,{TOPK},rows=3 cols=1024,zipf,{shape}")); + for run in RUN_DIRS { + std::fs::create_dir_all(dir.join(run)).unwrap(); + let summary: String = points + .iter() + .map(|p| format!("{p},1000,0.9,precision_at_k\n")) + .collect(); + let curve: String = points.iter().map(|p| format!("{p},1000,0.9,0\n")).collect(); + std::fs::write( + dir.join(run).join("saturation.csv"), + format!("{header},n_sat,final_error,error_metric\n{summary}"), + ) + .unwrap(); + std::fs::write( + dir.join(run).join("saturation_curve.csv"), + format!("{header},n,seed_mean_error,seed_se\n{curve}"), + ) + .unwrap(); + } + let loaded = SaturationCurves::load(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + let err = loaded.unwrap_err().to_string(); + assert!( + err.contains("full cross") && err.contains("(1.2, 100000.0)"), + "{err}" + ); + } + #[test] fn load_takes_a_point_in_both_runs_from_the_1e9_run() { let dir = std::env::temp_dir().join(format!("rqe-saturation-{}", std::process::id())); diff --git a/scripts/study_saturation.py b/scripts/study_saturation.py index 8727d8b8..b5fde9ed 100644 --- a/scripts/study_saturation.py +++ b/scripts/study_saturation.py @@ -23,8 +23,9 @@ 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. +The grid also holds every config at the optimizer-cost shape unless +--no-cost-shape: θ = 1.1 and K = 1e4 join --thetas and --cardinalities (a full +row and column, so the grid stays a full cross) and a = 2 joins --alphas. --resume keeps the complete curves of an interrupted accuracy run; --cost-rows 3 times only the rows=3 Vector2D configs. @@ -462,11 +463,13 @@ def main(): points.append((family, variant, config, comparator, metric, dataset, "pareto", alpha, "")) continue - # 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: + # Plus the cost table's shape as a full row and column (θ = 1.1 at + # every K, K = 1e4 at every θ), so its rows are points on a curve + # and the grid stays a full cross for the optimizer's bracketing. + grid_thetas = thetas + [COST_THETA] * (args.cost_shape and COST_THETA not in thetas) + grid_keys = cardinalities + [COST_KEYS] * ( + args.cost_shape and COST_KEYS not in cardinalities) + for theta, k in [(t, k) for t in grid_thetas for k in grid_keys]: dataset = ["--dataset", "zipf", "--zipf-s", str(theta), "--cardinality", str(k), "--dtype", "i64"] points.append((family, variant, config, comparator, metric, diff --git a/scripts/test_study_saturation.py b/scripts/test_study_saturation.py index 6df75564..a2ab0742 100644 --- a/scripts/test_study_saturation.py +++ b/scripts/test_study_saturation.py @@ -422,7 +422,21 @@ def test_the_grid_also_runs_the_optimizer_cost_shape(self): ], 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")}) + # A full row and column: θ = 1.1 at every K, K = 1e4 at every θ. + self.assertEqual(shapes, {("1.0", "1000"), ("1.0", "10000"), + ("1.1", "1000"), ("1.1", "10000")}) + + def test_a_grid_that_already_has_the_cost_shape_adds_nothing(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.1", "--cardinalities", "10000", "--n-max", "1e4", + "--per-decade", "1", "--seeds", "1", + ], check=True, capture_output=True) + with open(os.path.join(d, "saturation.csv"), newline="") as f: + shapes = [(r["param"], r["cardinality"]) for r in csv.DictReader(f)] + self.assertEqual(shapes, [("1.1", "10000")]) # Logs every call; atomic-costs reports `--rows` rows kept, 0 skipped.