PopTurk / code /scripts /06_fuse.py
Jyo-K's picture
Upload folder using huggingface_hub
d231962 verified
Raw
History Blame Contribute Delete
8.52 kB
"""Final step. Merge every lane, add the new features, decide, write the submission.
THIS RUNS ON ONE MACHINE AND MUST SEE EVERY SHARD. The competitive features and the one-owner
arbitration are both global: a record's competitor count is wrong if a fifth of the candidate
table is missing, and arbitration cannot resolve a conflict it cannot see. Running this per
lane and concatenating the outputs produces a file that looks fine and is wrong.
In --mode train it fits the stacker and reports val F0.5 with an ablation, so the gain from
each new feature block is visible separately. In --mode test it applies a saved bundle.
"""
from __future__ import annotations
import argparse
import glob
import json
import os
import sys
import joblib
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 ce_score as CE # noqa: E402
from berx import france_geo as G # noqa: E402
from berx import fuse as F # noqa: E402
from berx import paths as P # noqa: E402
from berx import structure as S # noqa: E402
BASE_FEATS = ["rrf", "n_channels", "s_e5_small", "s_e5_large", "s_bge_m3",
"r_e5_small", "r_e5_large", "r_bge_m3", "ce", "ce2", "ce_blend"]
def build(split: str, args) -> pd.DataFrame:
prep = os.path.dirname(P.work("prep", split, "_"))
s1 = pd.read_parquet(os.path.join(prep, "source1.parquet"))
pool = pd.read_parquet(os.path.join(prep, "pool.parquet"))
cand = pd.read_parquet(P.work("cand", f"{split}_union.parquet"))
print(f"union candidates: {len(cand):,}")
for col, pat in (("ce", args.ce_glob), ("ce2", args.ce2_glob)):
files = sorted(glob.glob(pat)) if pat else []
if not files:
print(f" {col}: no files matched {pat!r}")
cand[col] = np.nan
continue
sc = F.merge_shards(files, score_col=col)
print(f" {col}: {len(sc):,} scored pairs from {len(files)} file(s)")
cand = cand.merge(sc[["q", "c", col]], on=["q", "c"], how="left")
if cand["ce"].isna().any():
n = int(cand["ce"].isna().sum())
print(f" WARNING: {n:,} union pairs ({n/len(cand):.2%}) have no primary CE score. "
f"A lane is missing or its shard range did not cover them.")
# Blend on RANKS, not probabilities: the two encoders are not calibrated to each other.
if cand["ce2"].notna().any():
m = cand["ce"].notna() & cand["ce2"].notna()
cand["ce_blend"] = cand["ce"].fillna(0).to_numpy(np.float32)
cand.loc[m, "ce_blend"] = CE.blend(cand.loc[m, "ce"].to_numpy(np.float32),
cand.loc[m, "ce2"].to_numpy(np.float32),
mode=args.blend_mode)
else:
cand["ce_blend"] = cand["ce"]
cand[["ce", "ce2", "ce_blend"]] = cand[["ce", "ce2", "ce_blend"]].fillna(0.0)
feats = list(BASE_FEATS)
if not args.no_structure:
print("adding structure / competitive features ...")
ni = S.build_name_index(s1)
cand = S.add_features(
cand, s1["business_name"].to_numpy(), s1["country"].to_numpy(),
pool["business_name"].to_numpy(), pool["business_address"].to_numpy(),
pool["country"].to_numpy(), ni["count"], pcol="ce_blend")
feats += S.FEATURE_NAMES
gpath = P.work("geo", f"equiv_{split}.json")
if not args.no_geo and os.path.exists(gpath):
print("adding administrative-equivalence features ...")
tables = json.load(open(gpath, encoding="utf-8"))
matchers = {c: G.GeoMatcher(t) for c, t in tables.items()}
qcn = s1["country"].to_numpy()
# Parse each address once (12M), then every pair is set operations (24M).
qp = G.parse_many(s1["business_address"].to_numpy())
pp = G.parse_many(pool["business_address"].to_numpy())
blank = {k: 0.0 for k in G.FEATURE_NAMES}
qi, ci = cand["q"].to_numpy(), cand["c"].to_numpy()
cols = {k: np.zeros(len(cand), np.float32) for k in G.FEATURE_NAMES}
for j in range(len(cand)):
m = matchers.get(qcn[qi[j]])
r = m.features_pre(qp[qi[j]], pp[ci[j]]) if m is not None else blank
for k in G.FEATURE_NAMES:
cols[k][j] = r[k]
for k in G.FEATURE_NAMES:
cand[k] = cols[k]
feats += G.FEATURE_NAMES
elif not args.no_geo:
print(f" no geo table at {gpath}; skipping (run 02_france_geo.py first)")
return cand, feats, s1
def attach_labels(cand: pd.DataFrame, split: str, s1: pd.DataFrame):
prep = os.path.dirname(P.work("prep", split, "_"))
pool = pd.read_parquet(os.path.join(prep, "pool.parquet"))
gtp = P.ground_truth(split)
gt = (pd.read_csv(gtp, sep="\t", dtype=str, keep_default_na=False, na_filter=False)
if gtp.endswith(".tsv") else pd.read_parquet(gtp))
prow = {e: i for i, e in enumerate(pool["entity_id"])}
qrow = {e: i for i, e in enumerate(s1["entity_id"])}
truths = {}
for q, m in zip(gt["source1_entity_id"], gt["matched_entity_ids"]):
if q in qrow:
truths[qrow[q]] = {prow[x] for x in str(m).split(",") if x in prow}
y = np.fromiter((1 if c in truths.get(q, ()) else 0
for q, c in zip(cand["q"], cand["c"])), np.int8, len(cand))
cand["y"] = y
return truths
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--split", default="test")
ap.add_argument("--mode", default="test", choices=["train", "test"])
ap.add_argument("--ce-glob", default="")
ap.add_argument("--ce2-glob", default="")
ap.add_argument("--blend-mode", default="rank", choices=["rank", "p"])
ap.add_argument("--bundle", default="")
ap.add_argument("--threshold", type=float, default=-1.0, help="-1 = tune (train mode)")
ap.add_argument("--no-structure", action="store_true")
ap.add_argument("--no-geo", action="store_true")
ap.add_argument("--out", default="")
a = ap.parse_args()
cand, feats, s1 = build(a.split, a)
feats = [f for f in feats if f in cand.columns]
if a.mode == "train":
truths = attach_labels(cand, a.split, s1)
ids = sorted(truths)
cand["component"] = cand["q"] # replace with true components when available
print("\nablation (each block added to the one above):")
blocks = [("ce only", ["ce"]),
("+ retrieval union", [f for f in BASE_FEATS if f in cand.columns]),
("+ structure", [f for f in BASE_FEATS + S.FEATURE_NAMES if f in cand.columns]),
("+ geo", feats)]
best = None
for name, fs in blocks:
if not fs:
continue
b = F.fit_stacker(cand, fs)
cand["p"] = F.apply_stacker(b, cand)
thr, f05, _ = F.tune_threshold(cand, truths, ids)
print(f" {name:<22} {len(fs):>3} feats thr {thr:.3f} F0.5 {f05:.5f}")
best = (b, thr, f05)
bundle, thr, f05 = best
bundle["threshold"] = thr
p = a.bundle or P.work("bundle", f"{a.split}_v2.joblib")
joblib.dump(bundle, p)
print(f"\nwrote {p} val F0.5 {f05:.5f} at threshold {thr:.3f}")
return
assert a.bundle, "--bundle is required in test mode"
bundle = joblib.load(a.bundle)
cand["p"] = F.apply_stacker(bundle, cand)
thr = a.threshold if a.threshold >= 0 else bundle["threshold"]
all_q = np.arange(len(s1))
pred = F.predict_sets(cand, thr, all_q=all_q)
prep = os.path.dirname(P.work("prep", a.split, "_"))
pool = pd.read_parquet(os.path.join(prep, "pool.parquet"))
pid = pool["entity_id"].to_numpy()
qid = s1["entity_id"].to_numpy()
out = a.out or P.work("output_v2", "matching_results.tsv")
os.makedirs(os.path.dirname(out), exist_ok=True)
with open(out, "w", encoding="utf-8", newline="") as fh:
fh.write("source1_entity_id\tmatched_entity_ids\n")
for i in range(len(qid)):
fh.write(f"{qid[i]}\t{','.join(pid[c] for c in pred.get(i, []))}\n")
npred = sum(len(v) for v in pred.values())
nempty = sum(1 for v in pred.values() if not v)
print(f"wrote {out}")
print(f" {len(qid):,} S1 rows {npred:,} pairs {nempty:,} empty ({nempty/len(qid):.2%})")
print(f" threshold {thr:.3f}")
print(" run the official validator next: python utils/validate_submission.py "
f"{out} --check-ids")
if __name__ == "__main__":
main()