|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Benchmark runner for the local kll_sketch implementation.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import importlib |
| 8 | +import hashlib |
| 9 | +import math |
| 10 | +import time |
| 11 | +from pathlib import Path |
| 12 | +from typing import Callable, Dict, Iterable, List, Sequence |
| 13 | + |
| 14 | +import numpy as np |
| 15 | +import pandas as pd |
| 16 | + |
| 17 | + |
| 18 | +def _parse_args() -> argparse.Namespace: |
| 19 | + parser = argparse.ArgumentParser(description=__doc__) |
| 20 | + parser.add_argument("--module", default="kll_sketch", help="Module that exports the sketch class") |
| 21 | + parser.add_argument("--class", dest="cls", default="KLLSketch", help="Sketch class name inside the module") |
| 22 | + parser.add_argument("--outdir", default="bench_out", help="Directory for benchmark CSV outputs") |
| 23 | + parser.add_argument("--seed", type=int, default=42, help="Base RNG seed for reproducibility") |
| 24 | + parser.add_argument("--Ns", nargs="+", default=["1e5", "1e6"], help="Population sizes to benchmark") |
| 25 | + parser.add_argument( |
| 26 | + "--capacities", nargs="+", default=["200", "400", "800"], help="Sketch capacities to benchmark" |
| 27 | + ) |
| 28 | + parser.add_argument( |
| 29 | + "--distributions", |
| 30 | + nargs="+", |
| 31 | + default=["uniform", "normal", "exponential", "pareto", "bimodal"], |
| 32 | + help="Synthetic data distributions to sample", |
| 33 | + ) |
| 34 | + parser.add_argument( |
| 35 | + "--qs", |
| 36 | + nargs="+", |
| 37 | + default=["0.01", "0.05", "0.1", "0.25", "0.5", "0.75", "0.9", "0.95", "0.99"], |
| 38 | + help="Quantiles to evaluate", |
| 39 | + ) |
| 40 | + parser.add_argument("--shards", type=int, default=8, help="Number of shards for the merge benchmark") |
| 41 | + return parser.parse_args() |
| 42 | + |
| 43 | + |
| 44 | +def _to_int_list(values: Iterable[str]) -> List[int]: |
| 45 | + return [int(float(v)) for v in values] |
| 46 | + |
| 47 | + |
| 48 | +def _to_float_list(values: Iterable[str]) -> List[float]: |
| 49 | + return [float(v) for v in values] |
| 50 | + |
| 51 | + |
| 52 | +def _hash_seed(seed: int, *parts: object) -> int: |
| 53 | + material = "::".join(str(p) for p in (seed,) + parts) |
| 54 | + digest = hashlib.sha256(material.encode("utf-8")).hexdigest() |
| 55 | + return int(digest[:16], 16) |
| 56 | + |
| 57 | + |
| 58 | +def _uniform(rng: np.random.Generator, size: int) -> np.ndarray: |
| 59 | + return rng.uniform(0.0, 1.0, size) |
| 60 | + |
| 61 | + |
| 62 | +def _normal(rng: np.random.Generator, size: int) -> np.ndarray: |
| 63 | + return rng.normal(0.0, 1.0, size) |
| 64 | + |
| 65 | + |
| 66 | +def _exponential(rng: np.random.Generator, size: int) -> np.ndarray: |
| 67 | + return rng.exponential(scale=1.0, size=size) |
| 68 | + |
| 69 | + |
| 70 | +def _pareto(rng: np.random.Generator, size: int) -> np.ndarray: |
| 71 | + return rng.pareto(a=1.5, size=size) |
| 72 | + |
| 73 | + |
| 74 | +def _bimodal(rng: np.random.Generator, size: int) -> np.ndarray: |
| 75 | + left = size // 2 |
| 76 | + right = size - left |
| 77 | + first = rng.normal(-2.0, 1.0, left) |
| 78 | + second = rng.normal(2.0, 0.5, right) |
| 79 | + data = np.concatenate([first, second]) if size else np.empty(0, dtype=float) |
| 80 | + rng.shuffle(data) |
| 81 | + return data |
| 82 | + |
| 83 | + |
| 84 | +DATA_GENERATORS: Dict[str, Callable[[np.random.Generator, int], np.ndarray]] = { |
| 85 | + "uniform": _uniform, |
| 86 | + "normal": _normal, |
| 87 | + "exponential": _exponential, |
| 88 | + "pareto": _pareto, |
| 89 | + "bimodal": _bimodal, |
| 90 | +} |
| 91 | + |
| 92 | + |
| 93 | +def _validate_distributions(names: Sequence[str]) -> None: |
| 94 | + unknown = sorted(set(names) - DATA_GENERATORS.keys()) |
| 95 | + if unknown: |
| 96 | + raise ValueError(f"Unknown distributions requested: {', '.join(unknown)}") |
| 97 | + |
| 98 | + |
| 99 | +def _instantiate_sketch(sketch_cls, capacity: int, seed: int): |
| 100 | + try: |
| 101 | + return sketch_cls(capacity=capacity, rng_seed=seed) |
| 102 | + except TypeError: |
| 103 | + # Older signatures might use positional arguments only. |
| 104 | + return sketch_cls(capacity) |
| 105 | + |
| 106 | + |
| 107 | +def main() -> None: |
| 108 | + args = _parse_args() |
| 109 | + |
| 110 | + Ns = _to_int_list(args.Ns) |
| 111 | + capacities = _to_int_list(args.capacities) |
| 112 | + qs = _to_float_list(args.qs) |
| 113 | + _validate_distributions(args.distributions) |
| 114 | + |
| 115 | + module = importlib.import_module(args.module) |
| 116 | + cls_name = args.cls |
| 117 | + if not hasattr(module, cls_name): |
| 118 | + fallback_names = [] |
| 119 | + if not cls_name.endswith("Sketch"): |
| 120 | + fallback_names.append(f"{cls_name}Sketch") |
| 121 | + fallback_names.append("KLLSketch") |
| 122 | + for candidate in fallback_names: |
| 123 | + if hasattr(module, candidate): |
| 124 | + cls_name = candidate |
| 125 | + break |
| 126 | + else: |
| 127 | + available = ", ".join(sorted(attr for attr in dir(module) if not attr.startswith("_"))) |
| 128 | + raise AttributeError( |
| 129 | + f"{module.__name__!r} does not define {args.cls!r}. Available attributes: {available}" |
| 130 | + ) |
| 131 | + |
| 132 | + sketch_cls = getattr(module, cls_name) |
| 133 | + |
| 134 | + outdir = Path(args.outdir) |
| 135 | + outdir.mkdir(parents=True, exist_ok=True) |
| 136 | + |
| 137 | + accuracy_records: List[Dict[str, object]] = [] |
| 138 | + throughput_records: List[Dict[str, object]] = [] |
| 139 | + latency_records: List[Dict[str, object]] = [] |
| 140 | + merge_records: List[Dict[str, object]] = [] |
| 141 | + |
| 142 | + for dist in args.distributions: |
| 143 | + for N in Ns: |
| 144 | + combo_seed = _hash_seed(args.seed, dist, N) |
| 145 | + data_rng = np.random.default_rng(combo_seed) |
| 146 | + generator = DATA_GENERATORS[dist] |
| 147 | + data = generator(data_rng, N).astype(float, copy=False) |
| 148 | + if data.size != N: |
| 149 | + data = np.resize(data, N) |
| 150 | + |
| 151 | + exact_quantiles = np.quantile(data, qs, method="linear") |
| 152 | + exact_map = dict(zip(qs, exact_quantiles)) |
| 153 | + |
| 154 | + for capacity in capacities: |
| 155 | + sketch = _instantiate_sketch(sketch_cls, capacity, args.seed) |
| 156 | + start = time.perf_counter() |
| 157 | + for value in data: |
| 158 | + sketch.add(float(value)) |
| 159 | + update_elapsed = time.perf_counter() - start |
| 160 | + updates_per_sec = (N / update_elapsed) if update_elapsed > 0 else math.inf |
| 161 | + |
| 162 | + throughput_records.append( |
| 163 | + { |
| 164 | + "distribution": dist, |
| 165 | + "N": int(N), |
| 166 | + "capacity": int(capacity), |
| 167 | + "update_time_s": update_elapsed, |
| 168 | + "updates_per_sec": updates_per_sec, |
| 169 | + } |
| 170 | + ) |
| 171 | + |
| 172 | + for q in qs: |
| 173 | + q_float = float(q) |
| 174 | + q_start = time.perf_counter() |
| 175 | + approx = sketch.quantile(q_float) |
| 176 | + q_elapsed = time.perf_counter() - q_start |
| 177 | + latency_records.append( |
| 178 | + { |
| 179 | + "distribution": dist, |
| 180 | + "N": int(N), |
| 181 | + "capacity": int(capacity), |
| 182 | + "q": q_float, |
| 183 | + "latency_us": q_elapsed * 1e6, |
| 184 | + } |
| 185 | + ) |
| 186 | + accuracy_records.append( |
| 187 | + { |
| 188 | + "distribution": dist, |
| 189 | + "N": int(N), |
| 190 | + "capacity": int(capacity), |
| 191 | + "mode": "single", |
| 192 | + "q": q_float, |
| 193 | + "estimate": approx, |
| 194 | + "exact": exact_map[q_float], |
| 195 | + "abs_error": abs(approx - exact_map[q_float]), |
| 196 | + } |
| 197 | + ) |
| 198 | + |
| 199 | + shard_arrays = np.array_split(data, args.shards) |
| 200 | + shard_sketches = [] |
| 201 | + for shard_idx, shard in enumerate(shard_arrays): |
| 202 | + shard_sketch = _instantiate_sketch( |
| 203 | + sketch_cls, capacity, args.seed + shard_idx + 1 |
| 204 | + ) |
| 205 | + for value in shard: |
| 206 | + shard_sketch.add(float(value)) |
| 207 | + shard_sketches.append(shard_sketch) |
| 208 | + |
| 209 | + merge_target = _instantiate_sketch(sketch_cls, capacity, args.seed) |
| 210 | + merge_start = time.perf_counter() |
| 211 | + for shard_sketch in shard_sketches: |
| 212 | + merge_target.merge(shard_sketch) |
| 213 | + merge_elapsed = time.perf_counter() - merge_start |
| 214 | + |
| 215 | + merge_records.append( |
| 216 | + { |
| 217 | + "distribution": dist, |
| 218 | + "N": int(N), |
| 219 | + "capacity": int(capacity), |
| 220 | + "shards": int(args.shards), |
| 221 | + "merge_time_s": merge_elapsed, |
| 222 | + } |
| 223 | + ) |
| 224 | + |
| 225 | + for q in qs: |
| 226 | + q_float = float(q) |
| 227 | + approx = merge_target.quantile(q_float) |
| 228 | + accuracy_records.append( |
| 229 | + { |
| 230 | + "distribution": dist, |
| 231 | + "N": int(N), |
| 232 | + "capacity": int(capacity), |
| 233 | + "mode": "merged", |
| 234 | + "q": q_float, |
| 235 | + "estimate": approx, |
| 236 | + "exact": exact_map[q_float], |
| 237 | + "abs_error": abs(approx - exact_map[q_float]), |
| 238 | + } |
| 239 | + ) |
| 240 | + |
| 241 | + accuracy_path = outdir / "accuracy.csv" |
| 242 | + throughput_path = outdir / "update_throughput.csv" |
| 243 | + latency_path = outdir / "query_latency.csv" |
| 244 | + merge_path = outdir / "merge.csv" |
| 245 | + |
| 246 | + pd.DataFrame.from_records(accuracy_records).to_csv(accuracy_path, index=False) |
| 247 | + pd.DataFrame.from_records(throughput_records).to_csv(throughput_path, index=False) |
| 248 | + pd.DataFrame.from_records(latency_records).to_csv(latency_path, index=False) |
| 249 | + pd.DataFrame.from_records(merge_records).to_csv(merge_path, index=False) |
| 250 | + |
| 251 | + print("Benchmark artifacts written to:") |
| 252 | + print(f" {accuracy_path}") |
| 253 | + print(f" {throughput_path}") |
| 254 | + print(f" {latency_path}") |
| 255 | + print(f" {merge_path}") |
| 256 | + |
| 257 | + |
| 258 | +if __name__ == "__main__": |
| 259 | + main() |
0 commit comments