File size: 4,371 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
"""Assemble model-4's stage-2 tables into labelled train / unlabelled test frames.

WHY THIS EXISTS. model-4 already scored every test candidate and left the result on disk:
`stage2/test_scores.parquet`, 9,980,755 rows of (q, c, p1, p, ce) - the table that produced
leaderboard 0.979241. The train side is there too, with labels. So the whole feature-and-
decision track can be run on existing scores, with no retrieval and no cross-encoder pass.
That is the difference between a submission in an hour and a submission in six.

THE SPLIT IS CLEAN, WHICH MATTERS MORE THAN THE SPEED. `s2/train.parquet` covers 296,148 S1:
197,435 from g_stack and 98,713 from g_val, and **zero** from g_ce. So fitting on g_stack and
reading g_val is an honest held-out measurement against a cross-encoder that never saw either.
Every earlier number in this project came from a 20k cache drawn with `RandomState(42)` where
the split used `default_rng(42)` - not the val split at all, and about 7% seen in training.
This replaces that.

ALIGNMENT. `ce_scores/<split>/shard_*.npy` concatenate in shard order to exactly the row count
of the matching `s2/<split>.parquet`. That is checked, not assumed; a silent off-by-one shard
would attach every cross-encoder score to the wrong pair and still produce a plausible file.
"""
from __future__ import annotations

import argparse
import glob
import os
import sys

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 paths as P  # noqa: E402

M4 = os.environ.get("BERX_M4", "/scratch/user4/dai/model-4/work")


def load_ce(split: str, n_expect: int) -> np.ndarray:
    fs = sorted(glob.glob(os.path.join(M4, "ce_scores", split, "shard_*.npy")))
    assert fs, f"no ce score shards under {M4}/ce_scores/{split}"
    parts = [np.load(f) for f in fs]
    ce = np.concatenate(parts)
    assert len(ce) == n_expect, (
        f"ce_scores/{split} has {len(ce):,} scores but s2/{split}.parquet has {n_expect:,} "
        f"rows. They are positionally aligned, so this mismatch means a shard is missing or "
        f"out of order - every score would attach to the wrong pair.")
    print(f"  ce {split}: {len(fs)} shards, {len(ce):,} scores")
    return ce.astype(np.float32)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="both", choices=["train", "test", "both"])
    a = ap.parse_args()

    splits = ["train", "test"] if a.split == "both" else [a.split]
    sp = np.load(os.path.join(M4, "splits.npz"))

    for split in splits:
        f = os.path.join(M4, "s2", f"{split}.parquet")
        df = pd.read_parquet(f)
        print(f"\n{f}: {len(df):,} rows, cols {list(df.columns)}")
        df["ce"] = load_ce(split, len(df))

        if split == "train":
            g_stack, g_val, g_ce = set(sp["g_stack"].tolist()), set(sp["g_val"].tolist()), \
                set(sp["g_ce"].tolist())
            q = df["q"].to_numpy()
            grp = np.where(np.isin(q, list(g_val)), "val",
                           np.where(np.isin(q, list(g_stack)), "stack", "other"))
            df["grp"] = grp
            leak = int(np.isin(q, list(g_ce)).sum())
            assert leak == 0, (
                f"{leak:,} rows belong to g_ce entities. The cross-encoder trained on those, "
                f"so any gain measured with them is partly leakage.")
            print(f"  groups: {pd.Series(grp).value_counts().to_dict()}")
            print(f"  label rate {df['y'].mean():.4%}   g_ce leakage: none")
            # n_true per S1 is needed by the metric: an entity with true matches that this
            # table never retrieved still counts against recall.
            df.attrs["n_true"] = None

        out = P.work("m4", f"{split}.parquet")
        df.to_parquet(out, index=False, compression="zstd")
        print(f"  wrote {out}  ({os.path.getsize(out)/2**20:.0f} MB)")

    # Ground truth for the train entities, as {q: set(c)}, so recall counts copies that the
    # candidate table never contained.
    if "train" in splits:
        gtq, gtc = sp["gt_q"], sp["gt_c"]
        np.savez_compressed(P.work("m4", "truth.npz"), gt_q=gtq, gt_c=gtc,
                            g_stack=sp["g_stack"], g_val=sp["g_val"])
        print(f"\n  wrote truth.npz  {len(gtq):,} ground-truth pairs")


if __name__ == "__main__":
    main()