File size: 10,748 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Track 1. Add the new features to model-4's existing scores, gate on a clean val, ship.



    # measure (fit on g_stack, read g_val)

    python scripts/11_rescore.py --mode train

    # apply, only if the gate passed

    python scripts/11_rescore.py --mode test --bundle work/rescore/bundle.joblib



WHAT IS BEING TESTED. model-4 has no feature for "how many S1 share this candidate's name".

On its own stack, among empty-address candidates whose name_core equals the S1's:



    unique among the country's S1    mean p 0.714   actual match rate 0.982

    shared by 3 or more S1          mean p 0.280   actual 0.170



The model under-predicts the first group by 0.27 and over-predicts the third. Per coarse

group its calibration is perfect, so nothing short of conditioning on the competitor count

reveals it. These features supply exactly that count, plus the address-equivalence signal for

France, and the stacker is refit on top of model-4's own p1 and cross-encoder score.



THE ABLATION IS THE POINT. Four nested feature sets are fitted and read on g_val, so the gain

from each block is separable and a block that does nothing is visible rather than absorbed.



THE GATE. Ship only if the full set beats the baseline set by at least --min-gain on g_val.

Both numbers come from the same stacker on the same split, so the comparison is like for like

even if this stacker is not tuned as finely as model-4's own.

"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

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 evaluate as E  # 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 = ["p1", "p1_rank", "p1_gap", "ce"]
M4 = os.environ.get("BERX_M4", "/scratch/user4/dai/model-4/work")


def prep_dir(split: str) -> str:
    return os.path.dirname(P.work("prep", split, "_"))


