Download mini_lib.py from LocalLLaMA/browsecomp-plus-mini: direct link, hf CLI and curl.
- Browser
- Download file 8.86 kB
-
https://huggingface.co/datasets/LocalLLaMA/browsecomp-plus-mini/resolve/main/mini_lib.py
- Command line
-
hf download hf://datasets/LocalLLaMA/browsecomp-plus-mini/mini_lib.py
-
curl -L -o mini_lib.py https://huggingface.co/datasets/LocalLLaMA/browsecomp-plus-mini/resolve/main/mini_lib.py
8.86 kB
| """Shared helpers for browsecomp-plus-mini: loading the run matrix, system weights, | |
| weighted rank metrics, pair agreement by gap, and the select/validate/test protocol. | |
| Input (not redistributed here): a 0/1 matrix `matrix.csv` (rows = BrowseComp-Plus query_id, | |
| columns = published runs, 1 = answer matched the gold answer under normalized exact match, | |
| see grader.py), `runs.json` (one record per run: run, system, ...), and | |
| `short_single_gold.json` ({query_id: bool}, true when the gold answer is a short single entity). | |
| """ | |
| import csv, json, collections | |
| import numpy as np | |
| def load(dirpath): | |
| rows = list(csv.reader(open(f"{dirpath}/matrix.csv"))) | |
| runs = rows[0][1:] | |
| qids = [r[0] for r in rows[1:]] | |
| X = np.array([[float(v) for v in r[1:]] for r in rows[1:]]).T # runs x queries | |
| meta = {m["run"]: m for m in json.load(open(f"{dirpath}/runs.json"))} | |
| systems = [meta[r]["system"] for r in runs] | |
| k = collections.Counter(systems) | |
| w = np.array([1.0 / k[s] for s in systems]) # 1/k per system | |
| short = json.load(open(f"{dirpath}/short_single_gold.json")) | |
| pool = np.array([bool(short[q]) for q in qids]) | |
| return dict(runs=runs, qids=qids, X=X, full=X.mean(1), systems=systems, w=w, pool=pool, meta=meta) | |
| def rankdata(a): | |
| order = np.argsort(a, kind="mergesort") | |
| r = np.empty(len(a)); r[order] = np.arange(len(a)) | |
| # average ties | |
| vals, inv = np.unique(a, return_inverse=True) | |
| sums = np.bincount(inv, r); cnts = np.bincount(inv) | |
| return (sums / cnts)[inv] | |
| def wpearson(a, b, w): | |
| am = (w * a).sum() / w.sum(); bm = (w * b).sum() / w.sum() | |
| da, db = a - am, b - bm | |
| den = np.sqrt((w * da * da).sum() * (w * db * db).sum()) | |
| return float((w * da * db).sum() / den) if den > 0 else 0.0 | |
| def wspearman(a, b, w): | |
| """weighted Spearman: weighted Pearson correlation of the (unweighted) ranks""" | |
| return wpearson(rankdata(a), rankdata(b), w) | |
| def wspearman_cols(S, f, w): | |
| """weighted Spearman of each column of S (runs x candidates) against f""" | |
| rf = rankdata(f) | |
| R = np.apply_along_axis(rankdata, 0, S) | |
| wn = w / w.sum() | |
| Rc = R - (wn[:, None] * R).sum(0); fc = rf - (wn * rf).sum() | |
| num = (wn[:, None] * Rc * fc[:, None]).sum(0) | |
| den = np.sqrt((wn[:, None] * Rc ** 2).sum(0) * (wn * fc ** 2).sum()) | |
| return np.where(den > 0, num / np.where(den > 0, den, 1), 0.0) | |
| BANDS = [("more than 10 points", 0.10, 9.0), ("5 to 10 points", 0.05, 0.10), ("2 to 5 points", 0.02, 0.05), ("under 2 points", 0.0, 0.02)] | |
| def pair_agreement(full, sub, w, idx, systems=None, cross_system_only=False): | |
| """weighted share of run pairs ordered the same way by the subset, by size of the full-benchmark gap. | |
| A tie on the subset counts as not agreeing.""" | |
| out = [] | |
| idx = list(idx) | |
| for name, lo, hi in BANDS: | |
| ok = tot = 0.0; n = 0 | |
| for a_ in range(len(idx)): | |
| for b_ in range(a_ + 1, len(idx)): | |
| i, j = idx[a_], idx[b_] | |
| if cross_system_only and systems[i] == systems[j]: | |
| continue | |
| g = abs(full[i] - full[j]) | |
| if lo <= g < hi: | |
| pw = w[i] * w[j]; n += 1; tot += pw | |
| if (full[i] - full[j]) * (sub[i] - sub[j]) > 0: | |
| ok += pw | |
| out.append(dict(gap=name, n_pairs=n, agreement_pct=round(100 * ok / tot, 1) if tot else None)) | |
| return out | |
| def calibrated_mae(full, sub, w, fit_idx, eval_idx): | |
| co = np.polyfit(sub[fit_idx], full[fit_idx], 1, w=np.sqrt(w[fit_idx])) | |
| pred = np.polyval(co, sub[eval_idx]) | |
| return float((w[eval_idx] * np.abs(pred - full[eval_idx])).sum() / w[eval_idx].sum()), co | |
| def split_systems(systems, full, w, seed): | |
| """three-way split of SYSTEMS, stratified by system accuracy: sort systems by mean full score, | |
| take them in blocks of three and deal one to each split in random order.""" | |
| rng = np.random.default_rng(seed) | |
| sysacc = collections.defaultdict(list) | |
| for s, f in zip(systems, full): | |
| sysacc[s].append(f) | |
| order = sorted(sysacc, key=lambda s: np.mean(sysacc[s])) | |
| parts = ([], [], []) | |
| for b in range(0, len(order), 3): | |
| block = order[b:b + 3] | |
| for p, s in zip(rng.permutation(3), block): | |
| parts[p].append(s) | |
| return parts # select, validate, test | |
| def run_idx(systems, sysset): | |
| return np.array([i for i, s in enumerate(systems) if s in sysset]) | |
| def objective(S, f, w, mae_pen=1.0): | |
| rho = wspearman_cols(S, f, w) | |
| mae = (w[:, None] * np.abs(S - f[:, None])).sum(0) / w.sum() | |
| return rho - mae_pen * mae | |
| def greedy(D, idx, n, cand_mask): | |
| X, full, w = D["X"][idx], D["full"][idx], D["w"][idx] | |
| p = (w[:, None] * X).sum(0) / w.sum() | |
| var = p * (1 - p) | |
| ok = cand_mask & (p > 0) & (p < 1) | |
| pool = list(np.where(ok)[0]) | |
| sub = sorted(pool, key=lambda t: -var[t])[:3] | |
| pool = [t for t in pool if t not in sub] | |
| while len(sub) < n: | |
| base = X[:, sub].sum(1) | |
| S = (base[:, None] + X[:, pool]) / (len(sub) + 1) | |
| j = int(np.argmax(objective(S, full, w))) | |
| sub.append(pool.pop(j)) | |
| return sub | |
| def climb(D, idx, start, cand_mask, rounds=6): | |
| X, full, w = D["X"][idx], D["full"][idx], D["w"][idx] | |
| p = (w[:, None] * X).sum(0) / w.sum() | |
| allowed = np.where(cand_mask & (p > 0) & (p < 1))[0] | |
| sub = list(start); n = len(sub) | |
| cur = float(objective((X[:, sub].mean(1))[:, None], full, w)[0]) | |
| for _ in range(rounds): | |
| moved = False | |
| for i in range(n): | |
| rest = [t for t in allowed if t not in sub] | |
| base = X[:, sub].sum(1) - X[:, sub[i]] | |
| S = (base[:, None] + X[:, rest]) / n | |
| sc = objective(S, full, w) | |
| j = int(np.argmax(sc)) | |
| if sc[j] > cur + 1e-9: | |
| sub[i] = rest[j]; cur = float(sc[j]); moved = True | |
| if not moved: | |
| break | |
| return sub | |
| def candidates(D, sel_idx, n, cand_mask, seed, restarts=6): | |
| rng = np.random.default_rng(seed) | |
| allowed = np.where(cand_mask)[0] | |
| c = [greedy(D, sel_idx, n, cand_mask)] | |
| c.append(climb(D, sel_idx, c[0], cand_mask)) | |
| X = D["X"][sel_idx] | |
| p = X.mean(0) | |
| allowed = [t for t in allowed if 0 < p[t] < 1] | |
| for _ in range(restarts): | |
| c.append(climb(D, sel_idx, list(rng.choice(allowed, n, replace=False)), cand_mask)) | |
| return c | |
| def rho_on(D, sub, idx): | |
| return wspearman(D["X"][idx][:, sub].mean(1), D["full"][idx], D["w"][idx]) | |
| def stratified(D, idx, n, cand_mask, nbins): | |
| """difficulty-stratified pick: split candidate queries into `nbins` bands of solve rate and take the | |
| most discriminating queries in each (discrimination = weighted point-biserial correlation between | |
| solving the query and the run's full-benchmark score).""" | |
| X, f, w = D["X"][idx], D["full"][idx], D["w"][idx] | |
| p = (w[:, None] * X).sum(0) / w.sum() | |
| fc = f - (w * f).sum() / w.sum(); Xc = X - p | |
| disc = (w[:, None] * Xc * fc[:, None]).sum(0) / np.sqrt((w[:, None] * Xc ** 2).sum(0) * (w * fc ** 2).sum() + 1e-12) | |
| ok = np.where(cand_mask & (p > 0.02) & (p < 0.98))[0] | |
| qs = np.quantile(p[ok], np.linspace(0, 1, nbins + 1)) | |
| per = [n // nbins + (1 if i < n % nbins else 0) for i in range(nbins)] | |
| sel = [] | |
| for b in range(nbins): | |
| inb = ok[(p[ok] >= qs[b]) & ((p[ok] < qs[b + 1]) if b < nbins - 1 else (p[ok] <= qs[b + 1]))] | |
| sel += [int(t) for t in inb[np.argsort(-disc[inb])][:per[b]] if t not in sel] | |
| return sel | |
| def methods(seed): | |
| """candidate selection methods; each maps (D, run_idx, n, mask) -> list of query indices""" | |
| m = {f"stratified_{b}": (lambda b: lambda D, i, n, c: stratified(D, i, n, c, b))(b) for b in (1, 2, 3, 4, 5)} | |
| m["greedy"] = lambda D, i, n, c: greedy(D, i, n, c) | |
| m["greedy_climb"] = lambda D, i, n, c: climb(D, i, greedy(D, i, n, c), c) | |
| for r in range(3): | |
| def f(D, i, n, c, r=r): | |
| rng = np.random.default_rng(1000 * seed + r) | |
| p = D["X"][i].mean(0) | |
| allowed = [t for t in np.where(c)[0] if 0 < p[t] < 1] | |
| return climb(D, i, list(rng.choice(allowed, n, replace=False)), c) | |
| m[f"climb_restart_{r}"] = f | |
| return m | |
| def honest_pick(D, n, seed): | |
| """SELECT fits every method; VALIDATE chooses the method; the chosen method is refit on SELECT+VALIDATE; | |
| TEST is only used to score the result.""" | |
| S, V, T = split_systems(D["systems"], D["full"], D["w"], seed) | |
| si, vi, ti = run_idx(D["systems"], S), run_idx(D["systems"], V), run_idx(D["systems"], T) | |
| M = methods(seed) | |
| val = {k: rho_on(D, f(D, si, n, D["pool"]), vi) for k, f in M.items()} | |
| best = max(val, key=val.get) | |
| sub = M[best](D, np.concatenate([si, vi]), n, D["pool"]) | |
| return dict(subset=sub, method=best, validate_rho=val, split=(S, V, T), idx=(si, vi, ti)) | |