"""Train the pair matcher: features -> LightGBM -> isotonic calibration -> expected-F0.5 decode. python -m src.train_matcher --cands cands_train.parquet --norm-dir ROOT/norm \ --pairs ROOT/parquet/pairs.parquet --gt ROOT/parquet/gt.parquet --out-dir ROOT/models/m1 \ [--folds-file ROOT/artifacts/folds.parquet] [--max-s1 300000] [--holdout-country India] \ [--pair-audit ROOT/artifacts/pair_audit.parquet] [--neg-ratio 0] [--workers 16] Evaluation protocol (docs/cv_protocol.md) * Folds: GroupKFold by S1 id with a fixed seed (--fold-seed). The assignment covers every S1 id of the gt file, is written to /folds.parquet (s1_id, fold) and, with --folds-file, is read from / created once at that path and reused by every experiment. * Every model probability that feeds calibration or a decoder setting is out-of-fold: fold model k is trained on the other folds (early stopping on a --inner-val-frac slice of THEIR S1 ids) and predicts fold k. Isotonic calibration and the threshold-decoder cut-off are fit on those OOF probabilities only. * Headline = macro F0.5 (src/metric.py) over ALL evaluated S1 ids of the gt file, singletons and ids without any candidate included (empty prediction), after decode + one-parent rule. * Breakdown per country, per source, per true-match-count bucket (0..5+), per noise category when --pair-audit is given; decoder mean expected F0.5 printed next to the realised score. Variants (metrics.json -> "results"; every number is stored under the variant that produced it) kfold_oof default mode: the whole evaluated S1 set, OOF probabilities. loco: --holdout-country X: the k-fold pipeline runs on the OTHER countries only (OOF -> calibrator), country X is scored with the average of the fold models exactly like France in src/predict.py (X is an unseen category). Nothing is tuned on X. Also reported: loco:/train_oof (OOF on the training countries) and loco:/oracle_calibration (diagnostic only: calibrator fit on X labels). /... diagnostics of the same probabilities: no_one_parent, raw_probs (no calibration), threshold_oof (plain threshold chosen on OOF), sweep. Evaluated S1 set (--eval-universe): 'all' = every gt S1 id of the candidate countries in the normalised S1 table; 'cands' = only S1 ids present in the candidate table (blocking ran with --max-s1); 'auto' = 'all' when the candidates cover >= 50% of it. --max-s1 N samples N of them AFTER the competition features were computed on the whole candidate table. Outputs in --out-dir: model_fold{k}.txt (predict.py averages them) [or model_full.txt with --refit], calibrator.pkl, folds.parquet, features.json, metrics.json, importance.csv, oof.parquet (s1_id, cand_id, label, raw, cal, fold; fold -1 = held-out country). """ from __future__ import annotations import argparse import json import os import pickle import sys import time import numpy as np import pandas as pd import polars as pl import pyarrow as pa if __package__ in (None, ""): # allow `python src/train_matcher.py` sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from src.decode import decode_arrays # noqa: E402 from src.features import (BLOCK_FLAGS, BLOCK_RANKS, BLOCK_SIMS, build_features, build_idf_tables, # noqa: E402 feature_columns, load_norm, log) from src.metric import breakdown, entity_scores # noqa: E402 from src.normalize import country_key # noqa: E402 CAND_COLUMNS = ["s1_id", "cand_id", "country", "src"] + BLOCK_SIMS + ["from_reverse"] + BLOCK_FLAGS + BLOCK_RANKS THRESHOLDS = [round(x, 2) for x in np.arange(0.30, 0.901, 0.05)] NOISE_FLAGS = ["indic_name", "domain_form", "former_form", "addr_empty"] # ---------------------------------------------------------------------------------------------- # Shared helpers (also used by src/predict.py) # ---------------------------------------------------------------------------------------------- def read_cands(path: str) -> pl.DataFrame: import pyarrow.parquet as pq names = set(pq.ParquetFile(path).schema_arrow.names) missing = {"s1_id", "cand_id"} - names if missing: raise ValueError(f"{path}: candidate parquet lacks {sorted(missing)}") return pl.read_parquet(path, columns=[c for c in CAND_COLUMNS if c in names]) def load_tables(norm_dir: str, s1_table: str, pool_tables: str): s1 = load_norm(os.path.join(norm_dir, f"{s1_table}.parquet")) pool = load_norm([os.path.join(norm_dir, f"{t.strip()}.parquet") for t in pool_tables.split(",") if t.strip()]) return s1, pool def one_parent(selected: np.ndarray, pool_rows: np.ndarray, probs: np.ndarray) -> np.ndarray: """Keep, for every pool record selected by several S1 records, only the highest-probability claim (ties: first row). Returns a new mask.""" idx = np.flatnonzero(selected) out = np.zeros(len(selected), dtype=bool) if len(idx) == 0: return out order = np.lexsort((-probs[idx], pool_rows[idx])) sidx = idx[order] pr = pool_rows[sidx] first = np.ones(len(sidx), dtype=bool) first[1:] = pr[1:] != pr[:-1] out[sidx[first]] = True return out def _as_arrow(series): return series if isinstance(series, (pa.Array, pa.ChunkedArray)) else pa.array(series) def selected_pred(mask: np.ndarray, probs: np.ndarray, s1_rows: np.ndarray, s1_ids, cand_ids) -> dict: """{s1_id: [cand ids, prob desc]} for the rows in ``mask`` (row-aligned arrays).""" rows = np.flatnonzero(mask) if len(rows) == 0: return {} rows = rows[np.lexsort((-probs[rows], s1_rows[rows]))] take = pa.array(rows, pa.int64()) s1s = _as_arrow(s1_ids).take(take).to_pylist() cs = _as_arrow(cand_ids).take(take).to_pylist() out: dict = {} for s, c in zip(s1s, cs): lst = out.get(s) if lst is None: out[s] = [c] else: lst.append(c) return out def predict_raw(boosters, feats: pd.DataFrame, feat_cols: list, chunk_rows: int = 2_000_000, num_threads: int = 0) -> np.ndarray: """Average predicted probability of the boosters, in row chunks (bounded conversion memory).""" n = len(feats) out = np.zeros(n, dtype=np.float64) for lo in range(0, n, chunk_rows): X = feats.iloc[lo:lo + chunk_rows][feat_cols] acc = np.zeros(len(X)) for b in boosters: acc += b.predict(X, num_threads=num_threads) out[lo:lo + len(X)] = acc / len(boosters) return out def add_missing_features(feats: pd.DataFrame, feat_cols: list) -> list: missing = [f for f in feat_cols if f not in feats.columns] for f in missing: feats[f] = np.float32(np.nan) return missing def read_gt(path: str) -> pl.DataFrame: """gt parquet (source1_entity_id, matched_entity_ids as comma string or list) -> s1_id, matched(list).""" g = pl.read_parquet(path) g = g.rename({g.columns[0]: "s1_id", g.columns[1]: "matched"}).select("s1_id", "matched") if g.schema["matched"] == pl.Utf8: g = g.with_columns(pl.col("matched").fill_null("").str.split(",")) return g.with_columns(pl.col("s1_id").cast(pl.Utf8).str.strip_chars(), pl.col("matched").list.eval(pl.element().cast(pl.Utf8).str.strip_chars()) .list.eval(pl.element().filter(pl.element().str.len_chars() > 0))) # ---------------------------------------------------------------------------------------------- # Folds # ---------------------------------------------------------------------------------------------- def _assign_folds(ids: list, k: int, seed: int) -> pl.DataFrame: ids = sorted(set(ids)) fold = np.random.default_rng(seed).permutation(len(ids)) % k return pl.DataFrame({"s1_id": ids, "fold": fold.astype(np.int8)}) def load_or_make_folds(a, all_ids: list) -> pl.DataFrame: """Fixed S1-level fold assignment: read --folds-file when it exists, otherwise create it over all gt S1 ids (and write it there once). Always copied to /folds.parquet.""" if a.folds_file and os.path.exists(a.folds_file): f = pl.read_parquet(a.folds_file).select(pl.col("s1_id").cast(pl.Utf8), pl.col("fold").cast(pl.Int8)) k = int(f.get_column("fold").max()) + 1 if k != a.folds: print(f"WARNING: --folds {a.folds} ignored, {a.folds_file} has {k} folds", file=sys.stderr) a.folds = k missing = sorted(set(all_ids) - set(f.get_column("s1_id").to_list())) if missing: print(f"WARNING: {len(missing):,} gt S1 ids missing from {a.folds_file}; assigned with seed " f"{a.fold_seed} (not written back)", file=sys.stderr) f = pl.concat([f, _assign_folds(missing, k, a.fold_seed)]) log(f"folds: reused {a.folds_file} ({k} folds)") else: f = _assign_folds(all_ids, a.folds, a.fold_seed) if a.folds_file: os.makedirs(os.path.dirname(os.path.abspath(a.folds_file)), exist_ok=True) f.write_parquet(a.folds_file) log(f"folds: created {a.folds_file} ({a.folds} folds, seed {a.fold_seed}, {f.height:,} S1 ids)") f.write_parquet(os.path.join(a.out_dir, "folds.parquet")) return f # ---------------------------------------------------------------------------------------------- # Training helpers # ---------------------------------------------------------------------------------------------- def _params(a) -> dict: return dict(objective="binary", learning_rate=a.lr, num_leaves=a.leaves, min_data_in_leaf=a.min_data_in_leaf, feature_fraction=a.feature_fraction, bagging_fraction=0.8, bagging_freq=1, lambda_l2=1.0, max_bin=255, num_threads=a.workers, verbose=-1, seed=a.seed, metric="binary_logloss", max_cat_to_onehot=8, cat_smooth=10.0) def _sample_negatives(rows: np.ndarray, y: np.ndarray, s1_rank: np.ndarray, neg_ratio: float, hard_rank: int, rng) -> tuple[np.ndarray, np.ndarray]: """All positives + negatives ranked <= hard_rank within their S1 (by base score) + a Bernoulli sample of the rest weighted 1/q, so about neg_ratio negatives per positive are kept.""" w = np.ones(len(rows), dtype=np.float32) if neg_ratio <= 0: return rows, w yy = y[rows] hard = (yy == 0) & (s1_rank[rows] <= hard_rank) easy = (yy == 0) & ~hard n_pos, n_hard, n_easy = int((yy == 1).sum()), int(hard.sum()), int(easy.sum()) budget = neg_ratio * n_pos - n_hard q = 1.0 if n_easy == 0 else float(np.clip(budget / n_easy, 0.01, 1.0)) keep = ~easy | (rng.random(len(rows)) < q) w[easy] = 1.0 / q log(f" negatives: {n_pos:,} pos, {n_hard:,} hard neg kept, easy neg sampled at q={q:.3f} " f"-> {int(keep.sum()):,} training rows") return rows[keep], w[keep] def _fit(X: pd.DataFrame, y: np.ndarray, tr_rows, w_tr, va_rows, a, cat_cols): import lightgbm as lgb Xtr = X.iloc[tr_rows] # categories absent from the training rows (the held-out country) become NaN at predict time, # exactly like an unseen test country for c in cat_cols: Xtr = Xtr.assign(**{c: Xtr[c].cat.remove_unused_categories()}) dtr = lgb.Dataset(Xtr, label=y[tr_rows], weight=w_tr, categorical_feature=cat_cols or "auto", free_raw_data=True) dva = lgb.Dataset(X.iloc[va_rows], label=y[va_rows], reference=dtr, categorical_feature=cat_cols or "auto") t = time.time() cbs = [lgb.early_stopping(a.early_stop, verbose=False)] if a.log_period > 0: cbs.append(lgb.log_evaluation(a.log_period)) b = lgb.train(_params(a), dtr, num_boost_round=a.rounds, valid_sets=[dva], valid_names=["val"], callbacks=cbs) log(f" trained on {len(tr_rows):,} rows: best_iter={b.best_iteration}, " f"val logloss={b.best_score['val']['binary_logloss']:.5f} ({time.time() - t:.0f}s)") return b def _pair_metrics(y: np.ndarray, p: np.ndarray) -> dict: from sklearn.metrics import log_loss, roc_auc_score out = {"n": int(len(y)), "pos": int(y.sum())} if 0 < y.sum() < len(y): out.update(auc=float(roc_auc_score(y, p)), logloss=float(log_loss(y, np.clip(p, 1e-6, 1 - 1e-6)))) return out def _nan_to_none(v): return None if isinstance(v, float) and np.isnan(v) else v # ---------------------------------------------------------------------------------------------- # Evaluation # ---------------------------------------------------------------------------------------------- class EvalContext: """Row-aligned arrays + truth for one evaluated S1 set.""" def __init__(self, feats: pd.DataFrame, rows: np.ndarray, y: np.ndarray, truth: dict, groups: dict, a, audit: pl.DataFrame | None = None): self.rows = rows self.s1_rows = feats["s1_row"].to_numpy()[rows] self.pool_rows = feats["pool_row"].to_numpy()[rows] take = pa.array(rows, pa.int64()) self.s1_ids = _as_arrow(feats["s1_id"]).take(take) self.cand_ids = _as_arrow(feats["cand_id"]).take(take) self.y = y[rows] self.truth = truth self.groups = groups self.a = a self.audit = audit if "is_s2" in feats.columns: self.is_s2 = feats["is_s2"].to_numpy()[rows] > 0.5 else: self.is_s2 = np.asarray([x.startswith("S2-") for x in self.cand_ids.to_pylist()], dtype=bool) u, first = np.unique(self.s1_rows, return_index=True) self.code_to_id = dict(zip(u.tolist(), self.s1_ids.take(pa.array(first, pa.int64())).to_pylist())) def score_mask(self, sel: np.ndarray, probs: np.ndarray, apply_one_parent: bool = True): if apply_one_parent: sel = one_parent(sel, self.pool_rows, probs) pred = selected_pred(sel, probs, self.s1_rows, self.s1_ids, self.cand_ids) pred_sets = {k: set(v) for k, v in pred.items()} sc = entity_scores(pred_sets, self.truth) return (float(sc["f05"].mean()) if len(sc) else float("nan")), sel, pred_sets, sc def decode(self, probs: np.ndarray, apply_one_parent: bool = True): a = self.a r = decode_arrays(self.s1_rows, probs, method="expected_f", min_prob=a.min_prob, max_k=a.max_k, n_jobs=a.workers) return self.score_mask(r.selected, probs, apply_one_parent) + (r,) def best_threshold(self, probs: np.ndarray) -> tuple[float, dict]: sweep = {th: self.score_mask(probs > th, probs)[0] for th in THRESHOLDS} return max(sweep.items(), key=lambda kv: kv[1])[0], sweep def _source_metrics(ctx: EvalContext, sel: np.ndarray) -> dict: out = {} for src, is_src in (("S2", ctx.is_s2), ("S3", ~ctx.is_s2)): n_true = sum(1 for v in ctx.truth.values() for x in v if x.startswith(src + "-")) tp = int((sel & is_src & (ctx.y == 1)).sum()) n_pred = int((sel & is_src).sum()) p = tp / n_pred if n_pred else float("nan") r = tp / n_true if n_true else float("nan") f = 1.25 * p * r / (0.25 * p + r) if (n_pred and n_true and tp) else 0.0 out[src] = {"pairs_true": n_true, "pairs_pred": n_pred, "tp": tp, "precision": p, "recall": r, "f05": f, "blocking_recall": float((is_src & (ctx.y == 1)).sum() / n_true) if n_true else float("nan")} return out def _noise_metrics(ctx: EvalContext, sel: np.ndarray, sc: pd.DataFrame) -> list: """Per noise category of the TRUE pairs (pair-audit parquet): pair recall of the final prediction, blocking recall, and macro F0.5 over the S1 ids having >= 1 true pair of that category.""" au = ctx.audit if au is None or au.height == 0: return [] got = pl.DataFrame({"a": ctx.s1_ids.take(pa.array(np.flatnonzero(sel), pa.int64())).to_pylist(), "b": ctx.cand_ids.take(pa.array(np.flatnonzero(sel), pa.int64())).to_pylist()}, schema={"a": pl.Utf8, "b": pl.Utf8}).with_columns(pl.lit(True).alias("pred")) pos = np.flatnonzero(ctx.y == 1) inc = pl.DataFrame({"a": ctx.s1_ids.take(pa.array(pos, pa.int64())).to_pylist(), "b": ctx.cand_ids.take(pa.array(pos, pa.int64())).to_pylist()}, schema={"a": pl.Utf8, "b": pl.Utf8}).with_columns(pl.lit(True).alias("in_cands")) au = (au.join(got, on=["a", "b"], how="left").join(inc, on=["a", "b"], how="left") .with_columns(pl.col("pred").fill_null(False), pl.col("in_cands").fill_null(False))) ent_f = sc["f05"] out = [] for cat, expr in [("all_true_pairs", pl.lit(True)), ("indic_script", pl.col("indic_name")), ("domain_form", pl.col("domain_form")), ("former_name", pl.col("former_form")), ("rename", pl.col("rename")), ("empty_address", pl.col("addr_empty")), ("none_of_these", pl.col("none"))]: g = au.filter(expr) ents = [e for e in g.get_column("a").unique().to_list() if e in ent_f.index] out.append({"category": cat, "pairs": g.height, "pair_recall": float(g.get_column("pred").mean()) if g.height else None, "blocking_recall": float(g.get_column("in_cands").mean()) if g.height else None, "entities": len(ents), "entity_macro_f05": float(ent_f.loc[ents].mean()) if ents else None}) return out def evaluate(variant: str, protocol: str, ctx: EvalContext, cal: np.ndarray, raw: np.ndarray | None = None, sweep: bool = True, threshold_from_oof: float | None = None) -> dict: """Decode + one-parent + macro F0.5 over the whole evaluated S1 set; the headline number of ``variant`` plus its diagnostics.""" t = time.time() res: dict = {"variant": variant, "protocol": protocol, "n_s1": len(ctx.truth), "n_rows": int(len(ctx.rows))} n_true_pairs = sum(len(v) for v in ctx.truth.values()) res["blocking_pair_recall"] = float(ctx.y.sum() / n_true_pairs) if n_true_pairs else float("nan") res["pair_cal"] = _pair_metrics(ctx.y, cal) if raw is not None: res["pair_raw"] = _pair_metrics(ctx.y, raw) score, sel, pred, sc, dres = ctx.decode(cal, apply_one_parent=True) res["macro_f05"] = score # the decoder's own expectation (before the one-parent rule) vs what it realised ids_c = [ctx.code_to_id[c] for c in dres.entity_ids.tolist()] exp = pd.Series(dres.expected_f05, index=ids_c) exp = exp[exp.index.isin(sc.index)] res["n_s1_with_cands"] = int(len(exp)) res["expected_f05_mean_with_cands"] = float(exp.mean()) if len(exp) else float("nan") res["realised_f05_mean_with_cands"] = float(sc.loc[exp.index, "f05"].mean()) if len(exp) else float("nan") # no candidates -> empty prediction, which the model expects to be right (E = 1) res["expected_f05_mean_all"] = float((exp.sum() + (len(sc) - len(exp))) / len(sc)) if len(sc) else float("nan") res["macro_f05_no_one_parent"] = ctx.decode(cal, apply_one_parent=False)[0] if raw is not None: res["macro_f05_raw_probs"] = ctx.decode(raw, apply_one_parent=True)[0] if threshold_from_oof is not None: res["threshold_oof"] = threshold_from_oof res["macro_f05_threshold_oof"] = ctx.score_mask(cal > threshold_from_oof, cal)[0] res["per_source"] = _source_metrics(ctx, sel) res["noise"] = _noise_metrics(ctx, sel, sc) bd = breakdown(pred, ctx.truth, ctx.groups, scores=sc) res["breakdown"] = [{"dimension": d, "slice": s, **{k: _nan_to_none(v) for k, v in row.items()}} for (d, s), row in bd.to_dict(orient="index").items()] if sweep: best, sw = ctx.best_threshold(cal) res["threshold_sweep"] = {str(k): v for k, v in sw.items()} res["threshold_sweep_best"] = best print(f"\n==== [{variant}] macro F0.5 = {score:.5f} ({protocol})") print(f" S1 ids {len(ctx.truth):,} ({res['n_s1_with_cands']:,} with candidates), rows {len(ctx.rows):,}, " f"blocking pair recall {res['blocking_pair_recall']:.4f} [{time.time() - t:.0f}s]") print(f" decoder expected F0.5 {res['expected_f05_mean_all']:.5f} vs realised {score:.5f} (all S1); " f"with candidates: expected {res['expected_f05_mean_with_cands']:.5f} vs realised " f"{res['realised_f05_mean_with_cands']:.5f}") pr_ = res["pair_cal"] print(f" pair-level diagnostics: calibrated AUC {pr_.get('auc', float('nan')):.5f} logloss " f"{pr_.get('logloss', float('nan')):.5f}" + (f" | raw AUC {res['pair_raw'].get('auc', float('nan')):.5f} logloss " f"{res['pair_raw'].get('logloss', float('nan')):.5f}" if raw is not None else "")) print(f" [{variant}/no_one_parent] {res['macro_f05_no_one_parent']:.5f}" + (f" [{variant}/raw_probs] {res['macro_f05_raw_probs']:.5f}" if raw is not None else "") + (f" [{variant}/threshold_oof t={threshold_from_oof}] {res['macro_f05_threshold_oof']:.5f}" if threshold_from_oof is not None else "")) if sweep: print(f" [{variant}/sweep] plain threshold p > t (one-parent), diagnostic: " + " ".join(f"{k}:{v:.4f}" for k, v in res["threshold_sweep"].items())) for s, m in res["per_source"].items(): print(f" source {s}: pair P {m['precision']:.4f} R {m['recall']:.4f} F0.5 {m['f05']:.4f} " f"(true {m['pairs_true']:,}, pred {m['pairs_pred']:,}, blocking recall {m['blocking_recall']:.4f})") if res["noise"]: print(" noise category (true pairs): pairs pair_recall blocking_recall entities entity_macro_F0.5") for r in res["noise"]: f = lambda v, w=8: f"{v:{w}.4f}" if v is not None else " " * (w - 3) + "n/a" # noqa: E731 print(f" {r['category']:22s} {r['pairs']:9,} {f(r['pair_recall'])} {f(r['blocking_recall'])}" f" {r['entities']:8,} {f(r['entity_macro_f05'])}") with pd.option_context("display.max_rows", 200, "display.max_columns", None, "display.width", 250, "display.float_format", "{:.4f}".format): print(bd) return res def _load_audit(path: str | None, eval_ids: pl.Series) -> pl.DataFrame | None: if not path: return None import pyarrow.parquet as pq names = set(pq.ParquetFile(path).schema_arrow.names) cols = ["a", "b"] + [c for c in NOISE_FLAGS + ["name_j"] if c in names] au = (pl.read_parquet(path, columns=cols).with_columns(pl.col("a").cast(pl.Utf8), pl.col("b").cast(pl.Utf8)) .join(pl.DataFrame({"a": eval_ids}), on="a", how="semi").unique(["a", "b"])) for c in NOISE_FLAGS: au = au.with_columns((pl.col(c).cast(pl.Boolean).fill_null(False) if c in au.columns else pl.lit(False)).alias(c)) nj = pl.col("name_j").cast(pl.Float64).fill_null(1.0) if "name_j" in au.columns else pl.lit(1.0) au = au.with_columns((nj.eq(0) & ~pl.col("indic_name") & ~pl.col("domain_form") & ~pl.col("former_form")) .alias("rename")) au = au.with_columns((~pl.col("indic_name") & ~pl.col("domain_form") & ~pl.col("former_form") & ~pl.col("rename") & ~pl.col("addr_empty")).alias("none")) log(f"pair audit: {au.height:,} true pairs of evaluated S1 ids from {path}") return au # ---------------------------------------------------------------------------------------------- # Main pipeline # ---------------------------------------------------------------------------------------------- def run(a) -> dict: t_all = time.time() os.makedirs(a.out_dir, exist_ok=True) rng = np.random.default_rng(a.seed) timings = {} t = time.time() cands = read_cands(a.cands) s1_tab, pool_tab = load_tables(a.norm_dir, a.s1_table, a.pool_tables) gt = read_gt(a.gt) log(f"loaded: cands {cands.height:,} rows, S1 {s1_tab.num_rows:,}, pool {pool_tab.num_rows:,}, gt {gt.height:,}") idf = build_idf_tables(s1_tab) folds_df = load_or_make_folds(a, gt.get_column("s1_id").to_list()) timings["load"] = time.time() - t # ---- evaluated S1 universe s1_meta = pl.from_arrow(s1_tab.select(["entity_id", "country"])).rename({"entity_id": "s1_id"}) ck_map = {c: country_key(c) for c in s1_meta.get_column("country").fill_null("").unique().to_list()} s1_meta = s1_meta.with_columns(pl.col("s1_id").cast(pl.Utf8), pl.col("country").fill_null("").replace_strict(ck_map, return_dtype=pl.Utf8) .alias("ck")).unique("s1_id", keep="first") cand_s1 = cands.select(pl.col("s1_id").cast(pl.Utf8)).unique() cand_meta = cand_s1.join(s1_meta, on="s1_id", how="inner") cand_cks = set(cand_meta.get_column("ck").unique().to_list()) univ_all = s1_meta.filter(pl.col("ck").is_in(list(cand_cks))).join(gt.select("s1_id"), on="s1_id", how="semi") cov = cand_meta.join(univ_all, on="s1_id", how="semi").height / max(univ_all.height, 1) mode = a.eval_universe if a.eval_universe != "auto" else ("all" if cov >= 0.5 else "cands") universe = (univ_all if mode == "all" else univ_all.join(cand_s1, on="s1_id", how="semi")).sort("s1_id") log(f"S1 universe: {universe.height:,} ids ({mode}; candidates cover {cov:.1%} of the " f"{univ_all.height:,} gt S1 ids in countries {sorted(cand_cks)})") if cov < 0.5: print("WARNING: candidate table covers < 50% of the S1 ids: assuming blocking ran on an S1 subsample. " "Pool-side competition features (c_p_*) then see fewer competing S1 records than at test " "time; prefer blocking the full train S1 or pass --drop-features c_p_n,c_p_rank,c_p_gap," "c_p_margin,c_p_n_rel.", file=sys.stderr) if a.max_s1 and a.max_s1 < universe.height: universe = universe.sample(n=a.max_s1, seed=a.seed, shuffle=False) universe = universe.join(folds_df, on="s1_id", how="left") holdout = country_key(a.holdout_country) if a.holdout_country else None if holdout is not None and universe.filter(pl.col("ck") == holdout).height == 0: raise SystemExit(f"--holdout-country {a.holdout_country!r} ({holdout}) not among {sorted(cand_cks)}") if holdout is not None and universe.filter(pl.col("ck") != holdout).height == 0: raise SystemExit("--holdout-country leaves no training country") by_c = dict(universe.group_by("ck").len().iter_rows()) log(f"evaluated S1 ids: {universe.height:,} {by_c}") # ---- features (competition context = full candidate table) t = time.time() feats = build_features(cands, s1_tab, pool_tab, idf, n_jobs=a.workers, task_rows=a.task_rows, keep_s1=universe.get_column("s1_id")) timings["features"] = time.time() - t del cands, s1_tab, pool_tab, idf # ---- labels + fold / country of every row pairs = pl.read_parquet(a.pairs) pairs = pairs.rename({pairs.columns[0]: "s1_id", pairs.columns[1]: "cand_id"}).select( pl.col("s1_id").cast(pl.Utf8), pl.col("cand_id").cast(pl.Utf8)) pairs = pairs.join(universe.select("s1_id"), on="s1_id", how="semi").unique() keys = pl.from_arrow(pa.table({"s1_id": _as_arrow(feats["s1_id"]), "cand_id": _as_arrow(feats["cand_id"])})) lab = (keys.with_row_index("_i") .join(pairs.with_columns(pl.lit(1, dtype=pl.Int8).alias("y")), on=["s1_id", "cand_id"], how="left") .join(universe.select("s1_id", "fold", "ck"), on="s1_id", how="left").sort("_i")) y = lab.get_column("y").fill_null(0).to_numpy().astype(np.int8) fold_row = lab.get_column("fold").fill_null(-9).to_numpy().astype(np.int16) ck_row = lab.get_column("ck").fill_null("").to_numpy() del keys, lab log(f"labels: {int(y.sum()):,} positive of {len(y):,} rows ({y.mean():.4f}); gt pairs of evaluated S1: {pairs.height:,}") # ---- truth, groups, audit gsub = gt.join(universe.select("s1_id"), on="s1_id", how="inner") truth = {s: set(m or ()) for s, m in zip(gsub.get_column("s1_id").to_list(), gsub.get_column("matched").to_list())} groups = dict(zip(universe.get_column("s1_id").to_list(), universe.get_column("ck").to_list())) audit = _load_audit(a.pair_audit, universe.get_column("s1_id")) del gt, gsub feat_cols = [f for f in feature_columns(feats) if f not in set(filter(None, a.drop_features.split(",")))] cat_cols = [c for c in feat_cols if isinstance(feats[c].dtype, pd.CategoricalDtype)] X = feats[feat_cols] s1_rank = feats["c_s1_rank"].to_numpy() s1r = feats["s1_row"].to_numpy() n = len(feats) is_train = (ck_row != holdout) if holdout is not None else np.ones(n, dtype=bool) is_eval = (ck_row == holdout) if holdout is not None else np.ones(n, dtype=bool) metrics = {"config": vars(a), "universe_mode": mode, "n_eval_s1": len(truth), "eval_s1_by_country": by_c, "n_rows": n, "n_pos": int(y.sum()), "folds": a.folds, "fold_seed": a.fold_seed, "folds_file": a.folds_file, "results": {}} # ---- k-fold on the training rows (all rows, or the non-held-out countries) from sklearn.isotonic import IsotonicRegression t = time.time() u_rows, inv = np.unique(s1r, return_inverse=True) inner = (np.random.default_rng(a.seed + 1).random(len(u_rows)) < a.inner_val_frac)[inv] oof = np.full(n, np.nan) raw_eval = np.zeros(n) if holdout is not None else None boosters, model_files, best_iters = [], [], [] for k in range(a.folds): te = np.flatnonzero(is_train & (fold_row == k)) tr_all = np.flatnonzero(is_train & (fold_row != k)) va = tr_all[inner[tr_all]] tr = tr_all[~inner[tr_all]] log(f"fold {k + 1}/{a.folds}: fit {len(tr):,} rows, early-stop {len(va):,}, predict {len(te):,}") tr, w = _sample_negatives(tr, y, s1_rank, a.neg_ratio, a.hard_neg_rank, rng) b = _fit(X, y, tr, w, va, a, cat_cols) if len(te): oof[te] = predict_raw([b], X.iloc[te], feat_cols, num_threads=a.workers) if holdout is not None: ev = np.flatnonzero(is_eval) raw_eval[ev] += predict_raw([b], X.iloc[ev], feat_cols, num_threads=a.workers) / a.folds best_iters.append(b.best_iteration) fn = f"model_fold{k}.txt" b.save_model(os.path.join(a.out_dir, fn), num_iteration=b.best_iteration) boosters.append(b) model_files.append(fn) tr_rows = np.flatnonzero(is_train & (fold_row >= 0)) iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0).fit(oof[tr_rows], y[tr_rows]) cal_oof = np.full(n, np.nan) cal_oof[tr_rows] = iso.predict(oof[tr_rows]) metrics["best_iterations"] = best_iters timings["train"] = time.time() - t # ---- evaluation t = time.time() train_truth = {k: v for k, v in truth.items() if holdout is None or groups.get(k) != holdout} ctx_oof = EvalContext(feats, tr_rows, y, train_truth, groups, a, audit) t_oof, _ = ctx_oof.best_threshold(cal_oof[tr_rows]) # decoder setting fitted on OOF only if holdout is None: v = "kfold_oof" metrics["headline"] = v metrics["results"][v] = evaluate( v, f"{a.folds}-fold GroupKFold by S1 (seed {a.fold_seed}), OOF probabilities, isotonic fit on OOF, " f"expected-F0.5 decode + one-parent, all {len(train_truth):,} evaluated S1 ids", ctx_oof, cal_oof[tr_rows], oof[tr_rows], threshold_from_oof=t_oof) else: v = f"loco:{holdout}" metrics["headline"] = v ev = np.flatnonzero(is_eval) ev_truth = {k: s for k, s in truth.items() if groups.get(k) == holdout} ctx_ev = EvalContext(feats, ev, y, ev_truth, groups, a, audit) cal_ev = iso.predict(raw_eval[ev]) metrics["results"][v] = evaluate( v, f"train {sorted(cand_cks - {holdout})} only ({a.folds} fold models averaged, isotonic fit on their " f"OOF), score all {len(ev_truth):,} evaluated S1 ids of {holdout} (unseen category, nothing tuned on it)", ctx_ev, cal_ev, raw_eval[ev], threshold_from_oof=t_oof) v2 = f"loco:{holdout}/train_oof" metrics["results"][v2] = evaluate( v2, f"OOF on the training countries {sorted(cand_cks - {holdout})}", ctx_oof, cal_oof[tr_rows], oof[tr_rows], sweep=False) iso_o = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0).fit(raw_eval[ev], y[ev]) s_or = ctx_ev.decode(iso_o.predict(raw_eval[ev]))[0] v3 = f"loco:{holdout}/oracle_calibration" metrics["results"][v3] = {"variant": v3, "macro_f05": s_or, "protocol": f"DIAGNOSTIC ONLY: isotonic fit on {holdout} labels (not allowed for tuning)"} print(f"\n [{v3}] {s_or:.5f} -> calibration transfer loss " f"{s_or - metrics['results'][v]['macro_f05']:+.5f} (diagnostic, uses {holdout} labels)") timings["eval"] = time.time() - t # ---- optional refit on all training rows if a.refit: import lightgbm as lgb rounds = int(np.mean(best_iters) * 1.1) + 1 log(f"refit on all training rows for {rounds} rounds") tr, w = _sample_negatives(np.flatnonzero(is_train), y, s1_rank, a.neg_ratio, a.hard_neg_rank, rng) Xtr = X.iloc[tr] for c in cat_cols: Xtr = Xtr.assign(**{c: Xtr[c].cat.remove_unused_categories()}) bfull = lgb.train(_params(a), lgb.Dataset(Xtr, label=y[tr], weight=w, categorical_feature=cat_cols or "auto"), num_boost_round=rounds) bfull.save_model(os.path.join(a.out_dir, "model_full.txt")) model_files = ["model_full.txt"] print("NOTE: --refit model is used by predict.py; the calibrator was fit on fold-model OOF probabilities", file=sys.stderr) # ---- importance imp = pd.DataFrame({"feature": feat_cols}) imp["gain"] = np.mean([bb.feature_importance("gain") for bb in boosters], axis=0) imp["split"] = np.mean([bb.feature_importance("split") for bb in boosters], axis=0) imp["gain_pct"] = 100 * imp["gain"] / max(imp["gain"].sum(), 1e-12) imp = imp.sort_values("gain", ascending=False).reset_index(drop=True) imp.to_csv(os.path.join(a.out_dir, "importance.csv"), index=False) print("\nfeature importance (mean gain % over fold models, top 40):") for r in imp.head(40).itertuples(): print(f" {r.feature:22s} {r.gain_pct:6.2f}% splits {r.split:8.0f}") metrics["importance_top"] = imp.head(40).to_dict(orient="records") # ---- save with open(os.path.join(a.out_dir, "calibrator.pkl"), "wb") as fh: pickle.dump(iso, fh) meta = {"features": feat_cols, "categorical": cat_cols, "models": model_files, "calibrator": "calibrator.pkl", "decode": {"min_prob": a.min_prob, "max_k": a.max_k, "threshold_oof": t_oof}, "variant": metrics["headline"], "holdout_country": holdout, "train_config": vars(a)} with open(os.path.join(a.out_dir, "features.json"), "w") as fh: json.dump(meta, fh, indent=1) raw_all = oof.copy() cal_all = cal_oof.copy() fold_out = fold_row.astype(np.int8) if holdout is not None: ev = np.flatnonzero(is_eval) raw_all[ev] = raw_eval[ev] cal_all[ev] = iso.predict(raw_eval[ev]) fold_out[ev] = -1 import pyarrow.parquet as pq pq.write_table(pa.table({"s1_id": _as_arrow(feats["s1_id"]), "cand_id": _as_arrow(feats["cand_id"]), "label": pa.array(y), "raw": pa.array(raw_all.astype(np.float32)), "cal": pa.array(cal_all.astype(np.float32)), "fold": pa.array(fold_out)}), os.path.join(a.out_dir, "oof.parquet"), compression="zstd") timings["total"] = time.time() - t_all metrics["timings_s"] = {k: round(v, 1) for k, v in timings.items()} with open(os.path.join(a.out_dir, "metrics.json"), "w") as fh: json.dump(metrics, fh, indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o)) hv = metrics["results"][metrics["headline"]] print(f"\nHEADLINE [{metrics['headline']}] macro F0.5 = {hv['macro_f05']:.5f} " f"(decoder expected {hv['expected_f05_mean_all']:.5f}) over {hv['n_s1']:,} S1 ids") log(f"saved {model_files}, calibrator.pkl, folds.parquet, features.json, metrics.json, oof.parquet in " f"{a.out_dir}; timings {metrics['timings_s']}") return metrics def build_parser() -> argparse.ArgumentParser: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--cands", required=True, help="blocking candidates parquet (train)") ap.add_argument("--norm-dir", required=True, help="dir with .parquet and .parquet") ap.add_argument("--pairs", required=True, help="pairs.parquet (a=s1_id, b=cand_id)") ap.add_argument("--gt", required=True, help="gt.parquet (source1_entity_id, matched_entity_ids)") ap.add_argument("--out-dir", required=True) ap.add_argument("--s1-table", default="s1") ap.add_argument("--pool-tables", default="s2,s3") ap.add_argument("--max-s1", type=int, default=0, help="evaluate/train on a random sample of N S1 ids") ap.add_argument("--holdout-country", default=None, help="leave-one-country-out: train on the others, score X") ap.add_argument("--folds", type=int, default=5) ap.add_argument("--fold-seed", type=int, default=2026, help="seed of the S1-level fold assignment") ap.add_argument("--folds-file", default=None, help="shared fold assignment (s1_id, fold): reused when it exists, created there otherwise") ap.add_argument("--pair-audit", default=None, help="parquet a,b,indic_name,domain_form,former_form,addr_empty,name_j for the noise breakdown") ap.add_argument("--eval-universe", choices=["auto", "all", "cands"], default="auto") ap.add_argument("--neg-ratio", type=float, default=0.0, help="keep ~R negatives per positive in training folds (0 = keep all); weighted 1/q") ap.add_argument("--hard-neg-rank", type=int, default=3, help="negatives with S1 base rank <= this are always kept") ap.add_argument("--inner-val-frac", type=float, default=0.1, help="share of each fold's training S1 ids used for early stopping") ap.add_argument("--drop-features", default="", help="comma-separated feature names to exclude") ap.add_argument("--refit", action="store_true", help="also train one model on all rows and use it for predict") ap.add_argument("--workers", type=int, default=os.cpu_count()) ap.add_argument("--task-rows", type=int, default=50_000) ap.add_argument("--lr", type=float, default=0.05) ap.add_argument("--leaves", type=int, default=127) ap.add_argument("--min-data-in-leaf", type=int, default=200) ap.add_argument("--feature-fraction", type=float, default=0.8) ap.add_argument("--rounds", type=int, default=3000) ap.add_argument("--early-stop", type=int, default=100) ap.add_argument("--log-period", type=int, default=100) ap.add_argument("--min-prob", type=float, default=0.0, help="decode: never predict a candidate with p < this") ap.add_argument("--max-k", type=int, default=None, help="decode: cap on matches per S1") ap.add_argument("--seed", type=int, default=0) return ap def main(argv=None) -> int: run(build_parser().parse_args(argv)) return 0 if __name__ == "__main__": raise SystemExit(main())