| """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
|
| from berx import retrieve as R
|
|
|
|
|
| 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")
|
|
|
|
|
| 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}"
|
|
|
|
|
|
|
|
|
|
|
| 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_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)
|
| 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()
|
|
|