File size: 41,069 Bytes
15c4ef8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 | #!/usr/bin/env python3
"""Dense-retrieval candidate generation (multilingual-e5-large) for AMLC 2026 entity resolution.
For every Source-1 record, retrieve Source-2 u Source-3 records of the SAME country as the union of
* the top-K_full (default 30) pool records by cosine on the full-text e5 vectors (name + address), and
* the top-K_name (default 10) pool records by cosine on the name-only e5 vectors.
Search is exact brute force on the GPU: fp16 matmul (fp32 accumulation) against the whole country pool held
in GPU memory, per-chunk top-(K+margin), then exact fp32 cosine rescoring of the shortlist and final top-K.
For pairs found by only one list the other cosine is computed explicitly, so both sim columns are always set.
Inputs (HF dataset Arushhh/amlc-work, downloaded under --hub):
emb/e5_{full,name}/{table}.npy float16 (n, 1024), L2-normalised, norm-parquet row order
emb/e5_{full,name}/{table}_ids.parquet entity_id, same order
norm/{table}.parquet entity_id, country (lowercase)
split train: S1 = s1, pool = s2 u s3; split test: S1 = t1, pool = t2 u t3
Output {out_dir}/{split}_cands{tag}.parquet, one row per (s1_id, cand_id), columns
s1_id, cand_id, country, src ('S2'/'S3' = cand_id prefix), sim_e5_full, sim_e5_name (float32 cosine),
from_reverse (always False), f_e5_full, f_e5_name (bool: pair is in that list),
rank_e5_full, rank_e5_name (int32, 1-based rank in that list, -1 if absent)
plus {split}_cands{tag}_metrics.json (timings, candidates per S1, pairs per list and, when --gt is given,
pair recall against the ground truth: overall / per country / per source / per list, recall@k, entity level).
Per country (GPU passes; the pool of one variant is resident in GPU memory, sharded if it does not fit):
1. name vectors of the pool -> name top-K for all S1 of the country
2. full vectors -> full top-K, plus the full cosine of every name-list pair
3. name vectors again -> name cosine of every full-list pair
4. union -> per-country part parquet (checkpoint; uploaded to S3), finally concatenated into one file.
Checks: --self-test appends the queried S1 vectors to the pool (a record must retrieve itself at rank 1);
--verify N brute-forces the exact fp32 top-K for N random queries per country/list and compares.
Example: python dense_retrieval.py --split train
python dense_retrieval.py --split test --countries france --max-s1 20000 --self-test --tag _selftest --s3 ''
"""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import argparse
import json
import queue
import subprocess
import threading
import time
import numpy as np
import polars as pl
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
import torch
SPLITS = {"train": ("s1", ("s2", "s3")), "test": ("t1", ("t2", "t3"))}
DIM = 1024
RETRIEVAL_ORDER = ("name", "full") # name first: pass 2 (full) fills name-list full-sims on the fly
OUT_SCHEMA = pa.schema(
[
("s1_id", pa.string()),
("cand_id", pa.string()),
("country", pa.string()),
("src", pa.string()),
("sim_e5_full", pa.float32()),
("sim_e5_name", pa.float32()),
("from_reverse", pa.bool_()),
("f_e5_full", pa.bool_()),
("f_e5_name", pa.bool_()),
("rank_e5_full", pa.int32()),
("rank_e5_name", pa.int32()),
]
)
T0 = time.time()
UPLOADS: list[threading.Thread] = []
def log(msg: str) -> None:
print(f"{time.strftime('%H:%M:%S')} [{time.time() - T0:7.0f}s] {msg}", flush=True)
def gpu_mem() -> str:
f, t = torch.cuda.mem_get_info()
return f"gpu free {f / 1e9:.1f}/{t / 1e9:.1f} GB, peak alloc {torch.cuda.max_memory_allocated() / 1e9:.1f} GB"
def s3_put(local: str, key: str, args, background: bool = True) -> None:
if not args.s3:
return
dst = args.s3.rstrip("/") + "/" + key
def run():
t = time.time()
r = subprocess.run(["aws", "s3", "cp", "--only-show-errors", local, dst], capture_output=True, text=True)
if r.returncode:
log(f"S3 upload FAILED {local} -> {dst}: {r.stderr.strip()}")
else:
log(f"uploaded {local} -> {dst} ({os.path.getsize(local) / 1e6:,.1f} MB, {time.time() - t:.0f}s)")
if background:
th = threading.Thread(target=run, daemon=False)
th.start()
UPLOADS.append(th)
else:
run()
def s3_get(key: str, local: str, args) -> bool:
if not args.s3:
return False
r = subprocess.run(["aws", "s3", "cp", "--only-show-errors", args.s3.rstrip("/") + "/" + key, local], capture_output=True, text=True)
return r.returncode == 0
# --------------------------------------------------------------------------------------------- inputs
class Table:
"""ids / country / vector-file paths of one table; rows are in norm-parquet (= embedding) order."""
def __init__(self, hub: str, name: str, variants):
self.name = name
self.npy: dict[str, str] = {}
ids = None
for v in variants:
a = pq.read_table(f"{hub}/emb/e5_{v}/{name}_ids.parquet", columns=["entity_id"]).column("entity_id")
a = a.combine_chunks().cast(pa.string())
if ids is None:
ids = a
elif not ids.equals(a):
raise SystemExit(f"{name}: e5_{v} ids differ from e5_{variants[0]} ids (row order mismatch)")
path = f"{hub}/emb/e5_{v}/{name}.npy"
mm = np.load(path, mmap_mode="r")
if mm.shape != (len(a), DIM) or mm.dtype != np.float16:
raise SystemExit(f"{path}: shape {mm.shape} dtype {mm.dtype}, expected ({len(a)}, {DIM}) float16")
self.npy[v] = path
del mm
norm = pl.read_parquet(f"{hub}/norm/{name}.parquet", columns=["entity_id", "country"])
if norm.height == len(ids) and pl.Series(ids).equals(norm.get_column("entity_id"), check_names=False):
country = norm.get_column("country")
else:
log(f"WARNING {name}: norm parquet order differs from embedding ids; joining on entity_id")
country = (
pl.DataFrame({"entity_id": pl.Series(ids)})
.join(norm, on="entity_id", how="left", maintain_order="left")
.get_column("country")
)
country = country.cast(pl.Utf8).fill_null("").str.strip_chars().str.to_lowercase()
self.ids = ids
self.country = country.to_numpy()
self.n = len(ids)
vc = dict(zip(*np.unique(self.country, return_counts=True)))
log(f"table {name}: {self.n:,} rows; countries {{{', '.join(f'{k}: {v:,}' for k, v in vc.items())}}}")
def rows(self, country: str) -> np.ndarray:
return np.flatnonzero(self.country == country)
def iter_rows(path: str, rows: np.ndarray, chunk_rows: int = 131072):
"""Sequentially read the (n, DIM) float16 .npy at `path`; yield (a, b, vecs) with vecs = file rows rows[a:b]
(rows sorted ascending). A reader thread prefetches so disk reads overlap with the consumer."""
mm = np.load(path, mmap_mode="r")
n, off = mm.shape[0], mm.offset
del mm
rb = DIM * 2
q: queue.Queue = queue.Queue(maxsize=3)
def reader():
try:
bounds = np.searchsorted(rows, np.arange(0, n + chunk_rows, chunk_rows))
with open(path, "rb", buffering=0) as f:
for ci in range(len(bounds) - 1):
a, b = int(bounds[ci]), int(bounds[ci + 1])
if a == b:
continue
lo, hi = int(rows[a]), int(rows[b - 1]) + 1
buf = np.empty((hi - lo, DIM), np.float16)
mv = memoryview(buf).cast("B")
f.seek(off + lo * rb)
got = 0
while got < len(mv):
k = f.readinto(mv[got:])
if not k:
raise IOError(f"short read in {path} at row {lo}")
got += k
q.put((a, b, buf if (b - a) == (hi - lo) else buf[rows[a:b] - lo]))
q.put(None)
except BaseException as e: # surface reader errors in the consumer
q.put(e)
th = threading.Thread(target=reader, daemon=True)
th.start()
while True:
item = q.get()
if item is None:
break
if isinstance(item, BaseException):
raise item
yield item
th.join()
def load_host(table: Table, variant: str, rows: np.ndarray) -> np.ndarray:
out = np.empty((len(rows), DIM), np.float16)
for a, b, v in iter_rows(table.npy[variant], rows):
out[a:b] = v
return out
class PoolPart:
"""A contiguous block of the country pool: rows of a Table (disk) or, for --self-test, host arrays."""
def __init__(self, label, ids: pa.Array, table: Table | None = None, rows=None, host=None):
self.label, self.ids, self.table, self.rows, self.host = label, ids, table, rows, host
self.n = len(ids)
def to_gpu(self, variant, lo, hi, dst: torch.Tensor):
"""copy part-local rows [lo, hi) of `variant` into dst (a (hi-lo, DIM) cuda view)."""
if self.host is not None:
dst.copy_(torch.from_numpy(self.host[variant][lo:hi]))
return
for a, b, v in iter_rows(self.table.npy[variant], self.rows[lo:hi]):
dst[a:b].copy_(torch.from_numpy(v))
@torch.no_grad()
def load_pool_gpu(parts, variant, s, e):
"""Pool-local rows [s, e) of `variant` -> (P fp16 cuda (e-s, DIM), fp32 row norms)."""
P = torch.empty((e - s, DIM), dtype=torch.float16, device="cuda")
off = 0
for part in parts:
lo, hi = max(s, off), min(e, off + part.n)
if lo < hi:
part.to_gpu(variant, lo - off, hi - off, P[lo - s : hi - s])
off += part.n
Pn = torch.cat([P[i : i + 262144].float().norm(dim=1) for i in range(0, e - s, 262144)])
return P, Pn
# --------------------------------------------------------------------------------------------- GPU kernels
@torch.no_grad()
def retrieve(Q: np.ndarray, P, Pn, k: int, args, tag: str):
"""exact top-k cosine of every row of Q (host fp16) against P. Returns shard-local idx (n,k) int64, sim fp32."""
n, m = len(Q), P.shape[0]
k_eff = min(k, m)
kk = min(k + args.margin, m)
B = args.batch
torch.cuda.empty_cache()
free = torch.cuda.mem_get_info()[0]
chunk = int((free - args.work_gb * 1e9) / (B * 2 * args.sims_factor))
chunk = max(65536, min(args.max_chunk, chunk)) // 4096 * 4096
log(f" {tag}: retrieve k={k_eff} (+margin {kk - k_eff}) for {n:,} queries vs {m:,} pool, batch {B}, pool chunk {chunk:,}, group {args.group} ({gpu_mem()})")
G = args.group
if G:
chunk = max(G, chunk // G * G)
ar_g = torch.arange(G or 1, device="cuda")
idx_out = np.empty((n, k_eff), np.int64)
sim_out = np.empty((n, k_eff), np.float32)
t0 = time.time()
next_log = args.log_every
for s in range(0, n, B):
q = torch.from_numpy(Q[s : s + B]).cuda()
bs = q.shape[0]
vs, ix = [], []
for c0 in range(0, m, chunk):
C = min(chunk, m - c0)
Cg = C // G * G if G else 0
if Cg >= kk * G and G:
# grouped top-k (exact): the top-kk entries lie in the kk groups of G columns with the largest max
S = torch.matmul(q, P[c0 : c0 + Cg].T) # fp16 in/out, fp32 accumulate
gm = S.view(bs, Cg // G, G).amax(2)
_, gi = torch.topk(gm, kk, dim=1, sorted=False)
cols = (gi.unsqueeze(2) * G + ar_g).reshape(bs, -1)
v, j = torch.topk(torch.gather(S, 1, cols), kk, dim=1, sorted=False)
i = torch.gather(cols, 1, j)
del S, gm, gi, cols
vs.append(v)
ix.append(i.add_(c0))
else:
Cg = 0
if Cg < C:
S = torch.matmul(q, P[c0 + Cg : c0 + C].T)
v, i = torch.topk(S, min(kk, S.shape[1]), dim=1, sorted=False)
del S
vs.append(v)
ix.append(i.add_(c0 + Cg))
v, i = torch.cat(vs, 1), torch.cat(ix, 1)
if v.shape[1] > kk:
v, j = torch.topk(v, kk, dim=1, sorted=False)
i = torch.gather(i, 1, j)
# exact fp32 cosine of the shortlist, then final sorted top-k
qf = q.float()
cand = P[i.reshape(-1)].view(bs, -1, DIM).float()
ex = torch.bmm(cand, qf.unsqueeze(2)).squeeze(2) / (qf.norm(dim=1, keepdim=True) * Pn[i])
del cand
ex, j = torch.topk(ex, k_eff, dim=1, sorted=True)
i = torch.gather(i, 1, j)
idx_out[s : s + bs] = i.cpu().numpy()
sim_out[s : s + bs] = ex.cpu().numpy()
done = s + bs
if done >= next_log or done == n:
el = time.time() - t0
log(f" {tag}: {done:,}/{n:,} S1 rows {el:.0f}s {done / max(el, 1e-9):,.0f} rows/s eta {(n - done) * el / done:.0f}s")
while next_log <= done:
next_log += args.log_every
return idx_out, sim_out, {"chunk": chunk, "seconds": round(time.time() - t0, 1)}
@torch.no_grad()
def fill_cos(Q: np.ndarray, P, Pn, s: int, idx: np.ndarray, out: np.ndarray, B: int = 4096) -> None:
"""out[r, j] = cos(Q[r], pool[idx[r, j]]) for idx inside the resident shard [s, s+len(P))."""
e = s + P.shape[0]
for r in range(0, len(idx), B):
i = torch.from_numpy(idx[r : r + B]).cuda()
q = torch.from_numpy(Q[r : r + B]).cuda().float()
inside = (i >= s) & (i < e)
loc = (i - s).clamp_(0, P.shape[0] - 1)
cand = P[loc.reshape(-1)].view(i.shape[0], i.shape[1], DIM).float()
cs = torch.bmm(cand, q.unsqueeze(2)).squeeze(2) / (q.norm(dim=1, keepdim=True) * Pn[loc])
o = torch.from_numpy(out[r : r + B]).cuda()
out[r : r + B] = torch.where(inside, cs, o).cpu().numpy()
@torch.no_grad()
def brute_force_check(Q, P, Pn, idx, sim, k, n_check, rng, tag):
"""exact fp32 top-k for n_check random queries vs the retrieved lists (single-shard only)."""
n = len(Q)
sel = np.sort(rng.choice(n, min(n_check, n), replace=False))
q = torch.from_numpy(Q[sel]).cuda().float()
qn = q.norm(dim=1, keepdim=True)
best_v, best_i = None, None
for c0 in range(0, P.shape[0], 262144):
S = (q @ P[c0 : c0 + 262144].float().T) / (qn * Pn[c0 : c0 + 262144])
v, i = torch.topk(S, min(k, S.shape[1]), dim=1)
i += c0
if best_v is None:
best_v, best_i = v, i
else:
best_v, j = torch.topk(torch.cat([best_v, v], 1), k, dim=1)
best_i = torch.gather(torch.cat([best_i, i], 1), 1, j)
bv, bi = best_v.cpu().numpy(), best_i.cpu().numpy()
got_i, got_v = idx[sel], sim[sel]
overlap = np.array([len(set(a) & set(b)) / k for a, b in zip(bi, got_i)])
# boundary-tolerant: every retrieved sim >= exact k-th sim - 1e-4 and rank-wise sims agree
tol_ok = (got_v[:, -1] >= bv[:, -1] - 1e-4).mean()
sim_diff = float(np.abs(np.sort(got_v, 1) - np.sort(bv, 1)).max())
res = {
"n": int(len(sel)),
"mean_set_overlap": round(float(overlap.mean()), 5),
"min_set_overlap": round(float(overlap.min()), 4),
"share_exact_set": round(float((overlap == 1).mean()), 5),
"kth_sim_within_1e-4": round(float(tol_ok), 5),
"max_abs_sorted_sim_diff": round(sim_diff, 6),
}
log(f" {tag}: brute-force check {res}")
return res
# --------------------------------------------------------------------------------------------- per country
def plan_shards(n_pool: int, args):
torch.cuda.empty_cache()
free = torch.cuda.mem_get_info()[0]
per = int((free - args.reserve_gb * 1e9) // (DIM * 2))
if args.max_shard_rows:
per = min(per, args.max_shard_rows)
ns = max(1, -(-n_pool // per))
edges = np.linspace(0, n_pool, ns + 1).astype(np.int64)
return [(int(edges[i]), int(edges[i + 1])) for i in range(ns)]
def merge_shards(results, k):
if len(results) == 1:
return results[0]
idx = np.concatenate([r[0] for r in results], 1)
sim = np.concatenate([r[1] for r in results], 1)
o = np.argsort(-sim, axis=1, kind="stable")[:, :k]
return np.take_along_axis(idx, o, 1), np.take_along_axis(sim, o, 1)
def process_country(country, s1: Table, s1_rows, parts, args, variants, K, rng, tm):
n = len(s1_rows)
n_pool = sum(p.n for p in parts)
t = time.time()
Q = {v: load_host(s1, v, s1_rows) for v in variants}
tm["load_s1_vectors"] = round(time.time() - t, 1)
log(f" {country}: {n:,} S1 x {n_pool:,} pool ({', '.join(f'{p.label} {p.n:,}' for p in parts)}); S1 vectors loaded in {tm['load_s1_vectors']}s")
shards = plan_shards(n_pool, args)
if len(shards) > 1:
log(f" {country}: pool does not fit in GPU memory -> {len(shards)} shards {shards}")
lists: dict[str, tuple] = {} # variant -> (idx, sim)
cross: dict[tuple, np.ndarray] = {} # (list variant u, sim variant v) -> cos_v for pairs of list u
verify = {}
order = [v for v in RETRIEVAL_ORDER if v in variants]
todo_fill = {(u, v) for u in order for v in order if u != v}
passes = [(v, True) for v in order]
# a variant retrieved before another list existed needs a later fill-only pass
for v in order:
if any((u, v) in todo_fill and order.index(u) > order.index(v) for u in order):
passes.append((v, False))
for v, do_retrieve in passes:
tag = f"{country}/{v}" + ("" if do_retrieve else "-fill")
results = []
fill_targets = [u for u in lists if u != v and (u, v) in todo_fill]
for u in fill_targets:
cross[(u, v)] = np.full(lists[u][0].shape, np.nan, np.float32)
for si, (s, e) in enumerate(shards):
t = time.time()
P, Pn = load_pool_gpu(parts, v, s, e)
tm[f"{tag}/load_pool_s{si}"] = round(time.time() - t, 1)
log(f" {tag}: pool shard {si} [{s:,}, {e:,}) loaded in {tm[f'{tag}/load_pool_s{si}']}s ({gpu_mem()})")
if do_retrieve:
idx, sim, info = retrieve(Q[v], P, Pn, K[v], args, tag)
tm[f"{tag}/retrieve_s{si}"] = info["seconds"]
tm[f"{tag}/pool_chunk"] = info["chunk"]
if args.verify and len(shards) == 1:
verify[v] = brute_force_check(Q[v], P, Pn, idx, sim, idx.shape[1], args.verify, rng, tag)
results.append((idx + s, sim))
t = time.time()
for u in fill_targets:
fill_cos(Q[v], P, Pn, s, lists[u][0], cross[(u, v)])
if fill_targets:
tm[f"{tag}/fill_s{si}"] = round(time.time() - t, 1)
del P, Pn
torch.cuda.empty_cache()
for u in fill_targets:
todo_fill.discard((u, v))
bad = int(np.isnan(cross[(u, v)]).sum())
if bad:
raise RuntimeError(f"{tag}: {bad} unfilled cosines for list {u}")
if do_retrieve:
lists[v] = merge_shards(results, K[v])
del Q
return lists, cross, verify
def union_country(country, lists, cross, s1_ids_c: pa.Array, pool_ids: pa.Array, pool_src_code, src_dict, variants):
n = len(s1_ids_c)
empty_i, empty_f = np.zeros((n, 0), np.int64), np.zeros((n, 0), np.float32)
fi, fs = lists.get("full", (empty_i, empty_f))
ni, ns = lists.get("name", (empty_i, empty_f))
fns = cross.get(("full", "name"), np.full(fi.shape, np.nan, np.float32)) # name cosine of full-list pairs
nfs = cross.get(("name", "full"), np.full(ni.shape, np.nan, np.float32)) # full cosine of name-list pairs
kf, kn = fi.shape[1], ni.shape[1]
rank_name_of_f = np.full((n, kf), -1, np.int32)
name_only = np.ones((n, kn), bool)
CH = 100000
for r in range(0, n, CH):
eq = fi[r : r + CH, :, None] == ni[r : r + CH, None, :]
if kn and kf:
rank_name_of_f[r : r + CH] = np.where(eq.any(2), eq.argmax(2) + 1, -1)
name_only[r : r + CH] = ~eq.any(1)
both = rank_name_of_f > 0
cons = {}
if both.any():
rr, jj = np.nonzero(both)
d1 = np.abs(fns[rr, jj] - ns[rr, rank_name_of_f[rr, jj] - 1])
j2 = np.nonzero(ni[rr] == fi[rr, jj][:, None])[1]
d2 = np.abs(fs[rr, jj] - nfs[rr, j2])
cons = {"max_diff_name_sim": float(d1.max()), "max_diff_full_sim": float(d2.max())}
if max(cons.values()) > 1e-4:
raise RuntimeError(f"{country}: filled vs retrieved cosine mismatch {cons}")
rows_f = np.repeat(np.arange(n, dtype=np.int64), kf)
rr, jj = np.nonzero(name_only)
rows = np.concatenate([rows_f, rr])
cand = np.concatenate([fi.ravel(), ni[rr, jj]])
sim_full = np.concatenate([fs.ravel(), nfs[rr, jj]]).astype(np.float32)
sim_name = np.concatenate([fns.ravel(), ns[rr, jj]]).astype(np.float32)
rank_full = np.concatenate([np.tile(np.arange(1, kf + 1, dtype=np.int32), n), np.full(len(rr), -1, np.int32)])
rank_name = np.concatenate([rank_name_of_f.ravel(), (jj + 1).astype(np.int32)])
key = np.sort(rows * (1 << 32) + cand)
n_dup = int((key[1:] == key[:-1]).sum())
del key
if n_dup:
raise RuntimeError(f"{country}: {n_dup} duplicate (s1, cand) pairs after union")
o = np.argsort(rows, kind="stable") # per S1: full list by rank, then name-only pairs by name rank
rows, cand, sim_full, sim_name, rank_full, rank_name = (x[o] for x in (rows, cand, sim_full, sim_name, rank_full, rank_name))
N = len(rows)
tbl = pa.table(
{
"s1_id": s1_ids_c.take(pa.array(rows)),
"cand_id": pool_ids.take(pa.array(cand)),
"country": pa.array([country], pa.string()).take(pa.array(np.zeros(N, np.int32))),
"src": src_dict.take(pa.array(pool_src_code[cand])),
"sim_e5_full": pa.array(sim_full, pa.float32()),
"sim_e5_name": pa.array(sim_name, pa.float32()),
"from_reverse": pa.array(np.zeros(N, bool)),
"f_e5_full": pa.array(rank_full > 0),
"f_e5_name": pa.array(rank_name > 0),
"rank_e5_full": pa.array(rank_full, pa.int32()),
"rank_e5_name": pa.array(rank_name, pa.int32()),
},
schema=OUT_SCHEMA,
)
per_s1 = kf + name_only.sum(1)
stats = {
"pairs": int(N),
"pairs_full_list": int(n * kf),
"pairs_name_list": int(n * kn),
"pairs_in_both": int(both.sum()),
"pairs_full_only": int(n * kf - both.sum()),
"pairs_name_only": int(len(rr)),
"cands_per_s1_hist": {int(a): int(b) for a, b in zip(*np.unique(per_s1, return_counts=True))},
"sim_consistency": cons,
"duplicate_pairs": n_dup,
"top1_sim_full_mean": float(fs[:, 0].mean()) if kf else None,
"top1_sim_name_mean": float(ns[:, 0].mean()) if kn else None,
"kth_sim_full_mean": float(fs[:, -1].mean()) if kf else None,
"kth_sim_name_mean": float(ns[:, -1].mean()) if kn else None,
}
return tbl, stats
def hist_stats(h: dict) -> dict:
if not h:
return {}
vals = np.array(sorted(int(k) for k in h))
cnt = np.array([h[k] if k in h else h[str(k)] for k in vals], dtype=np.int64)
cum = np.cumsum(cnt) / cnt.sum()
def pct(p):
return int(vals[np.searchsorted(cum, p / 100.0)])
return {
"n_s1": int(cnt.sum()),
"mean": round(float((vals * cnt).sum() / cnt.sum()), 3),
"min": int(vals[0]),
"p50": pct(50),
"p90": pct(90),
"p99": pct(99),
"max": int(vals[-1]),
}
def merge_hists(hs):
out: dict = {}
for h in hs:
for k, v in h.items():
out[int(k)] = out.get(int(k), 0) + int(v)
return out
# --------------------------------------------------------------------------------------------- ground truth
def evaluate_gt(gt_path, out_path, queried: pl.DataFrame, pool_meta: pl.DataFrame, K) -> dict:
"""pair recall of the written candidates vs the ground truth, restricted to the queried S1."""
gt = pl.read_csv(gt_path, separator="\t", infer_schema_length=0, quote_char=None)
gt = gt.rename({gt.columns[0]: "s1_id", gt.columns[1]: "matched"}).select("s1_id", "matched")
n_gt_s1 = gt.height
gq = gt.join(queried, on="s1_id", how="inner")
pairs = (
gq.with_columns(pl.col("matched").str.split(","))
.explode("matched")
.with_columns(pl.col("matched").str.strip_chars())
.filter(pl.col("matched").is_not_null() & (pl.col("matched").str.len_chars() > 0))
.select("s1_id", pl.col("matched").alias("cand_id"), "country", pl.col("matched").str.slice(0, 2).alias("src"))
.unique(["s1_id", "cand_id"])
)
pairs = pairs.join(pool_meta, left_on="cand_id", right_on="entity_id", how="left")
pairs = pairs.with_columns(reachable=(pl.col("cand_country") == pl.col("country")).fill_null(False))
hits = (
pl.scan_parquet(out_path)
.select("s1_id", "cand_id", "f_e5_full", "f_e5_name", "rank_e5_full", "rank_e5_name")
.join(pairs.lazy().select("s1_id", "cand_id"), on=["s1_id", "cand_id"], how="inner")
.collect()
)
P = pairs.join(hits, on=["s1_id", "cand_id"], how="left").with_columns(
pl.col("f_e5_full").fill_null(False),
pl.col("f_e5_name").fill_null(False),
pl.col("rank_e5_full").fill_null(-1),
pl.col("rank_e5_name").fill_null(-1),
)
P = P.with_columns(union=pl.col("f_e5_full") | pl.col("f_e5_name"))
P = P.with_columns(
full_only=pl.col("f_e5_full") & ~pl.col("f_e5_name"),
name_only=pl.col("f_e5_name") & ~pl.col("f_e5_full"),
)
flags = ["f_e5_full", "f_e5_name", "union", "full_only", "name_only", "reachable"]
def agg(df):
r = df.select([pl.len().alias("n_gt_pairs")] + [pl.col(f).mean().round(5) for f in flags])
return r.to_dicts()[0]
def grouped(keys):
g = P.group_by(keys).agg([pl.len().alias("n_gt_pairs")] + [pl.col(f).mean().round(5) for f in flags]).sort(keys)
return {"|".join(str(r[k]) for k in keys): {kk: r[kk] for kk in ["n_gt_pairs"] + flags} for r in g.iter_rows(named=True)}
m = {
"note": "pair recall = share of ground-truth (s1_id, matched id) pairs of the queried S1 present in the candidates; "
"f_e5_full / f_e5_name = recall of each list alone; union = the candidate set; full_only / name_only = share found "
"by that list only; reachable = candidate exists in the same-country pool",
"gt_file_s1_rows": n_gt_s1,
"queried_s1_in_gt": gq.height,
"overall": agg(P),
"by_country": grouped(["country"]),
"by_source": grouped(["src"]),
"by_country_source": grouped(["country", "src"]),
}
rk = {}
for k in sorted({1, 2, 3, 5, 10, 15, 20, 25, 30, K.get("full", 30)}):
if k <= K.get("full", 0):
rk[f"full@{k}"] = round(float(((P["rank_e5_full"] >= 1) & (P["rank_e5_full"] <= k)).mean()), 5)
for k in sorted({1, 2, 3, 5, 10, K.get("name", 10)}):
if k <= K.get("name", 0):
rk[f"name@{k}"] = round(float(((P["rank_e5_name"] >= 1) & (P["rank_e5_name"] <= k)).mean()), 5)
m["recall_at_k"] = rk
e = P.group_by("s1_id", "country").agg(
pl.len().alias("n_true"),
pl.col("union").sum().alias("n_found"),
pl.col("f_e5_full").any().alias("any_full"),
pl.col("f_e5_name").any().alias("any_name"),
pl.col("union").any().alias("any_union"),
)
m["entity"] = {
"n_nonsingleton_s1": e.height,
"n_singleton_s1": gq.height - e.height,
"any_true_found_union": round(float(e["any_union"].mean()), 5),
"any_true_found_full": round(float(e["any_full"].mean()), 5),
"any_true_found_name": round(float(e["any_name"].mean()), 5),
"all_true_found_union": round(float((e["n_found"] == e["n_true"]).mean()), 5),
"true_pairs_per_nonsingleton_s1_mean": round(float(e["n_true"].mean()), 3),
"true_pairs_per_nonsingleton_s1_p99": int(e["n_true"].quantile(0.99)),
"true_pairs_per_nonsingleton_s1_max": int(e["n_true"].max()),
"share_s1_with_more_true_than_k_full": round(float((e["n_true"] > K.get("full", 30)).mean()), 5),
}
return m
def print_gt_report(ev):
o = ev["overall"]
log("=" * 100)
log(f"TRAIN PAIR RECALL vs ground truth (dense e5, full pool): {o['n_gt_pairs']:,} GT pairs of {ev['queried_s1_in_gt']:,} queried S1")
log(f" {'group':<22}{'n_gt_pairs':>12}{'full@K':>9}{'name@K':>9}{'UNION':>9}{'full_only':>10}{'name_only':>10}{'reachable':>10}")
rows = [("overall", o)] + [(f"country={k}", v) for k, v in ev["by_country"].items()] + [(f"src={k}", v) for k, v in ev["by_source"].items()]
rows += [(f"{k}", v) for k, v in ev["by_country_source"].items()]
for name, r in rows:
log(f" {name:<22}{r['n_gt_pairs']:>12,}{r['f_e5_full']:>9.4f}{r['f_e5_name']:>9.4f}{r['union']:>9.4f}{r['full_only']:>10.4f}{r['name_only']:>10.4f}{r['reachable']:>10.4f}")
log(f" recall@k: {ev['recall_at_k']}")
log(f" entity: {ev['entity']}")
log("=" * 100)
# --------------------------------------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--split", required=True, choices=sorted(SPLITS))
ap.add_argument("--hub", default="/opt/dlami/nvme/amlc/hub")
ap.add_argument("--out-dir", default="/opt/dlami/nvme/amlc/dense")
ap.add_argument("--tag", default="", help="suffix for output names (e.g. _smoke)")
ap.add_argument("--variants", default="full,name")
ap.add_argument("--k-full", type=int, default=30)
ap.add_argument("--k-name", type=int, default=10)
ap.add_argument("--margin", type=int, default=10, help="extra fp16 shortlist entries rescored exactly")
ap.add_argument("--batch", type=int, default=2048)
ap.add_argument("--max-chunk", type=int, default=1 << 20, help="max pool rows per matmul/topk chunk")
ap.add_argument("--group", type=int, default=64, help="grouped exact top-k: column group size (0 = plain torch.topk)")
ap.add_argument("--sims-factor", type=float, default=2.5, help="GPU bytes per sims element / 2 budgeted for topk workspace")
ap.add_argument("--work-gb", type=float, default=1.5, help="GPU memory kept free besides the sims chunk")
ap.add_argument("--reserve-gb", type=float, default=4.5, help="GPU memory not used for the pool when sharding")
ap.add_argument("--max-shard-rows", type=int, default=0, help="force pool sharding (testing)")
ap.add_argument("--countries", default="", help="comma-separated subset")
ap.add_argument("--pool-tables", default="", help="override the pool tables (testing), e.g. s2")
ap.add_argument("--max-s1", type=int, default=0, help="random S1 sample per country (0 = all)")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--self-test", action="store_true", help="append the queried S1 vectors to the pool; check self-retrieval")
ap.add_argument("--verify", type=int, default=512, help="brute-force exact check on N random queries per country/list (0=off)")
ap.add_argument("--gt", default=None, help="ground truth TSV (default for train: raw/dataset/train/train_ground_truth.tsv)")
ap.add_argument("--no-gt", action="store_true")
ap.add_argument("--s3", default="s3://amlc-2026-478982785786/dense", help="S3 prefix ('' = no upload)")
ap.add_argument("--log-every", type=int, default=100000)
ap.add_argument("--resume", action="store_true", help="reuse finished per-country parts (local or S3)")
args = ap.parse_args()
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
torch.backends.cuda.matmul.allow_tf32 = False
variants = [v.strip() for v in args.variants.split(",") if v.strip()]
K = {"full": args.k_full, "name": args.k_name}
K = {v: K[v] for v in variants}
if args.split == "train" and args.gt is None and not args.no_gt and not args.self_test:
args.gt = "/opt/dlami/nvme/amlc/raw/dataset/train/train_ground_truth.tsv"
if args.no_gt or args.self_test:
args.gt = None
os.makedirs(args.out_dir, exist_ok=True)
stem = f"{args.split}_cands{args.tag}"
out_path = f"{args.out_dir}/{stem}.parquet"
metrics_path = f"{args.out_dir}/{stem}_metrics.json"
part_dir = f"{args.out_dir}/parts_{stem}"
os.makedirs(part_dir, exist_ok=True)
log(f"dense retrieval split={args.split} variants={variants} K={K} out={out_path} torch {torch.__version__} {torch.cuda.get_device_name()}")
log(f"args: {vars(args)}")
s1_name, pool_names = SPLITS[args.split]
if args.pool_tables:
pool_names = tuple(t.strip() for t in args.pool_tables.split(",") if t.strip())
t = time.time()
s1 = Table(args.hub, s1_name, variants)
pools = [Table(args.hub, p, variants) for p in pool_names]
load_meta_s = round(time.time() - t, 1)
countries = sorted(set(np.unique(s1.country)))
if args.countries:
want = [c.strip().lower() for c in args.countries.split(",")]
countries = [c for c in countries if c in want]
log(f"countries: {countries}")
rng = np.random.default_rng(args.seed)
metrics = {
"split": args.split,
"s1_table": s1_name,
"pool_tables": list(pool_names),
"variants": variants,
"k": K,
"config": vars(args),
"encoder": "intfloat/multilingual-e5-large (fp16, 'query: ' prompt, L2-normalised)",
"gpu": torch.cuda.get_device_name(),
"load_meta_seconds": load_meta_s,
"per_country": {},
}
queried_frames = []
part_paths = []
for country in countries:
part_path = f"{part_dir}/{country}.parquet"
part_metrics = f"{part_dir}/{country}.json"
s1_rows = s1.rows(country)
if args.max_s1 and len(s1_rows) > args.max_s1:
s1_rows = np.sort(rng.choice(s1_rows, args.max_s1, replace=False))
if args.resume and not os.path.exists(part_metrics):
if s3_get(f"parts/{stem}/{country}.json", part_metrics, args) and s3_get(f"parts/{stem}/{country}.parquet", part_path, args):
log(f"{country}: fetched finished part from S3")
if args.resume and os.path.exists(part_metrics) and os.path.exists(part_path):
cm = json.load(open(part_metrics))
if cm.get("n_s1") == len(s1_rows):
log(f"{country}: resume -> reusing {part_path}")
metrics["per_country"][country] = cm
part_paths.append(part_path)
queried_frames.append(pl.Series("s1_id", s1.ids.take(pa.array(s1_rows))).to_frame().with_columns(country=pl.lit(country)))
continue
tc = time.time()
tm: dict = {}
parts = []
for pt in pools:
r = pt.rows(country)
parts.append(PoolPart(pt.name, pt.ids.take(pa.array(r)), table=pt, rows=r))
if args.self_test:
host = {v: load_host(s1, v, s1_rows) for v in variants}
parts.append(PoolPart("self(S1)", s1.ids.take(pa.array(s1_rows)), host=host))
log(f"=== {country}: {len(s1_rows):,} S1, pool {sum(p.n for p in parts):,} ===")
lists, cross, verify = process_country(country, s1, s1_rows, parts, args, variants, K, rng, tm)
self_res = {}
if args.self_test:
base = sum(p.n for p in parts[:-1])
own = base + np.arange(len(s1_rows))
for v, (idx, sim) in lists.items():
pos = idx == own[:, None]
found = pos.any(1)
rank1 = pos[:, 0]
own_sim = np.where(found, (sim * pos).sum(1), np.nan)
tie1 = found & (np.abs(sim[:, 0] - own_sim) <= 1e-4) # own vector tied with an identical record
self_res[v] = {
"own_at_rank1": round(float(rank1.mean()), 6),
"own_rank1_or_tied_top": round(float((rank1 | tie1).mean()), 6),
"own_in_list": round(float(found.mean()), 6),
"own_sim_min": float(np.nanmin(own_sim)) if found.any() else None,
}
log(f" SELF-TEST {country}/{v}: {self_res[v]}")
del host
t = time.time()
pool_ids = pa.concat_arrays([p.ids for p in parts])
src_str = pc.utf8_slice_codeunits(pool_ids, 0, 2)
denc = pc.dictionary_encode(src_str)
pool_src_code = denc.indices.to_numpy(zero_copy_only=False).astype(np.int32)
src_dict = denc.dictionary
s1_ids_c = s1.ids.take(pa.array(s1_rows))
tbl, stats = union_country(country, lists, cross, s1_ids_c, pool_ids, pool_src_code, src_dict, variants)
del lists, cross
tm["union"] = round(time.time() - t, 1)
t = time.time()
pq.write_table(tbl, part_path, compression="zstd", row_group_size=1 << 20)
tm["write_part"] = round(time.time() - t, 1)
del tbl
tm["total"] = round(time.time() - tc, 1)
cm = {
"n_s1": int(len(s1_rows)),
"n_pool": int(sum(p.n for p in parts)),
"n_pool_by_part": {p.label: int(p.n) for p in parts},
"timings_s": tm,
**stats,
"cands_per_s1": hist_stats(stats["cands_per_s1_hist"]),
"brute_force_check": verify,
"self_test": self_res,
"part_bytes": os.path.getsize(part_path),
}
json.dump(cm, open(part_metrics, "w"), indent=1)
metrics["per_country"][country] = cm
log(f"=== {country} done in {tm['total']}s: {stats['pairs']:,} pairs, cands/S1 {cm['cands_per_s1']}, timings {tm}")
part_paths.append(part_path)
queried_frames.append(pl.Series("s1_id", s1_ids_c).to_frame().with_columns(country=pl.lit(country)))
if not args.self_test:
s3_put(part_path, f"parts/{stem}/{country}.parquet", args)
s3_put(part_metrics, f"parts/{stem}/{country}.json", args)
# ---- concatenate parts into the single output file
t = time.time()
n_rows = 0
with pq.ParquetWriter(out_path, OUT_SCHEMA, compression="zstd") as w:
for p in part_paths:
pf = pq.ParquetFile(p)
for rg in range(pf.num_row_groups):
tb = pf.read_row_group(rg)
n_rows += tb.num_rows
w.write_table(tb.cast(OUT_SCHEMA))
metrics["write_output_seconds"] = round(time.time() - t, 1)
metrics["output"] = {"path": out_path, "rows": n_rows, "bytes": os.path.getsize(out_path)}
log(f"wrote {out_path}: {n_rows:,} rows, {os.path.getsize(out_path) / 1e9:.2f} GB in {metrics['write_output_seconds']}s")
if not args.self_test:
s3_put(out_path, f"{stem}.parquet", args)
pc_ = metrics["per_country"]
metrics["overall"] = {
"n_s1": sum(c["n_s1"] for c in pc_.values()),
"pairs": sum(c["pairs"] for c in pc_.values()),
"pairs_full_only": sum(c["pairs_full_only"] for c in pc_.values()),
"pairs_name_only": sum(c["pairs_name_only"] for c in pc_.values()),
"pairs_in_both": sum(c["pairs_in_both"] for c in pc_.values()),
"cands_per_s1": hist_stats(merge_hists([c["cands_per_s1_hist"] for c in pc_.values()])),
"seconds_per_country": {k: c["timings_s"]["total"] for k, c in pc_.items()},
}
log(f"overall: {metrics['overall']}")
# ---- sanity: schema + uniqueness on the written file
sch = pq.read_schema(out_path)
assert sch.names == OUT_SCHEMA.names, sch.names
dup = sum(c.get("duplicate_pairs", 0) for c in metrics["per_country"].values()) # checked per country in union
nnan = pl.scan_parquet(out_path).select(pl.col("sim_e5_full").is_nan().sum() + pl.col("sim_e5_full").is_null().sum(), pl.col("sim_e5_name").is_nan().sum() + pl.col("sim_e5_name").is_null().sum()).collect().row(0)
metrics["checks"] = {"duplicate_pairs": int(dup), "nan_sim_full": int(nnan[0]), "nan_sim_name": int(nnan[1])}
log(f"checks: {metrics['checks']}")
if args.gt:
t = time.time()
queried = pl.concat(queried_frames)
pool_meta = pl.concat(
[pl.DataFrame({"entity_id": pl.Series(p.ids), "cand_country": pl.Series(p.country, dtype=pl.Utf8)}) for p in pools]
)
ev = evaluate_gt(args.gt, out_path, queried, pool_meta, K)
ev["seconds"] = round(time.time() - t, 1)
metrics["gt_eval"] = ev
print_gt_report(ev)
json.dump(metrics, open(metrics_path, "w"), indent=1)
log(f"metrics -> {metrics_path}")
if not args.self_test:
s3_put(metrics_path, f"{stem}_metrics.json", args, background=False)
for th in UPLOADS:
th.join()
log("DONE")
if __name__ == "__main__":
main()
|