File size: 7,086 Bytes
d231962 | 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 | """Step C. GPU retrieval for one channel and one query shard.
CUDA_VISIBLE_DEVICES=0 nice -n 19 ionice -c3 python scripts/03_retrieve.py \
--split test --channel e5_small --k 100 --shard 0 --nshards 2
Two GPUs run the same command with --shard 0 and --shard 1. They share nothing, so either
shard can be re-run alone after a failure without redoing the other.
The channel matrices are expected at BERX_EMB/<channel>/<split>_{s1,pool}.npy, fp16, L2
normalised, in source row order. `--verify` checks the shapes against ids.json before
spending an hour on a matrix that turns out to be the wrong model - the two 1024-d channels
are interchangeable by shape and not by content, so shape alone will not catch a mix-up.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
import numpy as np
import pandas as pd
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from berx import paths as P # noqa: E402
from berx import retrieve as R # noqa: E402
def verify_ids(channel: str, split: str, which: str, prep: str, parquet: str, n_check=200_000):
"""Check the embedding's ids.txt against the prepared source, row by row.
Only the first and last `n_check` rows are compared in full: reading 10M ids takes longer
than the check is worth, and any offset introduced mid-file shifts every subsequent row,
so the tail catches it.
"""
ids_path = P.emb_ids(channel, split, which)
if not os.path.exists(ids_path):
print(f" ! no ids.txt for {channel}/{split}_{which}; row order UNVERIFIED")
return
want = pd.read_parquet(os.path.join(prep, parquet), columns=["entity_id"])["entity_id"]
with open(ids_path) as fh:
got = [ln.strip() for ln in fh]
assert len(got) == len(want), \
f"{ids_path}: {len(got):,} ids but the prepared {parquet} has {len(want):,} rows"
k = min(n_check, len(want))
head_bad = [i for i in range(k) if got[i] != want.iloc[i]]
tail_bad = [i for i in range(len(want) - k, len(want)) if got[i] != want.iloc[i]]
assert not head_bad and not tail_bad, (
f"{ids_path}: row order does not match {parquet}. "
f"First mismatch at row {(head_bad or tail_bad)[0]:,}. "
f"Every candidate index from there on would be wrong.")
print(f" ids verified: {channel}/{split}_{which} {len(got):,} rows, "
f"head+tail {k:,} each match")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--split", default="test")
ap.add_argument("--channel", required=True,
help="a configured channel, or an ad-hoc one built by 08_embed.py "
"(nameonly / addronly)")
ap.add_argument("--k", type=int, default=100)
ap.add_argument("--shard", type=int, default=0)
ap.add_argument("--nshards", type=int, default=1)
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--qchunk", type=int, default=4096)
ap.add_argument("--pblock", type=int, default=262_144)
ap.add_argument("--resident", default="auto", choices=["auto", "yes", "no"])
ap.add_argument("--max-queries", type=int, default=0,
help="debug: cap queries per country. Verifies the whole path on a busy "
"box in seconds instead of hours. Never use for a real run.")
ap.add_argument("--verify-only", action="store_true",
help="check shapes, normalisation and row order, then exit")
a = ap.parse_args()
prep = os.path.dirname(P.work("prep", a.split, "_"))
meta = json.load(open(os.path.join(prep, "ids.json")))
qc = np.load(os.path.join(prep, "country_s1.npy"))
pc = np.load(os.path.join(prep, "country_pool.npy"))
qp = P.emb(a.channel, a.split, "s1")
pp = P.emb(a.channel, a.split, "pool")
for p in (qp, pp):
assert os.path.exists(p), f"missing embedding matrix: {p}"
Q, Pm = np.load(qp, mmap_mode="r"), np.load(pp, mmap_mode="r")
# channel_cfg, not CHANNELS: the rescue channels (nameonly, addronly) are built on demand
# by 08_embed.py and have no declared entry.
want_dim = P.channel_cfg(a.channel)["dim"]
assert Q.shape == (meta["n_s1"], want_dim), \
f"{qp} is {Q.shape}, expected ({meta['n_s1']}, {want_dim})"
assert Pm.shape[1] == want_dim, f"{pp} is {Pm.shape[1]}-d, expected {want_dim}"
# A SUBSET pool (F4 covers only the address-less records) carries rows.npy mapping its
# rows back to rows of the FULL pool. Everything downstream indexes the full pool, so
# without this remap candidate index i means row i of a 265k subset while the fuse step
# reads it as row i of a 10M pool - wrong, and with nothing to signal it.
rows_path = P.emb_rows(a.channel, a.split, "pool")
prow = np.load(rows_path) if os.path.exists(rows_path) else None
if prow is not None and len(prow) != meta["n_pool"]:
assert len(prow) == Pm.shape[0], \
f"rows.npy has {len(prow):,} entries but the matrix has {Pm.shape[0]:,} rows"
print(f" subset pool: {Pm.shape[0]:,} of {meta['n_pool']:,} rows; "
f"candidate indices remapped through rows.npy")
pc = pc[prow]
else:
prow = None
assert Pm.shape[0] == meta["n_pool"], \
f"{pp} has {Pm.shape[0]:,} rows, expected {meta['n_pool']:,}"
nrm = np.linalg.norm(np.asarray(Q[:256], dtype=np.float32), axis=1)
assert abs(float(nrm.mean()) - 1.0) < 0.02, \
f"query rows are not L2-normalised (mean norm {nrm.mean():.4f}); cosine would be wrong"
# Verify row order by ENTITY ID, not by row count. A matrix with the right number of rows
# in the wrong order produces candidate indices that are wrong for every row after the
# first disturbance, and nothing downstream - not the validator, not the F0.5 - reports
# anything other than a mediocre score.
verify_ids(a.channel, a.split, "s1", prep, "source1.parquet")
if prow is None:
verify_ids(a.channel, a.split, "pool", prep, "pool.parquet")
if a.verify_only:
print("verify-only: shapes, normalisation and row order all check out.")
return
print(f"channel {a.channel} k={a.k} shard {a.shard}/{a.nshards} {a.device}")
t0 = time.time()
res = R.run_channel(qp, pp, qc, pc, a.k, a.device, a.shard, a.nshards,
qchunk=a.qchunk, pblock=a.pblock, resident=a.resident,
max_queries=a.max_queries or None)
if prow is not None:
res["c"] = prow[res["c"]].astype(np.int32) # subset row -> full pool row
df = pd.DataFrame(res)
out = P.work("retr", f"{a.split}_{a.channel}_s{a.shard}of{a.nshards}.parquet")
df.to_parquet(out, index=False)
el = time.time() - t0
print(f"wrote {out} {len(df):,} pairs {el/60:.1f} min "
f"({len(df)/max(el,1e-9):,.0f} pairs/s)")
if __name__ == "__main__":
main()
|