File size: 7,943 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 | """Collect candidates the rescue channels found that model-4 never scored, and shard them.
THE BUDGET IS THE WHOLE PROBLEM. Union the rescue channels naively and you get well over 100M
pairs. At roughly 2,400 pairs/s per GPU, four lanes clear about 35M pairs an hour, so an
unbounded union is a two-day job. Pairs are therefore selected, not merged:
1. Drop everything model-4 already scored. Its test table holds 9,980,755 pairs with a
cross-encoder score; re-scoring them buys nothing.
2. Keep every hit from the rescue channels (F4/F5). These are the targeted ones - the whole
point of building them - and they are few per S1 because k is small.
3. From the wide e5-small k=100 channel, keep only ranks beyond what model-4 used. Its
never-retrieved audit put 926 pairs (0.095 points) in fused rank 64-99, so the value
there is real but bounded; spending the entire budget on it would be a bad trade
against F4/F5, which target 0.42 points.
4. Cap per S1. Without a cap a handful of entities in dense name clusters absorb the budget.
Everything is reported, so if the total is still too large for the time available you can
lower --per-s1 and re-run in seconds rather than discovering it three hours into scoring.
"""
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 ce_score as CE # noqa: E402
from berx import fuse as F # noqa: E402
from berx import paths as P # noqa: E402
# "ename" is the measured character-TF-IDF channel (44% recovery at k=5). "nameonly" is my
# earlier dense version of the same idea, kept because it is already computed and costs
# nothing to union in. "addronly" is deliberately absent: measured at 6-12% recovery for
# 10-50 candidates per S1 and rejected.
RESCUE = ("ename", "nameonly")
def load_channel(split: str, ch: str):
fs = sorted(glob.glob(P.work("retr", f"{split}_{ch}_s*.parquet")))
if not fs:
return None
d = pd.concat([pd.read_parquet(f) for f in fs], ignore_index=True)
print(f" {ch:<10} {len(d):>12,} pairs from {len(fs)} file(s)")
return d
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--split", default="test")
ap.add_argument("--nshards", type=int, default=4)
ap.add_argument("--wide-rank-min", type=int, default=64,
help="from the wide channel keep only ranks >= this")
ap.add_argument("--per-s1", type=int, default=12, help="cap on NEW pairs per S1")
ap.add_argument("--rescue-rank-max", type=int, default=5,
help="unmeasured rescue channels are capped to this many per S1, "
"matching the k=5 that was measured for ename")
ap.add_argument("--max-total", type=int, default=60_000_000)
a = ap.parse_args()
have = pd.read_parquet(P.work("m4", f"{a.split}.parquet"), columns=["q", "c"])
print(f"model-4 already scored {len(have):,} pairs")
seen = set(map(tuple, have.to_numpy().tolist()))
# PRIORITY BY STRENGTH OF EVIDENCE, not by how many pairs a channel happens to emit.
#
# The first run of this script gave ename and nameonly the same priority and a cap of 24.
# Result: nameonly took 33.3M of the 41.6M budget and ename got 4.2M - so 80% of the GPU
# hours would have gone to the channel with NO measured recovery rate, and 10% to the one
# measured at 44%. A cap applied to a mixed pool silently ranks channels by verbosity.
#
# 0 ename character TF-IDF, MEASURED 44% recovery at k=5, 2.6% precision
# 1 nameonly my dense version of the same idea, UNMEASURED - capped to its top 5 so
# it can add diversity without dominating
# 2 e5_small tail ranks 64-99, bounded at <=0.095 points by measurement
PRIO = {"ename": 0, "nameonly": 1}
parts = []
for ch in RESCUE:
d = load_channel(a.split, ch)
if d is None:
continue
if ch != "ename" and a.rescue_rank_max:
before = len(d)
d = d[d["r"] < a.rescue_rank_max]
print(f" {ch}: kept {len(d):,} of {before:,} at rank < {a.rescue_rank_max}")
d = d.copy()
d["src"] = ch
d["prio"] = PRIO.get(ch, 1)
parts.append(d[["q", "c", "s", "r", "src", "prio"]])
wide = load_channel(a.split, "e5_small")
if wide is not None:
w = wide[wide["r"] >= a.wide_rank_min].copy()
print(f" e5_small kept {len(w):,} at rank >= {a.wide_rank_min}")
w["src"] = "e5_small_tail"
w["prio"] = 2
parts.append(w[["q", "c", "s", "r", "src", "prio"]])
if not parts:
sys.exit("no rescue channels found - run 08_embed.py and 03_retrieve.py first")
cand = pd.concat(parts, ignore_index=True)
cand = cand.sort_values(["prio", "s"], ascending=[True, False]) \
.drop_duplicates(["q", "c"], keep="first")
print(f"\nunion of rescue channels: {len(cand):,} unique pairs")
key = list(map(tuple, cand[["q", "c"]].to_numpy().tolist()))
fresh = np.fromiter((k not in seen for k in key), bool, len(key))
cand = cand[fresh]
print(f" not already scored by model-4: {len(cand):,} ({fresh.mean():.1%})")
# These enter as a GUARANTEED UNION, never through rank fusion. They are address-less
# records the other retrievers rank low; under RRF with one channel voting they land
# below the K cut and the whole channel is thrown away. Priority 0 keeps them.
cand = cand.sort_values(["q", "prio", "s"], ascending=[True, True, False])
cand = cand.groupby("q", sort=False).head(a.per_s1)
print(f" after per-S1 cap of {a.per_s1}: {len(cand):,} over {cand.q.nunique():,} S1")
print(f" by source: {cand.src.value_counts().to_dict()}")
if len(cand) > a.max_total:
cand = cand.sort_values(["prio", "s"], ascending=[True, False]).head(a.max_total)
print(f" TRIMMED to --max-total {a.max_total:,}")
d = os.path.dirname(P.work("prep", a.split, "_"))
s1 = pd.read_parquet(os.path.join(d, "source1.parquet"))
pool = pd.read_parquet(os.path.join(d, "pool.parquet"))
qi, ci = cand["q"].to_numpy(), cand["c"].to_numpy()
qn, qa, qc = (s1[k].to_numpy() for k in ("business_name", "business_address", "country"))
pn, pa, pc = (pool[k].to_numpy() for k in ("business_name", "business_address", "country"))
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)
rate = 2400 * a.nshards
print(f"\n{len(work):,} pairs to score. At ~2,400 pairs/s per lane x {a.nshards} lanes "
f"= {len(work)/rate/3600:.1f} h wall clock.")
shards = F.split_shards(work, a.nshards)
man = []
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
man.append({"shard": i, "n": len(sh), "mb": round(mb, 1),
"file": os.path.basename(p)})
print(f" shard {i}: {len(sh):>9,} pairs {mb:6.1f} MB")
import json
with open(P.work("shards", f"{a.split}_manifest.json"), "w") as fh:
json.dump({"split": a.split, "nshards": a.nshards, "total": len(work),
"shards": man}, fh, indent=1)
print(f"\nwrote {P.work('shards', f'{a.split}_manifest.json')}")
if __name__ == "__main__":
main()
|