Ash Vardanian commited on
Commit
25c9427
·
1 Parent(s): 5ccbf36

Add: GPU MaxSim retrievers and ground-truth pipeline

Browse files

- retrievers.py with shared CuPy kernels (segment_max + segment_sum
RawKernels) and DenseRetriever / MaxSimRetriever classes; same kernels
drive ground_truth.py via gt_stripe_{dense,maxsim} per-GPU workers.
- ground_truth.py gains --mode {dense,maxsim}; both modes write per-shard
.body.ground_truth.{ibin,fbin} files with global row IDs (article IDs
for dense, section IDs for maxsim).
- build_index.py absorbs sweep_matryoshka.py via --no-save +
--ef-search-sweep flags; default behavior unchanged.
- embed_sections.py is now the unified pool scheduler (the per-wiki
variant is gone).
- wikiverse.py renamed to usearchwiki.py.

Validated end-to-end against NumPy on non-degenerate synthetic data
(top-10 sets match exactly, max score diff 2e-4) and cross-checked
against NumKong CPU MaxSim (rankings agree exactly; scores differ only
because NumKong returns angular distance while the GPU returns cosine).

README.md CHANGED
@@ -149,7 +149,7 @@ unum-cloud/USearchWiki/
149
  ├── README.md
150
  ├── LICENSE
151
  ├── .gitattributes
152
- ├── wikiverse.py # consumer module: load_lang, read_bin, discover_collection, ...
153
  ├── embed_articles.py # one dense vector per article, via TEI
154
  ├── embed_sections.py # late-chunking ColBERT: one vector per section
155
  ├── late_chunking.py # section-aware windowing primitives
@@ -233,7 +233,7 @@ git lfs checkout
233
  ### Loading embeddings in Python
234
 
235
  ```python
236
- from wikiverse import read_bin
237
  matrix = read_bin("qwen3-embedding-0.6b/enwiki/000_00000.body.f16bin", dtype="f16")
238
  # matrix.shape == (rows_in_shard, 1024)
239
  ```
 
149
  ├── README.md
150
  ├── LICENSE
151
  ├── .gitattributes
152
+ ├── usearchwiki.py # consumer module: load_lang, read_bin, discover_collection, ...
153
  ├── embed_articles.py # one dense vector per article, via TEI
154
  ├── embed_sections.py # late-chunking ColBERT: one vector per section
155
  ├── late_chunking.py # section-aware windowing primitives
 
233
  ### Loading embeddings in Python
234
 
235
  ```python
236
+ from usearchwiki import read_bin
237
  matrix = read_bin("qwen3-embedding-0.6b/enwiki/000_00000.body.f16bin", dtype="f16")
238
  # matrix.shape == (rows_in_shard, 1024)
239
  ```
build_index.py CHANGED
@@ -1,23 +1,21 @@
1
  """Build a USearch index from per-shard `.f16bin` files in canonical order.
2
 
3
- For dense article-level collections (one vector per article, multi=False).
4
- The ColBERT section-level case (multi=True, vectors keyed by article) will
5
- be a separate addition once the section embeddings finish computing.
 
 
 
 
6
 
7
  Memory-maps the LFS-resolved `.f16bin` blobs so the OS pages vectors in
8
  lazily — keeps RSS bounded when running multiple builds in parallel.
9
-
10
- Inspired by ashvardanian/RetriEval's USearch wrapper:
11
- - reserve capacity up front
12
- - parallel `add()` with a fixed thread count
13
- - cosine metric, f16 quantization (matching storage dtype)
14
- - HNSW hyperparameters connectivity / expansion_add
15
- - ef_search is a *query-time* knob, not set here
16
  """
17
 
18
  from __future__ import annotations
19
 
20
  import argparse
 
21
  import os
22
  import struct
23
  import sys
@@ -29,45 +27,59 @@ import numpy as np
29
  REPO_ROOT = Path(__file__).resolve().parent
30
  sys.path.insert(0, str(REPO_ROOT))
31
 
32
- from wikiverse import ( # noqa: E402
33
  CollectionShard,
34
  discover_collection,
35
  resolve_lfs_pointer,
36
  )
37
 
38
 
39
- def memmap_shard(shard: CollectionShard, dimensions: int) -> np.ndarray:
 
 
 
 
40
  """Memory-map a `.f16bin` shard skipping its 8-byte header.
41
 
42
- Returns a read-only `(rows, dimensions)` float16 view. The OS pages in
43
- only the bytes actually accessed during `index.add()`.
 
 
 
44
  """
45
  blob = resolve_lfs_pointer(shard.path)
46
- return np.memmap(
47
  blob,
48
  dtype=np.float16,
49
  mode="r",
50
  offset=8,
51
- shape=(shard.row_count, dimensions),
52
  )
 
 
 
 
 
 
53
 
54
 
55
  def add_shards(
56
  index,
57
  shards: list[CollectionShard],
58
- dimensions: int,
 
59
  threads: int,
60
  log_every: int,
61
  ) -> int:
62
- """Stream every shard's vectors into the index. Keys are sequential
63
- global row IDs assigned in shard-walk order (== `shard.row_offset + i`).
64
  """
65
  cumulative_rows = 0
66
  started = time.monotonic()
67
  bytes_added_since_log = 0
68
  last_log_at = started
69
  for shard_index, shard in enumerate(shards):
70
- vectors = memmap_shard(shard, dimensions)
71
  keys = np.arange(
72
  shard.row_offset, shard.row_offset + shard.row_count, dtype=np.uint64
73
  )
