File size: 11,127 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
232
233
234
235
236
237
238
239
240
241
242
"""Merge shards, retrain the stacker on the new features, decide, arbitrate.

THE DECISION RULE AND WHY IT IS THE SHAPE IT IS

The metric is macro F0.5 over S1 entities, and for one entity with T true matches and k
predicted, of which TP are right:

    F0.5 = 1.25 * TP / (0.25 * T + k)

FP = k - TP and FN = T - TP cancel the TP terms in the denominator, which is why only TP, T
and k survive. Writing D = 0.25*T + k, adding one more pair is worth it exactly when its
TP:FP odds beat TP/(D - TP). At the shipped operating point that is 3.76:1. It approaches 4:1
only in the limit TP -> T, k -> T, so quoting a flat 4:1 sets the bar too high and discards
pairs that were worth taking.

ONE OWNER PER RECORD. A pool record belongs to exactly one S1. Enforcing it globally is free
precision. The tie-break is deliberate: sort by candidate id, then descending probability,
then S1 id ascending, and keep the first. The last key makes the result deterministic; without
it two runs with identical scores could emit different files.
"""
from __future__ import annotations

import numpy as np
import pandas as pd


# --------------------------------------------------------------------------- stacking

def fit_stacker(df: pd.DataFrame, feats: list[str], label: str = "y",
                group: str = "component", n_folds: int = 5, seed: int = 42,
                params: dict | None = None):
    """Cross-fitted LightGBM + isotonic calibration.

    Folds are grouped by `component` - the connected components of the label graph - not by
    S1 row. Two S1 entities that share a true target must not land on opposite sides of a
    fold, or the model sees the answer to one through the other.
    """
    import lightgbm as lgb
    from sklearn.isotonic import IsotonicRegression

    p = dict(objective="binary", learning_rate=0.05, num_leaves=63, min_data_in_leaf=200,
             feature_fraction=0.8, bagging_fraction=0.8, bagging_freq=1, verbosity=-1,
             num_threads=max(1, (len(feats) // 4) or 4))
    p.update(params or {})

    g = df[group].to_numpy() if group in df else df.index.to_numpy()
    uniq = np.unique(g)
    rng = np.random.default_rng(seed)
    fold_of = dict(zip(uniq, rng.integers(0, n_folds, len(uniq))))
    fold = np.array([fold_of[x] for x in g])

    X, y = df[feats].to_numpy(np.float32), df[label].to_numpy(np.int8)
    oof = np.zeros(len(df), dtype=np.float32)
    models = []
    for f in range(n_folds):
        tr, va = fold != f, fold == f
        if va.sum() == 0:
            continue
        m = lgb.train(p, lgb.Dataset(X[tr], label=y[tr]), num_boost_round=600)
        oof[va] = m.predict(X[va])
        models.append(m)

    iso = IsotonicRegression(out_of_bounds="clip").fit(oof, y)
    return {"models": models, "iso": iso, "feats": feats, "oof": oof}


def apply_stacker(bundle, df: pd.DataFrame) -> np.ndarray:
    X = df[bundle["feats"]].to_numpy(np.float32)
    raw = np.mean([m.predict(X) for m in bundle["models"]], axis=0)
    return bundle["iso"].predict(raw).astype(np.float32)


# --------------------------------------------------------------------------- decision

def resolve_conflicts(df: pd.DataFrame, prob_col: str = "p", qcol: str = "q",
                      ccol: str = "c") -> pd.DataFrame:
    """Global one-owner arbitration. Keeps the best-scoring S1 for each pool record."""
    d = df.sort_values([ccol, prob_col, qcol], ascending=[True, False, True], kind="mergesort")
    return d[~d.duplicated(subset=ccol, keep="first")]


def predict_sets(df: pd.DataFrame, threshold: float, qcol: str = "q", ccol: str = "c",
                 pcol: str = "p", arbitrate: bool = True,
                 all_q: np.ndarray | None = None, method: str = "threshold",
                 miss_mass: float = 0.0) -> dict:
    """Select, arbitrate, and return {q: [c, ...]} including empty predictions.

    `method` is "threshold" (flat cut) or "ef05" (expected-F0.5 per entity, see above).

    Entities with no accepted pair MUST appear with an empty list. A singleton scores 1.0 for
    a correct empty prediction and 0.0 for any prediction at all, so dropping such entities
    from the output is not a neutral omission - it changes the macro average.
    """
    if method == "ef05":
        sel = expected_f05_select(df, qcol, ccol, pcol, miss_mass)
    else:
        sel = df[df[pcol] >= threshold]
    if arbitrate:
        sel = resolve_conflicts(sel, pcol, qcol, ccol)
    out = {int(q): [int(x) for x in g[ccol]] for q, g in sel.groupby(qcol, sort=False)}
    if all_q is not None:
        for q in all_q:
            out.setdefault(int(q), [])
    return out


def expected_f05_select(df: pd.DataFrame, qcol: str = "q", ccol: str = "c", pcol: str = "p",
                        miss_mass: float = 0.0) -> pd.DataFrame:
    """Per entity, keep the top-k that maximises EXPECTED F0.5. Returns the kept rows.

    WHY NOT A FLAT THRESHOLD. The metric is per entity, and the value of one more pair
    depends on how many that entity already has. With D = 0.25*T + k, an extra pair pays
    only when its odds beat TP/(D - TP) - 3.76:1 at the shipped operating point. An entity
    with one confident match and an entity with six have different bars, and a single global
    threshold gives them the same one. model-4 drops 99.8% of its rejected true copies by
    this rule, so comparing a flat threshold against it measures the rule, not the features.

    THE APPROXIMATION. With probabilities sorted descending,
        E[TP@k] = sum of the top k          E[T] = sum of all p, plus miss_mass
        E[F0.5@k] ~ 1.25 * E[TP@k] / (0.25 * E[T] + k)
    and k=0 scores P(no true match at all) = prod(1 - p_i), which is what lets a singleton be
    predicted empty and score 1.0 rather than 0.0.

    This is the plug-in approximation, not the exact Poisson-binomial dynamic program. That
    is deliberate: the exact version was measured at -0.00089 against this one, because the
    extra precision buys nothing while the miss_mass term remains an estimate.

    `miss_mass` is the expected number of true matches that retrieval never produced. Leaving
    it at 0 tells the rule every true match is on the table, which makes it too eager to stop
    early; it should be set from measured retrieval recall.
    """
    d = df.sort_values([qcol, pcol], ascending=[True, False], kind="mergesort")
    q = d[qcol].to_numpy()
    p = d[pcol].to_numpy(dtype=np.float64)
    n = len(d)
    if n == 0:
        return d

    new = np.empty(n, dtype=bool)
    new[0] = True
    np.not_equal(q[1:], q[:-1], out=new[1:])
    gid = np.cumsum(new) - 1
    starts = np.flatnonzero(new)
    sizes = np.diff(np.append(starts, n))

    csum = np.cumsum(p)
    base = np.append(0.0, csum[starts[1:] - 1]) if len(starts) > 1 else np.array([0.0])
    e_tp = csum - base[gid]                                   # E[TP] at k = rank+1
    group_sum = e_tp[starts + sizes - 1][gid]
    k = (np.arange(n) - starts[gid] + 1).astype(np.float64)
    score = 1.25 * e_tp / (0.25 * (group_sum + miss_mass) + k)

    # k = 0 competes: prod(1 - p) over the group, via a log-sum to stay stable.
    lg = np.log1p(-np.clip(p, 0.0, 1.0 - 1e-12))
    lcum = np.cumsum(lg)
    lbase = np.append(0.0, lcum[starts[1:] - 1]) if len(starts) > 1 else np.array([0.0])
    ltot = (lcum - lbase[gid])[starts + sizes - 1]
    score0 = np.exp(ltot)

    keep = np.zeros(n, dtype=bool)
    for g in range(len(starts)):
        s, sz = starts[g], sizes[g]
        seg = score[s:s + sz]
        bi = int(np.argmax(seg))
        if seg[bi] >= score0[g]:
            keep[s:s + bi + 1] = True                          # take the top bi+1
    return d[keep]


def tune_threshold(df: pd.DataFrame, truths: dict, ids, lo: float = 0.30, hi: float = 0.90,
                   steps: int = 25, **kw):
    """Sweep the threshold and return (best_threshold, best_f05, the full curve).

    Sweep on a clean split. The shipped 0.70 was tuned on a cache drawn with the wrong RNG,
    so it is a threshold selected partly on data the model had seen.
    """
    from .evaluate import macro_f05

    curve = []
    for t in np.linspace(lo, hi, steps):
        pred = predict_sets(df, float(t), all_q=np.asarray(ids), **kw)
        m, _ = macro_f05(pred, truths, ids)
        curve.append((float(t), m["f05"], m["precision"], m["recall"]))
    best = max(curve, key=lambda r: r[1])
    return best[0], best[1], curve


def tune_decision(df: pd.DataFrame, truths: dict, ids, miss_masses=(0.0, 0.2, 0.4, 0.6),
                  **kw):
    """Pick the better of the two decision rules on this split, and report both.

    Both are reported because a gate that only prints the winner hides whether a gain came
    from the features or from swapping the rule underneath them.
    """
    from .evaluate import macro_f05

    thr, f_thr, _ = tune_threshold(df, truths, ids, **kw)
    best = {"method": "threshold", "threshold": thr, "f05": f_thr, "miss_mass": 0.0}
    for mm in miss_masses:
        pred = predict_sets(df, 0.0, all_q=np.asarray(ids), method="ef05", miss_mass=mm, **kw)
        m, _ = macro_f05(pred, truths, ids)
        if m["f05"] > best["f05"]:
            best = {"method": "ef05", "threshold": 0.0, "f05": m["f05"], "miss_mass": mm}
    return best, f_thr


# --------------------------------------------------------------------------- shards

def merge_shards(paths: list[str], on=("q", "c"), score_col: str = "ce") -> pd.DataFrame:
    """Concatenate scored shards and verify that together they cover the work exactly once.

    The assert is the point. Four lanes writing four files is four chances to lose one, and a
    missing shard does not raise - it produces a submission with a plausible score that is
    quietly missing a fifth of its candidates.
    """
    parts = [pd.read_parquet(p) for p in paths]
    out = pd.concat(parts, ignore_index=True)
    before = len(out)
    out = out.drop_duplicates(list(on))
    if len(out) != before:
        print(f"  WARNING: {before - len(out):,} duplicate pairs across shards "
              f"(overlapping shard ranges?)")
    assert out[score_col].notna().all(), f"{int(out[score_col].isna().sum()):,} unscored pairs"
    return out.reset_index(drop=True)


def split_shards(df: pd.DataFrame, n: int) -> list[pd.DataFrame]:
    """Split work into n contiguous shards of roughly equal TOKEN cost, not equal row count.

    Cross-encoder cost scales with sequence length, and empty-address records are much shorter
    than the rest. Splitting by row count hands the lane that happens to draw the long records
    a job that takes half again as long as its neighbours.
    """
    if n <= 1 or len(df) == 0:
        return [df.reset_index(drop=True)]
    cost = (df["len_a"] + df["len_b"]).to_numpy() if "len_a" in df else np.ones(len(df))
    cum = np.cumsum(cost)
    edges = np.searchsorted(cum, np.linspace(0, cum[-1], n + 1)[1:-1])
    bounds = [0, *edges.tolist(), len(df)]
    # iloc, not np.split: np.split on a DataFrame returns bare ndarrays and loses the columns
    return [df.iloc[bounds[i]:bounds[i + 1]].reset_index(drop=True) for i in range(n)]