Ash Vardanian commited on
Commit
d309c96
·
1 Parent(s): f550ce9

Add: Ground truth k-NN computation script

Browse files

Computes exact global top-k nearest neighbors per article for an embedding
collection using tiled FP16xFP16->FP32 GEMMs on multiple GPUs. Streams the
whole corpus past per-GPU resident query stripes, double-buffers candidate
tiles, uses torch.topk for the per-tile partial sort (~150x faster than
cupy.argpartition), and writes per-shard `.body.ground_truth.{ibin,fbin}`
files row-aligned with the source `.body.f16bin` shards.

Sanitizes stray non-finite rows at load time (a few embeddings in the
collections have a single NaN among otherwise-zero entries; left alone they
poison every query's top-k).

Includes a synthetic end-to-end test under tests/.

Files changed (2) hide show
  1. ground_truth.py +582 -0
  2. tests/test_ground_truth.py +259 -0
ground_truth.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
14
+
15
+ import argparse
16
+ import multiprocessing as mp
17
+ import os
18
+ import struct
19
+ import time
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+
25
+ from wikiverse import write_bin
26
+
27
+
28
+ LFS_POINTER_PREFIX = b"version https://git-lfs"
29
+
30
+
31
+ def resolve_lfs_pointer(path: Path) -> Path:
32
+ """If `path` is a Git-LFS pointer file, return the materialized blob in `.git/lfs/objects`.
33
+
34
+ Pointer files are tiny ASCII stubs (~133 bytes) with an `oid sha256:<hex>` line.
35
+ Repositories cloned with `GIT_LFS_SKIP_SMUDGE=1` (or with `git lfs fetch` only)
36
+ keep the actual binaries under `.git/lfs/objects/<aa>/<bb>/<oid>` while the
37
+ working tree holds pointers. Reading those blobs in place avoids checking out
38
+ a duplicate copy of the dataset.
39
+ """
40
+ try:
41
+ if path.stat().st_size > 1024:
42
+ return path
43
+ except OSError:
44
+ return path
45
+ with open(path, "rb") as file:
46
+ head = file.read(256)
47
+ if not head.startswith(LFS_POINTER_PREFIX):
48
+ return path
49
+ oid: str | None = None
50
+ for line in head.decode("ascii", errors="ignore").splitlines():
51
+ if line.startswith("oid sha256:"):
52
+ oid = line.split(":", 1)[1].strip()
53
+ break
54
+ if not oid:
55
+ raise ValueError(f"{path}: looks like an LFS pointer but no sha256 oid line")
56
+ # Walk parents of the resolved path (so symlinked working trees still find the
57
+ # original repo's `.git/lfs/objects`).
58
+ for ancestor in path.resolve().parents:
59
+ candidate = ancestor / ".git" / "lfs" / "objects" / oid[:2] / oid[2:4] / oid
60
+ if candidate.is_file():
61
+ return candidate
62
+ raise FileNotFoundError(
63
+ f"{path}: LFS pointer references oid {oid} but no .git/lfs/objects/ contains it; "
64
+ f"run `git lfs fetch` or pass --output to a tree that has the blobs"
65
+ )
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class CollectionShard:
70
+ wikiname: str
71
+ stem: str
72
+ row_offset: int
73
+ row_count: int
74
+
75
+
76
+ def discover_shards(model_root: Path, suffix: str) -> list[CollectionShard]:
77
+ """Find every {wiki}/{stem}.{suffix}.f16bin under model_root in deterministic order."""
78
+ binaries: list[tuple[str, str, Path, int]] = []
79
+ for wiki_dir in sorted(model_root.iterdir()):
80
+ if not wiki_dir.is_dir():
81
+ continue
82
+ for path in sorted(wiki_dir.glob(f"*.{suffix}.f16bin")):
83
+ stem = path.name[: -len(f".{suffix}.f16bin")]
84
+ blob_path = resolve_lfs_pointer(path)
85
+ with open(blob_path, "rb") as file:
86
+ rows, _columns = struct.unpack("<II", file.read(8))
87
+ binaries.append((wiki_dir.name, stem, path, rows))
88
+
89
+ shards: list[CollectionShard] = []
90
+ offset = 0
91
+ for wikiname, stem, _path, row_count in binaries:
92
+ shards.append(
93
+ CollectionShard(
94
+ wikiname=wikiname,
95
+ stem=stem,
96
+ row_offset=offset,
97
+ row_count=row_count,
98
+ )
99
+ )
100
+ offset += row_count
101
+ return shards
102
+
103
+
104
+ def load_collection(
105
+ model_root: Path,
106
+ suffix: str,
107
+ dimensions: int,
108
+ shards: list[CollectionShard],
109
+ ) -> np.ndarray:
110
+ """Allocate one large host array and stream every shard body into its row range."""
111
+ total_vectors = sum(shard.row_count for shard in shards)
112
+ embeddings = np.empty((total_vectors, dimensions), dtype=np.float16)
113
+ started = time.monotonic()
114
+ for shard in shards:
115
+ path = model_root / shard.wikiname / f"{shard.stem}.{suffix}.f16bin"
116
+ blob_path = resolve_lfs_pointer(path)
117
+ with open(blob_path, "rb") as file:
118
+ header = file.read(8)
119
+ rows, columns = struct.unpack("<II", header)
120
+ if columns != dimensions:
121
+ raise ValueError(f"{path}: dim {columns} != expected {dimensions}")
122
+ if rows != shard.row_count:
123
+ raise ValueError(f"{path}: rows {rows} != cached {shard.row_count}")
124
+ destination = embeddings[shard.row_offset : shard.row_offset + rows]
125
+ file.readinto(memoryview(destination)) # type: ignore[arg-type]
126
+ del destination
127
+ elapsed = time.monotonic() - started
128
+ gigabytes = embeddings.nbytes / 1e9
129
+ print(
130
+ f"loaded {total_vectors:,} x {dimensions} fp16 ({gigabytes:.1f} GB) "
131
+ f"from {len(shards)} shards in {elapsed:.1f}s",
132
+ flush=True,
133
+ )
134
+
135
+ # Sanitize: a handful of rows in some collections contain a stray NaN/Inf
136
+ # (the embedder emitted noise for empty/degenerate articles). Even one
137
+ # NaN row poisons every query's top-k via NaN-tainted similarities.
138
+ # Coerce any non-finite row to a clean zero vector.
139
+ started = time.monotonic()
140
+ bad_rows: list[int] = []
141
+ chunk_rows = 1_000_000
142
+ for chunk_start in range(0, total_vectors, chunk_rows):
143
+ chunk_end = min(chunk_start + chunk_rows, total_vectors)
144
+ chunk = embeddings[chunk_start:chunk_end]
145
+ bad_mask = ~np.isfinite(chunk).all(axis=1)
146
+ if bad_mask.any():
147
+ local_bad = np.where(bad_mask)[0]
148
+ bad_rows.extend((chunk_start + local_bad).tolist())
149
+ chunk[bad_mask] = 0
150
+ elapsed = time.monotonic() - started
151
+ print(
152
+ f"sanitized {len(bad_rows)} non-finite rows -> zero vectors in {elapsed:.1f}s",
153
+ flush=True,
154
+ )
155
+ if bad_rows:
156
+ preview = bad_rows[:8]
157
+ print(f" bad row indices (first 8): {preview}", flush=True)
158
+ return embeddings
159
+
160
+
161
+ def worker_main(
162
+ gpu_index: int,
163
+ num_gpus: int,
164
+ embeddings: np.ndarray,
165
+ dimensions: int,
166
+ num_neighbors: int,
167
+ query_tile_rows: int,
168
+ candidate_tile_rows: int,
169
+ scratch_dir: Path,
170
+ ) -> None:
171
+ """One process per GPU. Streams the whole corpus past a resident query stripe."""
172
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_index)
173
+ import cupy # imported after CUDA_VISIBLE_DEVICES so this process binds to one GPU
174
+ import torch # only used for its highly-optimized fused top-k kernel
175
+
176
+ total_vectors = embeddings.shape[0]
177
+ stripe_start = (total_vectors * gpu_index) // num_gpus
178
+ stripe_end = (total_vectors * (gpu_index + 1)) // num_gpus
179
+ stripe_size = stripe_end - stripe_start
180
+ keep = num_neighbors + 1 # +1 so we always have headroom to drop the self-match
181
+
182
+ print(
183
+ f"[gpu{gpu_index}] queries [{stripe_start:,}, {stripe_end:,}) "
184
+ f"({stripe_size:,} rows), candidate corpus {total_vectors:,} rows",
185
+ flush=True,
186
+ )
187
+
188
+ # Resident query stripe on device (~16 GB at 8 GPUs, dim 1024).
189
+ query_stripe = cupy.asarray(embeddings[stripe_start:stripe_end])
190
+
191
+ # Pinned host scratch (one per slot) for async H2D of candidate tiles.
192
+ pinned_views: list[np.ndarray] = []
193
+ pinned_holders = [] # keep allocations alive
194
+ for _ in range(2):
195
+ pinned_memory = cupy.cuda.alloc_pinned_memory(
196
+ candidate_tile_rows * dimensions * 2
197
+ )
198
+ pinned_holders.append(pinned_memory)
199
+ view = np.frombuffer(
200
+ pinned_memory, dtype=np.float16, count=candidate_tile_rows * dimensions
201
+ ).reshape(candidate_tile_rows, dimensions)
202
+ pinned_views.append(view)
203
+
204
+ # Device candidate buffers (double-buffered).
205
+ candidate_buffers = [
206
+ cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
207
+ cupy.empty((candidate_tile_rows, dimensions), dtype=cupy.float16),
208
+ ]
209
+
210
+ # Pre-allocated FP32 similarity buffer reused as `out=` of every matmul.
211
+ similarity_buffer = cupy.empty(
212
+ (query_tile_rows, candidate_tile_rows), dtype=cupy.float32
213
+ )
214
+
215
+ # Running top-k state on device. -inf scores so the first tile populates them.
216
+ topk_scores = cupy.full((stripe_size, keep), -cupy.inf, dtype=cupy.float32)
217
+ topk_indices = cupy.full((stripe_size, keep), -1, dtype=cupy.int32)
218
+
219
+ copy_stream = cupy.cuda.Stream(non_blocking=True)
220
+ compute_stream = cupy.cuda.Stream(non_blocking=True)
221
+ copy_done = [
222
+ cupy.cuda.Event(disable_timing=True),
223
+ cupy.cuda.Event(disable_timing=True),
224
+ ]
225
+ compute_done = [
226
+ cupy.cuda.Event(disable_timing=True),
227
+ cupy.cuda.Event(disable_timing=True),
228
+ ]
229
+
230
+ candidate_offsets = list(range(0, total_vectors, candidate_tile_rows))
231
+
232
+ def stage_tile(slot: int, tile_offset: int) -> int:
233
+ """Stage a candidate tile: pinned scratch then async H2D into candidate_buffers[slot].
234
+
235
+ Host-side: waits for any previous H2D from this slot's pinned scratch before
236
+ overwriting it (otherwise the in-flight H2D could read torn data). Device-side:
237
+ waits for the previous compute that read this slot's device buffer.
238
+ """
239
+ count = min(candidate_tile_rows, total_vectors - tile_offset)
240
+ # Pinned scratch reuse: host-side wait on the previous H2D from this slot.
241
+ # (Synchronize on a never-recorded event is a no-op.)
242
+ copy_done[slot].synchronize()
243
+ np.copyto(
244
+ pinned_views[slot][:count], embeddings[tile_offset : tile_offset + count]
245
+ )
246
+ # Device buffer reuse: don't overwrite while compute is still reading it.
247
+ copy_stream.wait_event(compute_done[slot])
248
+ candidate_buffers[slot][:count].set(
249
+ pinned_views[slot][:count], stream=copy_stream
250
+ )
251
+ copy_done[slot].record(copy_stream)
252
+ return count
253
+
254
+ # Prime both slots so the steady-state loop has tiles ready on first compute.
255
+ counts = [0, 0]
256
+ for slot in range(min(2, len(candidate_offsets))):
257
+ counts[slot] = stage_tile(slot, candidate_offsets[slot])
258
+
259
+ started = time.monotonic()
260
+
261
+ for tile_idx, tile_offset in enumerate(candidate_offsets):
262
+ slot = tile_idx % 2
263
+ active_count = counts[slot]
264
+ active_device = candidate_buffers[slot][:active_count]
265
+
266
+ # Issue compute for the current tile, waiting for its H2D to complete.
267
+ compute_stream.wait_event(copy_done[slot])
268
+
269
+ with compute_stream:
270
+ for query_start in range(0, stripe_size, query_tile_rows):
271
+ query_end = min(query_start + query_tile_rows, stripe_size)
272
+ query_count = query_end - query_start
273
+ similarity_view = similarity_buffer[:query_count, :active_count]
274
+
275
+ # Pre-allocated FP32 buffer reused for every tile pair (the `out=` request).
276
+ cupy.matmul(
277
+ query_stripe[query_start:query_end],
278
+ active_device.T,
279
+ out=similarity_view,
280
+ )
281
+
282
+ # Top-k for this tile via torch.topk (much faster than
283
+ # cupy.argpartition: ~150x measured at 16K x 64K f32). The DLPack
284
+ # bridge zero-copies the cupy buffer; outputs are still on the
285
+ # same device. When the final tile is shorter than `keep`,
286
+ # take all rows and pad with -inf sentinels.
287
+ if active_count >= keep:
288
+ similarity_torch = torch.from_dlpack(similarity_view)
289
+ tile_values_torch, tile_local_torch = torch.topk(
290
+ similarity_torch, k=keep, dim=1, largest=True, sorted=False
291
+ )
292
+ tile_top_scores = cupy.from_dlpack(tile_values_torch)
293
+ tile_top_indices = cupy.from_dlpack(tile_local_torch).astype(
294
+ cupy.int32
295
+ ) + cupy.int32(tile_offset)
296
+ else:
297
+ pad = keep - active_count
298
+ sub_global = cupy.arange(
299
+ active_count, dtype=cupy.int32
300
+ ) + cupy.int32(tile_offset)
301
+ tile_top_indices = cupy.concatenate(
302
+ [
303
+ cupy.broadcast_to(sub_global, (query_count, active_count)),
304
+ cupy.full((query_count, pad), -1, dtype=cupy.int32),
305
+ ],
306
+ axis=1,
307
+ )
308
+ tile_top_scores = cupy.concatenate(
309
+ [
310
+ similarity_view,
311
+ cupy.full(
312
+ (query_count, pad), -cupy.inf, dtype=cupy.float32
313
+ ),
314
+ ],
315
+ axis=1,
316
+ )
317
+
318
+ # Merge running top-k with this tile's top-k. Combined width is
319
+ # 2 * keep, which is small enough that another torch.topk is the
320
+ # right tool here too.
321
+ running_indices_chunk = topk_indices[query_start:query_end]
322
+ running_scores_chunk = topk_scores[query_start:query_end]
323
+ combined_scores = cupy.concatenate(
324
+ [running_scores_chunk, tile_top_scores], axis=1
325
+ )
326
+ combined_indices = cupy.concatenate(
327
+ [running_indices_chunk, tile_top_indices], axis=1
328
+ )
329
+ combined_torch = torch.from_dlpack(combined_scores)
330
+ merge_values_torch, merge_pos_torch = torch.topk(
331
+ combined_torch, k=keep, dim=1, largest=True, sorted=False
332
+ )
333
+ merge_pos = cupy.from_dlpack(merge_pos_torch)
334
+ topk_scores[query_start:query_end] = cupy.from_dlpack(
335
+ merge_values_torch
336
+ )
337
+ topk_indices[query_start:query_end] = cupy.take_along_axis(
338
+ combined_indices, merge_pos, axis=1
339
+ )
340
+
341
+ compute_done[slot].record(compute_stream)
342
+
343
+ # Now that compute is queued, prefetch tile_idx+2 into this slot.
344
+ # copy_stream waits on compute_done[slot] before overwriting the device buffer,
345
+ # and stage_tile waits host-side on copy_done[slot] before overwriting pinned scratch.
346
+ prefetch_idx = tile_idx + 2
347
+ if prefetch_idx < len(candidate_offsets):
348
+ counts[slot] = stage_tile(slot, candidate_offsets[prefetch_idx])
349
+
350
+ if (tile_idx + 1) % 32 == 0 or tile_idx + 1 == len(candidate_offsets):
351
+ compute_stream.synchronize()
352
+ # Reclaim pooled blocks accumulated by intra-tile concat / take ops
353
+ # so pool growth doesn't drift toward the device limit.
354
+ cupy.get_default_memory_pool().free_all_blocks()
355
+ elapsed = time.monotonic() - started
356
+ done_candidates = (tile_idx + 1) * candidate_tile_rows
357
+ millions_per_second = done_candidates / max(elapsed, 1e-3) / 1e6
358
+ print(
359
+ f"[gpu{gpu_index}] tile {tile_idx + 1}/{len(candidate_offsets)} "
360
+ f"elapsed {elapsed:.0f}s ({millions_per_second:.2f}M cand/s)",
361
+ flush=True,
362
+ )
363
+
364
+ compute_stream.synchronize()
365
+
366
+ # Sort each row by descending score, then drop the self-match in a single shift.
367
+ sorted_order = cupy.argsort(-topk_scores, axis=1)
368
+ sorted_scores = cupy.take_along_axis(topk_scores, sorted_order, axis=1)
369
+ sorted_indices = cupy.take_along_axis(topk_indices, sorted_order, axis=1)
370
+
371
+ query_global_ids = cupy.arange(stripe_start, stripe_end, dtype=cupy.int32).reshape(
372
+ -1, 1
373
+ )
374
+ is_self = sorted_indices == query_global_ids
375
+ has_self = cupy.any(is_self, axis=1, keepdims=True)
376
+ self_pos = cupy.argmax(is_self.astype(cupy.int32), axis=1, keepdims=True)
377
+
378
+ output_columns = cupy.broadcast_to(
379
+ cupy.arange(num_neighbors, dtype=cupy.int32), (stripe_size, num_neighbors)
380
+ )
381
+ shift_mask = (output_columns >= self_pos) & has_self
382
+ source_columns = output_columns + shift_mask.astype(cupy.int32)
383
+ final_scores = cupy.take_along_axis(sorted_scores, source_columns, axis=1)
384
+ final_indices = cupy.take_along_axis(sorted_indices, source_columns, axis=1)
385
+
386
+ scratch_dir.mkdir(parents=True, exist_ok=True)
387
+ indices_path = scratch_dir / f"stripe_{gpu_index:02d}.ibin"
388
+ scores_path = scratch_dir / f"stripe_{gpu_index:02d}.fbin"
389
+ write_bin(indices_path, cupy.asnumpy(final_indices), dtype="i32")
390
+ write_bin(scores_path, cupy.asnumpy(final_scores), dtype="f32")
391
+
392
+ elapsed = time.monotonic() - started
393
+ print(
394
+ f"[gpu{gpu_index}] DONE {stripe_size:,} queries in {elapsed:.0f}s "
395
+ f"-> {indices_path.name}, {scores_path.name}",
396
+ flush=True,
397
+ )
398
+
399
+
400
+ def gather_outputs(
401
+ scratch_dir: Path,
402
+ model_root: Path,
403
+ suffix: str,
404
+ shards: list[CollectionShard],
405
+ num_gpus: int,
406
+ total_vectors: int,
407
+ num_neighbors: int,
408
+ ) -> None:
409
+ """Slice per-stripe scratch files into per-shard `.ground_truth.ibin` and `.ground_truth.fbin`,
410
+ so each shard's ground truth lives next to its source `.f16bin`.
411
+
412
+ Each per-stripe scratch is contiguous global rows. A single shard may straddle
413
+ a stripe boundary, so we may pull from up to two stripes per shard.
414
+ """
415
+ bytes_per_row_indices = num_neighbors * 4
416
+ bytes_per_row_scores = num_neighbors * 4
417
+ indices_files = [
418
+ open(scratch_dir / f"stripe_{gpu_index:02d}.ibin", "rb")
419
+ for gpu_index in range(num_gpus)
420
+ ]
421
+ scores_files = [
422
+ open(scratch_dir / f"stripe_{gpu_index:02d}.fbin", "rb")
423
+ for gpu_index in range(num_gpus)
424
+ ]
425
+ try:
426
+ # Stripe boundary table (cumulative row counts).
427
+ stripe_starts = [
428
+ (total_vectors * gpu_index) // num_gpus for gpu_index in range(num_gpus + 1)
429
+ ]
430
+ for shard in shards:
431
+ wiki_dir = model_root / shard.wikiname
432
+ wiki_dir.mkdir(parents=True, exist_ok=True)
433
+ indices_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.ibin"
434
+ scores_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.fbin"
435
+ with open(indices_path, "wb") as out_indices, open(
436
+ scores_path, "wb"
437
+ ) as out_scores:
438
+ out_indices.write(struct.pack("<II", shard.row_count, num_neighbors))
439
+ out_scores.write(struct.pack("<II", shard.row_count, num_neighbors))
440
+ cursor = shard.row_offset
441
+ shard_end = shard.row_offset + shard.row_count
442
+ while cursor < shard_end:
443
+ # Find which stripe owns `cursor`.
444
+ stripe_index = next(
445
+ gpu_index
446
+ for gpu_index in range(num_gpus)
447
+ if stripe_starts[gpu_index]
448
+ <= cursor
449
+ < stripe_starts[gpu_index + 1]
450
+ )
451
+ chunk_end = min(shard_end, stripe_starts[stripe_index + 1])
452
+ chunk_rows = chunk_end - cursor
453
+ offset_in_stripe = cursor - stripe_starts[stripe_index]
454
+ indices_files[stripe_index].seek(
455
+ 8 + offset_in_stripe * bytes_per_row_indices
456
+ )
457
+ scores_files[stripe_index].seek(
458
+ 8 + offset_in_stripe * bytes_per_row_scores
459
+ )
460
+ out_indices.write(
461
+ indices_files[stripe_index].read(
462
+ chunk_rows * bytes_per_row_indices
463
+ )
464
+ )
465
+ out_scores.write(
466
+ scores_files[stripe_index].read(
467
+ chunk_rows * bytes_per_row_scores
468
+ )
469
+ )
470
+ cursor = chunk_end
471
+ finally:
472
+ for handle in indices_files + scores_files:
473
+ handle.close()
474
+
475
+
476
+ def main() -> None:
477
+ parser = argparse.ArgumentParser()
478
+ parser.add_argument("--output", default="/home/ubuntu/wikiverse-data/embeddings")
479
+ parser.add_argument(
480
+ "--model-subdir",
481
+ default="qwen3-embedding-0.6b",
482
+ help="collection lives at {output}/{model-subdir}/",
483
+ )
484
+ parser.add_argument(
485
+ "--dimensions",
486
+ type=int,
487
+ default=1024,
488
+ help="embedding dimensionality (1024 Qwen3/arctic, 768 nomic, 4096 e5-mistral)",
489
+ )
490
+ parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
491
+ parser.add_argument("--num-neighbors", type=int, default=100)
492
+ parser.add_argument("--num-gpus", type=int, default=8)
493
+ parser.add_argument(
494
+ "--query-tile-rows",
495
+ type=int,
496
+ default=16384,
497
+ help="rows per query chunk inside the resident stripe",
498
+ )
499
+ parser.add_argument(
500
+ "--candidate-tile-rows",
501
+ type=int,
502
+ default=131072,
503
+ help="rows per candidate tile streamed past the query stripe",
504
+ )
505
+ args = parser.parse_args()
506
+
507
+ model_root = Path(args.output) / args.model_subdir
508
+ if not model_root.is_dir():
509
+ raise SystemExit(f"no collection at {model_root}")
510
+
511
+ shards = discover_shards(model_root, args.output_suffix)
512
+ if not shards:
513
+ raise SystemExit(f"no .{args.output_suffix}.f16bin files under {model_root}")
514
+ total_vectors = sum(shard.row_count for shard in shards)
515
+ print(
516
+ f"discovered {len(shards)} shards across "
517
+ f"{len({shard.wikiname for shard in shards})} wikis, "
518
+ f"{total_vectors:,} total rows",
519
+ flush=True,
520
+ )
521
+
522
+ embeddings = load_collection(
523
+ model_root, args.output_suffix, args.dimensions, shards
524
+ )
525
+
526
+ scratch_dir = model_root / f"_ground_truth_scratch_{args.output_suffix}"
527
+ scratch_dir.mkdir(parents=True, exist_ok=True)
528
+
529
+ mp_context = mp.get_context("fork")
530
+ workers: list[mp.Process] = []
531
+ for gpu_index in range(args.num_gpus):
532
+ process = mp_context.Process(
533
+ target=worker_main,
534
+ args=(
535
+ gpu_index,
536
+ args.num_gpus,
537
+ embeddings,
538
+ args.dimensions,
539
+ args.num_neighbors,
540
+ args.query_tile_rows,
541
+ args.candidate_tile_rows,
542
+ scratch_dir,
543
+ ),
544
+ )
545
+ process.start()
546
+ workers.append(process)
547
+
548
+ failed = False
549
+ for process in workers:
550
+ process.join()
551
+ if process.exitcode != 0:
552
+ failed = True
553
+ print(
554
+ f"worker pid {process.pid} exited with code {process.exitcode}",
555
+ flush=True,
556
+ )
557
+ if failed:
558
+ raise SystemExit("one or more GPU workers failed")
559
+
560
+ gather_outputs(
561
+ scratch_dir,
562
+ model_root,
563
+ args.output_suffix,
564
+ shards,
565
+ args.num_gpus,
566
+ total_vectors,
567
+ args.num_neighbors,
568
+ )
569
+ print(
570
+ f"wrote {len(shards)} per-shard "
571
+ f"`.{args.output_suffix}.ground_truth.ibin` + `.{args.output_suffix}.ground_truth.fbin` "
572
+ f"files under {model_root}",
573
+ flush=True,
574
+ )
575
+
576
+ for path in scratch_dir.iterdir():
577
+ path.unlink()
578
+ scratch_dir.rmdir()
579
+
580
+
581
+ if __name__ == "__main__":
582
+ main()
tests/test_ground_truth.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end synthetic test for ground_truth.py.
2
+
3
+ Generates a tiny multi-wiki, multi-shard tree of f16 embeddings, runs the full
4
+ script under --num-gpus 1, and validates outputs against a NumPy brute-force
5
+ reference. No real data needed.
6
+
7
+ Run:
8
+ python -m pytest tests/test_ground_truth.py -s
9
+ or directly:
10
+ python tests/test_ground_truth.py
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import struct
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+
24
+ REPO_ROOT = Path(__file__).resolve().parent.parent
25
+ sys.path.insert(0, str(REPO_ROOT))
26
+
27
+ from wikiverse import write_bin, read_bin # noqa: E402
28
+
29
+
30
+ def normalize_rows(matrix: np.ndarray) -> np.ndarray:
31
+ norms = np.linalg.norm(matrix, axis=1, keepdims=True)
32
+ norms[norms == 0] = 1.0
33
+ return matrix / norms
34
+
35
+
36
+ def build_synthetic_tree(
37
+ root: Path,
38
+ model_subdir: str,
39
+ dimensions: int,
40
+ wikis: dict[str, list[int]],
41
+ seed: int = 0,
42
+ ) -> tuple[np.ndarray, list[tuple[str, str, int, int]]]:
43
+ """Create {root}/{model_subdir}/{wiki}/{stem}.body.f16bin tree.
44
+
45
+ `wikis` maps wikiname -> list of shard sizes (row counts).
46
+ Returns the concatenated ground-truth embeddings (in deterministic shard order)
47
+ and a manifest of (wikiname, stem, row_offset, row_count).
48
+ """
49
+ rng = np.random.default_rng(seed)
50
+ model_root = root / model_subdir
51
+ all_rows: list[np.ndarray] = []
52
+ manifest: list[tuple[str, str, int, int]] = []
53
+ offset = 0
54
+ for wikiname in sorted(wikis):
55
+ wiki_dir = model_root / wikiname
56
+ wiki_dir.mkdir(parents=True, exist_ok=True)
57
+ for shard_index, row_count in enumerate(wikis[wikiname]):
58
+ stem = f"000_{shard_index:05d}"
59
+ raw = rng.standard_normal((row_count, dimensions)).astype(np.float32)
60
+ normalized = normalize_rows(raw).astype(np.float16)
61
+ write_bin(wiki_dir / f"{stem}.body.f16bin", normalized, dtype="f16")
62
+ all_rows.append(normalized)
63
+ manifest.append((wikiname, stem, offset, row_count))
64
+ offset += row_count
65
+ embeddings = np.concatenate(all_rows, axis=0) if all_rows else np.empty((0, dimensions), np.float16)
66
+ return embeddings, manifest
67
+
68
+
69
+ def assemble_per_shard(
70
+ model_root: Path, suffix: str, extension: str, dtype: str
71
+ ) -> np.ndarray:
72
+ """Read every `{wiki}/{stem}.{suffix}.ground_truth.{extension}` and
73
+ concatenate in the same deterministic order discover_shards uses (sorted
74
+ wikiname, then sorted stem)."""
75
+ parts: list[np.ndarray] = []
76
+ for wiki_dir in sorted(model_root.iterdir()):
77
+ if not wiki_dir.is_dir():
78
+ continue
79
+ for path in sorted(wiki_dir.glob(f"*.{suffix}.ground_truth.{extension}")):
80
+ parts.append(read_bin(path, dtype=dtype))
81
+ return np.concatenate(parts, axis=0) if parts else np.empty((0, 0), dtype=np.float32)
82
+
83
+
84
+ def reference_topk(
85
+ embeddings: np.ndarray, num_neighbors: int
86
+ ) -> tuple[np.ndarray, np.ndarray]:
87
+ """Brute-force exact top-k via NumPy float32 matmul, with self-match dropped."""
88
+ f32 = embeddings.astype(np.float32)
89
+ similarity = f32 @ f32.T
90
+ total = embeddings.shape[0]
91
+ # Drop self-match by setting diagonal to -inf, then take top-k.
92
+ np.fill_diagonal(similarity, -np.inf)
93
+ top_indices = np.argsort(-similarity, axis=1)[:, :num_neighbors].astype(np.int32)
94
+ top_scores = np.take_along_axis(similarity, top_indices, axis=1).astype(np.float32)
95
+ return top_indices, top_scores
96
+
97
+
98
+ def run_script(
99
+ output_root: Path,
100
+ model_subdir: str,
101
+ dimensions: int,
102
+ num_neighbors: int,
103
+ query_tile_rows: int,
104
+ candidate_tile_rows: int,
105
+ num_gpus: int = 1,
106
+ ) -> subprocess.CompletedProcess[str]:
107
+ cmd = [
108
+ sys.executable,
109
+ str(REPO_ROOT / "ground_truth.py"),
110
+ "--output", str(output_root),
111
+ "--model-subdir", model_subdir,
112
+ "--dimensions", str(dimensions),
113
+ "--output-suffix", "body",
114
+ "--num-neighbors", str(num_neighbors),
115
+ "--num-gpus", str(num_gpus),
116
+ "--query-tile-rows", str(query_tile_rows),
117
+ "--candidate-tile-rows", str(candidate_tile_rows),
118
+ ]
119
+ return subprocess.run(cmd, check=True, capture_output=True, text=True)
120
+
121
+
122
+ def compare_topk(
123
+ expected_indices: np.ndarray,
124
+ expected_scores: np.ndarray,
125
+ actual_indices: np.ndarray,
126
+ actual_scores: np.ndarray,
127
+ score_tolerance: float = 5e-3,
128
+ ) -> None:
129
+ """Top-k may reorder ties, so compare as sets-of-(index, score-bucket) per row."""
130
+ assert expected_indices.shape == actual_indices.shape, (
131
+ f"shape mismatch: {expected_indices.shape} vs {actual_indices.shape}"
132
+ )
133
+ rows, k = expected_indices.shape
134
+ mismatches: list[str] = []
135
+ for row in range(rows):
136
+ expected_set = set(expected_indices[row].tolist())
137
+ actual_set = set(actual_indices[row].tolist())
138
+ missing = expected_set - actual_set
139
+ if missing:
140
+ # If a missing expected index has a score essentially tied with an
141
+ # actual index, that's a tie-break difference, not a real bug.
142
+ tail_score_actual = float(actual_scores[row].min())
143
+ for missing_index in missing:
144
+ expected_pos = int(np.where(expected_indices[row] == missing_index)[0][0])
145
+ expected_score = float(expected_scores[row, expected_pos])
146
+ if abs(expected_score - tail_score_actual) > score_tolerance:
147
+ mismatches.append(
148
+ f"row {row}: expected idx {missing_index} (score "
149
+ f"{expected_score:.4f}) missing; actual tail score "
150
+ f"{tail_score_actual:.4f}"
151
+ )
152
+ break
153
+ # No self-match in actual:
154
+ if row in actual_set:
155
+ mismatches.append(f"row {row}: self-match {row} present in actual top-k")
156
+ if mismatches:
157
+ raise AssertionError(
158
+ f"{len(mismatches)} row mismatches; first 5:\n "
159
+ + "\n ".join(mismatches[:5])
160
+ )
161
+
162
+
163
+ def test_synthetic_end_to_end() -> None:
164
+ dimensions = 64
165
+ num_neighbors = 5
166
+ wikis = {
167
+ "alswiki": [120, 80],
168
+ "rwwiki": [50],
169
+ "simplewiki": [200, 30, 70],
170
+ }
171
+ with tempfile.TemporaryDirectory(prefix="gt_test_") as tmpdir:
172
+ root = Path(tmpdir)
173
+ embeddings, manifest = build_synthetic_tree(
174
+ root, "tiny-model", dimensions, wikis, seed=42
175
+ )
176
+ total_vectors = embeddings.shape[0]
177
+ print(f"synthetic corpus: {total_vectors} vectors x {dimensions} dim")
178
+
179
+ # Use small tile sizes so the tiling logic gets exercised.
180
+ completed = run_script(
181
+ root,
182
+ model_subdir="tiny-model",
183
+ dimensions=dimensions,
184
+ num_neighbors=num_neighbors,
185
+ query_tile_rows=37,
186
+ candidate_tile_rows=64,
187
+ )
188
+ print("--- script stdout (last 30 lines) ---")
189
+ print("\n".join(completed.stdout.splitlines()[-30:]))
190
+
191
+ model_root = root / "tiny-model"
192
+ # Per-shard `.ground_truth.{ibin,fbin}` files; reassemble into a global matrix
193
+ # using the same deterministic shard order the script uses.
194
+ actual_indices = assemble_per_shard(model_root, "body", "ibin", "i32")
195
+ actual_scores = assemble_per_shard(model_root, "body", "fbin", "f32")
196
+ assert actual_indices.shape == (total_vectors, num_neighbors), actual_indices.shape
197
+ assert actual_scores.shape == (total_vectors, num_neighbors), actual_scores.shape
198
+
199
+ # No global file or manifest should be left behind.
200
+ assert not (model_root / "ground_truth.body.ibin").exists()
201
+ assert not (model_root / "ground_truth.body.manifest.json").exists()
202
+
203
+ expected_indices, expected_scores = reference_topk(embeddings, num_neighbors)
204
+ compare_topk(expected_indices, expected_scores, actual_indices, actual_scores)
205
+
206
+ # Scratch dir cleaned up.
207
+ scratch = model_root / "_ground_truth_scratch_body"
208
+ assert not scratch.exists(), f"scratch dir not cleaned: {scratch}"
209
+
210
+ assert (actual_scores[:, 0] <= 1.0 + 1e-3).all()
211
+ for row in range(total_vectors):
212
+ assert row not in set(actual_indices[row].tolist())
213
+
214
+ print(f"PASS: {total_vectors} queries, k={num_neighbors}, all rows match")
215
+
216
+
217
+ def test_synthetic_multi_gpu_larger() -> None:
218
+ """Bigger corpus across 4 GPUs with realistic-shaped tiles."""
219
+ dimensions = 256
220
+ num_neighbors = 20
221
+ wikis = {
222
+ "alswiki": [800, 1200],
223
+ "rwwiki": [400],
224
+ "simplewiki": [2000, 600, 1100],
225
+ "enwiki": [1500, 1500],
226
+ }
227
+ with tempfile.TemporaryDirectory(prefix="gt_test_mgpu_") as tmpdir:
228
+ root = Path(tmpdir)
229
+ embeddings, _ = build_synthetic_tree(
230
+ root, "tiny-mgpu", dimensions, wikis, seed=7
231
+ )
232
+ total_vectors = embeddings.shape[0]
233
+ print(f"multi-gpu corpus: {total_vectors} vectors x {dimensions} dim")
234
+
235
+ completed = run_script(
236
+ root,
237
+ model_subdir="tiny-mgpu",
238
+ dimensions=dimensions,
239
+ num_neighbors=num_neighbors,
240
+ query_tile_rows=512,
241
+ candidate_tile_rows=1024,
242
+ num_gpus=4,
243
+ )
244
+ print("\n".join(completed.stdout.splitlines()[-15:]))
245
+
246
+ model_root = root / "tiny-mgpu"
247
+ actual_indices = assemble_per_shard(model_root, "body", "ibin", "i32")
248
+ actual_scores = assemble_per_shard(model_root, "body", "fbin", "f32")
249
+ assert actual_indices.shape == (total_vectors, num_neighbors)
250
+ assert actual_scores.shape == (total_vectors, num_neighbors)
251
+
252
+ expected_indices, expected_scores = reference_topk(embeddings, num_neighbors)
253
+ compare_topk(expected_indices, expected_scores, actual_indices, actual_scores)
254
+ print(f"PASS: {total_vectors} queries across 4 GPUs, all rows match")
255
+
256
+
257
+ if __name__ == "__main__":
258
+ test_synthetic_end_to_end()
259
+ test_synthetic_multi_gpu_larger()