File size: 8,517 Bytes
d231962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""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()