File size: 5,861 Bytes
3037e25 | 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 | #!/usr/bin/env python
"""MTEB-lite (eng): score a model on the selected items only and estimate its MTEB(eng, v2) scores.
Uses data/mteb_lite/MTEB_lite_eng.json (from mteb_lite_select.py): for every task the selected item ids
and the linear calibration (full ~ a + b * subset score). The model is loaded and prompted exactly as in
mteb_lite_score.py / run_mteb_english.py. Retrieval queries are ranked over their own candidate lists +
the shared random docs (as in the pool scoring), so subset scores are the ones the selection used.
python scripts/mteb_lite_eval.py --model hf:Qwen/Qwen3-Embedding-0.6B --name qwen3-0.6b
python scripts/mteb_lite_eval.py --model native:<export dir> --name NAME
python scripts/mteb_lite_eval.py --manifest data/mteb_lite_v2/MTEB_lite_eng.json --model ... --name NAME (v2)
python scripts/mteb_lite_eval.py --suite ara --manifest data/mteb_lite_ar_v2/MTEB_lite_ara.json --model ... --name NAME
Prints per-task subset / estimated scores and the estimated macro (mean over the 8 task types) and mean;
writes outputs/mteb_lite/eval/<NAME>.json.
"""
from __future__ import annotations
import os as _os
if _os.environ.get("ADIP_HF_ONLINE") != "1":
_os.environ.setdefault("HF_HUB_OFFLINE", "1")
_os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
_os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
import argparse
import json
import sys
import time
from collections import defaultdict
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent / "src"))
import mteb_lite_lib as L # noqa: E402
from mteb_lite_score import load_model # noqa: E402
def v2_estimate(doc: dict, ts: L.TaskScores) -> tuple[float, float]:
"""(subset statistic, estimated full score) for a v2 selection doc (mean / p-IRT / gp / set metric)."""
a, b = doc["calibration"]["a"], doc["calibration"]["b"]
if doc["estimator"] == "set_metric":
s = float(ts.subset(np.arange(ts.N), exact=True)[0])
return s, a + b * s
from mteb_lite_select_v2 import map_theta, predict_items
pos = {i: j for j, i in enumerate(ts.ids)}
y = np.array([ts.Y[0, pos[i]] for i in doc["ids"]])
y = np.where(np.isnan(y), np.nanmean(y) if np.isfinite(np.nanmean(y)) else 0.0, y)
w = np.array(doc["weights"])
est_mean = float((w * y).sum())
pp = doc["item_model"]
model = {k: (np.array(v) if isinstance(v, list) else v) for k, v in pp.items()}
ppos = {i: j for j, i in enumerate(doc["pool_ids"])}
sel = np.array([ppos[i] for i in doc["ids"]])
u = np.array(doc["pool_weights"])
th = map_theta(model, y, sel)
pred = predict_items(model, th)
rest = np.ones(len(u), bool)
rest[sel] = False
est_pirt = float((u[sel] * y).sum() + (u[rest] * pred[rest]).sum())
s = {"mean": est_mean, "pirt": est_pirt, "gp": 0.5 * (est_mean + est_pirt)}[doc["estimator"]]
return s, a + b * s
def main() -> None:
L.configure(L.suite_from_argv())
ap = argparse.ArgumentParser()
ap.add_argument("--suite", choices=["eng", "ara"], default="eng")
ap.add_argument("--model", required=True)
ap.add_argument("--name", required=True)
ap.add_argument("--manifest", default=str(L.LITE / L.SUITES[L.SUITE]["manifest"]),
help="v1 (data/mteb_lite*/) or v2 (data/mteb_lite*_v2/) manifest")
ap.add_argument("--tasks", default=None)
ap.add_argument("--batch-size", type=int, default=64)
ap.add_argument("--max-length", type=int, default=L.SUITES[L.SUITE]["max_length"])
ap.add_argument("--out", default=str(L.OUT / "eval"))
args = ap.parse_args()
man = json.loads(Path(args.manifest).read_text())
tasks = args.tasks.split(",") if args.tasks else list(man["tasks"])
model = load_model(args.model, args.max_length)
rows, t_all = {}, time.time()
for t in tasks:
spec = man["tasks"][t]
doc = (json.loads((Path(args.manifest).parent / spec["selection"]).read_text()) if "selection" in spec
else spec)
t0 = time.time()
pool = L.restrict_pool(L.load_pool(t), doc["ids"])
res, emb = L.score_pool(pool, model, batch_size=args.batch_size)
ts = L.TaskScores(t, [res], [emb], pool)
if "estimator" in doc:
s, est = v2_estimate(doc, ts)
else:
s = float(ts.subset(np.arange(ts.N), exact=True)[0])
est = doc["calibration"]["a"] + doc["calibration"]["b"] * s
rows[t] = {"type": spec["type"], "subset_score": s, "estimated_full": est, "n_items": ts.N,
"seconds": time.time() - t0}
print(f"[lite-eval] {args.name} {t:42s} subset {s:.4f} -> est. {est:.4f} ({time.time() - t0:.0f}s)",
flush=True)
by = defaultdict(list)
for r in rows.values():
by[r["type"]].append(100 * r["estimated_full"])
res = {"model": args.model, "name": args.name, "manifest": args.manifest, "n_tasks": len(rows),
"rows": rows, "by_type": {k: float(np.mean(v)) for k, v in by.items()},
"seconds": time.time() - t_all}
if len(rows) == len(man["tasks"]):
res["estimated_macro"] = float(np.mean(list(res["by_type"].values())))
res["estimated_mean"] = float(np.mean([100 * r["estimated_full"] for r in rows.values()]))
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
(out / f"{args.name}.json").write_text(json.dumps(res, indent=1))
for k, v in sorted(res["by_type"].items()):
print(f"[lite-eval] {args.name} {k:20s} {v:6.2f}")
print(f"[lite-eval] {args.name}: estimated {'MTEB(eng, v2)' if args.suite == 'eng' else 'Arabic MMTEB (42)'} macro {res.get('estimated_macro')} "
f"mean {res.get('estimated_mean')} ({len(rows)} tasks, {res['seconds']:.0f}s)", flush=True)
if __name__ == "__main__":
main()
|