File size: 24,212 Bytes
b8128a3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | """
annbench_core.py -- shared core for CS4.406 Assignment 3 (ANN benchmarking).
Every notebook writes an identical copy of this file, so each notebook runs standalone.
Conventions used everywhere in this project:
* All distances are SQUARED L2, computed on float32 vectors. GloVe is unit-normalised
first, so squared-L2 order == cosine order. We never rely on the scale of the
distances stored in the ann-benchmarks HDF5 files (euclidean vs cosine units);
those files are used for their neighbour IDS only, as an independent cross-check.
* k = 10 everywhere.
* Queries 0..4999 = TUNE split (parameter picking).
Queries 5000..9999 = EVAL split (every number that appears in the report).
* Timing is single-thread, one query at a time. See bench_single_query.
"""
import json
import os
import platform
import re
import subprocess
import sys
import time
import hashlib
import numpy as np
K = 10
TIE_EPS = 1e-6
TUNE = slice(0, 5000)
EVAL = slice(5000, 10000)
HF_REPO = "donbosoc/ire-a3-ann"
HF_REPO_TYPE = "dataset"
def _pick_scratch():
"""Scratch for big files: /kaggle/temp does not count against the 20 GB output quota,
but it is not guaranteed to exist or be writable, so fall back rather than crash."""
for cand in ("/kaggle/temp/a3", "/kaggle/working/tmp/a3", "/tmp/a3"):
try:
os.makedirs(cand, exist_ok=True)
probe = os.path.join(cand, ".w")
with open(probe, "w") as f:
f.write("x")
os.remove(probe)
return cand
except Exception:
continue
raise RuntimeError("no writable scratch directory found")
TMP = _pick_scratch()
OUT = "/kaggle/working" if os.path.isdir("/kaggle/working") else "./out"
def ensure_dirs():
for p in (TMP, f"{TMP}/data", f"{TMP}/gt", f"{TMP}/idx",
f"{OUT}/results", f"{OUT}/figures", f"{OUT}/logs", f"{OUT}/env"):
os.makedirs(p, exist_ok=True)
# --------------------------------------------------------------------------------------
# Environment
# --------------------------------------------------------------------------------------
def env_fingerprint(verbose=True):
"""Capture the machine + library versions behind every measurement.
Kaggle VMs are shared and the CPU model can differ between sessions, so this goes
into every results row and the report states it rather than claiming a quiet machine.
"""
info = {}
try:
cpuinfo = open("/proc/cpuinfo").read()
models = re.findall(r"^model name\s*:\s*(.+)$", cpuinfo, re.M)
info["cpu_model"] = models[0].strip() if models else "unknown"
info["cpu_logical"] = len(models)
except Exception:
info["cpu_model"], info["cpu_logical"] = platform.processor() or "unknown", os.cpu_count()
try:
mem_kb = int(re.search(r"MemTotal:\s*(\d+)", open("/proc/meminfo").read()).group(1))
info["mem_gb"] = round(mem_kb / 1048576, 1)
except Exception:
info["mem_gb"] = None
info["python"] = sys.version.split()[0]
info["numpy"] = np.__version__
for mod in ("faiss", "torch", "h5py"):
try:
info[mod] = __import__(mod).__version__
except Exception:
info[mod] = None
try:
import torch
info["gpu"] = torch.cuda.get_device_name(0) if torch.cuda.is_available() else None
except Exception:
info["gpu"] = None
try:
info["nvidia_smi"] = subprocess.run(
["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader"],
capture_output=True, text=True, timeout=30).stdout.strip()
except Exception:
info["nvidia_smi"] = None
# Stable id for "which machine produced this row".
key = f"{info['cpu_model']}|{info['cpu_logical']}|{info['mem_gb']}"
info["machine_id"] = hashlib.sha1(key.encode()).hexdigest()[:8]
if verbose:
print(f"machine_id : {info['machine_id']}")
print(f"cpu : {info['cpu_model']} ({info['cpu_logical']} logical)")
print(f"memory : {info['mem_gb']} GB")
print(f"gpu : {info['gpu']}")
print(f"versions : python {info['python']}, numpy {info['numpy']}, "
f"faiss {info['faiss']}, torch {info['torch']}, h5py {info['h5py']}")
return info
def set_single_thread():
"""Pin FAISS to one thread. Every benchmark number in this project is single-thread."""
import faiss
faiss.omp_set_num_threads(1)
n = faiss.omp_get_max_threads()
assert n == 1, f"expected 1 FAISS thread, got {n}"
return n
# --------------------------------------------------------------------------------------
# Hugging Face
# --------------------------------------------------------------------------------------
_TOKEN_NAMES = ["HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGINGFACEHUB_API_TOKEN",
"HF", "hf_token", "huggingface"]
def get_hf_token():
"""Find the HF token in Kaggle secrets, then the environment. Raises if absent."""
tried = []
try:
from kaggle_secrets import UserSecretsClient
client = UserSecretsClient()
for name in _TOKEN_NAMES:
try:
tok = client.get_secret(name)
if tok:
print(f"HF token: Kaggle secret '{name}'")
return tok.strip()
except Exception:
tried.append(f"secret:{name}")
except Exception:
tried.append("kaggle_secrets unavailable")
for name in _TOKEN_NAMES:
tok = os.environ.get(name)
if tok:
print(f"HF token: environment variable '{name}'")
return tok.strip()
tried.append(f"env:{name}")
raise RuntimeError(
"No Hugging Face token found. Add it under Notebook > Add-ons > Secrets with "
f"label 'HF_TOKEN' and attach it to this notebook. Tried: {tried}")
def hf_api(token=None):
from huggingface_hub import HfApi
return HfApi(token=token or get_hf_token())
def hf_ensure_repo(token=None):
api = hf_api(token)
api.create_repo(HF_REPO, repo_type=HF_REPO_TYPE, exist_ok=True, private=False)
return api
def hf_upload(local_path, path_in_repo, token=None, msg=None, quiet=False):
api = hf_api(token)
size = os.path.getsize(local_path) / 1e6
if not quiet:
print(f" -> hf://{HF_REPO}/{path_in_repo} ({size:.1f} MB)", flush=True)
api.upload_file(path_or_fileobj=local_path, path_in_repo=path_in_repo,
repo_id=HF_REPO, repo_type=HF_REPO_TYPE,
commit_message=msg or f"add {path_in_repo}")
def hf_download(path_in_repo, token=None, local_dir=None):
"""Return a local path for a repo file, or None if it is not in the repo."""
from huggingface_hub import hf_hub_download
try:
return hf_hub_download(repo_id=HF_REPO, repo_type=HF_REPO_TYPE,
filename=path_in_repo, token=token or get_hf_token(),
local_dir=local_dir or f"{TMP}/hf")
except Exception as e:
if "404" in str(e) or "EntryNotFound" in type(e).__name__:
return None
raise
# --------------------------------------------------------------------------------------
# Exact ground truth on the GPU
# --------------------------------------------------------------------------------------
def exact_gt_gpu(base, queries, k=100, chunk=None, mem_budget_gb=None,
refine=True, verbose=True):
"""Brute-force top-k by squared L2, selected on the GPU, then refined exactly.
The GPU pass uses the (|q|^2 + |b|^2 - 2 q.b) expansion in float32, which is fast but
loses a few ULPs. Selection errors from that can only happen between points that are
equal to within those ULPs -- i.e. ties, which our recall metric forgives anyway. The
returned DISTANCES are then recomputed by direct subtraction in float64, so the
threshold that recall@10 depends on is exact.
The distance block is (nq, chunk) float32, which at 10k queries is 400 MB per 10k
base vectors, so a fixed chunk would OOM a 16 GB T4 outright. `chunk` is derived from
the free VRAM and the query count unless given explicitly, and the block is written
into ONE preallocated buffer with in-place ops -- writing the expression out as
`q_sq + b_sq - 2*q@b.T` would allocate three such blocks per iteration instead.
Returns (ids int32 (nq,k), dists float64 (nq,k)) sorted ascending.
"""
import torch
assert base.dtype == np.float32 and queries.dtype == np.float32
dev = "cuda" if torch.cuda.is_available() else "cpu"
n, d = base.shape
nq = queries.shape[0]
k = min(k, n)
# torch.topk allocates a workspace about the size of its input, so the real peak is
# ~2x the distance block. Budget a fifth of free VRAM to leave headroom for that.
if mem_budget_gb is None:
if dev == "cuda":
torch.cuda.empty_cache()
mem_budget_gb = max(0.25, 0.20 * torch.cuda.mem_get_info()[0] / (1 << 30))
else:
mem_budget_gb = 2.0
auto = max(1024, int(mem_budget_gb * (1 << 30) / (nq * 4)))
chunk = min(chunk, auto) if chunk else auto
chunk = min(chunk, n)
q = torch.from_numpy(np.ascontiguousarray(queries).copy()).to(dev)
q_sq = (q * q).sum(1, keepdim=True)
buf = torch.empty((nq, chunk), device=dev, dtype=torch.float32)
best_d = best_i = None
t0 = time.perf_counter()
if verbose:
print(f" gt: {n:,} x {nq:,} in blocks of {chunk:,} "
f"(~{nq * chunk * 4 / 1e9:.2f} GB/block) on {dev}")
for s in range(0, n, chunk):
blk = torch.from_numpy(np.ascontiguousarray(base[s:s + chunk]).copy()).to(dev)
m = blk.shape[0]
dist = buf[:, :m]
torch.mm(q, blk.T, out=dist)
dist.mul_(-2.0).add_(q_sq).add_((blk * blk).sum(1)[None, :]).clamp_(min=0)
kk = min(k, m)
dv, di = torch.topk(dist, kk, dim=1, largest=False)
di = di + s
if best_d is None:
best_d, best_i = dv.clone(), di
else:
cd, ci = torch.cat([best_d, dv], 1), torch.cat([best_i, di], 1)
best_d, pos = torch.topk(cd, k, dim=1, largest=False)
best_i = torch.gather(ci, 1, pos)
del cd, ci, pos
del blk, dv, di
if verbose:
print(f"\r gt: {min(s + chunk, n):,}/{n:,} vectors", end="", flush=True)
if verbose:
print(f"\r gt: {n:,}/{n:,} vectors in {time.perf_counter() - t0:.1f}s on {dev}")
ids = best_i.cpu().numpy().astype(np.int32)
approx = best_d.cpu().numpy().astype(np.float64)
del q, q_sq, best_i, best_d, buf
if dev == "cuda":
torch.cuda.empty_cache()
if not refine:
return ids, approx
dists = exact_dists_for_ids(base, queries, ids)
order = np.argsort(dists, axis=1, kind="stable")
ids = np.take_along_axis(ids, order, axis=1)
dists = np.take_along_axis(dists, order, axis=1)
return ids, dists
def exact_dists_for_ids(base, queries, ids, block=512):
"""Exact squared-L2 distance from each query to each of its listed ids, in float64.
Direct subtraction (no q^2+b^2-2qb expansion), so there is no cancellation error.
ids == -1 (index returned fewer than k) yields +inf. Chunked over queries to bound
the (block, k, d) temporary.
"""
nq, kk = ids.shape
out = np.empty((nq, kk), dtype=np.float64)
for s in range(0, nq, block):
e = min(s + block, nq)
idx = ids[s:e]
valid = idx >= 0
vecs = base[np.where(valid, idx, 0)].astype(np.float64) # (b, k, d)
diff = vecs - queries[s:e].astype(np.float64)[:, None, :]
out[s:e] = np.where(valid, np.einsum("bkd,bkd->bk", diff, diff), np.inf)
return out
# --------------------------------------------------------------------------------------
# Recall@10, tie-aware (Part 1 asks for this specifically)
# --------------------------------------------------------------------------------------
def recall_at_k(retrieved_ids, retrieved_true_d, gt_dists, k=K, eps=TIE_EPS):
"""Per-query recall@k that does not punish ties at the k-th neighbour.
A returned id counts as correct when its EXACT distance is <= the exact distance of
the true k-th neighbour (plus a tiny slack). If the true 10th and 11th neighbours sit
at the same distance, returning either one is right, so membership of the stored
top-10 id list is the wrong test -- distance is the right one.
Duplicate ids are credited once, so an index that returns the same vector twice
cannot inflate its score.
retrieved_ids : (nq, k') ids from the index; -1 means "fewer than k' results".
retrieved_true_d : (nq, k') EXACT squared-L2 distances for those ids (inf for -1).
gt_dists : (nq, >=k) exact squared-L2 distances of the true neighbours, ascending.
returns : (nq,) float64 in [0, 1].
"""
retrieved_ids = np.asarray(retrieved_ids)
retrieved_true_d = np.asarray(retrieved_true_d, dtype=np.float64)
gt_dists = np.asarray(gt_dists, dtype=np.float64)
if retrieved_ids.ndim == 1:
retrieved_ids = retrieved_ids[None, :]
retrieved_true_d = retrieved_true_d[None, :]
gt_dists = gt_dists[None, :]
assert retrieved_ids.shape == retrieved_true_d.shape
assert gt_dists.shape[1] >= k, f"need >= {k} ground-truth distances"
dk = gt_dists[:, k - 1][:, None]
thresh = dk * (1.0 + eps) + eps # relative slack, plus absolute for dk == 0
hit = (retrieved_ids >= 0) & (retrieved_true_d <= thresh)
# Count DISTINCT hit ids per row.
masked = np.where(hit, retrieved_ids, -1)
masked = np.sort(masked, axis=1)
dup = np.zeros(masked.shape, dtype=bool)
dup[:, 1:] = masked[:, 1:] == masked[:, :-1]
n_hit = ((masked >= 0) & ~dup).sum(1)
return np.minimum(n_hit, k) / float(k)
def recall_from_ids(retrieved_ids, base, queries, gt_dists, k=K):
"""recall_at_k convenience wrapper that recomputes the exact distances itself.
Needed for IVF-PQ, whose returned distances are approximations of the real ones and
must never be fed to the recall metric.
"""
d = exact_dists_for_ids(base, queries, np.asarray(retrieved_ids))
return recall_at_k(retrieved_ids, d, gt_dists, k=k)
# --------------------------------------------------------------------------------------
# Timing
# --------------------------------------------------------------------------------------
def bench_single_query(search_fn, queries, repeats=3, warmup=50):
"""Time `search_fn` one query at a time, single thread; report the median run.
Per-query timers cost ~50-100 ns each against queries of 10^2-10^4 us, i.e. under
0.1%, so QPS is taken as n / sum(per-query latencies) from the same pass that
produces the latency percentiles.
"""
nq = len(queries)
for i in range(min(warmup, nq)):
search_fn(queries[i:i + 1])
runs = []
for _ in range(repeats):
lat = np.empty(nq, dtype=np.float64)
for i in range(nq):
t0 = time.perf_counter_ns()
search_fn(queries[i:i + 1])
lat[i] = time.perf_counter_ns() - t0
runs.append(lat)
qps = np.array([nq / (r.sum() / 1e9) for r in runs])
med = runs[int(np.argsort(qps)[len(qps) // 2])] # latencies of the median run
return dict(
qps_median=float(np.median(qps)),
qps_runs=[round(float(x), 2) for x in qps],
qps_spread_pct=round(float(100 * (qps.max() - qps.min()) / np.median(qps)), 2),
lat_p50_ms=float(np.percentile(med, 50) / 1e6),
lat_p95_ms=float(np.percentile(med, 95) / 1e6),
n_queries=int(nq), repeats=int(repeats),
)
def bench_batch(search_fn, queries, repeats=3, warmup=1):
"""Time one call that passes every query at once (Part 1's batched comparison)."""
nq = len(queries)
for _ in range(warmup):
search_fn(queries)
secs = []
for _ in range(repeats):
t0 = time.perf_counter_ns()
search_fn(queries)
secs.append((time.perf_counter_ns() - t0) / 1e9)
secs = np.array(secs)
return dict(qps_median=float(nq / np.median(secs)),
qps_runs=[round(float(nq / s), 2) for s in secs],
wall_s_median=float(np.median(secs)),
n_queries=int(nq), repeats=int(repeats))
# --------------------------------------------------------------------------------------
# Results table
# --------------------------------------------------------------------------------------
COLUMNS = [
"run_id", "timestamp", "part", "dataset", "n_vectors", "dim", "metric",
"index_kind", "build_params", "search_param_name", "search_param_value",
"recall_at_10", "recall_std", "qps_median", "qps_runs", "qps_spread_pct",
"lat_p50_ms", "lat_p95_ms", "build_time_s", "train_time_s", "add_time_s",
"index_size_bytes", "bytes_per_vector", "n_queries", "repeats", "threads",
"query_split", "machine_id", "cpu_model", "faiss_version", "notes",
]
class ResultsLog:
"""Append-only results table, mirrored to HF after every few rows.
One row per benchmark run, as the deliverable requires. Resumability comes from this
file: `done()` lets a restarted notebook skip measurements already in the table,
which is what makes a killed Kaggle session cheap.
"""
KEY = ("part", "dataset", "n_vectors", "index_kind", "build_params",
"search_param_name", "search_param_value")
def __init__(self, env, token=None, path=f"{OUT}/results/results.csv",
repo_path="results/results.csv", flush_every=5, pull=True):
import pandas as pd
self.pd, self.env, self.token = pd, env, token
self.path, self.repo_path, self.flush_every = path, repo_path, flush_every
self._since_flush = 0
os.makedirs(os.path.dirname(path), exist_ok=True)
df = None
if pull:
try:
remote = hf_download(repo_path, token=token)
if remote:
df = pd.read_csv(remote)
print(f"results.csv: pulled {len(df)} existing rows from HF")
except Exception as e:
print(f"results.csv: could not pull from HF ({e}); starting fresh")
if df is None and os.path.exists(path):
df = pd.read_csv(path)
print(f"results.csv: {len(df)} existing rows found locally")
if df is None:
df = pd.DataFrame(columns=COLUMNS)
print("results.csv: starting a new table")
for c in COLUMNS:
if c not in df.columns:
df[c] = None
self.df = df[COLUMNS]
self.df.to_csv(self.path, index=False)
@staticmethod
def _norm(params):
return json.dumps(params, sort_keys=True, separators=(",", ":")) \
if isinstance(params, dict) else str(params)
def done(self, part, dataset, n_vectors, index_kind, build_params,
search_param_name, search_param_value):
"""True when this exact measurement is already in the table."""
if len(self.df) == 0:
return False
want = (str(part), str(dataset), str(n_vectors), str(index_kind),
self._norm(build_params), str(search_param_name), str(search_param_value))
have = self.df[list(self.KEY)].astype(str)
return bool((have == self.pd.Series(want, index=list(self.KEY))).all(axis=1).any())
def add(self, *, part, dataset, n_vectors, dim, metric, index_kind, build_params,
search_param_name, search_param_value, recall, timing, build_time_s=None,
train_time_s=None, add_time_s=None, index_size_bytes=None,
query_split="eval", notes="", flush=False):
recall = np.asarray(recall, dtype=np.float64)
row = {
"run_id": f"{int(time.time() * 1000)}-{np.random.randint(1e6):06d}",
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
"part": part, "dataset": dataset, "n_vectors": int(n_vectors), "dim": int(dim),
"metric": metric, "index_kind": index_kind,
"build_params": self._norm(build_params),
"search_param_name": search_param_name, "search_param_value": search_param_value,
"recall_at_10": round(float(recall.mean()), 6),
"recall_std": round(float(recall.std()), 6),
"qps_median": round(float(timing["qps_median"]), 3),
"qps_runs": json.dumps(timing.get("qps_runs")),
"qps_spread_pct": timing.get("qps_spread_pct"),
"lat_p50_ms": timing.get("lat_p50_ms"),
"lat_p95_ms": timing.get("lat_p95_ms"),
"build_time_s": build_time_s, "train_time_s": train_time_s,
"add_time_s": add_time_s, "index_size_bytes": index_size_bytes,
"bytes_per_vector": (round(index_size_bytes / n_vectors, 2)
if index_size_bytes else None),
"n_queries": timing.get("n_queries"), "repeats": timing.get("repeats"),
"threads": 1, "query_split": query_split,
"machine_id": self.env.get("machine_id"), "cpu_model": self.env.get("cpu_model"),
"faiss_version": self.env.get("faiss"), "notes": notes,
}
new = self.pd.DataFrame([row])[COLUMNS]
self.df = new if len(self.df) == 0 else self.pd.concat(
[self.df, new], ignore_index=True)
self.df.to_csv(self.path, index=False)
self._since_flush += 1
if flush or self._since_flush >= self.flush_every:
self.flush()
return row
def flush(self):
self._since_flush = 0
try:
hf_upload(self.path, self.repo_path, token=self.token,
msg=f"results.csv: {len(self.df)} rows", quiet=True)
except Exception as e:
print(f" ! results.csv upload failed ({e}); the local copy is intact")
# --------------------------------------------------------------------------------------
# Misc
# --------------------------------------------------------------------------------------
def index_size_bytes(index, path=None):
"""Serialise a FAISS index to disk and measure it. Memory footprint ~= file size for
these index types, and it is the one number we can take reproducibly."""
import faiss
path = path or f"{TMP}/idx/_size_probe.faiss"
faiss.write_index(index, path)
n = os.path.getsize(path)
os.remove(path)
return n
def normalise(x):
"""Unit-normalise rows in place-ish. Zero rows are left as zeros."""
x = np.ascontiguousarray(x, dtype=np.float32)
nrm = np.linalg.norm(x, axis=1, keepdims=True)
nrm[nrm == 0] = 1.0
return (x / nrm).astype(np.float32)
def relative_contrast(gt_dists, mean_dist_sq, k=1):
"""RC = (mean distance to a random point) / (distance to the k-th neighbour).
Reported on true (non-squared) distances, the usual convention. Values near 1 mean
the nearest neighbour is barely nearer than anything else, which is exactly when
graph and cell indexes stop working.
"""
dk = np.sqrt(np.asarray(gt_dists, dtype=np.float64)[:, k - 1])
dk = np.where(dk == 0, np.finfo(np.float64).tiny, dk)
return np.sqrt(np.asarray(mean_dist_sq, dtype=np.float64)) / dk
def mean_sq_dist_to_random(base, queries, n_sample=100_000, seed=0):
"""Mean squared distance from each query to a random sample of the base."""
rng = np.random.default_rng(seed)
idx = rng.choice(len(base), size=min(n_sample, len(base)), replace=False)
sample = base[np.sort(idx)].astype(np.float32)
s_sq = (sample * sample).sum(1)
out = np.empty(len(queries), dtype=np.float64)
for s in range(0, len(queries), 512):
e = min(s + 512, len(queries))
q = queries[s:e].astype(np.float32)
d = (q * q).sum(1)[:, None] + s_sq[None, :] - 2.0 * (q @ sample.T)
out[s:e] = np.maximum(d, 0).mean(1)
return out
def human(n):
for unit in ("B", "KB", "MB", "GB"):
if abs(n) < 1024 or unit == "GB":
return f"{n:.1f} {unit}"
n /= 1024
|