From 875e9932294db92552ed2ffa305c11a79d9d9193 Mon Sep 17 00:00:00 2001 From: lerman25 Date: Mon, 23 Nov 2026 18:21:38 +0200 Subject: [PATCH] Train RAM HNSW hybrid policy trees from measured workloads --- docs/benchmarks_developer.md | 1 + docs/hnsw_policy_training.md | 122 ++++++++ scripts/HNSW_batches_clf.py | 26 +- scripts/hnsw_policy_training.py | 451 +++++++++++++++++++++++++++ scripts/test_hnsw_policy_training.py | 138 ++++++++ 5 files changed, 733 insertions(+), 5 deletions(-) create mode 100644 docs/hnsw_policy_training.md create mode 100644 scripts/hnsw_policy_training.py create mode 100644 scripts/test_hnsw_policy_training.py diff --git a/docs/benchmarks_developer.md b/docs/benchmarks_developer.md index eec35a8a5..1e27eda83 100644 --- a/docs/benchmarks_developer.md +++ b/docs/benchmarks_developer.md @@ -6,6 +6,7 @@ - [How to define and register a new test](#how-to-define-and-register-a-new-test) * [Fixtures](#fixtures) - [Benchmarks fixture classes hierarchy](#benchmarks-fixture-classes-hierarchy) +* [Training the RAM HNSW policy selector](hnsw_policy_training.md) # Directory structure The benchmark directory contains several types of files as follows: diff --git a/docs/hnsw_policy_training.md b/docs/hnsw_policy_training.md new file mode 100644 index 000000000..552797765 --- /dev/null +++ b/docs/hnsw_policy_training.md @@ -0,0 +1,122 @@ +# Training the RAM HNSW hybrid policy tree + +`scripts/HNSW_batches_clf.py` fits a fixed decision tree that predicts the +initial choice between `ADHOC_BF` and `BATCHES` for filtered KNN. Use paired +measurements to make a candidate tree, inspect workload-level validation, and +optionally export a standalone C++17 header. + +## Run the trainer + +Run these commands from the root of the VectorSimilarity checkout. The trainer +requires Python 3.10 or newer, NumPy, and scikit-learn. + +```sh +python3 -m venv .venv +. .venv/bin/activate +python -m pip install numpy scikit-learn + +python scripts/HNSW_batches_clf.py \ + --measurements controlled.jsonl customer-replay.jsonl \ + --holdout-workload customer-replay \ + --report policy-evaluation.json \ + --cpp hnsw_policy_candidate.h +``` + +The script prints the tree and writes a JSON report with the input SHA-256 +checksums, library versions, arguments, validation results, and tree. The +optional C++ header exposes `preferAdHocSearchCandidate(input)`. It returns +`true` for `ADHOC_BF` and `false` for `BATCHES`. Count features are converted +to float32 before evaluation, and the emitted constants preserve the fitted +thresholds. A runtime integration can call this helper and retain the +existing mode reporting and switching logic. + +Run the script with no arguments to fit and plot the historical labels. That +mode requires Matplotlib. Its archived feature arrays encode `k` as 5, 10, and +15, while the comments describe 5, 50, and 500. The historical mode preserves +the archived encoding. Measurement mode uses the actual query `k`. + +## Record paired measurements + +Collect both forced policies on the same RAM HNSW snapshot, query vector, +predicate, `k`, search settings, and deadline. Rotate the order across +repetitions. Verify the effective policy outside the timed region. Use exact +filtered top-k over the same stored vectors to compute recall. Also verify +result completeness, eligibility, and document uniqueness. When only three +documents qualify for `k=10`, the reference contains those three documents. +Use vector-stage results from customer replays before application grouping +or ranking. + +Store one object per line in JSONL. The following object is formatted across +lines for readability. Its timings are illustrative. + +```json +{ + "workload": "customer-replay", + "case": "query-01", + "cohort": "numeric-and", + "estimate_source": "planner", + "k": 2000, + "index_size": 57000, + "label_count": 57000, + "dim": 1024, + "m": 16, + "subset_size": 8500, + "actual_matches": 3400, + "runs": [{ + "ADHOC_BF": {"status": "ok", "mode": "ADHOC_BF", "ms": 12.1, "recall": 1.0}, + "BATCHES": {"status": "ok", "mode": "BATCHES", "ms": 15.3, "recall": 0.97}, + "AUTO": {"status": "ok", "mode": "BATCHES_TO_ADHOC_BF", "ms": 18.7, "recall": 1.0} + }] +} +``` + +- **`workload`** identifies an independent corpus or replay family. Keep + variants of the same corpus, including different `k` values and index + sizes, in the same workload. Use `cohort` to break those variants out in the + report. Use a unique `case` within each workload. +- **`index_size` and `label_count`** count vectors and distinct vector + labels, respectively. The five model features are `k`, index size, vector + dimension, graph `M`, and estimated selectivity. The selectivity calculation + mirrors RAM HNSW by clamping `subset_size` to index size and dividing by + label count. +- **`subset_size`** is the initial filter estimate supplied to the selector. + Record `actual_matches` when available to audit estimation error. For a + separate exact-count experiment, set both fields to the actual count, set + `estimate_source` to `exact`, and pass `--estimate-source exact`. + The trainer rejects mixed estimate sources. +- **`runs`** contains all paired repetitions for the case. Include both + forced policies and, optionally, AUTO in every repetition. Use + `{"status": "timeout"}` for a measured timeout. A successful forced policy + must report its requested mode. AUTO can report `ADHOC_BF`, `BATCHES`, or + `BATCHES_TO_ADHOC_BF`. + +## How the tree is fitted + +| Choice | Default and rationale | +| --- | --- | +| Recall floor | `--min-recall 0.95`. A policy qualifies only when every paired repetition completes and reaches the floor. An exact run with low recall invalidates the case. An exact timeout can favor BATCHES if BATCHES completes and qualifies. | +| Latency | Take the median across repetitions for each qualified policy. Each query is one training case, regardless of repetition count. | +| Minimum speedup | `--min-speedup 0.05`. When both policies qualify, require the slower-to-faster latency ratio to exceed 1.05 to use the case in fitting. Close cases contribute to evaluation. | +| Training weights | Give more weight to a costly wrong decision using the logarithm of the latency ratio, capped at a 10× ratio. Give each workload the same total weight so a large synthetic sweep cannot dominate a smaller replay by case count. | +| Tree size | `--max-leaf-nodes 20` preserves the historical size cap. `--min-samples-leaf 3` limits splits that depend on a few measurements. Use smaller trees when held-out quality and latency are comparable. | +| Leaf policy | Prefer the policy with fewer training quality or deadline failures in that leaf. Break ties using the fitted decision. | + +Use `--holdout-workload NAME` once per reserved workload. The final fit +excludes those measurements. The report also evaluates leave-one-workload-out +folds among the training workloads. A single training workload cannot supply +a workload-level fold on its own. + +## Review the candidate + +Start with the held-out reports. Check recall or timeout failures separately +from latency ratios. The latency metrics compare the selected forced policy +with the best qualifying forced policy and with measured AUTO when available. +Measured AUTO may switch mid-query. Validate an integrated candidate to +measure its own switching costs and end-to-end latency. + +Use the cohort and conflicting-feature reports to decide what to measure next. +For a wider sweep, vary index sizes and `k` around existing thresholds and +customer values, then vary selectivity and predicate shape. Include filters +with the same selectivity whose matches are near, far from, or independent of +the query vector. If they favor different policies despite identical model +inputs, the current features cannot distinguish those cases. diff --git a/scripts/HNSW_batches_clf.py b/scripts/HNSW_batches_clf.py index 8652db4c0..353e9c7c9 100644 --- a/scripts/HNSW_batches_clf.py +++ b/scripts/HNSW_batches_clf.py @@ -2,15 +2,16 @@ # Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or # the Server Side Public License v1 (SSPLv1). -import matplotlib.pyplot as plt -import numpy as np +import sys -from sklearn.tree import DecisionTreeClassifier -from sklearn import tree '''------------------- batches HNSW -----------------''' def print_tree(clf): + import matplotlib.pyplot as plt + import numpy as np + from sklearn import tree + tree.plot_tree(clf) plt.savefig('batches_vs_adhoc-HNSW.pdf') plt.show() @@ -49,11 +50,17 @@ def print_tree(clf): feature=feature[i], threshold=threshold[i], right=children_right[i])) -if __name__ == '__main__': +def train_legacy(): + import numpy as np + from sklearn.tree import DecisionTreeClassifier + clf = DecisionTreeClassifier(max_leaf_nodes=20) # features: (k, index_size, dim, M, r) # labels: 1: adhoc better, -1: batches better + # Preserve the historical encoding (k = 5, 10, 15 in X_1 through X_4). + # The experimental comments say 5, 50, 500. The script only records + # the winning policy for each comparison. Measured mode takes the actual k. y = [] # The following labels represent the results for experiments that were held for the following combinations: @@ -343,3 +350,12 @@ def print_tree(clf): print_tree(clf) # (k, index_size, dim, M, r) print(clf.predict([[10, 800000, 100, 50, 0.0001]])) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + train_legacy() + else: + from hnsw_policy_training import main + + main() diff --git a/scripts/hnsw_policy_training.py b/scripts/hnsw_policy_training.py new file mode 100644 index 000000000..3fe03d5d1 --- /dev/null +++ b/scripts/hnsw_policy_training.py @@ -0,0 +1,451 @@ +# Copyright Redis Ltd. 2021 - present +# Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or +# the Server Side Public License v1 (SSPLv1). + +"""Train and evaluate the RAM HNSW policy selector using paired measurements.""" + +import argparse +from collections import Counter, defaultdict +from dataclasses import dataclass +import hashlib +import json +import math +from pathlib import Path +from statistics import median + +import numpy as np +import sklearn +from sklearn.tree import DecisionTreeClassifier + + +ADHOC = "ADHOC_BF" +BATCHES = "BATCHES" +AUTO = "AUTO" +FEATURES = ("k", "index_size", "dim", "m", "selectivity") +AUTO_MODES = {ADHOC, BATCHES, "BATCHES_TO_ADHOC_BF"} + + +@dataclass(frozen=True) +class Measurement: + ms: float + recall: float + mode: str + + +@dataclass(frozen=True) +class Case: + workload: str + name: str + cohort: str + features: tuple + subset_size: int + actual_matches: int | None + runs: dict + + +@dataclass(frozen=True) +class Outcome: + case: Case + qualified_ms: dict + winner: str + weight: float + + +@dataclass(frozen=True) +class FittedPolicy: + tree: DecisionTreeClassifier + leaf_choices: dict + + def predict(self, features): + return [self.leaf_choices[node] for node in self.tree.apply(features)] + + +def integer(record, key, minimum=1): + value = record[key] + if type(value) is not int or not minimum <= value <= 2**64 - 1: + raise ValueError(f"{key} must be an integer in [{minimum}, 2**64 - 1]") + return value + + +def number(record, key, minimum, maximum=math.inf): + value = record[key] + if type(value) not in (float, int) or not math.isfinite(value): + raise ValueError(f"{key} must be a finite number") + if not minimum <= value <= maximum: + raise ValueError(f"{key} must be in [{minimum}, {maximum}]") + return float(value) + + +def nonempty_string(record, key): + value = record[key] + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{key} must be a nonempty string") + return value + + +def measurement(record, policy): + status = record["status"] + if status == "timeout": + # A timeout is a measured failure, with no fabricated latency or recall. + return None + if status != "ok": + raise ValueError(f"{policy} status must be ok or timeout, got {status!r}") + mode = nonempty_string(record, "mode") + if mode not in (AUTO_MODES if policy == AUTO else {policy}): + raise ValueError(f"{policy} ran in unexpected mode {mode!r}") + ms = number(record, "ms", 0) + if ms == 0: + raise ValueError("ms must be positive") + return Measurement(ms, number(record, "recall", 0, 1), mode) + + +def parse_case(record, estimate_source): + workload = nonempty_string(record, "workload") + name = nonempty_string(record, "case") + cohort = nonempty_string(record, "cohort") + if record["estimate_source"] != estimate_source: + raise ValueError(f"expected estimate_source={estimate_source!r}") + k = integer(record, "k") + size = integer(record, "index_size") + labels = integer(record, "label_count") + dim = integer(record, "dim") + m = integer(record, "m") + subset = integer(record, "subset_size", minimum=0) + actual = integer(record, "actual_matches", minimum=0) if "actual_matches" in record else None + if labels > size or (actual is not None and actual > labels): + raise ValueError("expected actual_matches <= label_count <= index_size") + if estimate_source == "exact" and actual != subset: + raise ValueError("exact selectivity requires subset_size == actual_matches") + # Mirror preferAdHocSearch's clamp and float division. The denominator + # counts labels, while index_size counts vectors, even for multi-value fields. + selectivity = np.float32(min(subset, size)) / np.float32(labels) + features = (k, size, dim, m, float(selectivity)) + + pairs = record["runs"] + if not isinstance(pairs, list) or not pairs: + raise ValueError("runs must be a nonempty list of paired repetitions") + policies = {ADHOC, BATCHES} + if AUTO in pairs[0]: + policies.add(AUTO) + runs = {policy: [] for policy in sorted(policies)} + for pair in pairs: + if set(pair) != policies: + raise ValueError("each repetition must contain ADHOC_BF and BATCHES, with optional AUTO") + for policy in runs: + runs[policy].append(measurement(pair[policy], policy)) + return Case(workload, name, cohort, features, subset, actual, runs) + + +def load_cases(paths, estimate_source): + cases = {} + sources = [] + for path in paths: + raw = path.read_bytes() + sources.append({"file": path.name, "sha256": hashlib.sha256(raw).hexdigest()}) + for line_no, line in enumerate(raw.decode().splitlines(), 1): + if not line.strip(): + continue + try: + case = parse_case(json.loads(line), estimate_source) + key = (case.workload, case.name) + if key in cases: + raise ValueError(f"duplicate case {key!r}; combine its paired repetitions") + cases[key] = case + except (KeyError, TypeError, ValueError, OverflowError) as exc: + raise ValueError(f"{path}:{line_no}: {exc}") from exc + return [cases[key] for key in sorted(cases)], sources + + +def score_case(case, recall_floor, margin): + qualified = { + policy: median(run.ms for run in runs) + for policy, runs in case.runs.items() + if all(run is not None and run.recall >= recall_floor for run in runs) + } + if any(run is not None and run.recall < recall_floor for run in case.runs[ADHOC]): + # Unexpectedly low exact recall suggests a bad comparison. A measured + # timeout is different: BATCHES may meet the deadline and recall floor. + return None + forced = [policy for policy in (ADHOC, BATCHES) if policy in qualified] + if not forced: + return None + best = min(forced, key=qualified.get) + if len(forced) == 1: + return Outcome(case, qualified, best, math.log(10)) + speedup = (max(qualified[ADHOC], qualified[BATCHES]) / + min(qualified[ADHOC], qualified[BATCHES])) + weight = min(math.log(speedup), math.log(10)) if speedup > 1 + margin else 0.0 + return Outcome(case, qualified, best, weight) + + +def fit(outcomes, max_leaves, min_leaf): + decisive = [item for item in outcomes if item.weight > 0] + if not decisive: + raise ValueError("training set contains no decisive, recall-qualified comparisons") + # Equal total influence per workload, then weight by the cost of a wrong + # decision within that workload. Repetitions never become duplicate rows. + workload_weights = defaultdict(float) + for row in decisive: + workload_weights[row.case.workload] += row.weight + weights = [row.weight / workload_weights[row.case.workload] for row in decisive] + model = DecisionTreeClassifier( + max_leaf_nodes=max_leaves, min_samples_leaf=min_leaf, random_state=0 + ) + model.fit( + [row.case.features for row in decisive], [row.winner for row in decisive], + sample_weight=weights, + ) + features = [row.case.features for row in outcomes] + nodes = model.apply(features) + failures = defaultdict(Counter) + leaf_choices = dict(zip(nodes, model.predict(features), strict=True)) + for node, item in zip(nodes, outcomes, strict=True): + for policy in (ADHOC, BATCHES): + if policy not in item.qualified_ms: + failures[node][policy] += 1 + for node, preferred in leaf_choices.items(): + # The weighted split finds speedups. Within a leaf, use the policy + # with fewer observed quality/deadline failures first. + leaf_choices[node] = min((ADHOC, BATCHES), key=lambda policy: ( + failures[node][policy], policy != preferred, + )) + return FittedPolicy(model, leaf_choices) + + +def describe_choices(outcomes, choices): + slowdowns = [] + auto_ratios = [] + failures = 0 + for item, choice in zip(outcomes, choices, strict=True): + selected = item.qualified_ms.get(choice) + if selected is None: + failures += 1 + continue + slowdowns.append(selected / item.qualified_ms[item.winner]) + if AUTO in item.qualified_ms: + auto_ratios.append(selected / item.qualified_ms[AUTO]) + + return { + "cases": len(outcomes), + "selected": dict(sorted(Counter(choices).items())), + "quality_or_timeout_failures": failures, + "within_5pct_of_best_forced": sum(value <= 1.05 for value in slowdowns), + "median_slowdown": median(slowdowns) if slowdowns else None, + "p90_slowdown": float(np.quantile(slowdowns, 0.9)) if slowdowns else None, + "worst_slowdown": max(slowdowns, default=None), + "comparable_auto_cases": len(auto_ratios), + "median_latency_over_measured_auto": median(auto_ratios) if auto_ratios else None, + } + + +def evaluate(model, outcomes): + if not outcomes: + return None + choices = model.predict([item.case.features for item in outcomes]) + cohorts = defaultdict(list) + winners_by_features = defaultdict(set) + for item, choice in zip(outcomes, choices, strict=True): + cohorts[item.case.cohort].append((item, choice)) + if item.weight > 0: + winners_by_features[tuple(np.float32(item.case.features))].add(item.winner) + return { + "candidate": describe_choices(outcomes, choices), + "always_adhoc": describe_choices(outcomes, [ADHOC] * len(outcomes)), + "always_batches": describe_choices(outcomes, [BATCHES] * len(outcomes)), + "measured_auto": describe_choices( + [item for item in outcomes if AUTO in item.case.runs], + [AUTO for item in outcomes if AUTO in item.case.runs], + ), + "auto_recorded_cases": sum(AUTO in item.case.runs for item in outcomes), + "auto_modes": dict(sorted(Counter( + run.mode if run else "timeout" + for item in outcomes for run in item.case.runs.get(AUTO, []) + ).items())), + "conflicting_decisive_feature_vectors": sum( + len(winners) > 1 for winners in winners_by_features.values() + ), + "by_cohort": { + cohort: describe_choices(*zip(*rows)) for cohort, rows in sorted(cohorts.items()) + }, + "decisions": [{ + "workload": item.case.workload, + "case": item.case.name, + "cohort": item.case.cohort, + "features": dict(zip(FEATURES, item.case.features)), + "subset_size": item.case.subset_size, + "actual_matches": item.case.actual_matches, + "best_forced": item.winner, + "decisive": item.weight > 0, + "choice": choice, + "qualified_ms": item.qualified_ms, + } for item, choice in zip(outcomes, choices, strict=True)], + } + + +def export_rule(model, node=0): + tree = model.tree.tree_ + left, right = tree.children_left[node], tree.children_right[node] + if left == right: + return {"policy": str(model.leaf_choices[node])} + if_le, if_gt = export_rule(model, left), export_rule(model, right) + if if_le == if_gt: + return if_le + return { + "feature": FEATURES[tree.feature[node]], + "threshold": float(tree.threshold[node]), + "if_le": if_le, + "if_gt": if_gt, + } + + +def print_rule(rule, depth=0): + indent = " " * depth + if "policy" in rule: + print(f"{indent}{rule['policy']}") + return + print(f"{indent}if {rule['feature']} <= {rule['threshold']:.9g}") + print_rule(rule["if_le"], depth + 1) + print(f"{indent}else") + print_rule(rule["if_gt"], depth + 1) + + +def export_cpp(rule): + """Emit an offline candidate with the same float32 inputs used by sklearn.""" + expressions = { + "k": "static_cast(input.k)", + "index_size": "static_cast(input.indexSize)", + "dim": "static_cast(input.dimension)", + "m": "static_cast(input.m)", + "selectivity": "selectivity", + } + + def render(node, depth): + indent = " " * depth + if "policy" in node: + return [indent + ("return true;" if node["policy"] == ADHOC else "return false;")] + expression = expressions[node["feature"]] + # Preserve the double-precision threshold, including the midpoint + # between adjacent values of a float32 feature. + threshold = node["threshold"].hex() + return [ + f"{indent}if ({expression} <= {threshold}) {{", + *render(node["if_le"], depth + 1), + f"{indent}}}", + *render(node["if_gt"], depth), + ] + + header = """// Generated by scripts/HNSW_batches_clf.py. +// Candidate for offline evaluation. +#pragma once + +#include +#include + +struct HnswPolicyInput { + std::size_t k; + std::size_t indexSize; + std::size_t dimension; + std::size_t m; + std::size_t subsetSize; + std::size_t labelCount; +}; + +// True selects ADHOC_BF, false selects BATCHES. +inline bool preferAdHocSearchCandidate(const HnswPolicyInput &input) { + [[maybe_unused]] const float selectivity = + input.indexSize == 0 + ? 0.0f + : static_cast(std::min(input.subsetSize, input.indexSize)) / + static_cast(input.labelCount); +""" + return header + "\n".join(render(rule, 1)) + "\n}\n" + + +def train(args): + cases, sources = load_cases(args.measurements, args.estimate_source) + workloads = sorted({case.workload for case in cases}) + held_out = set(args.holdout_workload) + if missing := held_out.difference(workloads): + raise ValueError(f"unknown holdout workloads: {', '.join(sorted(missing))}") + by_workload = {name: [] for name in workloads} + unusable = Counter() + for case in cases: + outcome = score_case(case, args.min_recall, args.min_speedup) + if outcome: + by_workload[case.workload].append(outcome) + else: + unusable[case.workload] += 1 + + train_groups = [name for name in workloads if name not in held_out] + training = [item for name in train_groups for item in by_workload[name]] + model = fit(training, args.max_leaf_nodes, args.min_samples_leaf) + cross_validation = {} + for name in train_groups: + other_cases = [item for item in training if item.case.workload != name] + if not by_workload[name] or not any(item.weight > 0 for item in other_cases): + cross_validation[name] = None + continue + fold_model = fit(other_cases, args.max_leaf_nodes, args.min_samples_leaf) + cross_validation[name] = evaluate(fold_model, by_workload[name]) + + return model, { + "format_version": 1, + "numpy_version": np.__version__, + "sklearn_version": sklearn.__version__, + "sources": sources, + "estimate_source": args.estimate_source, + "features": FEATURES, + "parameters": { + "min_recall": args.min_recall, + "min_speedup": args.min_speedup, + "max_leaf_nodes": args.max_leaf_nodes, + "min_samples_leaf": args.min_samples_leaf, + }, + "workloads": { + name: { + "role": "holdout" if name in held_out else "train", + "usable": len(by_workload[name]), + "decisive": dict(sorted(Counter( + item.winner for item in by_workload[name] if item.weight > 0 + ).items())), + "unusable_comparisons": unusable[name], + } for name in workloads + }, + "training": evaluate(model, training), + "leave_one_workload_out": cross_validation, + "holdout": {name: evaluate(model, by_workload[name]) for name in sorted(held_out)}, + "tree": export_rule(model), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--measurements", nargs="+", type=Path, required=True, metavar="JSONL") + parser.add_argument("--report", type=Path, required=True, help="write checksummed inputs, evaluation and tree as JSON") + parser.add_argument("--cpp", type=Path, metavar="HEADER", help="write a standalone C++17 candidate") + parser.add_argument("--holdout-workload", action="append", default=[], metavar="NAME") + parser.add_argument("--estimate-source", choices=("planner", "exact"), default="planner", + help="require planner estimates (default) or run a separate exact-count experiment") + parser.add_argument("--min-recall", type=float, default=0.95) + parser.add_argument("--min-speedup", type=float, default=0.05, + help="required latency ratio minus one to use a comparison for fitting") + parser.add_argument("--max-leaf-nodes", type=int, default=20) + parser.add_argument("--min-samples-leaf", type=int, default=3) + args = parser.parse_args() + if not 0 <= args.min_recall <= 1 or not math.isfinite(args.min_speedup) or args.min_speedup < 0: + parser.error("min-recall must be between 0 and 1 and min-speedup must be finite and nonnegative") + if args.max_leaf_nodes < 2 or args.min_samples_leaf < 1: + parser.error("max-leaf-nodes must be at least 2 and min-samples-leaf must be positive") + output_paths = [path.resolve() for path in (args.report, args.cpp) if path is not None] + if len(output_paths) != len(set(output_paths)): + parser.error("report and C++ output must be different files") + if set(output_paths).intersection(path.resolve() for path in args.measurements): + parser.error("outputs must not overwrite their inputs") + try: + _, report = train(args) + args.report.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n", encoding="utf-8") + if args.cpp is not None: + args.cpp.write_text(export_cpp(report["tree"]), encoding="utf-8") + except (OSError, ValueError) as exc: + parser.error(str(exc)) + print_rule(report["tree"]) diff --git a/scripts/test_hnsw_policy_training.py b/scripts/test_hnsw_policy_training.py new file mode 100644 index 000000000..95b53d765 --- /dev/null +++ b/scripts/test_hnsw_policy_training.py @@ -0,0 +1,138 @@ +# Copyright Redis Ltd. 2021 - present +# Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or +# the Server Side Public License v1 (SSPLv1). + +import argparse +import json +from pathlib import Path +import shutil +import subprocess +from tempfile import TemporaryDirectory +import unittest + +from hnsw_policy_training import ( + ADHOC, AUTO, BATCHES, export_cpp, export_rule, fit, parse_case, score_case, train, +) + + +def run(policy, ms, recall=1.0): + return {"status": "ok", "mode": policy, "ms": ms, "recall": recall} + + +def case(workload="customer", name="q1", k=2000, subset=4000, adhoc_ms=10, batches_ms=2): + return { + "workload": workload, + "case": name, + "cohort": "numeric-and", + "k": k, + "index_size": 5700, + "label_count": 5700, + "dim": 1024, + "m": 16, + "subset_size": subset, + "actual_matches": 2000, + "estimate_source": "planner", + "runs": [{ + ADHOC: run(ADHOC, adhoc_ms), + BATCHES: run(BATCHES, batches_ms), + AUTO: run("BATCHES_TO_ADHOC_BF", 15), + }], + } + + +class PolicyTrainingTests(unittest.TestCase): + def test_high_k_reaches_model_and_estimate_matches_runtime_clamp(self): + record = case(k=2000, subset=9999) + record["label_count"] = 2850 + parsed = parse_case(record, "planner") + self.assertEqual(parsed.features, (2000, 5700, 1024, 16, 2.0)) + self.assertEqual(parsed.actual_matches, 2000) + + def test_exact_counts_are_kept_out_of_planner_runs(self): + record = case() + record["estimate_source"] = "exact" + with self.assertRaisesRegex(ValueError, "expected estimate_source"): + parse_case(record, "planner") + with self.assertRaisesRegex(ValueError, "subset_size == actual_matches"): + parse_case(record, "exact") + + def test_runtime_switch_is_allowed_only_for_auto(self): + record = case() + record["runs"][0][BATCHES] = run("BATCHES_TO_ADHOC_BF", 1) + with self.assertRaisesRegex(ValueError, "unexpected mode"): + parse_case(record, "planner") + + def test_quality_overrides_speed_and_measured_timeouts(self): + record = case() + record["runs"][0][BATCHES]["recall"] = 0.90 + result = score_case(parse_case(record, "planner"), 0.95, 0.05) + self.assertEqual(result.winner, ADHOC) + self.assertNotIn(BATCHES, result.qualified_ms) + record["runs"][0][BATCHES]["recall"] = 0.99 + record["runs"][0][ADHOC] = {"status": "timeout"} + result = score_case(parse_case(record, "planner"), 0.95, 0.05) + self.assertEqual(result.winner, BATCHES) + record["runs"][0][ADHOC] = run(ADHOC, 10, recall=0.90) + self.assertIsNone(score_case(parse_case(record, "planner"), 0.95, 0.05)) + + def test_leaf_with_conflicting_evidence_uses_fewer_quality_failures(self): + records = [case(name=f"q{i}") for i in range(6)] + records[-1]["runs"][0][BATCHES]["recall"] = 0.90 + outcomes = [score_case(parse_case(record, "planner"), 0.95, 0.05) for record in records] + model = fit(outcomes, max_leaves=4, min_leaf=1) + self.assertEqual(model.tree.predict([outcomes[0].case.features]).tolist(), [BATCHES]) + self.assertEqual(model.predict([outcomes[0].case.features]), [ADHOC]) + self.assertEqual(export_rule(model), {"policy": ADHOC}) + + def test_holdout_is_not_fit_and_rule_matches_model(self): + records = [case("train-a", "low-k", k=25, adhoc_ms=1), + case("train-b", "high-k", k=2000), + case("held", "different-high-k", k=2000, adhoc_ms=1)] + with TemporaryDirectory() as directory: + path = Path(directory) / "cases.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in records)) + args = argparse.Namespace( + measurements=[path], estimate_source="planner", holdout_workload=["held"], + min_recall=0.95, min_speedup=0.05, max_leaf_nodes=4, min_samples_leaf=1, + ) + model, report = train(args) + self.assertEqual(report["training"]["candidate"]["cases"], 2) + self.assertEqual(set(report["leave_one_workload_out"]), {"train-a", "train-b"}) + held = report["holdout"]["held"]["decisions"][0] + self.assertEqual(held["choice"], BATCHES) + self.assertEqual(held["best_forced"], ADHOC) + self.assertEqual(report["tree"]["feature"], "k") + self.assertEqual(report["tree"]["if_le"]["policy"], ADHOC) + self.assertEqual(report["tree"]["if_gt"]["policy"], BATCHES) + predicted, = model.predict([parse_case(records[-1], "planner").features]) + self.assertEqual(predicted, held["choice"]) + + @unittest.skipUnless(shutil.which("c++"), "a C++ compiler is needed to check header parity") + def test_generated_cpp_preserves_float32_splits(self): + lower = case(name="lower", k=16777216, adhoc_ms=1) + upper = case(name="upper", k=16777218) + outcomes = [score_case(parse_case(row, "planner"), 0.95, 0.05) for row in (lower, upper)] + model = fit(outcomes, max_leaves=4, min_leaf=1) + features = [parse_case(case(k=k), "planner").features + for k in (16777216, 16777217, 16777218)] + expected = [policy == ADHOC for policy in model.predict(features)] + with TemporaryDirectory() as directory: + folder = Path(directory) + (folder / "policy.h").write_text(export_cpp(export_rule(model))) + source = folder / "test.cpp" + cases = "\n".join( + f" assert(preferAdHocSearchCandidate({{{k}, 5700, 1024, 16, 4000, 5700}})" + f" == {str(result).lower()});" + for (k, *_), result in zip(features, expected, strict=True) + ) + source.write_text( + '#include "policy.h"\n#include \nint main() {\n' + cases + "\n}\n" + ) + executable = folder / "test" + subprocess.run(["c++", "-std=c++17", "-Wall", "-Wextra", "-Werror", source, + "-o", executable], check=True) + subprocess.run([executable], check=True) + + +if __name__ == "__main__": + unittest.main()