File size: 4,956 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
"""Step 4. Turn the retrieval union into self-contained cross-encoder work shards.

DESIGN DECISION: THE TEXT TRAVELS WITH THE SHARD.

A shard could have been (q, c) index pairs, with the lane joining them against the source
files itself. That would be smaller. It is rejected because it makes every lane depend on
having the identical source files in the identical row order, and a Colab VM that downloaded
a slightly different copy would produce scores for the wrong pairs with nothing to detect it.
Embedding the rendered text costs a few hundred MB and makes a shard a closed unit: one file
in, one file out, no shared state, no row-order contract.

WHAT GETS SHARDED. Only pairs that do not already have a cross-encoder score. The union with
K=100 produces far more candidates than the shipped K=64, but most of the overlap is already
scored; re-scoring it is the single easiest way to waste a GPU-hour here.

BALANCING. Shards are equal in TOKEN cost, not row count - see fuse.split_shards.
"""
from __future__ import annotations

import argparse
import glob
import json
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 ce_score as CE  # noqa: E402
from berx import fuse as F  # noqa: E402
from berx import paths as P  # noqa: E402
from berx import retrieve as R  # noqa: E402


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--split", default="test")
    ap.add_argument("--nshards", type=int, default=4,
                    help="lanes: college GPU0, college GPU1, Colab A, Colab B")
    ap.add_argument("--already-scored", default="",
                    help="parquet with q,c already having a CE score; those pairs are skipped")
    ap.add_argument("--max-pairs", type=int, default=0, help="0 = no cap; for smoke tests")
    a = ap.parse_args()

    prep = os.path.dirname(P.work("prep", a.split, "_"))
    s1 = pd.read_parquet(os.path.join(prep, "source1.parquet"))
    pool = pd.read_parquet(os.path.join(prep, "pool.parquet"))

    frames = {}
    for ch in P.CHANNELS:
        fs = sorted(glob.glob(P.work("retr", f"{a.split}_{ch}_s*.parquet")))
        if not fs:
            print(f"  {ch}: no shards found, skipping")
            continue
        d = pd.concat([pd.read_parquet(f) for f in fs], ignore_index=True)
        frames[ch] = {k: d[k].to_numpy() for k in ("q", "c", "s", "r")}
        print(f"  {ch}: {len(d):,} pairs from {len(fs)} shard file(s)")
    assert frames, "no retrieval output found - run 03_retrieve.py first"

    u = R.union(frames)
    print(f"\nunion: {len(u):,} unique pairs over {u['q'].nunique():,} S1 entities")
    print(f"  found by 1 / 2 / 3 channels: "
          f"{(u.n_channels == 1).sum():,} / {(u.n_channels == 2).sum():,} / "
          f"{(u.n_channels == 3).sum():,}")
    u.to_parquet(P.work("cand", f"{a.split}_union.parquet"), index=False)

    todo = u
    if a.already_scored and os.path.exists(a.already_scored):
        old = pd.read_parquet(a.already_scored)[["q", "c"]]
        before = len(todo)
        todo = todo.merge(old.assign(_h=1), on=["q", "c"], how="left")
        todo = todo[todo["_h"].isna()].drop(columns="_h")
        print(f"  {before - len(todo):,} pairs already scored; {len(todo):,} remain")
    if a.max_pairs:
        todo = todo.head(a.max_pairs)

    qn = s1["business_name"].to_numpy()
    qa = s1["business_address"].to_numpy()
    qc = s1["country"].to_numpy()
    pn = pool["business_name"].to_numpy()
    pa = pool["business_address"].to_numpy()
    pc = pool["country"].to_numpy()

    qi, ci = todo["q"].to_numpy(), todo["c"].to_numpy()
    work = pd.DataFrame({
        "q": qi.astype(np.int32),
        "c": ci.astype(np.int32),
        "text_a": [CE.pair_text(qn[i], qa[i], qc[i]) for i in qi],
        "text_b": [CE.pair_text(pn[i], pa[i], pc[i]) for i in ci],
    })
    work["len_a"] = work["text_a"].str.len().astype(np.int32)
    work["len_b"] = work["text_b"].str.len().astype(np.int32)

    shards = F.split_shards(work, a.nshards)
    manifest = []
    for i, sh in enumerate(shards):
        p = P.work("shards", f"{a.split}_shard{i}of{a.nshards}.parquet")
        sh.to_parquet(p, index=False, compression="zstd")
        mb = os.path.getsize(p) / 2 ** 20
        manifest.append({"shard": i, "n": len(sh), "file": os.path.basename(p),
                         "mb": round(mb, 1),
                         "tokens_est": int((sh.len_a + sh.len_b).sum() // 4)})
        print(f"  shard {i}: {len(sh):>9,} pairs  {mb:6.1f} MB  "
              f"~{manifest[-1]['tokens_est']/1e6:.0f}M tokens")

    mpath = P.work("shards", f"{a.split}_manifest.json")
    with open(mpath, "w") as fh:
        json.dump({"split": a.split, "nshards": a.nshards, "shards": manifest}, fh, indent=1)
    print(f"\nwrote {mpath}")
    print("Next: upload with scripts/01_upload_hf.py --what shards")


if __name__ == "__main__":
    main()