|
| 1 | +"""pgvector vs TurboVec dual-index benchmark. |
| 2 | +
|
| 3 | +Default mode is offline/synthetic so CI does not need Postgres or the optional |
| 4 | +TurboVec package. When ``turbovec`` + ``numpy`` are installed, the report also |
| 5 | +includes a real ``IdMapIndex`` row behind ``KB_VECTOR=turbovec``. |
| 6 | +
|
| 7 | +Postgres/pgvector remains the primary CI gate. This bench never promotes |
| 8 | +TurboVec. |
| 9 | +""" |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import argparse |
| 13 | +import os |
| 14 | +import random |
| 15 | +import resource |
| 16 | +import statistics |
| 17 | +import time |
| 18 | +from pathlib import Path |
| 19 | +from typing import Sequence |
| 20 | + |
| 21 | +from kb_engine.store import FakeTurboVecStore, TurboVecStore, create_turbovec_store |
| 22 | + |
| 23 | + |
| 24 | +def _vectors(n: int, dim: int) -> list[list[float]]: |
| 25 | + rng = random.Random(42) |
| 26 | + return [[rng.uniform(-1.0, 1.0) for _ in range(dim)] for _ in range(n)] |
| 27 | + |
| 28 | + |
| 29 | +def _p95(values: Sequence[float]) -> float: |
| 30 | + if not values: |
| 31 | + return 0.0 |
| 32 | + ordered = sorted(values) |
| 33 | + idx = min(len(ordered) - 1, int(round((len(ordered) - 1) * 0.95))) |
| 34 | + return ordered[idx] |
| 35 | + |
| 36 | + |
| 37 | +def _bench_store(name: str, store, n: int, dim: int, queries: int) -> dict[str, float | str]: |
| 38 | + vectors = _vectors(n, dim) |
| 39 | + store.add_with_ids(list(range(1, n + 1)), vectors) |
| 40 | + latencies: list[float] = [] |
| 41 | + for query in _vectors(queries, dim): |
| 42 | + started = time.perf_counter() |
| 43 | + store.search(query, k=8) |
| 44 | + latencies.append((time.perf_counter() - started) * 1000) |
| 45 | + return { |
| 46 | + "backend": name, |
| 47 | + "count": n, |
| 48 | + "dim": dim, |
| 49 | + "p95_ms": _p95(latencies), |
| 50 | + "mean_ms": statistics.fmean(latencies) if latencies else 0.0, |
| 51 | + "rss_mb": _rss_mb(), |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +def run_bench(n: int = 1000, dim: int = 32, queries: int = 50) -> list[dict[str, float | str]]: |
| 56 | + # Align dim to TurboVec's multiple-of-8 constraint for the real path. |
| 57 | + real_dim = dim if dim % 8 == 0 else dim + (8 - dim % 8) |
| 58 | + rows: list[dict[str, float | str]] = [ |
| 59 | + # Exact cosine baseline (in-memory Fake) — not live Postgres/pgvector ANN. |
| 60 | + _bench_store("exact-cosine-baseline", FakeTurboVecStore(dim=real_dim), n, real_dim, queries), |
| 61 | + _bench_store("turbovec-fake-sidecar", FakeTurboVecStore(dim=real_dim), n, real_dim, queries), |
| 62 | + ] |
| 63 | + # Optional real package path (install: uv pip install 'kb-engine[turbovec]') |
| 64 | + try: |
| 65 | + store = create_turbovec_store(dim=real_dim) |
| 66 | + if isinstance(store, TurboVecStore): |
| 67 | + rows.append(_bench_store("turbovec-real-idmap", store, n, real_dim, queries)) |
| 68 | + else: |
| 69 | + rows.append({ |
| 70 | + "backend": "turbovec-real-idmap", |
| 71 | + "count": n, |
| 72 | + "dim": real_dim, |
| 73 | + "p95_ms": 0.0, |
| 74 | + "mean_ms": 0.0, |
| 75 | + "rss_mb": _rss_mb(), |
| 76 | + "note": "skipped: turbovec not installed; Fake used", |
| 77 | + }) |
| 78 | + except Exception as exc: # pragma: no cover - environment-specific |
| 79 | + rows.append({ |
| 80 | + "backend": "turbovec-real-idmap", |
| 81 | + "count": n, |
| 82 | + "dim": real_dim, |
| 83 | + "p95_ms": 0.0, |
| 84 | + "mean_ms": 0.0, |
| 85 | + "rss_mb": _rss_mb(), |
| 86 | + "note": f"skipped: {exc}", |
| 87 | + }) |
| 88 | + return rows |
| 89 | + |
| 90 | + |
| 91 | +def _rss_mb() -> float: |
| 92 | + raw = float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) |
| 93 | + # Linux reports KiB; macOS reports bytes. |
| 94 | + return raw / (1024 * 1024) if raw > 10_000_000 else raw / 1024 |
| 95 | + |
| 96 | + |
| 97 | +def render_markdown(rows: list[dict[str, float | str]]) -> str: |
| 98 | + kb_vector = os.environ.get("KB_VECTOR", "pgvector") |
| 99 | + lines = [ |
| 100 | + "# Vector Bench", |
| 101 | + "", |
| 102 | + "> Dual-index sidecar report. TurboVec is optional; pgvector remains the", |
| 103 | + f"> default primary backend (`KB_VECTOR={kb_vector}`). Real TurboVec rows", |
| 104 | + "> appear only when `turbovec`+`numpy` are installed (`kb-engine[turbovec]`).", |
| 105 | + "> This artifact does **not** promote TurboVec.", |
| 106 | + "", |
| 107 | + "| Backend | Vectors | Dim | p95 ms | Mean ms | RSS MB | Note |", |
| 108 | + "| --- | ---: | ---: | ---: | ---: | ---: | --- |", |
| 109 | + ] |
| 110 | + for row in rows: |
| 111 | + note = str(row.get("note", "")) |
| 112 | + lines.append( |
| 113 | + "| {backend} | {count} | {dim} | {p95_ms:.3f} | {mean_ms:.3f} | {rss_mb:.1f} | {note} |".format( |
| 114 | + backend=row["backend"], |
| 115 | + count=row["count"], |
| 116 | + dim=row["dim"], |
| 117 | + p95_ms=float(row["p95_ms"]), |
| 118 | + mean_ms=float(row["mean_ms"]), |
| 119 | + rss_mb=float(row["rss_mb"]), |
| 120 | + note=note, |
| 121 | + ) |
| 122 | + ) |
| 123 | + lines.append("") |
| 124 | + return "\n".join(lines) |
| 125 | + |
| 126 | + |
| 127 | +def main() -> int: |
| 128 | + parser = argparse.ArgumentParser(description=__doc__) |
| 129 | + parser.add_argument("--n", type=int, default=1000) |
| 130 | + parser.add_argument("--dim", type=int, default=32) |
| 131 | + parser.add_argument("--queries", type=int, default=50) |
| 132 | + parser.add_argument( |
| 133 | + "--out", |
| 134 | + default="../vault/_meta/dashboards/vector-bench.md", |
| 135 | + help="markdown report path", |
| 136 | + ) |
| 137 | + args = parser.parse_args() |
| 138 | + |
| 139 | + rows = run_bench(n=args.n, dim=args.dim, queries=args.queries) |
| 140 | + report = render_markdown(rows) |
| 141 | + out = Path(args.out) |
| 142 | + out.parent.mkdir(parents=True, exist_ok=True) |
| 143 | + out.write_text(report, encoding="utf-8") |
| 144 | + print(report) |
| 145 | + print(f"wrote {out}") |
| 146 | + return 0 |
| 147 | + |
| 148 | + |
| 149 | +if __name__ == "__main__": |
| 150 | + raise SystemExit(main()) |
0 commit comments