def add_all(df: pd.DataFrame, split: str, use_geo: bool = True):
    """Attach structure and geo features. `split` selects which source files to read."""
    d = prep_dir(split)
    s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
    pool = pd.read_parquet(os.path.join(d, "pool.parquet"))

    # ---- the six measured name-sharing features (MODEL5_FALSE_NEGATIVE_FIXES.md s3.1)
    t0 = time.time()
    print(f"  name_core / name_ns over {len(s1):,} S1 and {len(pool):,} pool rows ...",
          flush=True)
    s1 = pd.concat([s1, S.name_key_columns(s1)], axis=1)
    pool = pd.concat([pool, S.name_key_columns(pool)], axis=1)
    pool["addr_empty"] = (pool["business_address"].astype(str).str.strip() == "")
    nf = S.name_features(df, s1, pool)
    for c in S.NAME_FEATURES:
        df[c] = nf[c].to_numpy()
    print(f"  name-sharing features: {time.time()-t0:.0f}s", flush=True)

    t0 = time.time()
    print(f"  building name index over {len(s1):,} S1 rows ...", flush=True)
    ni = S.build_name_index(s1)
    df = S.add_features(df, 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")
    print(f"  structure features: {time.time()-t0:.0f}s")
    feats = list(BASE) + S.NAME_FEATURES + S.FEATURE_NAMES

    gpath = P.work("geo", f"equiv_{split}.json")
    if use_geo and os.path.exists(gpath):
        t0 = time.time()
        tables = json.load(open(gpath, encoding="utf-8"))
        matchers = {c: G.GeoMatcher(t) for c, t in tables.items()}
        qcn = s1["country"].to_numpy()
        qi, ci = df["q"].to_numpy(), df["c"].to_numpy()
        # Parse only the addresses these candidates reference.
        uq, uc = np.unique(qi), np.unique(ci)
        qa, pa = s1["business_address"].to_numpy(), pool["business_address"].to_numpy()
        qp = {int(i): G.parse_address(qa[i]) for i in uq}
        pp = {int(i): G.parse_address(pa[i]) for i in uc}
        blank = {k: 0.0 for k in G.FEATURE_NAMES}
        cols = {k: np.zeros(len(df), np.float32) for k in G.FEATURE_NAMES}
        stepj = max(1, len(df) // 10)
        for j in range(len(df)):
            if j % stepj == 0 and j:
                print(f"    geo {j:>12,}/{len(df):,} ({j/len(df):5.1%})", flush=True)
            m = matchers.get(qcn[qi[j]])
            r = m.features_pre(qp[int(qi[j])], pp[int(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:
            df[k] = cols[k]
        feats += G.FEATURE_NAMES
        print(f"  geo features: {time.time()-t0:.0f}s")
    elif use_geo:
        print(f"  no geo table at {gpath}; continuing without it")
    return df, feats


def truths_for(qs, gt_q, gt_c):
    keep = np.isin(gt_q, qs)
    out = {int(q): set() for q in qs}
    for q, c in zip(gt_q[keep], gt_c[keep]):
        out[int(q)].add(int(c))
    return out


def evaluate_block(tr, va, feats, truths, ids, name, n_folds=3):
    b = F.fit_stacker(tr, feats, label="y", group="q", n_folds=n_folds)
    va = va.copy()
    va["p"] = F.apply_stacker(b, va)
    # Both decision rules, because model-4 selects by expected-F0.5 and a flat threshold is
    # a different rule. Reporting only the winner would hide whether a gain came from the
    # features or from swapping the rule underneath them.
    best, f_thr = F.tune_decision(va, truths, ids)
    pred = F.predict_sets(va, best["threshold"], all_q=np.asarray(ids),
                          method=best["method"], miss_mass=best["miss_mass"])
    m, _ = E.macro_f05(pred, truths, ids)
    print(f"  {name:<26} {len(feats):>3} feats   {best['method']:<9} "
          f"F0.5 {best['f05']:.5f}  (flat thr {f_thr:.5f})   "
          f"P {m['precision']:.4f}  R {m['recall']:.4f}")
    b["threshold"] = best["threshold"]
    b["method"] = best["method"]
    b["miss_mass"] = best["miss_mass"]
    return b, best["f05"]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mode", required=True, choices=["train", "test"])
    ap.add_argument("--bundle", default="")
    ap.add_argument("--min-gain", type=float, default=0.0015,
                    help="required g_val gain of the full set over the baseline set")
    ap.add_argument("--no-geo", action="store_true")
    ap.add_argument("--out", default="")
    a = ap.parse_args()

    if a.mode == "train":
        df = pd.read_parquet(P.work("m4", "train.parquet"))
        df, feats = add_all(df, "train", use_geo=not a.no_geo)
        tr = df[df.grp == "stack"]
        va = df[df.grp == "val"]
        t = np.load(P.work("m4", "truth.npz"))
        ids = sorted(set(va["q"].unique().tolist()))
        truths = truths_for(np.array(ids), t["gt_q"], t["gt_c"])
        nt = np.mean([len(v) for v in truths.values()])
        print(f"\nfit on {len(tr):,} stack rows / {tr.q.nunique():,} S1")
        print(f"read on {len(va):,} val rows / {len(ids):,} S1, mean true matches {nt:.2f}\n")

        # The six measured features get their own block, BEFORE my own set, so the number
        # that lands can be compared directly against the +0.0032 he measured. Putting them
        # last would have let my features absorb credit for them.
        blocks = [
            ("baseline (model-4 cols)", BASE),
            ("+ 6 name-sharing [measured]", BASE + S.NAME_FEATURES),
            ("+ my structure", BASE + S.NAME_FEATURES
             + [f for f in S.FEATURE_NAMES if f in df.columns]),
            ("+ geo", feats),
        ]
        results = []
        for name, fs in blocks:
            fs = [f for f in fs if f in df.columns]
            results.append((name, *evaluate_block(tr, va, fs, truths, ids, name)))

        base_f05 = results[0][2]
        best_name, best_b, best_f05 = max(results, key=lambda r: r[2])
        gain = best_f05 - base_f05
        print(f"\n  baseline {base_f05:.5f}  ->  best '{best_name}' {best_f05:.5f}  "
              f"({gain:+.5f})")
        print(f"  model-4's own val F0.5 for reference: 0.98298")

        p = a.bundle or P.work("rescore", "bundle.joblib")
        joblib.dump(best_b, p)
        json.dump({"base": base_f05, "best": best_f05, "gain": gain,
                   "threshold": best_b["threshold"], "block": best_name,
                   "pass": bool(gain >= a.min_gain)},
                  open(P.work("rescore", "gate.json"), "w"), indent=1)

        if gain >= a.min_gain:
            print(f"\n  GATE A PASS ({gain:+.5f} >= {a.min_gain}). Run --mode test.")
        else:
            print(f"\n  GATE A FAIL ({gain:+.5f} < {a.min_gain}).")
            print("  The global information is already in model-4's scores. Do not ship this;")
            print("  keep the existing submission and put the time into retrieval instead.")
            sys.exit(3)
        return

    assert a.bundle, "--mode test needs --bundle"
    b = joblib.load(a.bundle)
    df = pd.read_parquet(P.work("m4", "test.parquet"))
    df, _ = add_all(df, "test", use_geo=not a.no_geo)
    missing = [f for f in b["feats"] if f not in df.columns]
    assert not missing, f"test table is missing features the bundle needs: {missing}"
    df["p"] = F.apply_stacker(b, df)

    d = prep_dir("test")
    s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
    pool = pd.read_parquet(os.path.join(d, "pool.parquet"))
    pred = F.predict_sets(df, b["threshold"], all_q=np.arange(len(s1)),
                          method=b.get("method", "threshold"),
                          miss_mass=b.get("miss_mass", 0.0))

    out = a.out or P.work("output_v2", "matching_results.tsv")
    os.makedirs(os.path.dirname(out), exist_ok=True)
    qid, pid = s1["entity_id"].to_numpy(), pool["entity_id"].to_numpy()
    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"\nwrote {out}")
    print(f"  {len(qid):,} S1 rows   {npred:,} pairs   {nempty:,} empty ({nempty/len(qid):.2%})")
    print(f"  rule {b.get('method','threshold')}  threshold {b['threshold']:.3f}  "
          f"miss_mass {b.get('miss_mass',0.0)}")


if __name__ == "__main__":
    main()