Download code/scripts/13_ename.py from Jyo-K/PopTurk: direct link, hf CLI and curl.
- Browser
- Download file 9.02 kB
-
https://huggingface.co/datasets/Jyo-K/PopTurk/resolve/main/code/scripts/13_ename.py
- Command line
-
hf download hf://datasets/Jyo-K/PopTurk/code/scripts/13_ename.py
-
curl -L -o 13_ename.py https://huggingface.co/datasets/Jyo-K/PopTurk/resolve/main/code/scripts/13_ename.py
9.02 kB
| """Fix 2: name-only retrieval over address-less pool records, by character TF-IDF. | |
| Reproduced exactly from MODEL5_FALSE_NEGATIVE_FIXES.md s4.2, which is the version that was | |
| measured. Of 16,332 true copies model-4 never retrieved, 7,628 have an empty address, and | |
| this channel recovers them: | |
| k = 5 3,386 of 7,628 (44%) 2.6% of the channel's candidates are true copies | |
| k = 10 4,259 (56%) 1.4% | |
| k = 20 4,906 (64%) - | |
| k = 5 is the recommendation and the default here: 5 extra candidates per S1, about 8.7M test | |
| pairs, and the precision of the channel falls off fast beyond it. | |
| WHY CHARACTER TF-IDF AND NOT THE DENSE ENCODER. I first built this channel with e5-small | |
| embeddings, which was a guess. This recipe is the one with a measured recovery rate attached, | |
| it needs no GPU at all, and character 3-grams are the right tool for the failure being | |
| targeted: typos and spacing damage on a short name with no address to fall back on. | |
| THE TRAP THIS CHANNEL WALKS INTO (s4.4). These candidates are address-less records that the | |
| other retrievers rank low. Under reciprocal-rank fusion with one channel voting they land | |
| below rank 64 and get cut - so fusing them normally throws away the entire point. They must | |
| enter the candidate set as a GUARANTEED UNION after the cut. 12_new_pairs.py gives this | |
| channel priority 0 for exactly that reason. | |
| Address-only retrieval is deliberately NOT implemented: measured at 6-12% recovery, about | |
| +0.0002 val, for 10-50 candidates per S1. It was rejected on the evidence. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import sys | |
| import time | |
| import numpy as np | |
| import pandas as pd | |
| # Pin BLAS before numpy/scipy import, so each forked worker stays single-threaded. | |
| for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", | |
| "NUMEXPR_NUM_THREADS"): | |
| os.environ.setdefault(_v, "1") | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from berx import paths as P # noqa: E402 | |
| _G: dict = {} # set in the parent, inherited by forked workers | |
| def _block(args): | |
| """One query chunk, run in a forked worker. | |
| Q and D are inherited through fork rather than pickled. A country's TF-IDF matrices are | |
| hundreds of MB and pickling them per task would cost more than the multiply. | |
| """ | |
| s, e, k = args | |
| Q, DT = _G["Q"], _G["DT"] | |
| sim = (Q[s:e] @ DT).toarray() | |
| kk = min(k, sim.shape[1]) | |
| part = np.argpartition(-sim, kk - 1, axis=1)[:, :kk] | |
| rows = np.arange(e - s)[:, None] | |
| sv = sim[rows, part] | |
| order = np.argsort(-sv, axis=1) | |
| return s, e, part[rows, order].astype(np.int32), sv[rows, order].astype(np.float32) | |
| def topk_sparse(Q, D, k: int, chunk: int = 4096, workers: int = 0): | |
| """Top-k cosine per query row, over a pool of processes. | |
| Both matrices are L2-normalised TF-IDF, so the inner product IS the cosine. | |
| WHY PARALLEL. Serially this is one core of the 96 on the box: France measured at about | |
| 4 minutes, and the work scales with queries x documents, so India is 8.5x France and the | |
| whole channel projects to roughly an hour - on the critical path to the Colab lanes, for | |
| a step that is embarrassingly parallel over query chunks. | |
| Each worker is pinned to a single BLAS thread. Without that, N workers each spawn their | |
| own thread pool on a 96-core box and spend their time fighting each other for cache. | |
| """ | |
| import multiprocessing as mp | |
| n = Q.shape[0] | |
| idx = np.zeros((n, k), dtype=np.int32) | |
| val = np.zeros((n, k), dtype=np.float32) | |
| _G["Q"], _G["DT"] = Q, D.T.tocsc() | |
| tasks = [(s, min(s + chunk, n), k) for s in range(0, n, chunk)] | |
| if workers <= 0: | |
| # Leave headroom: this box is shared and has been made unusable before by a job that | |
| # took every core. | |
| workers = max(1, min(16, (os.cpu_count() or 8) // 4, len(tasks))) | |
| t0 = time.time() | |
| pool = None | |
| if workers == 1: | |
| results = map(_block, tasks) | |
| else: | |
| # fork, so Q and DT are inherited rather than pickled per task. Windows has no fork; | |
| # this runs on Linux, but falling back keeps the file testable anywhere. | |
| try: | |
| ctx = mp.get_context("fork") | |
| except ValueError: | |
| print(" no fork on this platform; running serially", flush=True) | |
| ctx = None | |
| if ctx is None: | |
| workers = 1 | |
| results = map(_block, tasks) | |
| pool = None | |
| else: | |
| pool = ctx.Pool(workers) | |
| results = pool.imap_unordered(_block, tasks, chunksize=1) | |
| done = 0 | |
| for s, e, bi, bv in results: | |
| kk = bi.shape[1] | |
| idx[s:e, :kk] = bi | |
| val[s:e, :kk] = bv | |
| done += e - s | |
| if done % (chunk * 20) < chunk: | |
| el = time.time() - t0 | |
| f = done / n | |
| print(f" {done:>9,}/{n:,} ({f:5.1%}) {workers}w " | |
| f"eta {el/max(f,1e-9)-el:6.0f}s", flush=True) | |
| if pool is not None: | |
| pool.close() | |
| pool.join() | |
| _G.clear() | |
| return idx, val | |
| def _self_test(): | |
| """Prove the parallel path returns exactly what the serial path returns. | |
| Run through the real entry point, not an imported copy: multiprocessing resolves the | |
| worker function by module name, so a module loaded under a synthetic name fails to | |
| pickle even though production is fine. | |
| """ | |
| from scipy import sparse | |
| D = sparse.random(3000, 150, density=0.1, format="csr", random_state=1, dtype=np.float32) | |
| Q = sparse.random(2000, 150, density=0.1, format="csr", random_state=2, dtype=np.float32) | |
| i1, v1 = topk_sparse(Q, D, 5, chunk=128, workers=1) | |
| i8, v8 = topk_sparse(Q, D, 5, chunk=128, workers=8) | |
| assert np.allclose(v1, v8), "parallel scores differ from serial" | |
| assert (i1 == i8).all(), "parallel indices differ from serial" | |
| print(f"self-test PASS: 8 workers match serial exactly on {Q.shape[0]:,} queries") | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--split", default="test") | |
| ap.add_argument("--k", type=int, default=5) | |
| ap.add_argument("--chunk", type=int, default=4096) | |
| ap.add_argument("--workers", type=int, default=0, help="0 = auto (capped, shared box)") | |
| ap.add_argument("--self-test", action="store_true", | |
| help="check the parallel path against the serial one, then exit") | |
| a = ap.parse_args() | |
| if a.self_test: | |
| _self_test() | |
| return | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| d = os.path.dirname(P.work("prep", a.split, "_")) | |
| s1 = pd.read_parquet(os.path.join(d, "source1.parquet")) | |
| pool = pd.read_parquet(os.path.join(d, "pool.parquet")) | |
| empty = (pool["business_address"].astype(str).str.strip() == "").to_numpy() | |
| print(f"{a.split}: {len(s1):,} S1, {len(pool):,} pool, " | |
| f"{int(empty.sum()):,} address-less ({empty.mean():.2%})") | |
| qs, cs, ss, rs = [], [], [], [] | |
| for country in sorted(set(s1["country"])): | |
| qrows = np.flatnonzero((s1["country"] == country).to_numpy()) | |
| drows = np.flatnonzero(empty & (pool["country"] == country).to_numpy()) | |
| if len(qrows) == 0 or len(drows) == 0: | |
| print(f" {country}: nothing to do") | |
| continue | |
| print(f" {country}: {len(qrows):,} queries x {len(drows):,} address-less docs", | |
| flush=True) | |
| docs = pool["business_name"].astype(str).to_numpy()[drows] | |
| qtxt = s1["business_name"].astype(str).to_numpy()[qrows] | |
| # Fitted on the DOCUMENTS, as measured - the idf weighting should describe the | |
| # address-less pool, not the S1 table. | |
| vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 3), sublinear_tf=True) | |
| t0 = time.time() | |
| D = vec.fit_transform(docs) | |
| Q = vec.transform(qtxt) | |
| print(f" tfidf {D.shape[1]:,} features in {time.time()-t0:.0f}s", flush=True) | |
| idx, val = topk_sparse(Q, D, a.k, a.chunk, a.workers) | |
| kk = idx.shape[1] | |
| qs.append(np.repeat(qrows, kk)) | |
| cs.append(drows[idx.ravel()]) | |
| ss.append(val.ravel()) | |
| rs.append(np.tile(np.arange(kk, dtype=np.int16), len(qrows))) | |
| assert qs, "no country produced candidates" | |
| out = pd.DataFrame({ | |
| "q": np.concatenate(qs).astype(np.int32), | |
| "c": np.concatenate(cs).astype(np.int32), | |
| "s": np.concatenate(ss).astype(np.float32), | |
| "r": np.concatenate(rs).astype(np.int16), | |
| }) | |
| out = out[out["s"] > 0] # a zero score means no shared 3-gram at all | |
| p = P.work("retr", f"{a.split}_ename_s0of1.parquet") | |
| out.to_parquet(p, index=False) | |
| print(f"\nwrote {p} {len(out):,} pairs " | |
| f"({len(out)/len(s1):.2f} per S1)") | |
| if __name__ == "__main__": | |
| main() | |