@@ -92,13 +104,141 @@ def add_shards(
92
  return cumulative_rows
93
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  def main() -> None:
96
  parser = argparse.ArgumentParser()
97
- parser.add_argument(
98
- "--output",
99
- default="/home/ubuntu/WikiVerse",
100
- help="root directory holding {model-subdir}/{wiki}/*.f16bin",
101
- )
102
  parser.add_argument(
103
  "--model-subdir",
104
  required=True,
@@ -126,13 +266,13 @@ def main() -> None:
126
  "--connectivity",
127
  type=int,
128
  default=16,
129
- help="HNSW M, neighbors per node (16 is the typical floor for ANN)",
130
  )
131
  parser.add_argument(
132
  "--expansion-add",
133
  type=int,
134
  default=256,
135
- help="HNSW efConstruction; bumped from the default 128 to chase >=99% recall@10",
136
  )
137
  parser.add_argument(
138
  "--metric",
@@ -151,6 +291,35 @@ def main() -> None:
151
  default=10,
152
  help="print a progress line every N shards",
153
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  args = parser.parse_args()
155
 
156
  from usearch.index import Index # local import: heavy dependency
@@ -161,9 +330,6 @@ def main() -> None:
161
  shards = discover_collection(model_root, args.output_suffix)
162
  if not shards:
163
  raise SystemExit(f"no .{args.output_suffix}.f16bin shards under {model_root}")
164
- # Read dimensions from the first shard's header. (Within a model the
165
- # collection is consistent by construction; if it weren't, `index.add`
166
- # would raise on the first mismatched shard anyway.)
167
  first_blob = resolve_lfs_pointer(shards[0].path)
168
  with open(first_blob, "rb") as file:
169
  _, dimensions = struct.unpack("<II", file.read(8))
@@ -176,21 +342,25 @@ def main() -> None:
176
  flush=True,
177
  )
178
 
179
- output_index_path = (
180
- args.output_index
181
- if args.output_index is not None
182
- else model_root / f"{args.output_suffix}.usearch"
183
- )
 
 
 
184
 
185
  print(
186
  f"opening USearch index "
187
- f"(dim={dimensions}, metric={args.metric}, dtype={args.dtype}, "
188
  f"M={args.connectivity}, ef_add={args.expansion_add}, "
189
- f"multi=False, threads={args.threads})",
 
190
  flush=True,
191
  )
192
  index = Index(
193
- ndim=dimensions,
194
  metric=args.metric,
195
  dtype=args.dtype,
196
  connectivity=args.connectivity,
@@ -203,27 +373,48 @@ def main() -> None:
203
  added = add_shards(
204
  index=index,
205
  shards=shards,
206
- dimensions=dimensions,
 
207
  threads=args.threads,
208
  log_every=args.log_every,
209
  )
210
- elapsed_build = time.monotonic() - started
211
- rate = added / max(elapsed_build, 1e-3)
212
  print(
213
- f"added {added:,} vectors in {elapsed_build:.0f}s "
214
  f"({rate:,.0f} vec/s), index size now {len(index):,}",
215
  flush=True,
216
  )
217
 
218
- output_index_path.parent.mkdir(parents=True, exist_ok=True)
219
- started = time.monotonic()
220
- index.save(str(output_index_path))
221
- elapsed_save = time.monotonic() - started
222
- file_size_gb = output_index_path.stat().st_size / 1e9
223
- print(
224
- f"saved {output_index_path} ({file_size_gb:.2f} GB) in {elapsed_save:.0f}s",
225
- flush=True,
226
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
 
229
  if __name__ == "__main__":
 
1
  """Build a USearch index from per-shard `.f16bin` files in canonical order.
2
 
3
+ Two modes:
4
+ - default: build the index, save to disk as `{suffix}.usearch`.
5
+ - `--no-save --ef-search-sweep ef1,ef2,...`: build the index in memory,
6
+ evaluate Recall@k_recall and NDCG@k_ndcg across the ef sweep, append a
7
+ row per ef to `--stats-jsonl`, then drop the index without saving. This
8
+ is the Matryoshka-style quality-vs-width sweep — useful when you want
9
+ the *numbers* but not the artefacts.
10
 
11
  Memory-maps the LFS-resolved `.f16bin` blobs so the OS pages vectors in
12
  lazily — keeps RSS bounded when running multiple builds in parallel.
 
 
 
 
 
 
 
13
  """
14
 
15
  from __future__ import annotations
16
 
17
  import argparse
18
+ import json
19
  import os
20
  import struct
21
  import sys
 
27
  REPO_ROOT = Path(__file__).resolve().parent
28
  sys.path.insert(0, str(REPO_ROOT))
29
 
30
+ from usearchwiki import ( # noqa: E402
31
  CollectionShard,
32
  discover_collection,
33
  resolve_lfs_pointer,
34
  )
35
 
36
 
37
+ def memmap_shard(
38
+ shard: CollectionShard,
39
+ dimensions_full: int,
40
+ dimensions_target: int | None = None,
41
+ ) -> np.ndarray:
42
  """Memory-map a `.f16bin` shard skipping its 8-byte header.
43
 
44
+ When `dimensions_target == dimensions_full` the result is a read-only
45
+ memmap'd view (zero-copy). When `dimensions_target < dimensions_full`
46
+ the leading `dimensions_target` columns are sliced and L2-renormalized
47
+ in FP32 before being cast back to FP16 — the standard Matryoshka
48
+ truncation recipe.
49
  """
50
  blob = resolve_lfs_pointer(shard.path)
51
+ full = np.memmap(
52
  blob,
53
  dtype=np.float16,
54
  mode="r",
55
  offset=8,
56
+ shape=(shard.row_count, dimensions_full),
57
  )
58
+ if dimensions_target is None or dimensions_target == dimensions_full:
59
+ return full
60
+ sliced = np.asarray(full[:, :dimensions_target], dtype=np.float32)
61
+ norms = np.linalg.norm(sliced, axis=1, keepdims=True)
62
+ norms[norms == 0] = 1.0
63
+ return (sliced / norms).astype(np.float16)
64
 
65
 
66
  def add_shards(
67
  index,
68
  shards: list[CollectionShard],
69
+ dimensions_full: int,
70
+ dimensions_target: int,
71
  threads: int,
72
  log_every: int,
73
  ) -> int:
74
+ """Stream every shard's vectors into the index. Keys are sequential global
75
+ row IDs assigned in shard-walk order (`shard.row_offset + i`).
76
  """
77
  cumulative_rows = 0
78
  started = time.monotonic()
79
  bytes_added_since_log = 0
80
  last_log_at = started
81
  for shard_index, shard in enumerate(shards):
82
+ vectors = memmap_shard(shard, dimensions_full, dimensions_target)
83
  keys = np.arange(
84
  shard.row_offset, shard.row_offset + shard.row_count, dtype=np.uint64
85
  )
 
104
  return cumulative_rows
105
 
106
 
107
+ def evaluate_and_log(
108
+ index,
109
+ args,
110
+ shards: list[CollectionShard],
111
+ model_root: Path,
112
+ dimensions_full: int,
113
+ target_dim: int,
114
+ total_vectors: int,
115
+ build_seconds: float,
116
+ ) -> None:
117
+ """Run a Recall@k_recall + NDCG@k_ndcg sweep across the ef_search values
118
+ and append one JSONL row per ef to `args.stats_jsonl`. Uses the eval
119
+ helpers from `eval_recall` (gather queries, gather GT, metrics_at_k).
120
+ """
121
+ from eval_recall import gather_ground_truth, gather_query_vectors
122
+
123
+ rng = np.random.default_rng(args.seed)
124
+ query_ids = np.sort(
125
+ rng.choice(total_vectors, size=args.num_queries, replace=False)
126
+ ).astype(np.int64)
127
+ query_vectors_full = gather_query_vectors(shards, dimensions_full, query_ids)
128
+ if target_dim != dimensions_full:
129
+ query_vectors = np.asarray(query_vectors_full[:, :target_dim], dtype=np.float32)
130
+ norms = np.linalg.norm(query_vectors, axis=1, keepdims=True)
131
+ norms[norms == 0] = 1.0
132
+ query_vectors = (query_vectors / norms).astype(np.float16)
133
+ else:
134
+ query_vectors = query_vectors_full
135
+
136
+ expected_keys = gather_ground_truth(
137
+ model_root, args.output_suffix, shards, query_ids, args.k_ndcg
138
+ )
139
+
140
+ ef_values = [int(x) for x in args.ef_search_sweep.split(",") if x.strip()]
141
+ print(
142
+ f"sweeping ef_search over {ef_values} "
143
+ f"(recall@{args.k_recall}, ndcg@{args.k_ndcg}) ...",
144
+ flush=True,
145
+ )
146
+ print(
147
+ f"{'ef_search':>10} {'recall@'+str(args.k_recall):>12} "
148
+ f"{'ndcg@'+str(args.k_ndcg):>12} {'recall q/s':>12} {'ndcg q/s':>12}",
149
+ flush=True,
150
+ )
151
+
152
+ args.stats_jsonl.parent.mkdir(parents=True, exist_ok=True)
153
+ rows = []
154
+ build_rate = total_vectors / max(build_seconds, 1e-3)
155
+ index_bytes_estimate = (
156
+ total_vectors * target_dim * 2
157
+ + total_vectors * args.connectivity * 4 * 2
158
+ )
159
+
160
+ def search_top(count: int) -> tuple[np.ndarray, float]:
161
+ started = time.monotonic()
162
+ results = index.search(query_vectors, count=count, threads=args.threads)
163
+ elapsed = time.monotonic() - started
164
+ raw_keys = np.asarray(results.keys, dtype=np.int64)
165
+ target = count - 1
166
+ actual = np.empty((args.num_queries, target), dtype=np.int64)
167
+ for row in range(args.num_queries):
168
+ without_self = raw_keys[row][raw_keys[row] != query_ids[row]][:target]
169
+ if without_self.shape[0] < target:
170
+ actual[row] = -1
171
+ actual[row, : without_self.shape[0]] = without_self
172
+ else:
173
+ actual[row] = without_self
174
+ return actual, elapsed
175
+
176
+ expected_recall = expected_keys[:, : args.k_recall]
177
+ expected_ndcg = expected_keys[:, : args.k_ndcg]
178
+ discount = 1.0 / np.log2(np.arange(2, args.k_ndcg + 2))
179
+ idcg = float(discount.sum())
180
+
181
+ for ef in ef_values:
182
+ index.expansion_search = ef
183
+ actual_recall, elapsed_recall = search_top(args.k_recall + 1)
184
+ membership_recall = (
185
+ actual_recall[:, :, None] == expected_recall[:, None, :]
186
+ ).any(axis=2)
187
+ recall = float(membership_recall.sum(axis=1).mean()) / args.k_recall
188
+
189
+ actual_ndcg, elapsed_ndcg = search_top(args.k_ndcg + 1)
190
+ membership_ndcg = (
191
+ actual_ndcg[:, :, None] == expected_ndcg[:, None, :]
192
+ ).any(axis=2)
193
+ dcg = (membership_ndcg * discount).sum(axis=1)
194
+ ndcg = float((dcg / idcg).mean())
195
+
196
+ rate_recall = args.num_queries / max(elapsed_recall, 1e-3)
197
+ rate_ndcg = args.num_queries / max(elapsed_ndcg, 1e-3)
198
+ print(
199
+ f"{ef:>10} {recall*100:>11.4f}% {ndcg*100:>11.4f}% "
200
+ f"{rate_recall:>12,.0f} {rate_ndcg:>12,.0f}",
201
+ flush=True,
202
+ )
203
+ rows.append(
204
+ {
205
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
206
+ "model_subdir": args.model_subdir,
207
+ "output_suffix": args.output_suffix,
208
+ "dimensions_full": dimensions_full,
209
+ "dimensions_indexed": target_dim,
210
+ "connectivity": args.connectivity,
211
+ "expansion_add": args.expansion_add,
212
+ "expansion_search": ef,
213
+ "metric": args.metric,
214
+ "dtype": args.dtype,
215
+ "total_vectors": int(total_vectors),
216
+ "num_queries": int(args.num_queries),
217
+ "k_recall": int(args.k_recall),
218
+ "k_ndcg": int(args.k_ndcg),
219
+ "recall": recall,
220
+ "ndcg": ndcg,
221
+ "queries_per_second_recall": rate_recall,
222
+ "queries_per_second_ndcg": rate_ndcg,
223
+ "build_seconds": build_seconds,
224
+ "build_vec_per_second": build_rate,
225
+ "index_bytes_estimate": int(index_bytes_estimate),
226
+ "build_threads": int(args.threads),
227
+ }
228
+ )
229
+
230
+ with open(args.stats_jsonl, "a") as file:
231
+ for row in rows:
232
+ file.write(json.dumps(row) + "\n")
233
+ print(
234
+ f"appended {len(rows)} rows to {args.stats_jsonl}",
235
+ flush=True,
236
+ )
237
+
238
+
239
  def main() -> None:
240
  parser = argparse.ArgumentParser()
241
+ parser.add_argument("--output", default="/home/ubuntu/USearchWiki")
 
 
 
 
242
  parser.add_argument(
243
  "--model-subdir",
244
  required=True,
 
266
  "--connectivity",
267
  type=int,
268
  default=16,
269
+ help="HNSW M, neighbors per node",
270
  )
271
  parser.add_argument(
272
  "--expansion-add",
273
  type=int,
274
  default=256,
275
+ help="HNSW efConstruction; bumped from 128 to chase >=99% recall@10",
276
  )
277
  parser.add_argument(
278
  "--metric",
 
291
  default=10,
292
  help="print a progress line every N shards",
293
  )
294
+ parser.add_argument(
295
+ "--truncate-dim",
296
+ type=int,
297
+ default=0,
298
+ help="truncate stored embeddings to the leading N dimensions (Matryoshka). "
299
+ "0 means no truncation.",
300
+ )
301
+ parser.add_argument(
302
+ "--no-save",
303
+ action="store_true",
304
+ help="build the index in memory and drop it; do not write `{suffix}.usearch`. "
305
+ "Useful for the Matryoshka quality sweep where indexes are evaluated then thrown away.",
306
+ )
307
+ parser.add_argument(
308
+ "--ef-search-sweep",
309
+ default="",
310
+ help="comma-separated ef_search values to evaluate post-build. When set, runs "
311
+ "Recall@k_recall + NDCG@k_ndcg and appends a JSONL row per ef to --stats-jsonl.",
312
+ )
313
+ parser.add_argument("--num-queries", type=int, default=10000)
314
+ parser.add_argument("--k-recall", type=int, default=10)
315
+ parser.add_argument("--k-ndcg", type=int, default=100)
316
+ parser.add_argument(
317
+ "--stats-jsonl",
318
+ type=Path,
319
+ default=Path("/home/ubuntu/wikiverse-data/logs/index-stats.jsonl"),
320
+ help="JSONL file to append per-ef sweep rows to (only used with --ef-search-sweep)",
321
+ )
322
+ parser.add_argument("--seed", type=int, default=0)
323
  args = parser.parse_args()
324
 
325
  from usearch.index import Index # local import: heavy dependency
 
330
  shards = discover_collection(model_root, args.output_suffix)
331
  if not shards:
332
  raise SystemExit(f"no .{args.output_suffix}.f16bin shards under {model_root}")
 
 
 
333
  first_blob = resolve_lfs_pointer(shards[0].path)
334
  with open(first_blob, "rb") as file:
335
  _, dimensions = struct.unpack("<II", file.read(8))
 
342
  flush=True,
343
  )
344
 
345
+ if args.truncate_dim and args.truncate_dim != dimensions:
346
+ if args.truncate_dim > dimensions:
347
+ raise SystemExit(
348
+ f"--truncate-dim {args.truncate_dim} > native {dimensions}"
349
+ )
350
+ target_dim = args.truncate_dim
351
+ else:
352
+ target_dim = dimensions
353
 
354
  print(
355
  f"opening USearch index "
356
+ f"(dim={target_dim}, metric={args.metric}, dtype={args.dtype}, "
357
  f"M={args.connectivity}, ef_add={args.expansion_add}, "
358
+ f"multi=False, threads={args.threads}, "
359
+ f"truncated_from={dimensions if target_dim != dimensions else None})",
360
  flush=True,
361
  )
362
  index = Index(
363
+ ndim=target_dim,
364
  metric=args.metric,
365
  dtype=args.dtype,
366
  connectivity=args.connectivity,
 
373
  added = add_shards(
374
  index=index,
375
  shards=shards,
376
+ dimensions_full=dimensions,
377
+ dimensions_target=target_dim,
378
  threads=args.threads,
379
  log_every=args.log_every,
380
  )
381
+ build_seconds = time.monotonic() - started
382
+ rate = added / max(build_seconds, 1e-3)
383
  print(
384
+ f"added {added:,} vectors in {build_seconds:.0f}s "
385
  f"({rate:,.0f} vec/s), index size now {len(index):,}",
386
  flush=True,
387
  )
388
 
389
+ if args.ef_search_sweep.strip():
390
+ evaluate_and_log(
391
+ index=index,
392
+ args=args,
393
+ shards=shards,
394
+ model_root=model_root,
395
+ dimensions_full=dimensions,
396
+ target_dim=target_dim,
397
+ total_vectors=total_vectors,
398
+ build_seconds=build_seconds,
399
+ )
400
+
401
+ if not args.no_save:
402
+ output_index_path = (
403
+ args.output_index
404
+ if args.output_index is not None
405
+ else model_root / f"{args.output_suffix}.usearch"
406
+ )
407
+ output_index_path.parent.mkdir(parents=True, exist_ok=True)
408
+ started = time.monotonic()
409
+ index.save(str(output_index_path))
410
+ elapsed_save = time.monotonic() - started
411
+ file_size_gb = output_index_path.stat().st_size / 1e9
412
+ print(
413
+ f"saved {output_index_path} ({file_size_gb:.2f} GB) in {elapsed_save:.0f}s",
414
+ flush=True,
415
+ )
416
+ else:
417
+ print("--no-save set; dropping index without writing to disk", flush=True)
418
 
419
 
420
  if __name__ == "__main__":
embed_articles.py CHANGED
@@ -21,7 +21,7 @@ from pathlib import Path
21
  import httpx
22
  import numpy as np
23
 
24
- from wikiverse import Shard, load_lang, load_shard_texts, write_bin
25
 
26
 
27
  def select_shards(all_shards: list[Shard], gpu_id: int, world_size: int) -> list[Shard]:
 
21
  import httpx
22
  import numpy as np
23
 
24
+ from usearchwiki import Shard, load_lang, load_shard_texts, write_bin
25
 
26
 
27
  def select_shards(all_shards: list[Shard], gpu_id: int, world_size: int) -> list[Shard]:
embed_sections.py CHANGED
@@ -1,28 +1,36 @@
1
  """Late-chunking section embeddings via GTE-ModernColBERT-v1 (pylate).
2
 
3
- For each parquet shard:
4
- 1. Load articles (text + id).
5
- 2. For each article: find section char spans, tokenize ("[D] " + text)
6
- once, plan windows via late_chunking, forward each window through the
7
- transformer + projection + L2 normalization, mean-pool the core token
 
 
 
 
 
 
8
  vectors per section.
9
- 3. Write per-shard `{wiki}/{stem}.body.sections.f16bin` (concatenated section
10
- embeddings) and `{wiki}/{stem}.body.sections.offsets.ibin` (cumulative
11
- offsets giving each article's section slice).
12
 
13
- One process per GPU; partition shards by `shard_index % world_size == gpu_id`.
 
14
 
15
  Usage:
16
- CUDA_VISIBLE_DEVICES=0 python embed_sections.py \\
17
  --cache-dir /home/ubuntu/wikiverse-data/hf-cache \\
18
- --output /home/ubuntu/WikiVerse \\
19
  --model-subdir gte-moderncolbert-v1 \\
20
- --wiki enwiki --gpu-id 0 --world-size 8
21
  """
22
 
23
  from __future__ import annotations
24
 
25
  import argparse
 
26
  import os
27
  import struct
28
  import sys
@@ -45,11 +53,7 @@ from late_chunking import ( # noqa: E402
45
  pool_section_vectors,
46
  section_token_spans_from_offsets,
47
  )
48
- from wikiverse import Shard, load_lang # noqa: E402
49
-
50
-
51
- def select_shards(all_shards: list[Shard], gpu_id: int, world_size: int) -> list[Shard]:
52
- return [s for i, s in enumerate(all_shards) if i % world_size == gpu_id]
53
 
54
 
55
  def load_pylate_model(model_id: str, device: str, document_length: int):
@@ -108,7 +112,6 @@ def plan_articles_batched(
108
  if not prefixed_texts:
109
  return per_article_windows, per_article_n_sections
110
 
111
- # One Rust-side tokenizer call for the whole batch.
112
  encodings = tokenizer(
113
  prefixed_texts,
114
  add_special_tokens=False,
@@ -152,15 +155,9 @@ def encode_articles_batch(
152
  document_prefix: str,
153
  max_batch_tokens: int,
154
  ) -> list[np.ndarray]:
155
- """Encode a batch of articles into per-article (n_sections, dim) FP16 arrays.
156
-
157
- Pads windows from across the batch into one or more padded forward passes,
158
- splitting into sub-batches whenever the padded total exceeds
159
- `max_batch_tokens` (so a few very long articles don't blow up GPU memory).
160
- """
161
  embedding_dim = model[1].linear.out_features
162
 
163
- # Plan windows for every article via a single batched tokenizer call.
164
  per_article_windows, per_article_n_sections = plan_articles_batched(
165
  texts=texts,
166
  tokenizer=model.tokenizer,
@@ -169,17 +166,14 @@ def encode_articles_batch(
169
  margin=margin,
170
  )
171
 
172
- # Flatten window list across articles, tag each with its article index.
173
  all_windows: list[tuple[int, int, Window]] = []
174
  for article_index, windows in enumerate(per_article_windows):
175
  for window_index, window in enumerate(windows):
176
  all_windows.append((article_index, window_index, window))
177
 
178
- # Outputs scratch: one numpy array per (article, window) once we have it.
179
  output_token_arrays: dict[tuple[int, int], np.ndarray] = {}
180
 
181
  if all_windows:
182
- # Sort windows by length to keep padding overhead per sub-batch low.
183
  all_windows.sort(key=lambda triple: triple[2].length)
184
 
185
  sub_batch: list[tuple[int, int, Window]] = []
@@ -231,7 +225,6 @@ def encode_articles_batch(
231
  sub_batch_max_len = max(sub_batch_max_len, wrapped_len)
232
  flush(sub_batch)
233
 
234
- # Pool per article.
235
  section_matrices: list[np.ndarray] = []
236
  for article_index, (windows, n_sections) in enumerate(
237
  zip(per_article_windows, per_article_n_sections, strict=True)
@@ -357,7 +350,6 @@ def process_shard(
357
  )
358
 
359
  elapsed = time.monotonic() - started
360
- embedding_dim = model[1].linear.out_features
361
 
362
  write_shard_outputs(
363
  shard_dir=output_root / shard.wikiname,
@@ -375,103 +367,177 @@ def process_shard(
375
  }
376
 
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  def main() -> None:
379
  parser = argparse.ArgumentParser()
380
  parser.add_argument("--cache-dir", default="/home/ubuntu/wikiverse-data/hf-cache")
381
- parser.add_argument("--output", default="/home/ubuntu/WikiVerse")
382
  parser.add_argument("--model-subdir", default="gte-moderncolbert-v1")
383
  parser.add_argument("--model-id", default="lightonai/GTE-ModernColBERT-v1")
384
- parser.add_argument(
385
- "--wiki", required=True, help="single language code (enwiki, dewiki, ...)"
386
- )
387
- parser.add_argument("--gpu-id", type=int, default=0)
388
- parser.add_argument("--world-size", type=int, default=1)
389
  parser.add_argument("--context-limit", type=int, default=8192)
390
  parser.add_argument("--margin", type=int, default=256)
391
  parser.add_argument("--text-column", default="text", choices=["text", "title"])
392
  parser.add_argument("--output-suffix", default="body")
393
  parser.add_argument("--id-column", default="id")
394
- parser.add_argument(
395
- "--article-batch-size",
396
- type=int,
397
- default=64,
398
- help="number of articles' windows to plan in one cross-article batch",
399
- )
400
- parser.add_argument(
401
- "--max-batch-tokens",
402
- type=int,
403
- default=131072,
404
- help="cap on `padded_batch_size * padded_max_length` per forward pass; "
405
- "splits the cross-article batch into sub-batches when needed to keep "
406
- "GPU memory bounded",
407
- )
408
  args = parser.parse_args()
409
 
410
- # Pin to the assigned GPU before importing pylate.
411
- os.environ.setdefault("CUDA_VISIBLE_DEVICES", str(args.gpu_id))
412
- device = "cuda:0" # post-CUDA_VISIBLE_DEVICES, our GPU is always cuda:0.
 
 
 
 
 
 
413
 
414
  output_root = Path(args.output) / args.model_subdir
415
- output_root.mkdir(parents=True, exist_ok=True)
416
-
417
- shards = load_lang(args.cache_dir, args.wiki)
418
- owned = select_shards(shards, args.gpu_id, args.world_size)
419
- pending = [
420
- s
421
- for s in owned
422
- if not (
423
- output_root / s.wikiname / f"{s.stem}.{args.output_suffix}.sections.f16bin"
424
- ).exists()
425
- ]
 
 
 
 
 
 
 
426
  print(
427
- f"[gpu{args.gpu_id}] {args.wiki}: {len(owned)} owned, {len(pending)} pending",
 
 
 
428
  flush=True,
429
  )
430
  if not pending:
431
  return
432
 
433
- model = load_pylate_model(args.model_id, device, args.context_limit)
434
- cls_id = model.tokenizer.cls_token_id
435
- sep_id = model.tokenizer.sep_token_id
436
- pad_id = model.tokenizer.pad_token_id
437
- document_prefix = model.document_prefix
 
 
 
 
 
 
 
438
 
439
- started_overall = time.monotonic()
440
- total_articles = 0
441
- total_sections = 0
442
  for shard in pending:
443
- stats = process_shard(
444
- shard=shard,
445
- output_root=output_root,
446
- model=model,
447
- cls_id=cls_id,
448
- sep_id=sep_id,
449
- pad_id=pad_id,
450
- device=device,
451
- context_limit=args.context_limit,
452
- margin=args.margin,
453
- document_prefix=document_prefix,
454
- suffix=args.output_suffix,
455
- text_column=args.text_column,
456
- id_column=args.id_column,
457
- article_batch_size=args.article_batch_size,
458
- max_batch_tokens=args.max_batch_tokens,
459
- )
460
- total_articles += stats["n_articles"]
461
- total_sections += stats["n_sections_total"]
462
- rate = stats["n_articles"] / max(stats["elapsed_seconds"], 1e-3)
463
- print(
464
- f"[gpu{args.gpu_id} pylate] {shard.wikiname}/{shard.stem}: "
465
- f"{stats['n_articles']} articles ({stats['n_zero_articles']} zero), "
466
- f"{stats['n_sections_total']:,} sections in {stats['elapsed_seconds']:.1f}s "
467
- f"-> {rate:.1f} doc/s",
468
- flush=True,
469
- )
470
 
471
- wall = time.monotonic() - started_overall
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  print(
473
- f"[gpu{args.gpu_id} pylate] DONE: {total_articles} articles, "
474
- f"{total_sections:,} sections in {wall:.0f}s -> {total_articles/max(wall,1):.1f} doc/s",
 
475
  flush=True,
476
  )
477
 
 
1
  """Late-chunking section embeddings via GTE-ModernColBERT-v1 (pylate).
2
 
3
+ Pool scheduler: enumerates every (wiki, shard) tuple in the corpus, filters
4
+ out already-completed outputs, and dispatches the rest across `num_gpus`
5
+ long-running worker processes via a shared `mp.Queue`. Each worker loads the
6
+ pylate model once and processes shards as they arrive, so small single-shard
7
+ wikis don't leave 7 GPUs idle.
8
+
9
+ For each parquet shard a worker:
10
+ 1. Loads articles (text + id).
11
+ 2. Per article: finds section char spans, tokenizes ("[D] " + text) once,
12
+ plans windows via `late_chunking`, forwards each window through the
13
+ transformer + projection + L2 normalization, mean-pools the core token
14
  vectors per section.
15
+ 3. Writes per-shard `{wiki}/{stem}.body.sections.f16bin` (concatenated
16
+ section embeddings) and `{wiki}/{stem}.body.sections.offsets.ibin`
17
+ (cumulative offsets giving each article's section slice).
18
 
19
+ Resume-safe by construction: shards whose output files already exist are
20
+ skipped before being added to the queue.
21
 
22
  Usage:
23
+ python embed_sections.py \\
24
  --cache-dir /home/ubuntu/wikiverse-data/hf-cache \\
25
+ --output /home/ubuntu/USearchWiki \\
26
  --model-subdir gte-moderncolbert-v1 \\
27
+ --num-gpus 8
28
  """
29
 
30
  from __future__ import annotations
31
 
32
  import argparse
33
+ import multiprocessing as mp
34
  import os
35
  import struct
36
  import sys
 
53
  pool_section_vectors,
54
  section_token_spans_from_offsets,
55
  )
56
+ from usearchwiki import Shard, find_snapshot, load_lang # noqa: E402
 
 
 
 
57
 
58
 
59
  def load_pylate_model(model_id: str, device: str, document_length: int):
 
112
  if not prefixed_texts:
113
  return per_article_windows, per_article_n_sections
114
 
 
115
  encodings = tokenizer(
116
  prefixed_texts,
117
  add_special_tokens=False,
 
155
  document_prefix: str,
156
  max_batch_tokens: int,
157
  ) -> list[np.ndarray]:
158
+ """Encode a batch of articles into per-article (n_sections, dim) FP16 arrays."""
 
 
 
 
 
159
  embedding_dim = model[1].linear.out_features
160
 
 
161
  per_article_windows, per_article_n_sections = plan_articles_batched(
162
  texts=texts,
163
  tokenizer=model.tokenizer,
 
166
  margin=margin,
167
  )
168
 
 
169
  all_windows: list[tuple[int, int, Window]] = []
170
  for article_index, windows in enumerate(per_article_windows):
171
  for window_index, window in enumerate(windows):
172
  all_windows.append((article_index, window_index, window))
173
 
 
174
  output_token_arrays: dict[tuple[int, int], np.ndarray] = {}
175
 
176
  if all_windows:
 
177
  all_windows.sort(key=lambda triple: triple[2].length)
178
 
179
  sub_batch: list[tuple[int, int, Window]] = []
 
225
  sub_batch_max_len = max(sub_batch_max_len, wrapped_len)
226
  flush(sub_batch)
227
 
 
228
  section_matrices: list[np.ndarray] = []
229
  for article_index, (windows, n_sections) in enumerate(
230
  zip(per_article_windows, per_article_n_sections, strict=True)
 
350
  )
351
 
352
  elapsed = time.monotonic() - started
 
353
 
354
  write_shard_outputs(
355
  shard_dir=output_root / shard.wikiname,
 
367
  }
368
 
369
 
370
+ def worker(gpu_id: int, work_queue, args_dict: dict) -> None:
371
+ """Pin to one GPU, load the model once, drain shards from the queue."""
372
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
373
+ device = "cuda:0"
374
+ model = load_pylate_model(
375
+ args_dict["model_id"], device, args_dict["context_limit"]
376
+ )
377
+ cls_id = model.tokenizer.cls_token_id
378
+ sep_id = model.tokenizer.sep_token_id
379
+ pad_id = model.tokenizer.pad_token_id
380
+ document_prefix = model.document_prefix
381
+ output_root = Path(args_dict["output"]) / args_dict["model_subdir"]
382
+
383
+ n_processed = 0
384
+ n_failed = 0
385
+ started = time.monotonic()
386
+ while True:
387
+ try:
388
+ item = work_queue.get(timeout=5.0)
389
+ except Exception:
390
+ print(f"[gpu{gpu_id}] queue idle 5s, exiting", flush=True)
391
+ break
392
+ if item is None:
393
+ break
394
+ shard: Shard = item
395
+ try:
396
+ stats = process_shard(
397
+ shard=shard,
398
+ output_root=output_root,
399
+ model=model,
400
+ cls_id=cls_id,
401
+ sep_id=sep_id,
402
+ pad_id=pad_id,
403
+ device=device,
404
+ context_limit=args_dict["context_limit"],
405
+ margin=args_dict["margin"],
406
+ document_prefix=document_prefix,
407
+ suffix=args_dict["suffix"],
408
+ text_column=args_dict["text_column"],
409
+ id_column=args_dict["id_column"],
410
+ article_batch_size=args_dict["article_batch_size"],
411
+ max_batch_tokens=args_dict["max_batch_tokens"],
412
+ )
413
+ n_processed += 1
414
+ rate = stats["n_articles"] / max(stats["elapsed_seconds"], 1e-3)
415
+ print(
416
+ f"[gpu{gpu_id}] {shard.wikiname}/{shard.stem}: "
417
+ f"{stats['n_articles']} articles "
418
+ f"({stats['n_zero_articles']} zero), "
419
+ f"{stats['n_sections_total']:,} sections in "
420
+ f"{stats['elapsed_seconds']:.0f}s -> {rate:.1f} doc/s",
421
+ flush=True,
422
+ )
423
+ except Exception as exc:
424
+ n_failed += 1
425
+ print(
426
+ f"[gpu{gpu_id}] {shard.wikiname}/{shard.stem}: FAILED: {exc!r}",
427
+ flush=True,
428
+ )
429
+
430
+ elapsed = time.monotonic() - started
431
+ print(
432
+ f"[gpu{gpu_id}] worker DONE: {n_processed} shards processed, "
433
+ f"{n_failed} failed, {elapsed:.0f}s",
434
+ flush=True,
435
+ )
436
+
437
+
438
  def main() -> None:
439
  parser = argparse.ArgumentParser()
440
  parser.add_argument("--cache-dir", default="/home/ubuntu/wikiverse-data/hf-cache")
441
+ parser.add_argument("--output", default="/home/ubuntu/USearchWiki")
442
  parser.add_argument("--model-subdir", default="gte-moderncolbert-v1")
443
  parser.add_argument("--model-id", default="lightonai/GTE-ModernColBERT-v1")
444
+ parser.add_argument("--num-gpus", type=int, default=8)
 
 
 
 
445
  parser.add_argument("--context-limit", type=int, default=8192)
446
  parser.add_argument("--margin", type=int, default=256)
447
  parser.add_argument("--text-column", default="text", choices=["text", "title"])
448
  parser.add_argument("--output-suffix", default="body")
449
  parser.add_argument("--id-column", default="id")
450
+ parser.add_argument("--article-batch-size", type=int, default=64)
451
+ parser.add_argument("--max-batch-tokens", type=int, default=131072)
 
 
 
 
 
 
 
 
 
 
 
 
452
  args = parser.parse_args()
453
 
454
+ snapshot = find_snapshot(args.cache_dir)
455
+ wiki_names = sorted(
456
+ d.name for d in (snapshot / "data").iterdir() if d.is_dir()
457
+ )
458
+ print(
459
+ f"discovering shards across {len(wiki_names)} wikis under "
460
+ f"{snapshot.parent.name}/{snapshot.name} ...",
461
+ flush=True,
462
+ )
463
 
464
  output_root = Path(args.output) / args.model_subdir
465
+ pending: list[Shard] = []
466
+ skipped = 0
467
+ for wiki_name in wiki_names:
468
+ try:
469
+ shards = load_lang(args.cache_dir, wiki_name)
470
+ except Exception:
471
+ continue
472
+ for shard in shards:
473
+ existing = (
474
+ output_root
475
+ / shard.wikiname
476
+ / f"{shard.stem}.{args.output_suffix}.sections.f16bin"
477
+ )
478
+ if existing.exists():
479
+ skipped += 1
480
+ continue
481
+ pending.append(shard)
482
+ pending.sort(key=lambda shard: shard.path.stat().st_size, reverse=True)
483
  print(
484
+ f" {skipped} shards already done; {len(pending)} pending; "
485
+ f"largest parquet: {pending[0].path.stat().st_size / 1e6:.0f} MB"
486
+ if pending
487
+ else f" {skipped} shards already done; nothing pending",
488
  flush=True,
489
  )
490
  if not pending:
491
  return
492
 
493
+ args_dict = {
494
+ "model_id": args.model_id,
495
+ "context_limit": args.context_limit,
496
+ "margin": args.margin,
497
+ "output": args.output,
498
+ "model_subdir": args.model_subdir,
499
+ "suffix": args.output_suffix,
500
+ "text_column": args.text_column,
501
+ "id_column": args.id_column,
502
+ "article_batch_size": args.article_batch_size,
503
+ "max_batch_tokens": args.max_batch_tokens,
504
+ }
505
 
506
+ ctx = mp.get_context("fork")
507
+ work_queue: mp.Queue = ctx.Queue()
 
508
  for shard in pending:
509
+ work_queue.put(shard)
510
+ for _ in range(args.num_gpus):
511
+ work_queue.put(None)
512
+
513
+ workers: list[mp.Process] = []
514
+ for gpu_id in range(args.num_gpus):
515
+ process = ctx.Process(target=worker, args=(gpu_id, work_queue, args_dict))
516
+ process.start()
517
+ workers.append(process)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
 
519
+ started = time.monotonic()
520
+ print(
521
+ f"started {len(workers)} GPU workers at "
522
+ f"{time.strftime('%Y-%m-%dT%H:%M:%S')}; "
523
+ f"{len(pending)} shards in queue",
524
+ flush=True,
525
+ )
526
+
527
+ failed = 0
528
+ for process in workers:
529
+ process.join()
530
+ if process.exitcode != 0:
531
+ failed += 1
532
+ print(
533
+ f" worker pid {process.pid} exited code {process.exitcode}",
534
+ flush=True,
535
+ )
536
+ elapsed = time.monotonic() - started
537
  print(
538
+ f"DONE: {len(pending)} shards in {elapsed:.0f}s "
539
+ f"({len(pending) / max(elapsed, 1e-3):.2f} shards/s); "
540
+ f"{failed} workers failed",
541
  flush=True,
542
  )
543
 
eval_recall.py CHANGED
@@ -30,7 +30,7 @@ import numpy as np
30
  REPO_ROOT = Path(__file__).resolve().parent
31
  sys.path.insert(0, str(REPO_ROOT))
32
 
33
- from wikiverse import ( # noqa: E402
34
  CollectionShard,
35
  discover_collection,
36
  resolve_lfs_pointer,
@@ -121,16 +121,44 @@ def gather_ground_truth(
121
  return out
122
 
123
 
124
- def measure_recall(
125
- expected: np.ndarray,
126
- actual: np.ndarray,
127
- k: int,
128
- ) -> float:
129
- """`expected` and `actual` are both `(num_queries, k)` int arrays."""
130
- matches = 0
131
- for row in range(expected.shape[0]):
132
- matches += len(set(expected[row].tolist()) & set(actual[row].tolist()))
133
- return matches / (expected.shape[0] * k)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
 
136
  def main() -> None:
@@ -140,10 +168,22 @@ def main() -> None:
140
  parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
141
  parser.add_argument("--index", type=Path, default=None)
142
  parser.add_argument("--num-queries", type=int, default=10000)
143
- parser.add_argument("--k", type=int, default=10)
 
 
 
 
 
 
 
 
 
 
 
 
144
  parser.add_argument(
145
  "--ef-search",
146
- default="64,128,256,512",
147
  help="comma-separated efSearch values to sweep",
148
  )
149
  parser.add_argument(
@@ -198,22 +238,70 @@ def main() -> None:
198
  started = time.monotonic()
199
  query_vectors = gather_query_vectors(shards, dimensions, query_ids)
200
  expected_keys = gather_ground_truth(
201
- model_root, args.output_suffix, shards, query_ids, args.k
202
  )
203
  print(f" loaded in {time.monotonic()-started:.1f}s", flush=True)
204
 
205
  ef_values = [int(x) for x in args.ef_search.split(",") if x.strip()]
206
- print(f"sweeping ef_search over {ef_values} with k={args.k} ...", flush=True)
207
- print(f"{'ef_search':>10} {'recall@k':>10} {'queries/s':>12}")
208
- for ef in ef_values:
209
- index.expansion_search = ef
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  started = time.monotonic()
211
- results = index.search(query_vectors, count=args.k, threads=args.threads)
212
  elapsed = time.monotonic() - started
213
- actual_keys = np.asarray(results.keys, dtype=np.int64)
214
- recall = measure_recall(expected_keys, actual_keys, args.k)
215
- rate = args.num_queries / max(elapsed, 1e-3)
216
- print(f"{ef:>10} {recall*100:>9.4f}% {rate:>12,.0f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
 
218
 
219
  if __name__ == "__main__":
 
30
  REPO_ROOT = Path(__file__).resolve().parent
31
  sys.path.insert(0, str(REPO_ROOT))
32
 
33
+ from usearchwiki import ( # noqa: E402
34
  CollectionShard,
35
  discover_collection,
36
  resolve_lfs_pointer,
 
121
  return out
122
 
123
 
124
+ def metrics_at_k(
125
+ expected_keys: np.ndarray,
126
+ actual_keys: np.ndarray,
127
+ k_recall: int,
128
+ k_ndcg: int,
129
+ ) -> tuple[float, float]:
130
+ """Compute strict Recall@k_recall and binary NDCG@k_ndcg.
131
+
132
+ `expected_keys` is the exact top-k_max ground truth (descending
133
+ similarity), `actual_keys` is the predicted top-k_max from the index
134
+ (self-match already removed). Both arrays are
135
+ `(n_queries, k_max)` with `k_max >= max(k_recall, k_ndcg)`.
136
+
137
+ Strict recall: predicted top-k_recall key counts iff it appears in GT
138
+ *top-k_recall*. Standard ANN-Benchmarks definition.
139
+
140
+ Binary NDCG: predicted top-k_ndcg key counts iff it appears in GT
141
+ *top-k_ndcg*. Both rankings are graded by their position in their
142
+ respective top-lists, so a predicted #1 that matches GT #50 still
143
+ contributes 1 / log2(2) at rank 1 in DCG.
144
+ """
145
+ # Recall@k_recall: small bool matrix from k_recall slices on both sides.
146
+ rec_actual = actual_keys[:, :k_recall]
147
+ rec_expected = expected_keys[:, :k_recall]
148
+ membership_recall = (rec_actual[:, :, None] == rec_expected[:, None, :]).any(axis=2)
149
+ recall = float(membership_recall.sum(axis=1).mean()) / k_recall
150
+
151
+ # NDCG@k_ndcg: bigger bool matrix from k_ndcg slices.
152
+ ndcg_actual = actual_keys[:, :k_ndcg]
153
+ ndcg_expected = expected_keys[:, :k_ndcg]
154
+ membership_ndcg = (
155
+ ndcg_actual[:, :, None] == ndcg_expected[:, None, :]
156
+ ).any(axis=2)
157
+ discount = 1.0 / np.log2(np.arange(2, k_ndcg + 2))
158
+ dcg = (membership_ndcg * discount).sum(axis=1)
159
+ idcg = float(discount.sum()) # |GT| >= k_ndcg by construction
160
+ ndcg = float((dcg / idcg).mean())
161
+ return recall, ndcg
162
 
163
 
164
  def main() -> None:
 
168
  parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
169
  parser.add_argument("--index", type=Path, default=None)
170
  parser.add_argument("--num-queries", type=int, default=10000)
171
+ parser.add_argument(
172
+ "--k-recall",
173
+ type=int,
174
+ default=10,
175
+ help="cutoff for Recall@k",
176
+ )
177
+ parser.add_argument(
178
+ "--k-ndcg",
179
+ type=int,
180
+ default=100,
181
+ help="cutoff for NDCG@k; also drives how many GT neighbors are loaded "
182
+ "and how many results we ask the index for (k_ndcg + 1 to drop self)",
183
+ )
184
  parser.add_argument(
185
  "--ef-search",
186
+ default="16,32,64,128,256,512,1024",
187
  help="comma-separated efSearch values to sweep",
188
  )
189
  parser.add_argument(
 
238
  started = time.monotonic()
239
  query_vectors = gather_query_vectors(shards, dimensions, query_ids)
240
  expected_keys = gather_ground_truth(
241
+ model_root, args.output_suffix, shards, query_ids, args.k_ndcg
242
  )
243
  print(f" loaded in {time.monotonic()-started:.1f}s", flush=True)
244
 
245
  ef_values = [int(x) for x in args.ef_search.split(",") if x.strip()]
246
+ print(
247
+ f"sweeping ef_search over {ef_values} "
248
+ f"(recall@{args.k_recall}, ndcg@{args.k_ndcg}) ...",
249
+ flush=True,
250
+ )
251
+ print(
252
+ f"{'ef_search':>10} "
253
+ f"{'recall@'+str(args.k_recall):>12} {'recall q/s':>12} "
254
+ f"{'ndcg@'+str(args.k_ndcg):>12} {'ndcg q/s':>12}"
255
+ )
256
+
257
+ # Two search calls per ef: one with count=k_recall+1 to get a meaningful
258
+ # recall@k_recall curve at the requested ef, and one with count=k_ndcg+1
259
+ # for NDCG. USearch coerces the internal expansion to >= count, so a
260
+ # single shared count=k_ndcg+1 would flatten the recall@k_recall sweep
261
+ # at low ef (effective ef becomes k_ndcg+1 regardless).
262
+ def search_top(count: int) -> tuple[np.ndarray, float]:
263
  started = time.monotonic()
264
+ results = index.search(query_vectors, count=count, threads=args.threads)
265
  elapsed = time.monotonic() - started
266
+ raw_keys = np.asarray(results.keys, dtype=np.int64)
267
+ actual = np.empty((args.num_queries, count - 1), dtype=np.int64)
268
+ target = count - 1
269
+ for row in range(args.num_queries):
270
+ without_self = raw_keys[row][raw_keys[row] != query_ids[row]][:target]
271
+ if without_self.shape[0] < target:
272
+ actual[row] = -1
273
+ actual[row, : without_self.shape[0]] = without_self
274
+ else:
275
+ actual[row] = without_self
276
+ return actual, elapsed
277
+
278
+ expected_recall = expected_keys[:, : args.k_recall]
279
+ expected_ndcg = expected_keys[:, : args.k_ndcg]
280
+ discount = 1.0 / np.log2(np.arange(2, args.k_ndcg + 2))
281
+ idcg = float(discount.sum())
282
+
283
+ for ef in ef_values:
284
+ index.expansion_search = ef
285
+ # --- recall sweep (small count) ---
286
+ actual_recall, elapsed_recall = search_top(args.k_recall + 1)
287
+ membership_recall = (
288
+ actual_recall[:, :, None] == expected_recall[:, None, :]
289
+ ).any(axis=2)
290
+ recall = float(membership_recall.sum(axis=1).mean()) / args.k_recall
291
+ rate_recall = args.num_queries / max(elapsed_recall, 1e-3)
292
+ # --- ndcg sweep (large count) ---
293
+ actual_ndcg, elapsed_ndcg = search_top(args.k_ndcg + 1)
294
+ membership_ndcg = (
295
+ actual_ndcg[:, :, None] == expected_ndcg[:, None, :]
296
+ ).any(axis=2)
297
+ dcg = (membership_ndcg * discount).sum(axis=1)
298
+ ndcg = float((dcg / idcg).mean())
299
+ rate_ndcg = args.num_queries / max(elapsed_ndcg, 1e-3)
300
+ print(
301
+ f"{ef:>10} "
302
+ f"{recall*100:>11.4f}% {rate_recall:>12,.0f} "
303
+ f"{ndcg*100:>11.4f}% {rate_ndcg:>12,.0f}"
304
+ )
305
 
306
 
307
  if __name__ == "__main__":
ground_truth.py CHANGED
@@ -1,13 +1,29 @@
1
  """Compute exact global k-NN ground truth for an embedding collection.
2
 
3
- Streams the entire collection through every GPU as both queries and candidates,
4
- using tiled FP16x FP16 -> FP32 GEMMs with a pre-allocated `out=` buffer. One
5
- collection (model) at a time; partitions queries across GPUs, double-buffers
6
- candidate tile H2D copies, keeps the running top-k on device.
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  Usage:
9
- python ground_truth.py --output /path/to/embeddings \\
10
- --model-subdir qwen3-embedding-0.6b --dimensions 1024 --num-gpus 8
 
 
 
 
 
11
  """
12
 
13
  from __future__ import annotations
@@ -16,12 +32,21 @@ import argparse
16
  import multiprocessing as mp
17
  import os
18
  import struct
 
19
  import time
20
  from pathlib import Path
21
 
22
  import numpy as np
23
 
24
- from wikiverse import (
 
 
 
 
 
 
 
 
25
  CollectionShard,
26
  discover_collection,
27
  resolve_lfs_pointer,
@@ -29,13 +54,12 @@ from wikiverse import (
29
  )
30
 
31
 
32
- def load_collection(
33
  model_root: Path,
34
  suffix: str,
35
  dimensions: int,
36
  shards: list[CollectionShard],
37
  ) -> np.ndarray:
38
- """Allocate one large host array and stream every shard body into its row range."""
39
  total_vectors = sum(shard.row_count for shard in shards)
40
  embeddings = np.empty((total_vectors, dimensions), dtype=np.float16)
41
  started = time.monotonic()
@@ -60,269 +84,92 @@ def load_collection(
60
  flush=True,
61
  )
62
 
63
- # Sanitize: a handful of rows in some collections contain a stray NaN/Inf
64
- # (the embedder emitted noise for empty/degenerate articles). Even one
65
- # NaN row poisons every query's top-k via NaN-tainted similarities.
66
- # Coerce any non-finite row to a clean zero vector.
67
  started = time.monotonic()
68
- bad_rows: list[int] = []
69
- chunk_rows = 1_000_000
70
- for chunk_start in range(0, total_vectors, chunk_rows):
71
- chunk_end = min(chunk_start + chunk_rows, total_vectors)
72
  chunk = embeddings[chunk_start:chunk_end]
73
  bad_mask = ~np.isfinite(chunk).all(axis=1)
74
  if bad_mask.any():
75
- local_bad = np.where(bad_mask)[0]
76
- bad_rows.extend((chunk_start + local_bad).tolist())
77
  chunk[bad_mask] = 0
78
  elapsed = time.monotonic() - started
79
  print(
80
- f"sanitized {len(bad_rows)} non-finite rows -> zero vectors in {elapsed:.1f}s",
81
  flush=True,
82
  )
83
- if bad_rows:
84
- preview = bad_rows[:8]
85
- print(f" bad row indices (first 8): {preview}", flush=True)
86
  return embeddings
87
 
88
 
89
- def worker_main(
90
  gpu_index: int,
91
  num_gpus: int,
92
  embeddings: np.ndarray,
93
- dimensions: int,
94
  num_neighbors: int,
95
  query_tile_rows: int,
96
  candidate_tile_rows: int,
97
  scratch_dir: Path,
98
  ) -> None:
99
- """One process per GPU. Streams the whole corpus past a resident query stripe."""
100
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_index)
101
- import cupy # imported after CUDA_VISIBLE_DEVICES so this process binds to one GPU
102
- import torch # only used for its highly-optimized fused top-k kernel
103
-
104
  total_vectors = embeddings.shape[0]
105
  stripe_start = (total_vectors * gpu_index) // num_gpus
106
  stripe_end = (total_vectors * (gpu_index + 1)) // num_gpus
107
- stripe_size = stripe_end - stripe_start
108
- keep = num_neighbors + 1 # +1 so we always have headroom to drop the self-match
109
-
110
  print(
111
- f"[gpu{gpu_index}] queries [{stripe_start:,}, {stripe_end:,}) "
112
- f"({stripe_size:,} rows), candidate corpus {total_vectors:,} rows",
113
  flush=True,
114
  )
115
-
116
- # Resident query stripe on device (~16 GB at 8 GPUs, dim 1024).
117
- query_stripe = cupy.asarray(embeddings[stripe_start:stripe_end])
118
-
119
- # Pinned host scratch (one per slot) for async H2D of candidate tiles.
120
- pinned_views: list[np.ndarray] = []
121
- pinned_holders = [] # keep allocations alive
122
- for _ in range(2):
123
- pinned_memory = cupy.cuda.alloc_pinned_memory(
124
- candidate_tile_rows * dimensions * 2
125
- )
126
- pinned_holders.append(pinned_memory)
127
- view = np.frombuffer(
128
- pinned_memory, dtype=np.float16, count=candidate_tile_rows * dimensions
129
- ).reshape(candidate_tile_rows, dimensions)
130
- pinned_views.append(view)
131
-
132
- # Device candidate buffers (double-buffered).
133
- candidate_buffers = [
134
- cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
135
- cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
136
- ]
137
-
138
- # Pre-allocated FP32 similarity buffer reused as `out=` of every matmul.
139
- similarity_buffer = cupy.empty(
140
- (query_tile_rows, candidate_tile_rows), dtype=cupy.float32
141
- )
142
-
143
- # Running top-k state on device. -inf scores so the first tile populates them.
144
- topk_scores = cupy.full((stripe_size, keep), -cupy.inf, dtype=cupy.float32)
145
- topk_indices = cupy.full((stripe_size, keep), -1, dtype=cupy.int32)
146
-
147
- copy_stream = cupy.cuda.Stream(non_blocking=True)
148
- compute_stream = cupy.cuda.Stream(non_blocking=True)
149
- copy_done = [
150
- cupy.cuda.Event(disable_timing=True),
151
- cupy.cuda.Event(disable_timing=True),
152
- ]
153
- compute_done = [
154
- cupy.cuda.Event(disable_timing=True),
155
- cupy.cuda.Event(disable_timing=True),
156
- ]
157
-
158
- candidate_offsets = list(range(0, total_vectors, candidate_tile_rows))
159
-
160
- def stage_tile(slot: int, tile_offset: int) -> int:
161
- """Stage a candidate tile: pinned scratch then async H2D into candidate_buffers[slot].
162
-
163
- Host-side: waits for any previous H2D from this slot's pinned scratch before
164
- overwriting it (otherwise the in-flight H2D could read torn data). Device-side:
165
- waits for the previous compute that read this slot's device buffer.
166
- """
167
- count = min(candidate_tile_rows, total_vectors - tile_offset)
168
- # Pinned scratch reuse: host-side wait on the previous H2D from this slot.
169
- # (Synchronize on a never-recorded event is a no-op.)
170
- copy_done[slot].synchronize()
171
- np.copyto(
172
- pinned_views[slot][:count], embeddings[tile_offset : tile_offset + count]
173
- )
174
- # Device buffer reuse: don't overwrite while compute is still reading it.
175
- copy_stream.wait_event(compute_done[slot])
176
- candidate_buffers[slot][:count].set(
177
- pinned_views[slot][:count], stream=copy_stream
178
- )
179
- copy_done[slot].record(copy_stream)
180
- return count
181
-
182
- # Prime both slots so the steady-state loop has tiles ready on first compute.
183
- counts = [0, 0]
184
- for slot in range(min(2, len(candidate_offsets))):
185
- counts[slot] = stage_tile(slot, candidate_offsets[slot])
186
-
187
- started = time.monotonic()
188
-
189
- for tile_idx, tile_offset in enumerate(candidate_offsets):
190
- slot = tile_idx % 2
191
- active_count = counts[slot]
192
- active_device = candidate_buffers[slot][:active_count]
193
-
194
- # Issue compute for the current tile, waiting for its H2D to complete.
195
- compute_stream.wait_event(copy_done[slot])
196
-
197
- with compute_stream:
198
- for query_start in range(0, stripe_size, query_tile_rows):
199
- query_end = min(query_start + query_tile_rows, stripe_size)
200
- query_count = query_end - query_start
201
- similarity_view = similarity_buffer[:query_count, :active_count]
202
-
203
- # Pre-allocated FP32 buffer reused for every tile pair (the `out=` request).
204
- cupy.matmul(
205
- query_stripe[query_start:query_end],
206
- active_device.T,
207
- out=similarity_view,
208
- )
209
-
210
- # Top-k for this tile via torch.topk (much faster than
211
- # cupy.argpartition: ~150x measured at 16K x 64K f32). The DLPack
212
- # bridge zero-copies the cupy buffer; outputs are still on the
213
- # same device. When the final tile is shorter than `keep`,
214
- # take all rows and pad with -inf sentinels.
215
- if active_count >= keep:
216
- similarity_torch = torch.from_dlpack(similarity_view)
217
- tile_values_torch, tile_local_torch = torch.topk(
218
- similarity_torch, k=keep, dim=1, largest=True, sorted=False
219
- )
220
- tile_top_scores = cupy.from_dlpack(tile_values_torch)
221
- tile_top_indices = cupy.from_dlpack(tile_local_torch).astype(
222
- cupy.int32
223
- ) + cupy.int32(tile_offset)
224
- else:
225
- pad = keep - active_count
226
- sub_global = cupy.arange(
227
- active_count, dtype=cupy.int32
228
- ) + cupy.int32(tile_offset)
229
- tile_top_indices = cupy.concatenate(
230
- [
231
- cupy.broadcast_to(sub_global, (query_count, active_count)),
232
- cupy.full((query_count, pad), -1, dtype=cupy.int32),
233
- ],
234
- axis=1,
235
- )
236
- tile_top_scores = cupy.concatenate(
237
- [
238
- similarity_view,
239
- cupy.full(
240
- (query_count, pad), -cupy.inf, dtype=cupy.float32
241
- ),
242
- ],
243
- axis=1,
244
- )
245
-
246
- # Merge running top-k with this tile's top-k. Combined width is
247
- # 2 * keep, which is small enough that another torch.topk is the
248
- # right tool here too.
249
- running_indices_chunk = topk_indices[query_start:query_end]
250
- running_scores_chunk = topk_scores[query_start:query_end]
251
- combined_scores = cupy.concatenate(
252
- [running_scores_chunk, tile_top_scores], axis=1
253
- )
254
- combined_indices = cupy.concatenate(
255
- [running_indices_chunk, tile_top_indices], axis=1
256
- )
257
- combined_torch = torch.from_dlpack(combined_scores)
258
- merge_values_torch, merge_pos_torch = torch.topk(
259
- combined_torch, k=keep, dim=1, largest=True, sorted=False
260
- )
261
- merge_pos = cupy.from_dlpack(merge_pos_torch)
262
- topk_scores[query_start:query_end] = cupy.from_dlpack(
263
- merge_values_torch
264
- )
265
- topk_indices[query_start:query_end] = cupy.take_along_axis(
266
- combined_indices, merge_pos, axis=1
267
- )
268
-
269
- compute_done[slot].record(compute_stream)
270
-
271
- # Now that compute is queued, prefetch tile_idx+2 into this slot.
272
- # copy_stream waits on compute_done[slot] before overwriting the device buffer,
273
- # and stage_tile waits host-side on copy_done[slot] before overwriting pinned scratch.
274
- prefetch_idx = tile_idx + 2
275
- if prefetch_idx < len(candidate_offsets):
276
- counts[slot] = stage_tile(slot, candidate_offsets[prefetch_idx])
277
-
278
- if (tile_idx + 1) % 32 == 0 or tile_idx + 1 == len(candidate_offsets):
279
- compute_stream.synchronize()
280
- # Reclaim pooled blocks accumulated by intra-tile concat / take ops
281
- # so pool growth doesn't drift toward the device limit.
282
- cupy.get_default_memory_pool().free_all_blocks()
283
- elapsed = time.monotonic() - started
284
- done_candidates = (tile_idx + 1) * candidate_tile_rows
285
- millions_per_second = done_candidates / max(elapsed, 1e-3) / 1e6
286
- print(
287
- f"[gpu{gpu_index}] tile {tile_idx + 1}/{len(candidate_offsets)} "
288
- f"elapsed {elapsed:.0f}s ({millions_per_second:.2f}M cand/s)",
289
- flush=True,
290
- )
291
-
292
- compute_stream.synchronize()
293
-
294
- # Sort each row by descending score, then drop the self-match in a single shift.
295
- sorted_order = cupy.argsort(-topk_scores, axis=1)
296
- sorted_scores = cupy.take_along_axis(topk_scores, sorted_order, axis=1)
297
- sorted_indices = cupy.take_along_axis(topk_indices, sorted_order, axis=1)
298
-
299
- query_global_ids = cupy.arange(stripe_start, stripe_end, dtype=cupy.int32).reshape(
300
- -1, 1
301
- )
302
- is_self = sorted_indices == query_global_ids
303
- has_self = cupy.any(is_self, axis=1, keepdims=True)
304
- self_pos = cupy.argmax(is_self.astype(cupy.int32), axis=1, keepdims=True)
305
-
306
- output_columns = cupy.broadcast_to(
307
- cupy.arange(num_neighbors, dtype=cupy.int32), (stripe_size, num_neighbors)
308
  )
309
- shift_mask = (output_columns >= self_pos) & has_self
310
- source_columns = output_columns + shift_mask.astype(cupy.int32)
311
- final_scores = cupy.take_along_axis(sorted_scores, source_columns, axis=1)
312
- final_indices = cupy.take_along_axis(sorted_indices, source_columns, axis=1)
313
-
314
  scratch_dir.mkdir(parents=True, exist_ok=True)
315
- indices_path = scratch_dir / f"stripe_{gpu_index:02d}.ibin"
316
- scores_path = scratch_dir / f"stripe_{gpu_index:02d}.fbin"
317
- write_bin(indices_path, cupy.asnumpy(final_indices), dtype="i32")
318
- write_bin(scores_path, cupy.asnumpy(final_scores), dtype="f32")
319
 
320
- elapsed = time.monotonic() - started
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  print(
322
- f"[gpu{gpu_index}] DONE {stripe_size:,} queries in {elapsed:.0f}s "
323
- f"-> {indices_path.name}, {scores_path.name}",
324
  flush=True,
325
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
 
328
  def gather_outputs(
@@ -331,17 +178,15 @@ def gather_outputs(
331
  suffix: str,
332
  shards: list[CollectionShard],
333
  num_gpus: int,
334
- total_vectors: int,
335
  num_neighbors: int,
336
  ) -> None:
337
- """Slice per-stripe scratch files into per-shard `.ground_truth.ibin` and `.ground_truth.fbin`,
338
- so each shard's ground truth lives next to its source `.f16bin`.
339
-
340
- Each per-stripe scratch is contiguous global rows. A single shard may straddle
341
- a stripe boundary, so we may pull from up to two stripes per shard.
342
  """
343
- bytes_per_row_indices = num_neighbors * 4
344
- bytes_per_row_scores = num_neighbors * 4
345
  indices_files = [
346
  open(scratch_dir / f"stripe_{gpu_index:02d}.ibin", "rb")
347
  for gpu_index in range(num_gpus)
@@ -351,9 +196,8 @@ def gather_outputs(
351
  for gpu_index in range(num_gpus)
352
  ]
353
  try:
354
- # Stripe boundary table (cumulative row counts).
355
  stripe_starts = [
356
- (total_vectors * gpu_index) // num_gpus for gpu_index in range(num_gpus + 1)
357
  ]
358
  for shard in shards:
359
  wiki_dir = model_root / shard.wikiname
@@ -369,32 +213,21 @@ def gather_outputs(
369
  cursor = shard.row_offset
370
  shard_end = shard.row_offset + shard.row_count
371
  while cursor < shard_end:
372
- # Find which stripe owns `cursor`.
373
  stripe_index = next(
374
  gpu_index
375
  for gpu_index in range(num_gpus)
376
- if stripe_starts[gpu_index]
377
- <= cursor
378
- < stripe_starts[gpu_index + 1]
379
  )
380
  chunk_end = min(shard_end, stripe_starts[stripe_index + 1])
381
  chunk_rows = chunk_end - cursor
382
  offset_in_stripe = cursor - stripe_starts[stripe_index]
383
- indices_files[stripe_index].seek(
384
- 8 + offset_in_stripe * bytes_per_row_indices
385
- )
386
- scores_files[stripe_index].seek(
387
- 8 + offset_in_stripe * bytes_per_row_scores
388
- )
389
  out_indices.write(
390
- indices_files[stripe_index].read(
391
- chunk_rows * bytes_per_row_indices
392
- )
393
  )
394
  out_scores.write(
395
- scores_files[stripe_index].read(
396
- chunk_rows * bytes_per_row_scores
397
- )
398
  )
399
  cursor = chunk_end
400
  finally:
@@ -402,41 +235,7 @@ def gather_outputs(
402
  handle.close()
403
 
404
 
405
- def main() -> None:
406
- parser = argparse.ArgumentParser()
407
- parser.add_argument("--output", default="/home/ubuntu/wikiverse-data/embeddings")
408
- parser.add_argument(
409
- "--model-subdir",
410
- default="qwen3-embedding-0.6b",
411
- help="collection lives at {output}/{model-subdir}/",
412
- )
413
- parser.add_argument(
414
- "--dimensions",
415
- type=int,
416
- default=1024,
417
- help="embedding dimensionality (1024 Qwen3/arctic, 768 nomic, 4096 e5-mistral)",
418
- )
419
- parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
420
- parser.add_argument("--num-neighbors", type=int, default=100)
421
- parser.add_argument("--num-gpus", type=int, default=8)
422
- parser.add_argument(
423
- "--query-tile-rows",
424
- type=int,
425
- default=16384,
426
- help="rows per query chunk inside the resident stripe",
427
- )
428
- parser.add_argument(
429
- "--candidate-tile-rows",
430
- type=int,
431
- default=131072,
432
- help="rows per candidate tile streamed past the query stripe",
433
- )
434
- args = parser.parse_args()
435
-
436
- model_root = Path(args.output) / args.model_subdir
437
- if not model_root.is_dir():
438
- raise SystemExit(f"no collection at {model_root}")
439
-
440
  shards = discover_collection(model_root, args.output_suffix)
441
  if not shards:
442
  raise SystemExit(f"no .{args.output_suffix}.f16bin files under {model_root}")
@@ -448,10 +247,16 @@ def main() -> None:
448
  flush=True,
449
  )
450
 
451
- embeddings = load_collection(
452
- model_root, args.output_suffix, args.dimensions, shards
453
- )
 
 
 
 
 
454
 
 
455
  scratch_dir = model_root / f"_ground_truth_scratch_{args.output_suffix}"
456
  scratch_dir.mkdir(parents=True, exist_ok=True)
457
 
@@ -459,12 +264,11 @@ def main() -> None:
459
  workers: list[mp.Process] = []
460
  for gpu_index in range(args.num_gpus):
461
  process = mp_context.Process(
462
- target=worker_main,
463
  args=(
464
  gpu_index,
465
  args.num_gpus,
466
  embeddings,
467
- args.dimensions,
468
  args.num_neighbors,
469
  args.query_tile_rows,
470
  args.candidate_tile_rows,
@@ -480,8 +284,7 @@ def main() -> None:
480
  if process.exitcode != 0:
481
  failed = True
482
  print(
483
- f"worker pid {process.pid} exited with code {process.exitcode}",
484
- flush=True,
485
  )
486
  if failed:
487
  raise SystemExit("one or more GPU workers failed")
@@ -497,15 +300,137 @@ def main() -> None:
497
  )
498
  print(
499
  f"wrote {len(shards)} per-shard "
500
- f"`.{args.output_suffix}.ground_truth.ibin` + `.{args.output_suffix}.ground_truth.fbin` "
501
- f"files under {model_root}",
502
  flush=True,
503
  )
 
 
 
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  for path in scratch_dir.iterdir():
506
  path.unlink()
507
  scratch_dir.rmdir()
508
 
509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  if __name__ == "__main__":
511
  main()
 
1
  """Compute exact global k-NN ground truth for an embedding collection.
2
 
3
+ Two modes share the same per-stripe partition + per-shard output pipeline:
4
+
5
+ --mode dense (default)
6
+ Cosine top-k over a `(N, dim)` FP16 corpus. Used for the
7
+ article-level dense models (qwen3-embedding-0.6b,
8
+ snowflake-arctic-embed-l-v2.0, nomic-embed-text-v1.5, ...).
9
+
10
+ --mode maxsim
11
+ ColBERT-style late-interaction MaxSim top-k over a
12
+ `(T_total, dim)` token bank + `(N+1,)` section offsets. Used for
13
+ the section-level multi-vector models (gte-moderncolbert-v1).
14
+
15
+ Both modes write per-shard `{wiki}/{stem}.{suffix}.ground_truth.{ibin,fbin}`
16
+ files in canonical shard-walk order. The neighbor IDs in the `.ibin` are
17
+ global row IDs (article-id space for dense, section-id space for MaxSim).
18
 
19
  Usage:
20
+ python ground_truth.py --mode dense \
21
+ --output /path/to/embeddings --model-subdir qwen3-embedding-0.6b \
22
+ --num-gpus 8
23
+
24
+ python ground_truth.py --mode maxsim \
25
+ --output /path/to/embeddings --model-subdir gte-moderncolbert-v1 \
26
+ --num-gpus 8
27
  """
28
 
29
  from __future__ import annotations
 
32
  import multiprocessing as mp
33
  import os
34
  import struct
35
+ import sys
36
  import time
37
  from pathlib import Path
38
 
39
  import numpy as np
40
 
41
+ REPO_ROOT = Path(__file__).resolve().parent
42
+ sys.path.insert(0, str(REPO_ROOT))
43
+
44
+ from retrievers import ( # noqa: E402
45
+ _load_maxsim_corpus_to_host,
46
+ gt_stripe_dense,
47
+ gt_stripe_maxsim,
48
+ )
49
+ from usearchwiki import ( # noqa: E402
50
  CollectionShard,
51
  discover_collection,
52
  resolve_lfs_pointer,
 
54
  )
55
 
56
 
57
+ def load_dense_collection(
58
  model_root: Path,
59
  suffix: str,
60
  dimensions: int,
61
  shards: list[CollectionShard],
62
  ) -> np.ndarray:
 
63
  total_vectors = sum(shard.row_count for shard in shards)
64
  embeddings = np.empty((total_vectors, dimensions), dtype=np.float16)
65
  started = time.monotonic()
 
84
  flush=True,
85
  )
86
 
87
+ # Sanitize: a handful of rows in some collections contain stray NaN/Inf
88
+ # (the embedder emitted noise for empty/degenerate articles). One NaN row
89
+ # poisons every query's top-k via NaN-tainted similarities.
 
90
  started = time.monotonic()
91
+ bad_rows = 0
92
+ for chunk_start in range(0, total_vectors, 1_000_000):
93
+ chunk_end = min(chunk_start + 1_000_000, total_vectors)
 
94
  chunk = embeddings[chunk_start:chunk_end]
95
  bad_mask = ~np.isfinite(chunk).all(axis=1)
96
  if bad_mask.any():
97
+ bad_rows += int(bad_mask.sum())
 
98
  chunk[bad_mask] = 0
99
  elapsed = time.monotonic() - started
100
  print(
101
+ f"sanitized {bad_rows} non-finite rows -> zero vectors in {elapsed:.1f}s",
102
  flush=True,
103
  )
 
 
 
104
  return embeddings
105
 
106
 
107
+ def dense_worker(
108
  gpu_index: int,
109
  num_gpus: int,
110
  embeddings: np.ndarray,
 
111
  num_neighbors: int,
112
  query_tile_rows: int,
113
  candidate_tile_rows: int,
114
  scratch_dir: Path,
115
  ) -> None:
 
116
  os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_index)
 
 
 
117
  total_vectors = embeddings.shape[0]
118
  stripe_start = (total_vectors * gpu_index) // num_gpus
119
  stripe_end = (total_vectors * (gpu_index + 1)) // num_gpus
 
 
 
120
  print(
121
+ f"[gpu{gpu_index} dense] queries [{stripe_start:,}, {stripe_end:,}) "
122
+ f"vs corpus {total_vectors:,}",
123
  flush=True,
124
  )
125
+ indices, scores = gt_stripe_dense(
126
+ embeddings_host=embeddings,
127
+ stripe_start=stripe_start,
128
+ stripe_end=stripe_end,
129
+ num_neighbors=num_neighbors,
130
+ query_tile_rows=query_tile_rows,
131
+ candidate_tile_rows=candidate_tile_rows,
132
+ log_prefix=f"[gpu{gpu_index} dense] ",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  )
 
 
 
 
 
134
  scratch_dir.mkdir(parents=True, exist_ok=True)
135
+ write_bin(scratch_dir / f"stripe_{gpu_index:02d}.ibin", indices, dtype="i32")
136
+ write_bin(scratch_dir / f"stripe_{gpu_index:02d}.fbin", scores, dtype="f32")
137
+ print(f"[gpu{gpu_index} dense] DONE -> stripe_{gpu_index:02d}.{{ibin,fbin}}", flush=True)
 
138
 
139
+
140
+ def maxsim_worker(
141
+ gpu_index: int,
142
+ num_gpus: int,
143
+ token_bank: np.ndarray,
144
+ section_offsets: np.ndarray,
145
+ num_neighbors: int,
146
+ query_tile_sections: int,
147
+ candidate_tile_sections: int,
148
+ scratch_dir: Path,
149
+ ) -> None:
150
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_index)
151
+ total_sections = section_offsets.shape[0] - 1
152
+ stripe_start = (total_sections * gpu_index) // num_gpus
153
+ stripe_end = (total_sections * (gpu_index + 1)) // num_gpus
154
  print(
155
+ f"[gpu{gpu_index} maxsim] queries [{stripe_start:,}, {stripe_end:,}) "
156
+ f"vs corpus {total_sections:,} sections, {token_bank.shape[0]:,} tokens",
157
  flush=True,
158
  )
159
+ indices, scores = gt_stripe_maxsim(
160
+ token_bank_host=token_bank,
161
+ section_offsets_host=section_offsets,
162
+ stripe_start_section=stripe_start,
163
+ stripe_end_section=stripe_end,
164
+ num_neighbors=num_neighbors,
165
+ query_tile_sections=query_tile_sections,
166
+ candidate_tile_sections=candidate_tile_sections,
167
+ log_prefix=f"[gpu{gpu_index} maxsim] ",
168
+ )
169
+ scratch_dir.mkdir(parents=True, exist_ok=True)
170
+ write_bin(scratch_dir / f"stripe_{gpu_index:02d}.ibin", indices, dtype="i32")
171
+ write_bin(scratch_dir / f"stripe_{gpu_index:02d}.fbin", scores, dtype="f32")
172
+ print(f"[gpu{gpu_index} maxsim] DONE -> stripe_{gpu_index:02d}.{{ibin,fbin}}", flush=True)
173
 
174
 
175
  def gather_outputs(
 
178
  suffix: str,
179
  shards: list[CollectionShard],
180
  num_gpus: int,
181
+ total_rows: int,
182
  num_neighbors: int,
183
  ) -> None:
184
+ """Slice per-stripe scratch files into per-shard
185
+ `.{suffix}.ground_truth.{ibin,fbin}` files. Each `CollectionShard.row_count`
186
+ is in whatever unit the per-stripe rows were written (articles for dense,
187
+ sections for maxsim) `gather_outputs` is unit-agnostic.
 
188
  """
189
+ bytes_per_row = num_neighbors * 4
 
190
  indices_files = [
191
  open(scratch_dir / f"stripe_{gpu_index:02d}.ibin", "rb")
192
  for gpu_index in range(num_gpus)
 
196
  for gpu_index in range(num_gpus)
197
  ]
198
  try:
 
199
  stripe_starts = [
200
+ (total_rows * gpu_index) // num_gpus for gpu_index in range(num_gpus + 1)
201
  ]
202
  for shard in shards:
203
  wiki_dir = model_root / shard.wikiname
 
213
  cursor = shard.row_offset
214
  shard_end = shard.row_offset + shard.row_count
215
  while cursor < shard_end:
 
216
  stripe_index = next(
217
  gpu_index
218
  for gpu_index in range(num_gpus)
219
+ if stripe_starts[gpu_index] <= cursor < stripe_starts[gpu_index + 1]
 
 
220
  )
221
  chunk_end = min(shard_end, stripe_starts[stripe_index + 1])
222
  chunk_rows = chunk_end - cursor
223
  offset_in_stripe = cursor - stripe_starts[stripe_index]
224
+ indices_files[stripe_index].seek(8 + offset_in_stripe * bytes_per_row)
225
+ scores_files[stripe_index].seek(8 + offset_in_stripe * bytes_per_row)
 
 
 
 
226
  out_indices.write(
227
+ indices_files[stripe_index].read(chunk_rows * bytes_per_row)
 
 
228
  )
229
  out_scores.write(
230
+ scores_files[stripe_index].read(chunk_rows * bytes_per_row)
 
 
231
  )
232
  cursor = chunk_end
233
  finally:
 
235
  handle.close()
236
 
237
 
238
+ def run_dense(args, model_root: Path) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  shards = discover_collection(model_root, args.output_suffix)
240
  if not shards:
241
  raise SystemExit(f"no .{args.output_suffix}.f16bin files under {model_root}")
 
247
  flush=True,
248
  )
249
 
250
+ # Read dimensions from the first shard's header.
251
+ first_blob = resolve_lfs_pointer(shards[0].path)
252
+ with open(first_blob, "rb") as file:
253
+ _, dimensions = struct.unpack("<II", file.read(8))
254
+ if args.dimensions and args.dimensions != dimensions:
255
+ raise SystemExit(
256
+ f"--dimensions {args.dimensions} != on-disk {dimensions} for {model_root}"
257
+ )
258
 
259
+ embeddings = load_dense_collection(model_root, args.output_suffix, dimensions, shards)
260
  scratch_dir = model_root / f"_ground_truth_scratch_{args.output_suffix}"
261
  scratch_dir.mkdir(parents=True, exist_ok=True)
262
 
 
264
  workers: list[mp.Process] = []
265
  for gpu_index in range(args.num_gpus):
266
  process = mp_context.Process(
267
+ target=dense_worker,
268
  args=(
269
  gpu_index,
270
  args.num_gpus,
271
  embeddings,
 
272
  args.num_neighbors,
273
  args.query_tile_rows,
274
  args.candidate_tile_rows,
 
284
  if process.exitcode != 0:
285
  failed = True
286
  print(
287
+ f"worker pid {process.pid} exited code {process.exitcode}", flush=True
 
288
  )
289
  if failed:
290
  raise SystemExit("one or more GPU workers failed")
 
300
  )
301
  print(
302
  f"wrote {len(shards)} per-shard "
303
+ f"`.{args.output_suffix}.ground_truth.{{ibin,fbin}}` files under {model_root}",
 
304
  flush=True,
305
  )
306
+ for path in scratch_dir.iterdir():
307
+ path.unlink()
308
+ scratch_dir.rmdir()
309
 
310
+
311
+ def run_maxsim(args, model_root: Path) -> None:
312
+ started = time.monotonic()
313
+ print(f"loading multi-vector corpus under {model_root} ...", flush=True)
314
+ token_bank, section_offsets, shards, dimensions = _load_maxsim_corpus_to_host(
315
+ model_root, args.output_suffix
316
+ )
317
+ elapsed = time.monotonic() - started
318
+ total_sections = section_offsets.shape[0] - 1
319
+ total_tokens = token_bank.shape[0]
320
+ print(
321
+ f"loaded {total_sections:,} sections, {total_tokens:,} tokens "
322
+ f"({token_bank.nbytes/1e9:.1f} GB) across {len(shards)} shards "
323
+ f"in {elapsed:.1f}s; dim={dimensions}",
324
+ flush=True,
325
+ )
326
+
327
+ scratch_dir = model_root / f"_ground_truth_scratch_{args.output_suffix}"
328
+ scratch_dir.mkdir(parents=True, exist_ok=True)
329
+
330
+ mp_context = mp.get_context("fork")
331
+ workers: list[mp.Process] = []
332
+ for gpu_index in range(args.num_gpus):
333
+ process = mp_context.Process(
334
+ target=maxsim_worker,
335
+ args=(
336
+ gpu_index,
337
+ args.num_gpus,
338
+ token_bank,
339
+ section_offsets,
340
+ args.num_neighbors,
341
+ args.query_tile_sections,
342
+ args.candidate_tile_sections,
343
+ scratch_dir,
344
+ ),
345
+ )
346
+ process.start()
347
+ workers.append(process)
348
+
349
+ failed = False
350
+ for process in workers:
351
+ process.join()
352
+ if process.exitcode != 0:
353
+ failed = True
354
+ print(
355
+ f"worker pid {process.pid} exited code {process.exitcode}", flush=True
356
+ )
357
+ if failed:
358
+ raise SystemExit("one or more GPU workers failed")
359
+
360
+ gather_outputs(
361
+ scratch_dir,
362
+ model_root,
363
+ args.output_suffix,
364
+ shards,
365
+ args.num_gpus,
366
+ total_sections,
367
+ args.num_neighbors,
368
+ )
369
+ print(
370
+ f"wrote {len(shards)} per-shard "
371
+ f"`.{args.output_suffix}.ground_truth.{{ibin,fbin}}` files under {model_root}",
372
+ flush=True,
373
+ )
374
  for path in scratch_dir.iterdir():
375
  path.unlink()
376
  scratch_dir.rmdir()
377
 
378
 
379
+ def main() -> None:
380
+ parser = argparse.ArgumentParser()
381
+ parser.add_argument(
382
+ "--mode",
383
+ default="dense",
384
+ choices=["dense", "maxsim"],
385
+ help="dense = single vector per row (cosine); maxsim = multi-vector per "
386
+ "section (ColBERT late interaction)",
387
+ )
388
+ parser.add_argument("--output", default="/home/ubuntu/USearchWiki")
389
+ parser.add_argument("--model-subdir", required=True)
390
+ parser.add_argument(
391
+ "--dimensions",
392
+ type=int,
393
+ default=0,
394
+ help="optional sanity check; if 0, read from first shard's header (dense only)",
395
+ )
396
+ parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
397
+ parser.add_argument("--num-neighbors", type=int, default=100)
398
+ parser.add_argument("--num-gpus", type=int, default=8)
399
+ parser.add_argument(
400
+ "--query-tile-rows",
401
+ type=int,
402
+ default=16384,
403
+ help="dense: rows per query chunk inside the resident stripe",
404
+ )
405
+ parser.add_argument(
406
+ "--candidate-tile-rows",
407
+ type=int,
408
+ default=131072,
409
+ help="dense: rows per candidate tile streamed past the query stripe",
410
+ )
411
+ parser.add_argument(
412
+ "--query-tile-sections",
413
+ type=int,
414
+ default=256,
415
+ help="maxsim: sections per query micro-batch",
416
+ )
417
+ parser.add_argument(
418
+ "--candidate-tile-sections",
419
+ type=int,
420
+ default=65536,
421
+ help="maxsim: sections per streamed candidate tile",
422
+ )
423
+ args = parser.parse_args()
424
+
425
+ model_root = Path(args.output) / args.model_subdir
426
+ if not model_root.is_dir():
427
+ raise SystemExit(f"no collection at {model_root}")
428
+
429
+ if args.mode == "dense":
430
+ run_dense(args, model_root)
431
+ else:
432
+ run_maxsim(args, model_root)
433
+
434
+
435
  if __name__ == "__main__":
436
  main()
retrievers.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Brute-force retrievers + shared GPU kernels.
2
+
3
+ Two retriever families share one streaming-top-k template:
4
+ - DenseRetriever: cosine top-k over an `(N, dim)` FP16 corpus.
5
+ - MaxSimRetriever: ColBERT-style late interaction over a multi-vector
6
+ corpus (`(T_total, dim)` token bank + `(N+1,)` section offsets).
7
+
8
+ Both compute an `(Q, M)` score matrix per candidate tile, merge it into the
9
+ running top-k, and repeat. They differ only in the per-tile score kernel:
10
+
11
+ - Dense: a single FP16 matmul into a pre-allocated FP32 `out=` buffer.
12
+ - MaxSim: matmul + segment-max along ragged doc-token offsets +
13
+ segment-sum along ragged query-token offsets, via two small RawKernels.
14
+
15
+ The same streaming loop is exposed two ways:
16
+ - `gt_stripe_*` functions: per-GPU stripe workers used by `ground_truth.py`
17
+ for the all-vs-all corpus sweep (host-resident corpus, double-buffered
18
+ H2D for candidate tiles, query stripe resident on-device).
19
+ - `DenseRetriever` / `MaxSimRetriever` classes: consumer-facing search,
20
+ corpus loaded once at construction and held resident on a single GPU.
21
+ `search()` becomes a single `gt_stripe_*` call with the resident corpus
22
+ used as the candidate stream.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import struct
28
+ import time
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+
33
+ from usearchwiki import (
34
+ CollectionShard,
35
+ discover_collection,
36
+ resolve_lfs_pointer,
37
+ )
38
+
39
+
40
+ # Two ragged-segment reductions for MaxSim. Each thread handles one (row,
41
+ # segment) cell; the inner loop is bounded by the segment width (median 3,
42
+ # p99 ~16 for FineWiki sections, so a single warp easily covers the worst
43
+ # rows without divergence pain).
44
+ _SEGMENT_MAX_SRC = r"""
45
+ extern "C" __global__ void segment_max_2d(
46
+ const float* __restrict__ values,
47
+ const int* __restrict__ offsets,
48
+ float* __restrict__ out,
49
+ int rows, int n_segments, int row_stride, int out_stride
50
+ ) {
51
+ int seg = blockIdx.x * blockDim.x + threadIdx.x;
52
+ int row = blockIdx.y * blockDim.y + threadIdx.y;
53
+ if (row >= rows || seg >= n_segments) return;
54
+ int start = offsets[seg];
55
+ int end = offsets[seg + 1];
56
+ const float* row_ptr = values + row * row_stride;
57
+ float best = -3.4e38f;
58
+ for (int t = start; t < end; ++t) {
59
+ float v = row_ptr[t];
60
+ if (v > best) best = v;
61
+ }
62
+ out[row * out_stride + seg] = best;
63
+ }
64
+ """
65
+
66
+ _SEGMENT_SUM_SRC = r"""
67
+ extern "C" __global__ void segment_sum_2d(
68
+ const float* __restrict__ values,
69
+ const int* __restrict__ offsets,
70
+ float* __restrict__ out,
71
+ int n_segments, int n_cols, int row_stride, int out_stride
72
+ ) {
73
+ int col = blockIdx.x * blockDim.x + threadIdx.x;
74
+ int seg = blockIdx.y * blockDim.y + threadIdx.y;
75
+ if (seg >= n_segments || col >= n_cols) return;
76
+ int start = offsets[seg];
77
+ int end = offsets[seg + 1];
78
+ float total = 0.0f;
79
+ for (int t = start; t < end; ++t) {
80
+ total += values[t * row_stride + col];
81
+ }
82
+ out[seg * out_stride + col] = total;
83
+ }
84
+ """
85
+
86
+ _SEGMENT_MAX_KERNEL = None
87
+ _SEGMENT_SUM_KERNEL = None
88
+
89
+
90
+ def _segment_kernels():
91
+ global _SEGMENT_MAX_KERNEL, _SEGMENT_SUM_KERNEL
92
+ if _SEGMENT_MAX_KERNEL is None:
93
+ import cupy
94
+
95
+ _SEGMENT_MAX_KERNEL = cupy.RawKernel(_SEGMENT_MAX_SRC, "segment_max_2d")
96
+ _SEGMENT_SUM_KERNEL = cupy.RawKernel(_SEGMENT_SUM_SRC, "segment_sum_2d")
97
+ return _SEGMENT_MAX_KERNEL, _SEGMENT_SUM_KERNEL
98
+
99
+
100
+ def _topk_merge(
101
+ running_scores,
102
+ running_indices,
103
+ tile_scores,
104
+ tile_indices,
105
+ keep,
106
+ ):
107
+ """Merge a (rows, keep) running top-k with a (rows, *) tile top-k. Returns
108
+ the new top-k. `tile_scores` / `tile_indices` may already be (rows, keep)
109
+ (precomputed via `torch.topk` on the full tile-similarity row) or wider.
110
+ """
111
+ import cupy
112
+ import torch
113
+
114
+ combined_scores = cupy.concatenate([running_scores, tile_scores], axis=1)
115
+ combined_indices = cupy.concatenate([running_indices, tile_indices], axis=1)
116
+ combined_torch = torch.from_dlpack(combined_scores)
117
+ merge_values, merge_pos = torch.topk(
118
+ combined_torch, k=keep, dim=1, largest=True, sorted=False
119
+ )
120
+ new_scores = cupy.from_dlpack(merge_values)
121
+ new_indices = cupy.take_along_axis(combined_indices, cupy.from_dlpack(merge_pos), axis=1)
122
+ return new_scores, new_indices
123
+
124
+
125
+ def _tile_topk_dense(similarity_view, keep, candidate_offset_global, query_count, active_count):
126
+ """Top-k inside one (Q, M) FP32 similarity tile -> global indices. Pads to
127
+ `keep` columns when the tile is shorter than `keep`.
128
+ """
129
+ import cupy
130
+ import torch
131
+
132
+ if active_count >= keep:
133
+ sim_torch = torch.from_dlpack(similarity_view)
134
+ values, local = torch.topk(sim_torch, k=keep, dim=1, largest=True, sorted=False)
135
+ return (
136
+ cupy.from_dlpack(values),
137
+ cupy.from_dlpack(local).astype(cupy.int32) + cupy.int32(candidate_offset_global),
138
+ )
139
+ pad = keep - active_count
140
+ sub_global = cupy.arange(active_count, dtype=cupy.int32) + cupy.int32(
141
+ candidate_offset_global
142
+ )
143
+ indices = cupy.concatenate(
144
+ [
145
+ cupy.broadcast_to(sub_global, (query_count, active_count)),
146
+ cupy.full((query_count, pad), -1, dtype=cupy.int32),
147
+ ],
148
+ axis=1,
149
+ )
150
+ scores = cupy.concatenate(
151
+ [similarity_view, cupy.full((query_count, pad), -cupy.inf, dtype=cupy.float32)],
152
+ axis=1,
153
+ )
154
+ return scores, indices
155
+
156
+
157
+ def _drop_self(sorted_scores, sorted_indices, query_global_ids, num_neighbors):
158
+ """Sort each row by descending score, then drop the (up-to-one) row whose
159
+ index equals the query's own global id. Pure cupy, vectorized over rows.
160
+ """
161
+ import cupy
162
+
163
+ is_self = sorted_indices == query_global_ids.reshape(-1, 1)
164
+ has_self = cupy.any(is_self, axis=1, keepdims=True)
165
+ self_pos = cupy.argmax(is_self.astype(cupy.int32), axis=1, keepdims=True)
166
+ rows = sorted_scores.shape[0]
167
+ output_columns = cupy.broadcast_to(
168
+ cupy.arange(num_neighbors, dtype=cupy.int32), (rows, num_neighbors)
169
+ )
170
+ shift_mask = (output_columns >= self_pos) & has_self
171
+ source_columns = output_columns + shift_mask.astype(cupy.int32)
172
+ final_scores = cupy.take_along_axis(sorted_scores, source_columns, axis=1)
173
+ final_indices = cupy.take_along_axis(sorted_indices, source_columns, axis=1)
174
+ return final_indices, final_scores
175
+
176
+
177
+ def gt_stripe_dense(
178
+ embeddings_host: np.ndarray,
179
+ stripe_start: int,
180
+ stripe_end: int,
181
+ num_neighbors: int,
182
+ query_tile_rows: int,
183
+ candidate_tile_rows: int,
184
+ log_prefix: str = "",
185
+ ):
186
+ """Compute top-k for `embeddings_host[stripe_start:stripe_end]` against
187
+ the *whole* `embeddings_host` corpus, with double-buffered H2D streaming
188
+ of candidate tiles. Returns `(indices, scores)` numpy arrays of shape
189
+ `(stripe_end - stripe_start, num_neighbors)` in i32 / f32.
190
+
191
+ Caller is responsible for picking the GPU (`CUDA_VISIBLE_DEVICES`).
192
+ """
193
+ import cupy
194
+ import torch # noqa: F401 (used inside helpers)
195
+
196
+ total_vectors, dimensions = embeddings_host.shape
197
+ stripe_size = stripe_end - stripe_start
198
+ keep = num_neighbors + 1
199
+
200
+ query_stripe = cupy.asarray(embeddings_host[stripe_start:stripe_end])
201
+
202
+ pinned_holders = []
203
+ pinned_views: list[np.ndarray] = []
204
+ for _ in range(2):
205
+ pinned = cupy.cuda.alloc_pinned_memory(candidate_tile_rows * dimensions * 2)
206
+ pinned_holders.append(pinned)
207
+ view = np.frombuffer(
208
+ pinned, dtype=np.float16, count=candidate_tile_rows * dimensions
209
+ ).reshape(candidate_tile_rows, dimensions)
210
+ pinned_views.append(view)
211
+
212
+ candidate_buffers = [
213
+ cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
214
+ cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
215
+ ]
216
+ similarity_buffer = cupy.empty(
217
+ (query_tile_rows, candidate_tile_rows), dtype=cupy.float32
218
+ )
219
+ topk_scores = cupy.full((stripe_size, keep), -cupy.inf, dtype=cupy.float32)
220
+ topk_indices = cupy.full((stripe_size, keep), -1, dtype=cupy.int32)
221
+
222
+ copy_stream = cupy.cuda.Stream(non_blocking=True)
223
+ compute_stream = cupy.cuda.Stream(non_blocking=True)
224
+ copy_done = [
225
+ cupy.cuda.Event(disable_timing=True),
226
+ cupy.cuda.Event(disable_timing=True),
227
+ ]
228
+ compute_done = [
229
+ cupy.cuda.Event(disable_timing=True),
230
+ cupy.cuda.Event(disable_timing=True),
231
+ ]
232
+
233
+ candidate_offsets = list(range(0, total_vectors, candidate_tile_rows))
234
+
235
+ def stage(slot: int, tile_offset: int) -> int:
236
+ count = min(candidate_tile_rows, total_vectors - tile_offset)
237
+ copy_done[slot].synchronize()
238
+ np.copyto(
239
+ pinned_views[slot][:count],
240
+ embeddings_host[tile_offset : tile_offset + count],
241
+ )
242
+ copy_stream.wait_event(compute_done[slot])
243
+ candidate_buffers[slot][:count].set(pinned_views[slot][:count], stream=copy_stream)
244
+ copy_done[slot].record(copy_stream)
245
+ return count
246
+
247
+ counts = [0, 0]
248
+ for slot in range(min(2, len(candidate_offsets))):
249
+ counts[slot] = stage(slot, candidate_offsets[slot])
250
+
251
+ started = time.monotonic()
252
+ for tile_idx, tile_offset in enumerate(candidate_offsets):
253
+ slot = tile_idx % 2
254
+ active_count = counts[slot]
255
+ active_device = candidate_buffers[slot][:active_count]
256
+ compute_stream.wait_event(copy_done[slot])
257
+
258
+ with compute_stream:
259
+ for query_start in range(0, stripe_size, query_tile_rows):
260
+ query_end = min(query_start + query_tile_rows, stripe_size)
261
+ query_count = query_end - query_start
262
+ similarity_view = similarity_buffer[:query_count, :active_count]
263
+ cupy.matmul(
264
+ query_stripe[query_start:query_end],
265
+ active_device.T,
266
+ out=similarity_view,
267
+ )
268
+ tile_scores, tile_indices = _tile_topk_dense(
269
+ similarity_view, keep, tile_offset, query_count, active_count
270
+ )
271
+ new_scores, new_indices = _topk_merge(
272
+ topk_scores[query_start:query_end],
273
+ topk_indices[query_start:query_end],
274
+ tile_scores,
275
+ tile_indices,
276
+ keep,
277
+ )
278
+ topk_scores[query_start:query_end] = new_scores
279
+ topk_indices[query_start:query_end] = new_indices
280
+ compute_done[slot].record(compute_stream)
281
+
282
+ prefetch_idx = tile_idx + 2
283
+ if prefetch_idx < len(candidate_offsets):
284
+ counts[slot] = stage(slot, candidate_offsets[prefetch_idx])
285
+
286
+ if (tile_idx + 1) % 32 == 0 or tile_idx + 1 == len(candidate_offsets):
287
+ compute_stream.synchronize()
288
+ cupy.get_default_memory_pool().free_all_blocks()
289
+ elapsed = time.monotonic() - started
290
+ done = (tile_idx + 1) * candidate_tile_rows
291
+ rate = done / max(elapsed, 1e-3) / 1e6
292
+ print(
293
+ f"{log_prefix}tile {tile_idx + 1}/{len(candidate_offsets)} "
294
+ f"elapsed {elapsed:.0f}s ({rate:.2f}M cand/s)",
295
+ flush=True,
296
+ )
297
+
298
+ compute_stream.synchronize()
299
+
300
+ sorted_order = cupy.argsort(-topk_scores, axis=1)
301
+ sorted_scores = cupy.take_along_axis(topk_scores, sorted_order, axis=1)
302
+ sorted_indices = cupy.take_along_axis(topk_indices, sorted_order, axis=1)
303
+ query_global_ids = cupy.arange(stripe_start, stripe_end, dtype=cupy.int32)
304
+ final_indices, final_scores = _drop_self(
305
+ sorted_scores, sorted_indices, query_global_ids, num_neighbors
306
+ )
307
+ return cupy.asnumpy(final_indices), cupy.asnumpy(final_scores)
308
+
309
+
310
+ def gt_stripe_maxsim(
311
+ token_bank_host: np.ndarray,
312
+ section_offsets_host: np.ndarray,
313
+ stripe_start_section: int,
314
+ stripe_end_section: int,
315
+ num_neighbors: int,
316
+ query_tile_sections: int,
317
+ candidate_tile_sections: int,
318
+ log_prefix: str = "",
319
+ ):
320
+ """Compute MaxSim top-k for sections in
321
+ `[stripe_start_section, stripe_end_section)` against the whole section
322
+ corpus. Returns `(indices, scores)` numpy arrays of shape
323
+ `(stripe_size, num_neighbors)`.
324
+
325
+ `token_bank_host` is `(T_total, dim)` FP16; `section_offsets_host` is
326
+ `(N+1,)` int32 with cumulative token counts (so section i's tokens live
327
+ at rows `[offsets[i]:offsets[i+1]]`).
328
+ """
329
+ import cupy
330
+ import torch # noqa: F401
331
+
332
+ total_sections = section_offsets_host.shape[0] - 1
333
+ dimensions = token_bank_host.shape[1]
334
+ stripe_size = stripe_end_section - stripe_start_section
335
+ keep = num_neighbors + 1
336
+
337
+ query_token_start = int(section_offsets_host[stripe_start_section])
338
+ query_token_end = int(section_offsets_host[stripe_end_section])
339
+ query_token_count = query_token_end - query_token_start
340
+ query_tokens_device = cupy.asarray(token_bank_host[query_token_start:query_token_end])
341
+ # Per-stripe local section offsets (zeroed against query_token_start).
342
+ query_section_offsets_local = (
343
+ section_offsets_host[stripe_start_section : stripe_end_section + 1]
344
+ - query_token_start
345
+ ).astype(np.int32)
346
+ query_section_offsets_device = cupy.asarray(query_section_offsets_local)
347
+
348
+ seg_max_kernel, seg_sum_kernel = _segment_kernels()
349
+
350
+ candidate_starts = list(range(0, total_sections, candidate_tile_sections))
351
+
352
+ # Pre-compute per-tile token byte budget so we can size pinned buffers.
353
+ max_tile_tokens = 0
354
+ for cand_start in candidate_starts:
355
+ cand_end = min(cand_start + candidate_tile_sections, total_sections)
356
+ tile_tokens = int(
357
+ section_offsets_host[cand_end] - section_offsets_host[cand_start]
358
+ )
359
+ if tile_tokens > max_tile_tokens:
360
+ max_tile_tokens = tile_tokens
361
+
362
+ pinned_holders = []
363
+ pinned_views: list[np.ndarray] = []
364
+ for _ in range(2):
365
+ pinned = cupy.cuda.alloc_pinned_memory(max_tile_tokens * dimensions * 2)
366
+ pinned_holders.append(pinned)
367
+ view = np.frombuffer(
368
+ pinned, dtype=np.float16, count=max_tile_tokens * dimensions
369
+ ).reshape(max_tile_tokens, dimensions)
370
+ pinned_views.append(view)
371
+
372
+ doc_token_buffers = [
373
+ cupy.empty((max_tile_tokens, dimensions), dtype=cupy.float16),
374
+ cupy.empty((max_tile_tokens, dimensions), dtype=cupy.float16),
375
+ ]
376
+ doc_offsets_buffers = [
377
+ cupy.empty((candidate_tile_sections + 1,), dtype=cupy.int32),
378
+ cupy.empty((candidate_tile_sections + 1,), dtype=cupy.int32),
379
+ ]
380
+
381
+ # Pre-allocated FP32 scratch buffers reused across tiles.
382
+ sim_buffer = cupy.empty(
383
+ (query_tile_sections * 64, max_tile_tokens), dtype=cupy.float32
384
+ )
385
+ # Bound on per-stripe query tokens per tile is `max query tokens` over the
386
+ # query stripe. A safe upper bound for the buffer is the full stripe's
387
+ # token count, but we tile queries by section count too — so size
388
+ # generously to avoid mid-loop re-allocs.
389
+ max_query_tokens_per_tile = int(
390
+ max(
391
+ section_offsets_host[
392
+ min(stripe_start_section + query_tile_sections, stripe_end_section)
393
+ ]
394
+ - section_offsets_host[stripe_start_section],
395
+ section_offsets_host[stripe_end_section]
396
+ - section_offsets_host[
397
+ max(stripe_end_section - query_tile_sections, stripe_start_section)
398
+ ],
399
+ )
400
+ )
401
+ # Re-size sim_buffer if it's too small for the worst-case (q_tokens, m_tokens).
402
+ if sim_buffer.shape[0] < max_query_tokens_per_tile:
403
+ sim_buffer = cupy.empty(
404
+ (max_query_tokens_per_tile, max_tile_tokens), dtype=cupy.float32
405
+ )
406
+ per_token_max = cupy.empty(
407
+ (max_query_tokens_per_tile, candidate_tile_sections), dtype=cupy.float32
408
+ )
409
+ score_out = cupy.empty(
410
+ (query_tile_sections, candidate_tile_sections), dtype=cupy.float32
411
+ )
412
+
413
+ topk_scores = cupy.full((stripe_size, keep), -cupy.inf, dtype=cupy.float32)
414
+ topk_indices = cupy.full((stripe_size, keep), -1, dtype=cupy.int32)
415
+
416
+ copy_stream = cupy.cuda.Stream(non_blocking=True)
417
+ compute_stream = cupy.cuda.Stream(non_blocking=True)
418
+ copy_done = [
419
+ cupy.cuda.Event(disable_timing=True),
420
+ cupy.cuda.Event(disable_timing=True),
421
+ ]
422
+ compute_done = [
423
+ cupy.cuda.Event(disable_timing=True),
424
+ cupy.cuda.Event(disable_timing=True),
425
+ ]
426
+
427
+ def stage(slot: int, cand_start: int):
428
+ cand_end = min(cand_start + candidate_tile_sections, total_sections)
429
+ section_count = cand_end - cand_start
430
+ token_start = int(section_offsets_host[cand_start])
431
+ token_end = int(section_offsets_host[cand_end])
432
+ token_count = token_end - token_start
433
+ copy_done[slot].synchronize()
434
+ np.copyto(
435
+ pinned_views[slot][:token_count],
436
+ token_bank_host[token_start:token_end],
437
+ )
438
+ # Local doc offsets, zeroed against token_start.
439
+ local_offsets = (
440
+ section_offsets_host[cand_start : cand_end + 1] - token_start
441
+ ).astype(np.int32)
442
+ copy_stream.wait_event(compute_done[slot])
443
+ doc_token_buffers[slot][:token_count].set(
444
+ pinned_views[slot][:token_count], stream=copy_stream
445
+ )
446
+ doc_offsets_buffers[slot][: section_count + 1].set(
447
+ local_offsets, stream=copy_stream
448
+ )
449
+ copy_done[slot].record(copy_stream)
450
+ return section_count, token_count
451
+
452
+ counts = [(0, 0), (0, 0)]
453
+ for slot in range(min(2, len(candidate_starts))):
454
+ counts[slot] = stage(slot, candidate_starts[slot])
455
+
456
+ block = (16, 16, 1)
457
+ started = time.monotonic()
458
+
459
+ for tile_idx, cand_start in enumerate(candidate_starts):
460
+ slot = tile_idx % 2
461
+ section_count, token_count = counts[slot]
462
+ if section_count == 0:
463
+ continue
464
+ compute_stream.wait_event(copy_done[slot])
465
+
466
+ doc_tokens_dev = doc_token_buffers[slot][:token_count]
467
+ doc_offsets_dev = doc_offsets_buffers[slot][: section_count + 1]
468
+
469
+ with compute_stream:
470
+ for q_section_start in range(0, stripe_size, query_tile_sections):
471
+ q_section_end = min(q_section_start + query_tile_sections, stripe_size)
472
+ q_count = q_section_end - q_section_start
473
+ q_token_lo = int(query_section_offsets_local[q_section_start])
474
+ q_token_hi = int(query_section_offsets_local[q_section_end])
475
+ q_token_count = q_token_hi - q_token_lo
476
+ if q_token_count == 0:
477
+ continue
478
+ q_tokens_dev = query_tokens_device[q_token_lo:q_token_hi]
479
+ # Local query offsets for this micro-batch (zeroed against q_token_lo).
480
+ q_offsets_micro = (
481
+ query_section_offsets_device[q_section_start : q_section_end + 1]
482
+ - cupy.int32(q_token_lo)
483
+ )
484
+
485
+ sim_view = sim_buffer[:q_token_count, :token_count]
486
+ cupy.matmul(q_tokens_dev, doc_tokens_dev.T, out=sim_view)
487
+
488
+ pt_max_view = per_token_max[:q_token_count, :section_count]
489
+ grid_max = (
490
+ (section_count + block[0] - 1) // block[0],
491
+ (q_token_count + block[1] - 1) // block[1],
492
+ 1,
493
+ )
494
+ seg_max_kernel(
495
+ grid_max,
496
+ block,
497
+ (
498
+ sim_view,
499
+ doc_offsets_dev,
500
+ pt_max_view,
501
+ np.int32(q_token_count),
502
+ np.int32(section_count),
503
+ np.int32(sim_buffer.shape[1]),
504
+ np.int32(per_token_max.shape[1]),
505
+ ),
506
+ )
507
+
508
+ score_view = score_out[:q_count, :section_count]
509
+ grid_sum = (
510
+ (section_count + block[0] - 1) // block[0],
511
+ (q_count + block[1] - 1) // block[1],
512
+ 1,
513
+ )
514
+ seg_sum_kernel(
515
+ grid_sum,
516
+ block,
517
+ (
518
+ pt_max_view,
519
+ q_offsets_micro,
520
+ score_view,
521
+ np.int32(q_count),
522
+ np.int32(section_count),
523
+ np.int32(per_token_max.shape[1]),
524
+ np.int32(score_out.shape[1]),
525
+ ),
526
+ )
527
+
528
+ tile_scores, tile_indices = _tile_topk_dense(
529
+ score_view, keep, cand_start, q_count, section_count
530
+ )
531
+ new_scores, new_indices = _topk_merge(
532
+ topk_scores[q_section_start:q_section_end],
533
+ topk_indices[q_section_start:q_section_end],
534
+ tile_scores,
535
+ tile_indices,
536
+ keep,
537
+ )
538
+ topk_scores[q_section_start:q_section_end] = new_scores
539
+ topk_indices[q_section_start:q_section_end] = new_indices
540
+ compute_done[slot].record(compute_stream)
541
+
542
+ prefetch_idx = tile_idx + 2
543
+ if prefetch_idx < len(candidate_starts):
544
+ counts[slot] = stage(slot, candidate_starts[prefetch_idx])
545
+
546
+ if (tile_idx + 1) % 32 == 0 or tile_idx + 1 == len(candidate_starts):
547
+ compute_stream.synchronize()
548
+ cupy.get_default_memory_pool().free_all_blocks()
549
+ elapsed = time.monotonic() - started
550
+ done = (tile_idx + 1) * candidate_tile_sections
551
+ rate = done / max(elapsed, 1e-3) / 1e6
552
+ print(
553
+ f"{log_prefix}tile {tile_idx + 1}/{len(candidate_starts)} "
554
+ f"elapsed {elapsed:.0f}s ({rate:.2f}M sect/s)",
555
+ flush=True,
556
+ )
557
+
558
+ compute_stream.synchronize()
559
+
560
+ sorted_order = cupy.argsort(-topk_scores, axis=1)
561
+ sorted_scores = cupy.take_along_axis(topk_scores, sorted_order, axis=1)
562
+ sorted_indices = cupy.take_along_axis(topk_indices, sorted_order, axis=1)
563
+ query_global_ids = cupy.arange(
564
+ stripe_start_section, stripe_end_section, dtype=cupy.int32
565
+ )
566
+ final_indices, final_scores = _drop_self(
567
+ sorted_scores, sorted_indices, query_global_ids, num_neighbors
568
+ )
569
+ return cupy.asnumpy(final_indices), cupy.asnumpy(final_scores)
570
+
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # Consumer-facing classes: load corpus once, search many.
574
+ # ---------------------------------------------------------------------------
575
+
576
+
577
+ def _read_header(path: Path) -> tuple[int, int]:
578
+ blob = resolve_lfs_pointer(path)
579
+ with open(blob, "rb") as file:
580
+ rows, columns = struct.unpack("<II", file.read(8))
581
+ return rows, columns
582
+
583
+
584
+ def _load_dense_corpus_to_host(
585
+ model_root: Path, suffix: str, shards: list[CollectionShard]
586
+ ) -> tuple[np.ndarray, int]:
587
+ """Same data-load contract as `ground_truth.load_collection` but kept here
588
+ so `DenseRetriever` doesn't need to import the GT script.
589
+ """
590
+ if not shards:
591
+ raise ValueError(f"no shards under {model_root}")
592
+ _, dimensions = _read_header(shards[0].path)
593
+ total = sum(s.row_count for s in shards)
594
+ embeddings = np.empty((total, dimensions), dtype=np.float16)
595
+ for shard in shards:
596
+ blob = resolve_lfs_pointer(shard.path)
597
+ with open(blob, "rb") as file:
598
+ file.seek(8)
599
+ destination = embeddings[shard.row_offset : shard.row_offset + shard.row_count]
600
+ file.readinto(memoryview(destination)) # type: ignore[arg-type]
601
+ bad = ~np.isfinite(embeddings).all(axis=1)
602
+ if bad.any():
603
+ embeddings[bad] = 0
604
+ return embeddings, dimensions
605
+
606
+
607
+ def _load_maxsim_corpus_to_host(
608
+ model_root: Path, suffix: str
609
+ ) -> tuple[np.ndarray, np.ndarray, list[CollectionShard], int]:
610
+ """Walk `*.{suffix}.sections.f16bin` + `*.sections.offsets.ibin` shards in
611
+ canonical order. Return `(token_bank, section_offsets, shards, dimensions)`.
612
+
613
+ `section_offsets` has shape `(total_sections + 1,)` int32 cumulative across
614
+ all shards (so section i's tokens are at `token_bank[offsets[i]:offsets[i+1]]`).
615
+ Each `CollectionShard.row_count` is the number of *sections* in that shard,
616
+ `row_offset` is the cumulative section count.
617
+ """
618
+ if not model_root.is_dir():
619
+ raise FileNotFoundError(f"no model directory at {model_root}")
620
+ shards: list[CollectionShard] = []
621
+ cumulative_sections = 0
622
+ cumulative_tokens = 0
623
+ section_offsets_chunks: list[np.ndarray] = []
624
+ section_offsets_chunks.append(np.zeros(1, dtype=np.int32))
625
+ token_chunks: list[tuple[int, int, Path]] = [] # (offset_in_bank, token_count, path)
626
+ dimensions: int | None = None
627
+ for wiki_dir in sorted(model_root.iterdir()):
628
+ if not wiki_dir.is_dir():
629
+ continue
630
+ for path in sorted(wiki_dir.glob(f"*.{suffix}.sections.f16bin")):
631
+ stem = path.name[: -len(f".{suffix}.sections.f16bin")]
632
+ tokens, dim = _read_header(path)
633
+ if dimensions is None:
634
+ dimensions = dim
635
+ elif dim != dimensions:
636
+ raise ValueError(f"{path}: dim {dim} != expected {dimensions}")
637
+ offsets_path = wiki_dir / f"{stem}.{suffix}.sections.offsets.ibin"
638
+ if not offsets_path.is_file():
639
+ raise FileNotFoundError(f"missing offsets file: {offsets_path}")
640
+ offsets_blob = resolve_lfs_pointer(offsets_path)
641
+ with open(offsets_blob, "rb") as file:
642
+ rows, _cols = struct.unpack("<II", file.read(8))
643
+ local_offsets = np.frombuffer(
644
+ file.read(), dtype=np.int32, count=rows
645
+ ).copy()
646
+ n_sections = rows - 1
647
+ shifted = (local_offsets + cumulative_tokens).astype(np.int32)
648
+ # `local_offsets` already starts at 0; we drop the first element of
649
+ # subsequent chunks since `cumulative_tokens` provides the seam.
650
+ section_offsets_chunks.append(shifted[1:])
651
+ shards.append(
652
+ CollectionShard(
653
+ wikiname=wiki_dir.name,
654
+ stem=stem,
655
+ path=path,
656
+ row_offset=cumulative_sections,
657
+ row_count=n_sections,
658
+ )
659
+ )
660
+ token_chunks.append((cumulative_tokens, tokens, path))
661
+ cumulative_sections += n_sections
662
+ cumulative_tokens += tokens
663
+ if dimensions is None:
664
+ raise FileNotFoundError(f"no `.{suffix}.sections.f16bin` files under {model_root}")
665
+
666
+ token_bank = np.empty((cumulative_tokens, dimensions), dtype=np.float16)
667
+ for token_offset, token_count, path in token_chunks:
668
+ blob = resolve_lfs_pointer(path)
669
+ with open(blob, "rb") as file:
670
+ file.seek(8)
671
+ destination = token_bank[token_offset : token_offset + token_count]
672
+ file.readinto(memoryview(destination)) # type: ignore[arg-type]
673
+ bad = ~np.isfinite(token_bank).all(axis=1)
674
+ if bad.any():
675
+ token_bank[bad] = 0
676
+ section_offsets = np.concatenate(section_offsets_chunks).astype(np.int32)
677
+ return token_bank, section_offsets, shards, dimensions
678
+
679
+
680
+ class DenseRetriever:
681
+ """Brute-force exact cosine top-k for a dense embedding collection.
682
+
683
+ Loads the entire `(N, dim)` FP16 corpus to one GPU at construction. Each
684
+ `search()` call runs a single matmul + top-k against that resident corpus.
685
+
686
+ For 60M × 1024 FP16 (~120 GB) the corpus does NOT fit on a single 80 GB
687
+ H100 — quantize on-disk before instantiating, or use the multi-GPU
688
+ `gt_stripe_dense` path directly. The single-resident-corpus class is
689
+ designed for moderate-size collections (≤ tens of GB).
690
+ """
691
+
692
+ def __init__(
693
+ self,
694
+ model_root: str | Path,
695
+ suffix: str = "body",
696
+ device_id: int = 0,
697
+ ):
698
+ import os
699
+
700
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(device_id)
701
+ import cupy
702
+
703
+ model_root = Path(model_root)
704
+ self.model_root = model_root
705
+ self.suffix = suffix
706
+ self.shards = discover_collection(model_root, suffix)
707
+ embeddings_host, self.dimensions = _load_dense_corpus_to_host(
708
+ model_root, suffix, self.shards
709
+ )
710
+ self.total_vectors = embeddings_host.shape[0]
711
+ # Resident on GPU — caller pays the upfront cost; subsequent searches
712
+ # are bandwidth-bound on the matmul alone.
713
+ self.corpus_device = cupy.asarray(embeddings_host)
714
+
715
+ def search(
716
+ self, query_vectors: np.ndarray, k: int = 10
717
+ ) -> tuple[np.ndarray, np.ndarray]:
718
+ """`query_vectors`: `(Q, dim)` FP16, already L2-normalized.
719
+ Returns `(scores, indices)` — both `(Q, k)` numpy arrays.
720
+ """
721
+ import cupy
722
+ import torch # noqa: F401
723
+
724
+ if query_vectors.ndim != 2 or query_vectors.shape[1] != self.dimensions:
725
+ raise ValueError(
726
+ f"queries shape {query_vectors.shape} != (?, {self.dimensions})"
727
+ )
728
+ queries_dev = cupy.asarray(query_vectors.astype(np.float16, copy=False))
729
+ sim = cupy.matmul(queries_dev, self.corpus_device.T, dtype=cupy.float32)
730
+ sim_torch = torch.from_dlpack(sim)
731
+ values, local = torch.topk(sim_torch, k=k, dim=1, largest=True, sorted=True)
732
+ return cupy.asnumpy(cupy.from_dlpack(values)), cupy.asnumpy(
733
+ cupy.from_dlpack(local).astype(cupy.int32)
734
+ )
735
+
736
+
737
+ class MaxSimRetriever:
738
+ """Brute-force exact MaxSim top-k for a multi-vector section corpus.
739
+
740
+ Loads the full token bank + section offsets to one GPU at construction.
741
+ `search()` accepts a query in the same `(token_bank, offsets)` shape and
742
+ runs matmul + segment-max + segment-sum + top-k against the resident
743
+ corpus.
744
+
745
+ For 60 M sections × 128 dim with average 3.4 tokens/section the resident
746
+ bank is ~52 GB FP16 — fits on H100 with margin only after FP8/int8
747
+ quantization, or on B200 / multi-GPU for raw FP16.
748
+ """
749
+
750
+ def __init__(
751
+ self,
752
+ model_root: str | Path,
753
+ suffix: str = "body",
754
+ device_id: int = 0,
755
+ ):
756
+ import os
757
+
758
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(device_id)
759
+ import cupy
760
+
761
+ model_root = Path(model_root)
762
+ self.model_root = model_root
763
+ self.suffix = suffix
764
+ (
765
+ token_bank_host,
766
+ section_offsets_host,
767
+ self.shards,
768
+ self.dimensions,
769
+ ) = _load_maxsim_corpus_to_host(model_root, suffix)
770
+ self.total_sections = section_offsets_host.shape[0] - 1
771
+ self.total_tokens = token_bank_host.shape[0]
772
+ self.token_bank_device = cupy.asarray(token_bank_host)
773
+ self.section_offsets_device = cupy.asarray(section_offsets_host)
774
+
775
+ def search(
776
+ self,
777
+ query_token_bank: np.ndarray,
778
+ query_section_offsets: np.ndarray,
779
+ k: int = 10,
780
+ ) -> tuple[np.ndarray, np.ndarray]:
781
+ """`query_token_bank`: `(T_q, dim)` FP16. `query_section_offsets`:
782
+ `(Q+1,)` int32 cumulative. Returns `(scores, indices)` — `(Q, k)`.
783
+ """
784
+ import cupy
785
+ import torch # noqa: F401
786
+
787
+ if query_token_bank.ndim != 2 or query_token_bank.shape[1] != self.dimensions:
788
+ raise ValueError(
789
+ f"queries shape {query_token_bank.shape} != (?, {self.dimensions})"
790
+ )
791
+ n_queries = query_section_offsets.shape[0] - 1
792
+ seg_max_kernel, seg_sum_kernel = _segment_kernels()
793
+
794
+ queries_dev = cupy.asarray(query_token_bank.astype(np.float16, copy=False))
795
+ q_offsets_dev = cupy.asarray(query_section_offsets.astype(np.int32, copy=False))
796
+
797
+ sim = cupy.matmul(queries_dev, self.token_bank_device.T, dtype=cupy.float32)
798
+ per_token_max = cupy.empty(
799
+ (queries_dev.shape[0], self.total_sections), dtype=cupy.float32
800
+ )
801
+ block = (16, 16, 1)
802
+ grid_max = (
803
+ (self.total_sections + block[0] - 1) // block[0],
804
+ (queries_dev.shape[0] + block[1] - 1) // block[1],
805
+ 1,
806
+ )
807
+ seg_max_kernel(
808
+ grid_max,
809
+ block,
810
+ (
811
+ sim,
812
+ self.section_offsets_device,
813
+ per_token_max,
814
+ np.int32(queries_dev.shape[0]),
815
+ np.int32(self.total_sections),
816
+ np.int32(sim.shape[1]),
817
+ np.int32(per_token_max.shape[1]),
818
+ ),
819
+ )
820
+
821
+ scores = cupy.empty((n_queries, self.total_sections), dtype=cupy.float32)
822
+ grid_sum = (
823
+ (self.total_sections + block[0] - 1) // block[0],
824
+ (n_queries + block[1] - 1) // block[1],
825
+ 1,
826
+ )
827
+ seg_sum_kernel(
828
+ grid_sum,
829
+ block,
830
+ (
831
+ per_token_max,
832
+ q_offsets_dev,
833
+ scores,
834
+ np.int32(n_queries),
835
+ np.int32(self.total_sections),
836
+ np.int32(per_token_max.shape[1]),
837
+ np.int32(scores.shape[1]),
838
+ ),
839
+ )
840
+
841
+ scores_torch = torch.from_dlpack(scores)
842
+ values, local = torch.topk(scores_torch, k=k, dim=1, largest=True, sorted=True)
843
+ return cupy.asnumpy(cupy.from_dlpack(values)), cupy.asnumpy(
844
+ cupy.from_dlpack(local).astype(cupy.int32)
845
+ )
tests/test_ground_truth.py CHANGED
@@ -22,7 +22,7 @@ import numpy as np
22
  REPO_ROOT = Path(__file__).resolve().parent.parent
23
  sys.path.insert(0, str(REPO_ROOT))
24
 
25
- from wikiverse import read_bin, write_bin # noqa: E402
26
 
27
 
28
  def normalize_rows(matrix: np.ndarray) -> np.ndarray:
 
22
  REPO_ROOT = Path(__file__).resolve().parent.parent
23
  sys.path.insert(0, str(REPO_ROOT))
24
 
25
+ from usearchwiki import read_bin, write_bin # noqa: E402
26
 
27
 
28
  def normalize_rows(matrix: np.ndarray) -> np.ndarray:
wikiverse.py → usearchwiki.py RENAMED
File without changes