"""Candidate generation (blocking) for the AMLC 2026 business entity resolution task. For every Source-1 record, retrieve plausible Source-2/Source-3 records of the SAME country (matches never cross country) as the union of several sparse top-K cosine retrievals: name char 3-gram TF-IDF on the spaceless name top k_name (S1 -> pool) nameaddr char 3-gram TF-IDF on name + ' ' + address top k_nameaddr (S1 -> pool) addr char 3-gram TF-IDF on address (empty -> skipped) top k_addr (S1 -> pool) word word 1+2-gram TF-IDF on name + ' ' + address top k_word (S1 -> pool) reverse nameaddr, pool -> S1 top reverse_k per pool record The union is needed because 14% of true pairs share no name token and 4% share no address token (never both), see docs/dataset_findings.md. TF-IDF: hashed features (sklearn HashingVectorizer, parallel), idf fit on S1 u pool of the country (smooth idf), sublinear tf, features with df > max_df * n dropped before the l2 norm, features present on only one side dropped after the norm (they cannot contribute to a dot product), float32 throughout. Top-K backends: sdt sparse_dot_topn.sp_matmul_topn with OpenMP threads, over row blocks of the query matrix. scipy fallback: chunked Q_chunk @ T.T with scipy, per-row top-K by argpartition, chunks sized by an estimate of multiply-adds so each worker's product stays bounded; forked worker processes share the target matrix copy-on-write. Output parquet columns: s1_id, cand_id, country, src, sim_name, sim_nameaddr, sim_addr, sim_word, f_name, f_nameaddr, f_addr, f_word, from_reverse, rank_name, rank_nameaddr, rank_addr, rank_word, rank_rev [, is_match when --gt]. f_* / from_reverse say which retrieval produced the pair; rank_* is the 0-based rank of the candidate in the S1 record's top-K list (rank_rev: rank of the S1 record in the pool record's reverse list), null when not retrieved. With --fill-sims (default) every sim_* column holds the exact cosine for every pair under that representation (so all four are usable as features); with --no-fill-sims sim_* is the retrieval cosine and null when that strategy did not retrieve the pair. Pre-normalised input: --norm-dir DIR [--split train|test] reads DIR/{s1,s2,s3}.parquet (or t1,t2,t3) written by scripts/preprocess_normalize.py; name = name_translit (fallback name_core), address = ' '.join(addr_tokens_translit), spaceless name = name without spaces. Note that table's country values are lowercased ('us', 'india'); they are used as-is. Normaliser hook (TSV input only): --normalizer pkg.module:function. The function receives a polars DataFrame with columns entity_id, business_name, business_address, country and must return it with string columns name_n and addr_n added (name_ns, the spaceless name, is derived if absent). Example: python -m src.blocking --s1 train_source1.tsv --s2 train_source2.tsv --s3 train_source3.tsv \ --gt train_ground_truth.tsv --out cands.parquet --max-s1 200000 --workers 30 """ from __future__ import annotations import argparse import gc import importlib import json import math import multiprocessing as mp import os import sys import time import warnings from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager import numpy as np import polars as pl import scipy.sparse as sp from sklearn.feature_extraction.text import HashingVectorizer # import before any fork try: # import before any fork as well (native OpenMP runtime) import sparse_dot_topn as _sdt except ImportError: _sdt = None warnings.filterwarnings("ignore", message=r".*fork.*") # polars' at-fork warning; workers never call polars warnings.filterwarnings("ignore", message=r".*empty_as_null.*") STRATS = ("name", "nameaddr", "addr", "word") SIM_COLS = [f"sim_{s}" for s in STRATS] FLAG_COLS = [f"f_{s}" for s in STRATS] + ["from_reverse"] RANK_COLS = [f"rank_{s}" for s in STRATS] + ["rank_rev"] NO_RANK = np.int16(32767) REV_CAPS = (0, 5, 10, 20, 40) # reverse-only pairs kept per S1 in the sweep (plus 'all') K_FRACS = (0.25, 0.5, 0.75, 1.0) # forward K scaling in the sweep SRC_COLS = ["entity_id", "business_name", "business_address", "country"] # -------------------------------------------------------------------------------------------- # logging, timing, memory # -------------------------------------------------------------------------------------------- _T0 = time.time() TIMINGS: dict[str, float] = {} def _mem_info(): rss = avail = None try: import psutil rss = psutil.Process().memory_info().rss avail = psutil.virtual_memory().available except Exception: try: with open("/proc/self/statm") as f: rss = int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") with open("/proc/meminfo") as f: for line in f: if line.startswith("MemAvailable:"): avail = int(line.split()[1]) * 1024 except Exception: pass return rss, avail def _peak_gb(): import resource scale = 1 if sys.platform == "darwin" else 1024 # ru_maxrss: bytes on macOS, KiB on Linux own = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * scale / 1e9 kids = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss * scale / 1e9 return own, kids def log(msg: str) -> None: rss, avail = _mem_info() parts = [f"{time.time() - _T0:8.1f}s"] if rss is not None: parts.append(f"rss={rss / 1e9:6.2f}GB") if avail is not None: parts.append(f"avail={avail / 1e9:6.1f}GB") print(f"[{' '.join(parts)}] {msg}", flush=True) @contextmanager def stage(name: str): t = time.time() log(f">> {name}") try: yield finally: dt = time.time() - t TIMINGS[name] = TIMINGS.get(name, 0.0) + dt log(f"<< {name} ({dt:.1f}s)") # -------------------------------------------------------------------------------------------- # loading and normalisation # -------------------------------------------------------------------------------------------- def read_tsv(path: str, columns: list[str] | None = None) -> pl.DataFrame: """Read a challenge TSV with every column as string, no quoting, empty -> ''.""" kw = dict(separator="\t", quote_char=None, infer_schema_length=0, truncate_ragged_lines=True, encoding="utf8-lossy", columns=columns) with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) df = pl.read_csv(path, **kw) return df.with_columns(pl.all().fill_null("")) def read_source(path: str) -> pl.DataFrame: df = read_tsv(path) missing = [c for c in SRC_COLS if c not in df.columns] if missing: raise ValueError(f"{path}: missing columns {missing}; got {df.columns}") return df.select( pl.col("entity_id").str.strip_chars(), pl.col("business_name"), pl.col("business_address"), pl.col("country").str.strip_chars(), ) def _nfkd(e: pl.Expr) -> pl.Expr: if hasattr(pl.col("x").str, "normalize"): return e.str.normalize("NFKD") import pyarrow.compute as pc # older polars: do it in arrow return e.map_batches(lambda s: pl.from_arrow(pc.utf8_normalize(s.to_arrow(), "NFKD")), return_dtype=pl.Utf8) def default_normalizer(df: pl.DataFrame) -> pl.DataFrame: """Light normaliser: NFKD, drop non-spacing marks (accents), lowercase, drop literal 'null' address components, every run of non letter/number/spacing-mark chars -> one space, strip. Spacing marks (\\p{Mc}) are kept so Indic words are not split at vowel signs.""" def base(col: str) -> pl.Expr: return _nfkd(pl.col(col)).str.replace_all(r"\p{Mn}+", "").str.to_lowercase() punct = r"[^\p{L}\p{N}\p{Mc}]+" name = base("business_name").str.replace_all(punct, " ").str.strip_chars() addr = base("business_address").str.replace_all(r"\bnull\b", " ").str.replace_all(punct, " ").str.strip_chars() return df.with_columns(name_n=name, addr_n=addr) def load_normalizer(spec: str | None): if not spec: return default_normalizer mod, _, fn = spec.partition(":") return getattr(importlib.import_module(mod), fn or "normalize") def apply_normalizer(fn, df: pl.DataFrame, src: str) -> pl.DataFrame: out = fn(df) for c in ("name_n", "addr_n"): if c not in out.columns: raise ValueError(f"normaliser must add column {c!r}") if "name_ns" not in out.columns: out = out.with_columns(name_ns=pl.col("name_n").str.replace_all(" ", "", literal=True)) return out.select( "entity_id", "country", pl.col("name_n").fill_null(""), pl.col("name_ns").fill_null(""), pl.col("addr_n").fill_null(""), pl.lit(src).alias("src"), ) NORM_TABLES = {"train": ("s1", "s2", "s3"), "test": ("t1", "t2", "t3")} def read_norm_parquet(path: str, src: str) -> pl.DataFrame: """Read a table written by scripts/preprocess_normalize.py and build the retrieval strings: name = name_translit (falls back to name_core when null/blank), address = ' '.join( addr_tokens_translit), spaceless name = name with whitespace removed.""" import pyarrow.parquet as pq have = set(pq.read_schema(path).names) need = {"entity_id", "country", "addr_tokens_translit"} if not need <= have or not ({"name_translit", "name_core"} & have): raise ValueError(f"{path}: needs {sorted(need)} and name_translit/name_core; has {sorted(have)}") cols = [c for c in ("entity_id", "country", "name_translit", "name_core", "addr_tokens_translit") if c in have] df = pl.read_parquet(path, columns=cols) blank = pl.lit(None, dtype=pl.Utf8) tr = pl.col("name_translit") if "name_translit" in have else blank core = pl.col("name_core") if "name_core" in have else blank ws = r"\s+" name = ( pl.when(tr.is_not_null() & (tr.str.strip_chars() != "")).then(tr).otherwise(core) .fill_null("").str.replace_all(ws, " ").str.strip_chars() ) addr = pl.col("addr_tokens_translit").list.join(" ").fill_null("").str.replace_all(ws, " ").str.strip_chars() return df.select( pl.col("entity_id").cast(pl.Utf8).str.strip_chars(), pl.col("country").cast(pl.Utf8).fill_null("").str.strip_chars(), name.alias("name_n"), name.str.replace_all(ws, "").alias("name_ns"), addr.alias("addr_n"), pl.lit(src).alias("src"), ) def strategy_texts(df: pl.DataFrame, strat: str) -> list[str]: if strat == "name": e = pl.col("name_ns") elif strat == "addr": e = pl.col("addr_n") else: # nameaddr, word e = pl.concat_str([pl.col("name_n"), pl.col("addr_n")], separator=" ").str.strip_chars() return df.select(e.alias("t")).get_column("t").to_list() def _gather(s: pl.Series, idx: np.ndarray) -> pl.Series: return s.gather(idx) if hasattr(s, "gather") else s.take(idx) # -------------------------------------------------------------------------------------------- # vectorisation (hashed, parallel) # -------------------------------------------------------------------------------------------- def _char3(s: str) -> list[str]: if not s: return [] s = f" {s} " return [s[i : i + 3] for i in range(len(s) - 2)] def _word12(s: str) -> list[str]: t = s.split() return t + [f"{a} {b}" for a, b in zip(t, t[1:])] _HV: dict = {} def _vec_worker(args): texts, kind, n_features = args hv = _HV.get((kind, n_features)) if hv is None: hv = HashingVectorizer( analyzer=_char3 if kind == "char" else _word12, n_features=n_features, alternate_sign=False, norm=None, dtype=np.float32, ) _HV[(kind, n_features)] = hv return hv.transform(texts).tocsr() def vectorize(texts: list[str], kind: str, n_features: int, vpool, chunk: int) -> sp.csr_matrix: if not texts: return sp.csr_matrix((0, n_features), dtype=np.float32) jobs = ((texts[i : i + chunk], kind, n_features) for i in range(0, len(texts), chunk)) parts = list(vpool.map(_vec_worker, jobs)) if vpool is not None else [_vec_worker(j) for j in jobs] X = sp.vstack(parts, format="csr") if len(parts) > 1 else parts[0] del parts return X.astype(np.float32, copy=False) def _blocks(n: int, step: int = 100_000_000): for lo in range(0, n, step): yield lo, min(n, lo + step) def _l2_normalize_rows(X: sp.csr_matrix, block: int = 1_000_000) -> None: n = X.shape[0] for lo in range(0, n, block): hi = min(n, lo + block) s, e = int(X.indptr[lo]), int(X.indptr[hi]) d = X.data[s:e] cs = np.zeros(e - s + 1, dtype=np.float64) np.cumsum(d.astype(np.float64) ** 2, out=cs[1:]) ip = X.indptr[lo : hi + 1] - s nrm = np.sqrt(np.maximum(cs[ip[1:]] - cs[ip[:-1]], 0.0)) nrm[nrm == 0] = 1.0 d *= np.repeat((1.0 / nrm).astype(np.float32), np.diff(ip)) def tfidf_pair(XA: sp.csr_matrix, XB: sp.csr_matrix, max_df: float) -> dict: """In place: counts -> (1+log tf) * idf, drop df>max_df*n, l2-normalise rows, then drop features absent from either side (no effect on A.B^T). idf fit on rows of XA u XB.""" F = XA.shape[1] dfA = np.bincount(XA.indices, minlength=F) dfB = np.bincount(XB.indices, minlength=F) n = XA.shape[0] + XB.shape[0] df = dfA + dfB idf = (np.log((1.0 + n) / (1.0 + df)) + 1.0).astype(np.float32) pruned = (df > max_df * n) if max_df < 1.0 else np.zeros(F, dtype=bool) idf[pruned] = 0.0 keep = (dfA > 0) & (dfB > 0) & ~pruned st = { "n_features_seen": int((df > 0).sum()), "n_features_pruned_maxdf": int(pruned.sum()), "n_features_kept": int(keep.sum()), } for tag, X in (("A", XA), ("B", XB)): nnz0 = X.nnz for lo, hi in _blocks(X.nnz): d = X.data[lo:hi] np.log(d, out=d) d += 1.0 d *= idf[X.indices[lo:hi]] X.eliminate_zeros() _l2_normalize_rows(X) for lo, hi in _blocks(X.nnz): X.data[lo:hi][~keep[X.indices[lo:hi]]] = 0.0 X.eliminate_zeros() X.sort_indices() st[f"nnz_{tag}_raw"] = int(nnz0) st[f"nnz_{tag}"] = int(X.nnz) st[f"empty_rows_{tag}"] = float((np.diff(X.indptr) == 0).mean()) if X.shape[0] else 0.0 return st # -------------------------------------------------------------------------------------------- # top-K sparse retrieval # -------------------------------------------------------------------------------------------- _G: dict = {} # globals shared with forked workers (copy-on-write) def _fork_pool(workers: int) -> ProcessPoolExecutor: """Fork-based pool: workers inherit module globals (_G) copy-on-write. A worker that dies raises BrokenProcessPool instead of hanging. On macOS run with OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES (Linux needs nothing).""" return ProcessPoolExecutor(max_workers=workers, mp_context=mp.get_context("fork")) def _row_costs(Q: sp.csr_matrix, df_t: np.ndarray, block: int = 1_000_000) -> np.ndarray: """Multiply-adds of row i of Q @ T.T = sum over its features of the feature's df in T.""" n = Q.shape[0] out = np.zeros(n, dtype=np.int64) for lo in range(0, n, block): hi = min(n, lo + block) s, e = int(Q.indptr[lo]), int(Q.indptr[hi]) cs = np.zeros(e - s + 1, dtype=np.int64) np.cumsum(df_t[Q.indices[s:e]], out=cs[1:]) ip = Q.indptr[lo : hi + 1] - s out[lo:hi] = cs[ip[1:]] - cs[ip[:-1]] return out def _plan_chunks(cost: np.ndarray, budget: float, max_rows: int) -> list[tuple[int, int]]: n = len(cost) cum = np.cumsum(cost) chunks, lo = [], 0 while lo < n: base = cum[lo - 1] if lo else 0 hi = int(np.searchsorted(cum, base + budget, side="right")) hi = min(max(hi, lo + 1), lo + max_rows, n) chunks.append((lo, hi)) lo = hi return chunks def _csr_rowwise_topk(C: sp.csr_matrix, k: int, min_sim: float, row_offset: int): indptr, ind, dat = C.indptr, C.indices, C.data n = C.shape[0] lens = np.diff(indptr) rows_all = np.repeat(np.arange(n, dtype=np.int32), lens) small = lens <= k sel = small[rows_all] & (dat > min_sim) R, Cc, V = [rows_all[sel]], [ind[sel]], [dat[sel]] for i in np.flatnonzero(~small): s, e = indptr[i], indptr[i + 1] d = dat[s:e] p = np.argpartition(d, (e - s) - k)[(e - s) - k :] p = p[d[p] > min_sim] R.append(np.full(len(p), i, dtype=np.int32)) Cc.append(ind[s:e][p]) V.append(d[p]) return ( np.concatenate(R).astype(np.int32) + np.int32(row_offset), np.concatenate(Cc).astype(np.int32), np.concatenate(V).astype(np.float32), ) def _topk_scipy_worker(task): lo, hi = task C = (_G["Q"][lo:hi] @ _G["TT"]).tocsr() return _csr_rowwise_topk(C, _G["k"], _G["min_sim"], lo) def _topk_scipy(Q, TT, k, min_sim, workers, chunks): _G.update(Q=Q, TT=TT, k=k, min_sim=min_sim) try: if workers > 1 and len(chunks) > 1: with _fork_pool(workers) as p: out = list(p.map(_topk_scipy_worker, chunks)) else: out = [_topk_scipy_worker(c) for c in chunks] finally: _G.clear() return out def _topk_sdt(Q, TT, k, min_sim, workers, rows_per_call): sp_matmul_topn = _sdt.sp_matmul_topn out = [] n = Q.shape[0] for lo in range(0, n, rows_per_call): hi = min(n, lo + rows_per_call) C = sp_matmul_topn( Q[lo:hi], TT, top_n=k, threshold=min_sim, sort=False, n_threads=workers if workers > 1 else None ).tocsr() rows = np.repeat(np.arange(lo, hi, dtype=np.int32), np.diff(C.indptr)) out.append((rows, C.indices.astype(np.int32), C.data.astype(np.float32))) return out def topk_search(Q: sp.csr_matrix, T: sp.csr_matrix, k: int, args, label: str): """Top-k columns of Q @ T.T per row of Q (cosine; rows are l2-normalised).""" empty = (np.zeros(0, np.int32), np.zeros(0, np.int32), np.zeros(0, np.float32)) if k <= 0 or Q.shape[0] == 0 or T.shape[0] == 0: return empty, {} TT = T.T.tocsr() # (F x n_target) cost = _row_costs(Q, np.diff(TT.indptr).astype(np.int64)) total_ops = int(cost.sum()) t = time.time() if args.backend == "sdt": out = _topk_sdt(Q, TT, k, args.min_sim, args.workers, args.sdt_rows) n_chunks = math.ceil(Q.shape[0] / args.sdt_rows) else: chunks = _plan_chunks(cost, args.chunk_ops, args.chunk_max_rows) n_chunks = len(chunks) out = _topk_scipy(Q, TT, k, args.min_sim, args.workers, chunks) del TT dt = time.time() - t qi = np.concatenate([o[0] for o in out]) if out else empty[0] ti = np.concatenate([o[1] for o in out]) if out else empty[1] sim = np.concatenate([o[2] for o in out]) if out else empty[2] st = { "n_query": int(Q.shape[0]), "n_target": int(T.shape[0]), "k": int(k), "est_mult_adds": total_ops, "max_row_mult_adds": int(cost.max()) if len(cost) else 0, "n_chunks": int(n_chunks), "seconds": round(dt, 2), "mult_adds_per_s": round(total_ops / dt, 1) if dt > 0 else None, "n_pairs": int(len(qi)), } log( f" {label}: {Q.shape[0]:,} x {T.shape[0]:,} k={k} ops={total_ops:.3e} " f"chunks={n_chunks} -> {len(qi):,} pairs in {dt:.1f}s ({st['mult_adds_per_s'] or 0:.2e} ops/s)" ) return (qi, ti, sim), st # -------------------------------------------------------------------------------------------- # exact cosines for arbitrary pairs (fill-sims) # -------------------------------------------------------------------------------------------- def _fill_worker(task): lo, hi = task a, b = _G["a"][lo:hi], _G["b"][lo:hi] res = {} for s, (XA, XB) in _G["mats"].items(): res[s] = np.asarray(XA[a].multiply(XB[b]).sum(axis=1), dtype=np.float32).ravel() return lo, res def fill_sims(a: np.ndarray, b: np.ndarray, mats: dict, workers: int, chunk: int) -> dict: n = len(a) out = {s: np.zeros(n, dtype=np.float32) for s in mats} tasks = [(lo, min(n, lo + chunk)) for lo in range(0, n, chunk)] _G.update(a=a, b=b, mats=mats) try: if workers > 1 and len(tasks) > 1: with _fork_pool(workers) as p: for lo, res in p.map(_fill_worker, tasks): for s, v in res.items(): out[s][lo : lo + len(v)] = v else: for t in tasks: lo, res = _fill_worker(t) for s, v in res.items(): out[s][lo : lo + len(v)] = v finally: _G.clear() return out # -------------------------------------------------------------------------------------------- # per-country blocking # -------------------------------------------------------------------------------------------- def _group_rank(g: np.ndarray, sim: np.ndarray) -> np.ndarray: """0-based rank of each element within its group g, by descending sim.""" if len(g) == 0: return np.zeros(0, dtype=np.int16) order = np.lexsort((-sim, g)) gs = g[order] starts = np.r_[0, np.flatnonzero(gs[1:] != gs[:-1]) + 1] pos = np.arange(len(gs)) - np.repeat(starts, np.diff(np.r_[starts, len(gs)])) r = np.empty(len(g), dtype=np.int64) r[order] = pos return np.minimum(r, int(NO_RANK) - 1).astype(np.int16) def _k_grid(k: int) -> list[int]: return sorted({x for x in (1, 2, 3, 5, 10, 15, 20, 30, 50, 100) if x < k} | {k}) def _sweeps(a, q_idx, n_a, ranks, is_match, rev_only_rank, kmap, args) -> dict: """Pair counts / true-pair counts / per-S1 candidate counts under alternative K and reverse-cap settings, computed from the retrieved (uncapped) pairs.""" out: dict = {"recall_at_k": {}, "configs": {}} fwd = [s for s in STRATS if kmap[s] > 0] for s in fwd: r = ranks[s] out["recall_at_k"][s] = {int(k): int((is_match & (r < k)).sum()) for k in _k_grid(kmap[s])} if args.reverse_k > 0: r = ranks["rev"] out["recall_at_k"]["rev"] = {int(k): int((is_match & (r < k)).sum()) for k in range(1, args.reverse_k + 1)} from_rev = ranks["rev"] != NO_RANK def add(name, keep): out["configs"][name] = { "pairs": int(keep.sum()), "true": int((keep & is_match).sum()), "per_s1": np.bincount(a[keep], minlength=n_a)[q_idx], } for f in K_FRACS: keep = from_rev.copy() for s in fwd: keep |= ranks[s] < max(1, math.ceil(f * kmap[s])) add(f"k_x{f}", keep) keep_norev = np.zeros(len(a), dtype=bool) for s in fwd: keep_norev |= ranks[s] < max(1, math.ceil(f * kmap[s])) add(f"k_x{f}_norev", keep_norev) fwd_any = np.zeros(len(a), dtype=bool) for s in fwd: fwd_any |= ranks[s] != NO_RANK for c in REV_CAPS: add(f"revcap_{c}", fwd_any | (rev_only_rank < c)) return out def block_country(country, s1c, poolc, q_idx, args, vpool, gt_pairs_c): n_a, n_b = s1c.height, poolc.height sampled = len(q_idx) < n_a is_query = np.zeros(n_a, dtype=bool) is_query[q_idx] = True kmap = {"name": args.k_name, "nameaddr": args.k_nameaddr, "addr": args.k_addr, "word": args.k_word} results: dict[str, tuple] = {} mats: dict[str, tuple] = {} cstats: dict = {"n_s1_full": n_a, "n_s1_query": int(len(q_idx)), "n_pool": n_b, "strategies": {}} for strat in STRATS: k = kmap[strat] need_rev = strat == "nameaddr" and args.reverse_k > 0 if k <= 0 and not need_rev: continue kind = "word" if strat == "word" else "char" nf = 1 << (args.hash_bits_word if kind == "word" else args.hash_bits_char) tag = f"{country}/{strat}" sst: dict = {} with stage(f"{tag}/vectorize"): XA = vectorize(strategy_texts(s1c, strat), kind, nf, vpool, args.vec_chunk) XB = vectorize(strategy_texts(poolc, strat), kind, nf, vpool, args.vec_chunk) with stage(f"{tag}/tfidf"): sst["tfidf"] = tfidf_pair(XA, XB, args.max_df) log(f" {tag} tfidf: {sst['tfidf']}") if k > 0: with stage(f"{tag}/topk_forward"): Q = XA[q_idx] if sampled else XA (qi, ti, sim), sst["forward"] = topk_search(Q, XB, k, args, f"{tag} fwd") del Q a = q_idx[qi].astype(np.int32) if sampled else qi results[strat] = (a, ti, sim, _group_rank(qi, sim)) if need_rev: with stage(f"{tag}/topk_reverse"): if sampled and args.reverse_scope == "sample": T = XA[q_idx] (qi, ti, sim), sst["reverse"] = topk_search(XB, T, args.reverse_k, args, f"{tag} rev") del T rrank = _group_rank(qi, sim) a, b = q_idx[ti].astype(np.int32), qi else: (qi, ti, sim), sst["reverse"] = topk_search(XB, XA, args.reverse_k, args, f"{tag} rev") rrank = _group_rank(qi, sim) # rank among the pool record's full S1 list keep = is_query[ti] a, b, sim, rrank = ti[keep], qi[keep], sim[keep], rrank[keep] results["rev"] = (a, b, sim, rrank) if args.fill_sims and k > 0: mats[strat] = (XA, XB) else: del XA, XB gc.collect() cstats["strategies"][strat] = sst with stage(f"{country}/union"): frames = [] for s_, (a, b, sim, rank) in results.items(): key = a.astype(np.int64) * n_b + b.astype(np.int64) frames.append(pl.DataFrame({"key": key, f"sim_{s_}": sim, f"rank_{s_}": rank})) present = list(results) if frames: U = ( pl.concat(frames, how="diagonal") .group_by("key") .agg([pl.col(f"sim_{x}").max() for x in present] + [pl.col(f"rank_{x}").min() for x in present]) .sort("key") ) else: U = pl.DataFrame({"key": np.zeros(0, np.int64)}) del frames, results for x in list(STRATS) + ["rev"]: if f"sim_{x}" not in U.columns: U = U.with_columns(pl.lit(None, dtype=pl.Float32).alias(f"sim_{x}"), pl.lit(None, dtype=pl.Int16).alias(f"rank_{x}")) U = U.with_columns(sim_na_ret=pl.coalesce("sim_nameaddr", "sim_rev")) key = U.get_column("key").to_numpy() a = (key // n_b).astype(np.int32) ranks = {x: U.get_column(f"rank_{x}").fill_null(NO_RANK).to_numpy() for x in list(STRATS) + ["rev"]} fwd_any = np.zeros(len(key), dtype=bool) for x in STRATS: fwd_any |= ranks[x] != NO_RANK rev_only = (ranks["rev"] != NO_RANK) & ~fwd_any rev_only_rank = np.full(len(key), NO_RANK, dtype=np.int16) rev_only_rank[rev_only] = _group_rank(a[rev_only], U.get_column("sim_na_ret").to_numpy()[rev_only]) is_match = None if gt_pairs_c is not None: ga = gt_pairs_c.join(s1c.select("entity_id").with_row_index("a"), left_on="s1_id", right_on="entity_id") ga = ga.join(poolc.select("entity_id").with_row_index("b"), left_on="cand_id", right_on="entity_id") gkey = np.sort(ga.get_column("a").to_numpy().astype(np.int64) * n_b + ga.get_column("b").to_numpy().astype(np.int64)) pos = np.searchsorted(gkey, key) is_match = (pos < len(gkey)) & (gkey[np.minimum(pos, max(len(gkey) - 1, 0))] == key) if len(gkey) else np.zeros(len(key), bool) cstats["sweeps"] = _sweeps(a, q_idx, n_a, ranks, is_match, rev_only_rank, kmap, args) cstats["n_pairs_before_cap"] = int(len(key)) cstats["n_reverse_only_pairs"] = int(rev_only.sum()) if args.reverse_cap > 0: keep = rev_only_rank < args.reverse_cap keep |= ~rev_only U = U.filter(pl.Series(keep)) key, a = key[keep], a[keep] is_match = is_match[keep] if is_match is not None else None b = (key % n_b).astype(np.int32) del ranks, fwd_any, rev_only, rev_only_rank log(f" {country}: {len(a):,} unique candidate pairs") if args.fill_sims and mats: with stage(f"{country}/fill_sims"): filled = fill_sims(a, b, mats, args.workers, args.fill_chunk) U = U.with_columns([pl.Series(f"sim_{x}", v) for x, v in filled.items()]) del filled else: U = U.with_columns(sim_nameaddr=pl.col("sim_na_ret")) del mats gc.collect() with stage(f"{country}/assemble"): cols = { "s1_id": _gather(s1c.get_column("entity_id"), a), "cand_id": _gather(poolc.get_column("entity_id"), b), "country": pl.repeat(country, len(a), eager=True, dtype=pl.Utf8).alias("country"), "src": _gather(poolc.get_column("src"), b), } for x in STRATS: cols[f"sim_{x}"] = U.get_column(f"sim_{x}").cast(pl.Float32) for x in STRATS: cols[f"f_{x}"] = U.get_column(f"rank_{x}").is_not_null().alias(f"f_{x}") cols["from_reverse"] = U.get_column("rank_rev").is_not_null().alias("from_reverse") for x in list(STRATS) + ["rev"]: cols[f"rank_{x}"] = U.get_column(f"rank_{x}").cast(pl.Int16) if is_match is not None: cols["is_match"] = pl.Series("is_match", is_match) out = pl.DataFrame(cols) del U per_s1 = np.bincount(a, minlength=n_a)[q_idx] cstats["n_pairs"] = int(out.height) cstats["pairs_per_strategy"] = {c: int(out.get_column(c).sum()) for c in FLAG_COLS} return out, per_s1, cstats # -------------------------------------------------------------------------------------------- # evaluation # -------------------------------------------------------------------------------------------- def _dist(x: np.ndarray) -> dict: if len(x) == 0: return {} return { "mean": round(float(x.mean()), 3), "p50": float(np.percentile(x, 50)), "p90": float(np.percentile(x, 90)), "p99": float(np.percentile(x, 99)), "max": int(x.max()), "share_zero": round(float((x == 0).mean()), 5), } def evaluate(gt_pairs: pl.DataFrame, hits: pl.DataFrame, query_ids: pl.DataFrame) -> dict: """gt_pairs: s1_id,cand_id,country,src for queried S1 ids. hits: candidate rows with is_match (s1_id,cand_id,country,src,flags). query_ids: s1_id,country of all queried S1.""" hits = hits.with_columns(union=pl.lit(True)) names = FLAG_COLS + ["union"] m: dict = {} def recall(group: list[str]): if group: tot = gt_pairs.group_by(group).agg(pl.len().alias("n_gt")) hit = hits.group_by(group).agg([pl.col(f).sum() for f in names]) j = tot.join(hit, on=group, how="left").fill_null(0).sort(group) return { "|".join(str(r[g]) for g in group): { "n_gt_pairs": int(r["n_gt"]), **{f: round(r[f] / r["n_gt"], 5) if r["n_gt"] else None for f in names}, } for r in j.iter_rows(named=True) } n = gt_pairs.height return {"n_gt_pairs": n, **{f: round(hits.get_column(f).sum() / n, 5) if n else None for f in names}} m["pair_recall"] = { "overall": recall([]), "by_country": recall(["country"]), "by_source": recall(["src"]), "by_country_source": recall(["country", "src"]), } n = gt_pairs.height strat_flags = FLAG_COLS only, without = {}, {} for f in strat_flags: others = [g for g in strat_flags if g != f] any_other = pl.any_horizontal([pl.col(g) for g in others]) only[f] = round(hits.filter(pl.col(f) & ~any_other).height / n, 5) if n else None without[f] = round(hits.filter(any_other).height / n, 5) if n else None m["pair_recall_only_this_strategy"] = only m["pair_recall_union_without"] = without ns = gt_pairs.select("s1_id", "country").unique() ent = hits.group_by("s1_id").agg([pl.col(f).any() for f in names]) e = ns.join(ent, on="s1_id", how="left").fill_null(False) n_ns = e.height m["entity_any_found"] = { "n_nonsingleton_entities": n_ns, "overall": {f: round(e.get_column(f).sum() / n_ns, 5) if n_ns else None for f in names}, "by_country": { str(r["country"]): {f: round(r[f] / r["n"], 5) for f in names} for r in e.group_by("country").agg([pl.len().alias("n")] + [pl.col(f).sum() for f in names]).sort("country").iter_rows(named=True) }, } m["n_query_s1"] = query_ids.height m["n_query_singletons"] = query_ids.height - n_ns # all-true-found per entity (the matcher's recall ceiling at entity level) per = gt_pairs.group_by("s1_id").agg(pl.len().alias("n_true")).join( hits.group_by("s1_id").agg(pl.len().alias("n_found")), on="s1_id", how="left" ).fill_null(0) m["entity_all_found"] = round(float((per.get_column("n_found") == per.get_column("n_true")).mean()), 5) if per.height else None return m def print_report(metrics: dict) -> None: ev = metrics.get("eval") print("\n================ BLOCKING REPORT ================") print(f"countries: {', '.join(metrics['countries'])}") print(f"queried S1: {metrics['n_query_s1']:,} pool (all countries): {metrics['n_pool_total']:,}") print(f"candidate pairs: {metrics['n_pairs']:,} reduction ratio: {metrics['reduction_ratio']:.6f}") print(f"candidates per S1: {metrics['cands_per_s1']}") print("pairs per strategy:", {k: f"{v:,}" for k, v in metrics["pairs_per_strategy"].items()}) if not ev: return names = FLAG_COLS + ["union"] pr = ev["pair_recall"] cols = [("overall", pr["overall"])] cols += [(f"src={k}", v) for k, v in pr["by_source"].items()] cols += [(f"{k}", v) for k, v in pr["by_country"].items()] hdr = f"{'strategy':<14}" + "".join(f"{c[0][:13]:>14}" for c in cols) + f"{'ent_any':>10}{'only_this':>11}{'union_wo':>10}" print("\nPAIR RECALL (share of ground-truth pairs retrieved)") print(f"{'n_gt_pairs':<14}" + "".join(f"{c[1]['n_gt_pairs']:>14,}" for c in cols)) print(hdr) for f in names: row = f"{f:<14}" + "".join(f"{(c[1][f] or 0):>14.4f}" for c in cols) row += f"{ev['entity_any_found']['overall'][f] or 0:>10.4f}" if f != "union": row += f"{ev['pair_recall_only_this_strategy'][f] or 0:>11.4f}{ev['pair_recall_union_without'][f] or 0:>10.4f}" print(row) print(f"entities with ALL true matches retrieved: {ev['entity_all_found']}") print("by country x source (union):", {k: v["union"] for k, v in pr["by_country_source"].items()}) print(f"non-singleton queried entities: {ev['entity_any_found']['n_nonsingleton_entities']:,} singletons: {ev['n_query_singletons']:,}") if ev.get("recall_at_k"): print("\nPAIR RECALL @ k (per strategy, share of all ground-truth pairs)") for st_, d in ev["recall_at_k"].items(): print(f" {st_:<9}" + " ".join(f"@{k}:{v:.4f}" for k, v in d.items())) if ev.get("sweeps"): print("\nSWEEPS (computed from the uncapped retrieval; k_xF scales every forward K by F)") print(f" {'config':<18}{'union_rec':>10}{'pairs':>14}{'mean/S1':>9}{'p50':>6}{'p90':>6}{'p99':>6}{'max':>7}") for name, d in ev["sweeps"].items(): c = d["cands_per_s1"] print(f" {name:<18}{d['union_pair_recall'] or 0:>10.4f}{d['pairs']:>14,}{c.get('mean', 0):>9.1f}" f"{c.get('p50', 0):>6.0f}{c.get('p90', 0):>6.0f}{c.get('p99', 0):>6.0f}{c.get('max', 0):>7}") # -------------------------------------------------------------------------------------------- # main # -------------------------------------------------------------------------------------------- def parse_args(argv=None): p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.ArgumentDefaultsHelpFormatter) p.add_argument("--s1", default=None, help="Source-1 TSV (not needed with --norm-dir)") p.add_argument("--s2", default=None) p.add_argument("--s3", default=None) p.add_argument( "--norm-dir", default=None, help="read pre-normalised DIR/{s1,s2,s3}.parquet (or t1,t2,t3 with --split test) from " "scripts/preprocess_normalize.py instead of the TSVs + light normaliser", ) p.add_argument("--split", choices=["train", "test"], default="train", help="which tables to read from --norm-dir") p.add_argument("--gt", default=None, help="train_ground_truth.tsv; enables recall metrics and is_match column") p.add_argument("--out", required=True, help="output parquet; metrics go to .metrics.json") p.add_argument("--max-s1", type=int, default=None, help="random S1 subsample (pool stays FULL)") p.add_argument("--seed", type=int, default=13) p.add_argument("--k-name", type=int, default=20) p.add_argument("--k-nameaddr", type=int, default=20) p.add_argument("--k-addr", type=int, default=15) p.add_argument("--k-word", type=int, default=10) p.add_argument("--reverse-k", type=int, default=3) p.add_argument( "--reverse-scope", choices=["full", "sample"], default="full", help="with --max-s1: reverse search against the full country S1 (exact, costs a full reverse pass) " "or only the sample (fast, overstates reverse recall)", ) p.add_argument( "--reverse-cap", type=int, default=0, help="keep at most this many reverse-only pairs per S1 (highest nameaddr cosine); 0 = keep all. " "The metrics JSON has a sweep over caps to choose it", ) p.add_argument("--workers", type=int, default=min(30, os.cpu_count() or 1)) p.add_argument("--country-filter", default=None, help="comma-separated countries to process") p.add_argument("--normalizer", default=None, help="pkg.module:function hook (see module docstring)") p.add_argument("--backend", choices=["auto", "sdt", "scipy"], default="auto") p.add_argument("--max-df", type=float, default=0.02, help="drop features with df > max_df * (n_s1 + n_pool); 1 = off") p.add_argument("--min-sim", type=float, default=0.0, help="keep cosines strictly above this") p.add_argument("--hash-bits-char", type=int, default=22) p.add_argument("--hash-bits-word", type=int, default=24) p.add_argument("--vec-chunk", type=int, default=20000) p.add_argument("--sdt-rows", type=int, default=200000, help="query rows per sparse_dot_topn call") p.add_argument("--chunk-ops", type=float, default=5e7, help="scipy backend: multiply-adds per chunk") p.add_argument("--chunk-max-rows", type=int, default=20000, help="scipy backend: max query rows per chunk") p.add_argument("--fill-sims", action=argparse.BooleanOptionalAction, default=True) p.add_argument("--fill-chunk", type=int, default=200000) a = p.parse_args(argv) if not a.norm_dir and not (a.s1 and a.s2 and a.s3): p.error("give --s1 --s2 --s3, or --norm-dir") return a def main(argv=None) -> dict: args = parse_args(argv) if args.backend == "auto": omp = _sdt is not None and getattr(_sdt, "_has_openmp_support", True) args.backend = "sdt" if _sdt is not None and (omp or args.workers <= 1) else "scipy" if args.backend == "sdt" and _sdt is None: raise SystemExit("--backend sdt requested but sparse_dot_topn is not importable (pip install sparse-dot-topn)") args.workers = max(1, args.workers) log(f"config: {vars(args)}") # fork the vectoriser pool while the process is still small (fork happens on first submit) vpool = _fork_pool(args.workers) if args.workers > 1 else None if vpool is not None: vpool.submit(int).result() out_dir = os.path.dirname(os.path.abspath(args.out)) os.makedirs(out_dir, exist_ok=True) metrics_path = os.path.splitext(args.out)[0] + ".metrics.json" norm = load_normalizer(args.normalizer) if args.norm_dir: if args.normalizer or args.s1: log(" --norm-dir given: --s1/--s2/--s3 and --normalizer are ignored") paths = [os.path.join(args.norm_dir, f"{t}.parquet") for t in NORM_TABLES[args.split]] else: paths = [args.s1, args.s2, args.s3] with stage("load+normalise"): S = {} for tag, path in zip(("S1", "S2", "S3"), paths): if args.norm_dir: S[tag] = read_norm_parquet(path, tag) else: S[tag] = apply_normalizer(norm, read_source(path), tag) if args.country_filter: keep = [c.strip() for c in args.country_filter.split(",")] S[tag] = S[tag].filter(pl.col("country").is_in(keep)) log(f" {tag}: {S[tag].height:,} rows from {path}") s1 = S.pop("S1") pool = pl.concat([S.pop("S2"), S.pop("S3")]) rng = np.random.default_rng(args.seed) is_q = np.ones(s1.height, dtype=bool) if args.max_s1 and args.max_s1 < s1.height: is_q[:] = False is_q[rng.choice(s1.height, args.max_s1, replace=False)] = True s1 = s1.with_columns(pl.Series("is_query", is_q)) query_ids = s1.filter(pl.col("is_query")).select(pl.col("entity_id").alias("s1_id"), "country") log(f"queried S1: {query_ids.height:,} of {s1.height:,}; pool: {pool.height:,}") gt_pairs = None if args.gt: with stage("load_gt"): gt = read_tsv(args.gt) gt = gt.rename({gt.columns[0]: "s1_id", gt.columns[1]: "matched"}).select("s1_id", "matched") gt_pairs = ( gt.join(query_ids, on="s1_id", how="inner") .with_columns(pl.col("matched").str.split(",")) .explode("matched") # empty lists -> null row, removed by the filter below .with_columns(pl.col("matched").str.strip_chars()) .filter(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"]) ) n_missing = query_ids.height - gt.join(query_ids, on="s1_id", how="inner").height log(f" gt pairs for queried S1: {gt_pairs.height:,}; queried S1 absent from gt file: {n_missing:,}") del gt countries = sorted(s1.get_column("country").unique().to_list()) metrics: dict = {"config": vars(args), "countries": countries, "per_country": {}} writer = None per_s1_all, hits_all = [], [] sweep_acc: dict = {"recall_at_k": {}, "configs": {}} total_pairs, all_pairs_space = 0, 0 pps = {c: 0 for c in FLAG_COLS} try: import pyarrow.parquet as pq for country in countries: s1c = s1.filter(pl.col("country") == country) poolc = pool.filter(pl.col("country") == country) q_idx = np.flatnonzero(s1c.get_column("is_query").to_numpy()).astype(np.int64) if len(q_idx) == 0: continue all_pairs_space += len(q_idx) * poolc.height if poolc.height == 0: per_s1_all.append(np.zeros(len(q_idx), dtype=np.int64)) for acc in sweep_acc["configs"].values(): acc["per_s1"].append(np.zeros(len(q_idx), dtype=np.int64)) metrics["per_country"][country] = {"n_s1_query": int(len(q_idx)), "n_pool": 0, "n_pairs": 0} continue log(f"=== {country}: S1 {s1c.height:,} (queried {len(q_idx):,}) x pool {poolc.height:,} ===") gtc = gt_pairs.filter(pl.col("country") == country) if gt_pairs is not None else None out, per_s1, cst = block_country(country, s1c, poolc, q_idx, args, vpool, gtc) sw = cst.pop("sweeps", None) if sw: for st_, d in sw["recall_at_k"].items(): acc = sweep_acc["recall_at_k"].setdefault(st_, {}) for k, v in d.items(): acc[k] = acc.get(k, 0) + v for name, d in sw["configs"].items(): acc = sweep_acc["configs"].setdefault(name, {"pairs": 0, "true": 0, "per_s1": []}) acc["pairs"] += d["pairs"] acc["true"] += d["true"] acc["per_s1"].append(d["per_s1"]) if gtc is not None: cst["gt_pairs_not_in_country_pool"] = int(gtc.filter(~pl.col("cand_id").is_in(poolc.get_column("entity_id"))).height) hits_all.append(out.filter(pl.col("is_match")).select(["s1_id", "cand_id", "country", "src"] + FLAG_COLS)) with stage(f"{country}/write"): tbl = out.to_arrow() if writer is None: writer = pq.ParquetWriter(args.out, tbl.schema, compression="zstd") writer.write_table(tbl.cast(writer.schema)) del tbl per_s1_all.append(per_s1) total_pairs += out.height for c in FLAG_COLS: pps[c] += cst["pairs_per_strategy"][c] metrics["per_country"][country] = cst del out, s1c, poolc gc.collect() if writer is None: # nothing produced: write an empty file with the schema empty = pl.DataFrame( {"s1_id": [], "cand_id": [], "country": [], "src": []}, schema={c: pl.Utf8 for c in ["s1_id", "cand_id", "country", "src"]} ).with_columns([pl.lit(None, dtype=pl.Float32).alias(c) for c in SIM_COLS] + [pl.lit(None, dtype=pl.Boolean).alias(c) for c in FLAG_COLS]) empty.write_parquet(args.out) finally: if writer is not None: writer.close() if vpool is not None: vpool.shutdown(wait=False, cancel_futures=True) per_s1 = np.concatenate(per_s1_all) if per_s1_all else np.zeros(0, dtype=np.int64) metrics.update( n_query_s1=int(query_ids.height), n_pool_total=int(pool.height), n_pairs=int(total_pairs), all_within_country_pairs=int(all_pairs_space), reduction_ratio=(1.0 - total_pairs / all_pairs_space) if all_pairs_space else None, cands_per_s1=_dist(per_s1), pairs_per_strategy=pps, ) if gt_pairs is not None: with stage("evaluate"): hits = pl.concat(hits_all) if hits_all else pl.DataFrame(schema={"s1_id": pl.Utf8, "cand_id": pl.Utf8, "country": pl.Utf8, "src": pl.Utf8, **{c: pl.Boolean for c in FLAG_COLS}}) metrics["eval"] = evaluate(gt_pairs, hits, query_ids) n_gt = gt_pairs.height metrics["eval"]["recall_at_k"] = { st_: {str(k): round(v / n_gt, 5) for k, v in sorted(d.items())} for st_, d in sweep_acc["recall_at_k"].items() } if n_gt else {} metrics["eval"]["sweeps"] = { name: { "union_pair_recall": round(d["true"] / n_gt, 5) if n_gt else None, "pairs": d["pairs"], "cands_per_s1": _dist(np.concatenate(d["per_s1"])) if d["per_s1"] else {}, } for name, d in sweep_acc["configs"].items() } own, kids = _peak_gb() metrics["timings_s"] = {k: round(v, 2) for k, v in TIMINGS.items()} metrics["total_seconds"] = round(time.time() - _T0, 1) metrics["peak_rss_gb"] = {"main": round(own, 2), "largest_child": round(kids, 2)} with open(metrics_path, "w") as f: json.dump(metrics, f, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o)) print_report(metrics) log(f"wrote {args.out} and {metrics_path}; peak rss main={own:.2f}GB child={kids:.2f}GB") return metrics if __name__ == "__main__": main()