File size: 23,738 Bytes
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
 
 
 
 
 
 
f8f07da
 
3037e25
ac198e3
 
 
 
 
 
 
 
 
 
 
3037e25
 
 
 
ac198e3
 
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
3037e25
 
 
 
 
ac198e3
3037e25
ac198e3
 
 
3037e25
 
 
 
 
 
 
 
ac198e3
 
 
 
 
 
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
 
3037e25
 
 
 
 
 
 
 
ac198e3
3037e25
 
 
 
 
 
ac198e3
 
3037e25
 
 
ac198e3
 
3037e25
 
ac198e3
 
 
 
 
 
 
 
 
 
 
 
3037e25
 
 
 
 
 
ac198e3
 
 
 
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3037e25
ac198e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3037e25
 
ac198e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3037e25
 
 
 
ac198e3
 
3037e25
 
 
 
 
 
 
ac198e3
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
3037e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac198e3
 
 
3037e25
 
 
ac198e3
 
3037e25
ac198e3
 
 
 
 
 
 
 
 
 
 
 
3037e25
 
 
ac198e3
 
 
 
f8f07da
 
 
 
 
 
ac198e3
 
 
3037e25
 
 
 
 
 
ac198e3
 
f8f07da
ac198e3
3037e25
ac198e3
 
 
3037e25
 
 
 
 
 
 
 
 
ac198e3
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
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#!/usr/bin/env python
"""Build the public, ID-only MTEB-lite release folder (Hugging Face dataset repo ADIP-QCRI/MTEB-lite).

  python scripts/mteb_lite_release.py build      [--out outputs/hf_upload/MTEB-lite]   specs, manifests, docs, code
  python scripts/mteb_lite_release.py roundtrip  [--jobs 16]   reconstruct every task with mteb_lite.py from the
                                                 original datasets and compare with our local pools (texts must match)
  python scripts/mteb_lite_release.py stats      texts / tokens / est. encode minutes per config (Qwen3 tokenizer)

Configs: eng (data/mteb_lite_v2, K=100), eng-super (data/mteb_lite_super_v2, K=20); ara / ara-super slot in the
same way (CONFIGS) once the Arabic selection exists. No text from any dataset is written: only ids, row indices,
qrels / label weights needed for scoring, selection weights and calibration coefficients.
"""
from __future__ import annotations

import argparse
import csv
import json
import shutil
import sys
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import mteb_lite_lib as L  # noqa: E402

REPO = L.REPO
OUT = REPO / "outputs" / "hf_upload" / "MTEB-lite"
ALL_CONFIGS = {  # config -> (suite, selection dir, validation report stem, selection version)
    "eng@v2": ("eng", REPO / "data" / "mteb_lite_v2", REPO / "outputs" / "mteb_lite" / "selection_report_v2", "v2"),
    "eng-super@v2": ("eng", REPO / "data" / "mteb_lite_super_v2", REPO / "outputs" / "mteb_lite" / "selection_report_v2_super", "v2"),
    "eng@v3": ("eng", REPO / "data" / "mteb_lite_v3", REPO / "outputs" / "mteb_lite" / "selection_report_v3", "v3"),
    "eng-super@v3": ("eng", REPO / "data" / "mteb_lite_super_v3", REPO / "outputs" / "mteb_lite" / "selection_report_v3_super", "v3"),
    "ara@v3": ("ara", REPO / "data" / "mteb_lite_ar", REPO / "outputs" / "mteb_lite_ar" / "selection_report", "v3"),
    "ara-super@v3": ("ara", REPO / "data" / "mteb_lite_ar_super", REPO / "outputs" / "mteb_lite_ar" / "selection_report_super", "v3"),
    "ara@v4": ("ara", REPO / "data" / "mteb_lite_ar_v4", REPO / "outputs" / "mteb_lite_ar" / "selection_report_v4", "v4"),
    "ara-super@v4": ("ara", REPO / "data" / "mteb_lite_ar_super_v4", REPO / "outputs" / "mteb_lite_ar" / "selection_report_v4_super", "v4"),
}
CONFIGS: dict = {}     # config -> (suite, selection dir, report stem, version); set by set_configs()


def set_configs(names: list[str], versions: dict) -> None:
    """versions: {config: selection version} (default v3 for ara*, v2 for eng*)."""
    CONFIGS.clear()
    for n in names:
        v = versions.get(n, "v3" if n.startswith("ara") else "v2")
        CONFIGS[n] = ALL_CONFIGS[f"{n}@{v}"]


BENCH = {"eng": "MTEB(eng, v2)", "ara": "Arabic MMTEB (42 test tasks)"}
TOK_PER_S = 30000          # measured: Qwen3-Embedding-0.6B in our MTEB runs, 25-33k tokens/s on one GPU
CODE = ["mteb_lite_lib.py", "mteb_lite_pool.py", "mteb_lite_score.py", "mteb_lite_score_merges.py",
        "mteb_lite_select.py", "mteb_lite_select_v2.py", "mteb_lite_eval.py", "mteb_lite_public_full.py",
        "mteb_lite_score_list.sh", "mteb_lite_release.py", "mteb_lite_release_docs.py",
        "mteb_lite_release_models.py"]


def manifest_of(sel_dir: Path, suite: str) -> dict:
    return json.loads((sel_dir / L.SUITES[suite]["manifest"]).read_text())


def task_release_spec(task: str, doc: dict, pool: dict, suite: str) -> dict:
    """ID-only description of one task's selected items (+ everything scoring needs)."""
    t = L.get_task(task)
    rp = L.restrict_pool(pool, doc["ids"])
    ty = pool["type"]
    spec = {"task": task, "type": ty, "main_score": pool["main_score"], "eval_split": pool["eval_split"],
            "hf_subsets": pool["hf_subset"] if isinstance(pool["hf_subset"], list) else [pool["hf_subset"]],
            "dataset": {"path": t.metadata.dataset.get("path"), "revision": t.metadata.dataset.get("revision")},
            "K": len(doc["ids"]), "ids": doc["ids"],
            "estimator": {"mean": "weighted_mean", "pirt": "pirt", "gp": "gp"}.get(doc["estimator"], "set_metric"),
            "calibration": doc["calibration"], "item_key": L.ITEM_KEY[ty]}
    if suite == "eng":
        spec["benchmark"] = L.BENCHMARK
    else:
        spec["hf_subsets_filter"] = spec["hf_subsets"]
    if doc["estimator"] in ("mean", "pirt", "gp"):
        spec["weights"] = doc["weights"]
        if doc["estimator"] != "mean":      # p-IRT: item ids + item parameters of the whole candidate pool
            spec["irt"] = {"pool_ids": doc["pool_ids"], "pool_weights": doc["pool_weights"],
                           "item_model": doc["item_model"], "theta_scale": doc.get("theta_scale")}
    elif doc["estimator"] != "set_metric":
        raise ValueError(f"{task}: estimator {doc['estimator']} not supported by the release loader")
    if ty == "Reranking" and "ndcg" in str(pool["main_score"]).lower():
        spec["item_key"] = "ndcg10"
    if ty == "Retrieval":
        spec["candidates"] = rp["candidates"]
        spec["qrels"] = rp["qrels"]
        spec["ignore_identical_ids"] = rp.get("ignore_identical_ids", False)
        # content hashes: some mteb loaders number queries / docs via enumerate(set(...)) (e.g. MintakaRetrieval), so
        # their ids change with PYTHONHASHSEED; the loader maps texts by hash and keeps these ids (qrels stay valid)
        import hashlib
        h = lambda x: hashlib.sha1(x.encode("utf-8")).hexdigest()[:16]  # noqa: E731
        spec["text_sha1"] = {"queries": {q: h(v) for q, v in rp["queries"].items()},
                             "docs": {d: h(v) for d, v in rp["corpus"].items()}}
        if "random_docs_by_subset" in rp:
            spec["random_docs_by_subset"] = rp["random_docs_by_subset"]
            spec["query_subset"] = rp["query_subset"]
        else:
            spec["random_docs"] = rp["random_docs"]
    elif ty == "Classification":
        if "groups" in pool:
            groups = {k: {"train_rows": g["train"]["orig_index"], "experiments": g["experiments"]}
                      for k, g in pool["groups"].items()}
        else:
            groups = {"": {"train_rows": pool["train"]["orig_index"], "experiments": pool["experiments"]}}
        spec.update({"groups": groups, "samples_per_label": pool.get("samples_per_label"),
                     "n_experiments": pool.get("n_experiments"), "undersampling_seed": 42,
                     "logreg": {"random_state": 42, "max_iter": 100}})
    elif ty == "PairClassification":
        spec["label_weights"] = pool.get("label_weights")
    elif ty == "Clustering":
        spec["n_levels"] = pool["n_levels"]
        spec["max_depth"] = getattr(t, "max_depth", None)
        spec["multi_set"] = any("subset" in x for x in pool["items"])
        spec["kmeans"] = {"runs": L.KMEANS_RUNS, "random_state": "run index", "n_init": 1, "max_iter": 100}
    elif ty == "BitextMining":
        tgt = {x["id"]: x["target"] for x in rp["items"]}
        spec["targets"] = [tgt[i] for i in doc["ids"]]                 # aligned with spec["ids"]
        spec["bitext_candidates"] = rp["bitext_candidates"]
        spec["parallel"] = pool.get("parallel", False)
    return spec


# ----------------------------------------------------------------------------- build
def build(out: Path) -> None:
    out.mkdir(parents=True, exist_ok=True)
    for cfg, (suite, sel_dir, rep, ver) in CONFIGS.items():
        L.configure(suite)
        man = manifest_of(sel_dir, suite)
        d = out / cfg
        if d.exists():
            shutil.rmtree(d)
        d.mkdir(parents=True)
        tasks, cal_rows = {}, []
        fulls = full_scores_of(suite)
        for task, m in man["tasks"].items():
            doc = json.loads((sel_dir / m["selection"]).read_text())
            spec = task_release_spec(task, doc, L.load_pool(task), suite)
            fit = calib_fit(task, doc, suite, fulls)
            spec["calibration"] = {**spec["calibration"], **fit}
            (d / f"{task}.json").write_text(json.dumps(spec))
            tasks[task] = {"type": spec["type"], "main_score": spec["main_score"], "K": spec["K"],
                           "estimator": spec["estimator"], "calibration": spec["calibration"],
                           "dataset": spec["dataset"], "eval_split": spec["eval_split"], "hf_subsets": spec["hf_subsets"]}
            cal_rows.append({"task": task, "task_type": spec["type"], "main_score": spec["main_score"],
                             "estimator": spec["estimator"], "K": spec["K"], "a": spec["calibration"]["a"],
                             "b": spec["calibration"]["b"], "n_fit_models": fit["n_fit"], "fit_pearson_r": fit["fit_r"],
                             "fit_residual_sd": fit["fit_resid_sd"],
                             "fitted_on": f"models.csv rows with role_{cfg} = selection+calibration+LOMO-held-out "
                                          "(those with a full score for this task)"})
        with open(d / "calibration.csv", "w", newline="") as f:
            w = csv.DictWriter(f, fieldnames=list(cal_rows[0]))
            w.writeheader()
            w.writerows(cal_rows)
        import mteb
        manifest = {"name": "MTEB-lite", "config": cfg, "benchmark": BENCH[suite],
                    "source_benchmark": L.BENCHMARK if suite == "eng" else "MMTEB Arabic subsets",
                    "mteb_version": mteb.__version__, "K": man["K"], "K_set": man.get("K_set", man["K"]),
                    "n_tasks": len(tasks), "aggregate": {"macro": "mean over task types of the mean over tasks (x100)",
                                                         "mean": "mean over tasks (x100)"},
                    "method": man["method"], "selection_version": ver,
                    "n_reference_models": len(man["reference_models"]), "reference_models": man["reference_models"],
                    "calibration": "full_estimate = a + b * subset_statistic per task (see calibration.csv)",
                    "tasks": tasks}
        (d / "manifest.json").write_text(json.dumps(manifest, indent=1))
        vd = out / "validation"
        vd.mkdir(exist_ok=True)
        for ext in (".md", ".json"):        # no internal absolute paths in the public copies
            txt = rep.with_suffix(ext).read_text().replace(str(REPO) + "/", "").replace(str(REPO), ".")
            (vd / f"{cfg}{ext}").write_text(txt)
        print(f"[release] {cfg}: {len(tasks)} tasks -> {d}")
    shutil.copy(HERE / "mteb_lite_hf" / "mteb_lite.py", out / "mteb_lite.py")
    cd = out / "code"
    if cd.exists():
        shutil.rmtree(cd)
    cd.mkdir()
    for f in CODE:
        shutil.copy(HERE / f, cd / f)
    write_models_csv(out)
    write_docs(out)
    for pc in out.rglob("__pycache__"):
        shutil.rmtree(pc, ignore_errors=True)


# ----------------------------------------------------------------------------- calibration / models.csv
_FULLS: dict = {}


def full_scores_of(suite: str) -> dict:
    """{model: {task: full main score}} of every scored model of the suite (as the selection used them)."""
    if suite not in _FULLS:
        import mteb_lite_select as S1
        import mteb_lite_select_v2 as S2
        L.configure(suite)
        names = sorted(p.name for p in L.SCORES.iterdir() if p.is_dir())
        csvp = str(L.LITE / "public_full.csv")
        _FULLS[suite] = S1.full_scores(names, csvp) if suite == "eng" else S2.ara_full_scores(names, csvp)
    return _FULLS[suite]


def calib_fit(task: str, doc: dict, suite: str, fulls: dict) -> dict:
    """Goodness of the per-task linear calibration on the reference models it was fitted on."""
    import numpy as np
    import mteb_lite_select_v2 as S2
    L.configure(suite)
    names = [n for n in doc["reference_models"] if task in fulls.get(n, {})]
    res, embs = [], []
    for n in names:
        r, e = L.load_scores(n, task)
        res.append(r)
        embs.append(e)
    pool = L.load_pool(task)
    ts = L.TaskScores(task, res, embs, pool)
    f = np.array([fulls[n][task] for n in names])
    cols = np.array([ts.ids.index(i) for i in doc["ids"]])
    if doc["estimator"] == "set_metric":
        est = ts.subset(cols, exact=ts.type == "Clustering")
    else:
        Y = np.where(np.isnan(ts.Y), np.nan_to_num(np.nanmean(ts.Y, 0))[None], ts.Y)
        w = np.array(doc["weights"])
        est = (Y[:, cols] * w[None]).sum(1)
        if doc["estimator"] in ("pirt", "gp"):
            model = {k: (np.array(v) if isinstance(v, list) else v) for k, v in doc["item_model"].items()}
            u = np.array(doc["pool_weights"])
            ppos = {i: j for j, i in enumerate(doc["pool_ids"])}
            sel = np.array([ppos[i] for i in doc["ids"]])
            rest = np.ones(len(u), bool)
            rest[sel] = False
            pir = []
            for m in range(len(names)):
                th = S2.map_theta(model, Y[m, cols], sel)
                pir.append((u[sel] * Y[m, cols]).sum() + (u[rest] * S2.predict_items(model, th)[rest]).sum())
            pir = np.array(pir)
            est = pir if doc["estimator"] == "pirt" else 0.5 * (est + pir)
    a, b = doc["calibration"]["a"], doc["calibration"]["b"]
    pred = a + b * est
    ok = ~np.isnan(pred)
    r = float(np.corrcoef(pred[ok], f[ok])[0, 1]) if ok.sum() > 2 and pred[ok].std() > 0 else float("nan")
    return {"n_fit": int(ok.sum()), "fit_r": r, "fit_resid_sd": float(np.std(f[ok] - pred[ok]))}


def write_models_csv(out: Path) -> list[dict]:
    import mteb_lite_release_models as RM
    import mteb_lite_select_v2 as S2
    roles = {}
    for cfg, (suite, sel_dir, rep, ver) in CONFIGS.items():
        r = json.loads(rep.with_suffix(".json").read_text())
        combo = r["choice"].get("combo")
        agg = set((r["aggregate"]["family"].get(combo) or {}).get("models", []))
        roles[cfg] = (suite, set(r["reference"]), agg)
    suites = [su for su in ("eng", "ara") if L.SUITES[su]["out"].joinpath("scores").exists()]   # all scored suites
    scored = {}
    for su in suites:
        L.configure(su)
        scored[su] = {p.name for p in L.SCORES.iterdir() if p.is_dir()}
    fulls = {su: full_scores_of(su) for su in suites}
    names = sorted(set().union(*scored.values()))
    rows = []
    for n in names:
        d = RM.describe(n)
        row = {"internal_id": n, "display_name": d["display_name"], "family": d["family"], "type": d["type"],
               "merge_recipe": d["recipe"],
               "suites_scored": "/".join(su for su in suites if n in scored[su])}
        for su in suites:
            nt = len(fulls[su].get(n, {})) if n in scored[su] else 0
            row[f"full_score_source_{su}"] = ("" if not nt else ("official MTEB results" if d["type"] == "public"
                                                                 else "our runs (mteb 1.39.7)"))
            row[f"tasks_with_full_score_{su}"] = nt
        for cfg, (su, ref, agg) in roles.items():
            if n in ref:
                role = "selection+calibration+LOMO-held-out" + ("+aggregate-validation" if n in agg else "")
            elif n in scored[su] and fulls[su].get(n):
                role = "not used (family cap: <=3 per family)" if S2.family(n) in {S2.family(m) for m in ref} \
                    else "not used"
            elif n in scored[su]:
                role = "not used (no full scores)"
            else:
                role = "-"
            row[f"role_{cfg}"] = role
        rows.append(row)
    with open(out / "models.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0]))
        w.writeheader()
        w.writerows(rows)
    print(f"[release] models.csv: {len(rows)} models")
    return rows


# ----------------------------------------------------------------------------- stats / roundtrip
def stats() -> dict:
    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-Embedding-0.6B")
    res = {}
    for cfg, (suite, sel_dir, _, _v) in CONFIGS.items():
        L.configure(suite)
        man = manifest_of(sel_dir, suite)
        cap = L.SUITES[suite]["max_length"] or 8192
        n_items = n_texts = n_tok = 0
        per = {}
        for task, m in man["tasks"].items():
            doc = json.loads((sel_dir / m["selection"]).read_text())
            rp = L.restrict_pool(L.load_pool(task), doc["ids"])
            texts = list(dict.fromkeys(L.texts_to_encode(rp)))
            k = 0
            for s in range(0, len(texts), 4096):
                enc = tok([t for t, _ in texts[s:s + 4096]], add_special_tokens=False)["input_ids"]
                k += sum(min(len(e), cap) + (20 if r != "document" else 1) for e, (_, r) in zip(enc, texts[s:s + 4096]))
            per[task] = {"items": len(doc["ids"]), "texts": len(texts), "tokens": k}
            n_items += len(doc["ids"])
            n_texts += len(texts)
            n_tok += k
        res[cfg] = {"items": n_items, "texts": n_texts, "tokens": n_tok, "minutes_0.6B": n_tok / TOK_PER_S / 60,
                    "per_task": per}
        print(f"[release] {cfg}: {n_items} items, {n_texts} texts, {n_tok / 1e6:.2f}M tokens, "
              f"~{n_tok / TOK_PER_S / 60:.1f} min / 0.6B model")
    (OUT / "stats.json").write_text(json.dumps(res, indent=1)) if OUT.exists() else None
    return res


def canon(p: dict) -> dict:
    t = p["type"]
    if t == "Retrieval":
        return {"queries": p["queries"], "corpus": p["corpus"], "candidates": p["candidates"], "qrels": p["qrels"],
                "random": p.get("random_docs", p.get("random_docs_by_subset"))}
    c = {"items": [{k: ([str(v) for v in x[k]] if k == "labels" else (str(x[k]) if k == "label" else x[k]))
                    for k in sorted(x)} for x in sorted(p["items"], key=lambda x: x["id"])]}
    if t == "Classification":
        groups = p["groups"] if "groups" in p else {"": {"train": p["train"], "experiments": p["experiments"]}}
        c["train"] = {k: [list(g["train"]["text"]), [str(v) for v in g["train"]["label"]], g["experiments"]]
                      for k, g in groups.items()}
    if t == "BitextMining":
        c["texts"] = {k: p["bitext_texts"][k] for k in sorted(p["bitext_texts"])}
        c["cands"] = p["bitext_candidates"]
    return c


def roundtrip_one(cfg: str, task: str, out: str) -> dict:
    sys.path.insert(0, out)
    import mteb_lite as ML
    ML.HERE = Path(out)
    suite, sel_dir, _, _v = CONFIGS[cfg]
    L.configure(suite)
    spec = json.loads((Path(out) / cfg / f"{task}.json").read_text())
    rp = L.restrict_pool(L.load_pool(task), spec["ids"])
    try:
        got = ML.load_task(cfg, task, spec)
    except Exception as e:
        import traceback
        return {"cfg": cfg, "task": task, "ok": False, "error": f"{type(e).__name__}: {e}", "tb": traceback.format_exc()[-800:]}
    a, b = canon(rp), canon(got)
    bad = []
    for k in a:
        if a[k] != b.get(k):
            if isinstance(a[k], dict):
                diff = [x for x in a[k] if a[k][x] != b.get(k, {}).get(x)]
                bad.append(f"{k}: {len(diff)} differ, e.g. {diff[:3]}")
            elif isinstance(a[k], list):
                diff = [i for i, (x, y) in enumerate(zip(a[k], b.get(k, []))) if x != y]
                bad.append(f"{k}: {len(diff)} differ (len {len(a[k])} vs {len(b.get(k, []))}), e.g. {diff[:3]}")
            else:
                bad.append(k)
    n = len(rp["queries"]) if rp["type"] == "Retrieval" else len(rp["items"])
    return {"cfg": cfg, "task": task, "ok": not bad, "n": n, "mismatch": bad}


def roundtrip(out: Path, jobs: int, cfgs: list[str]) -> None:
    from concurrent.futures import ProcessPoolExecutor
    work = []
    for cfg in cfgs:
        man = json.loads((out / cfg / "manifest.json").read_text())
        work += [(cfg, t, str(out)) for t in man["tasks"]]
    res = []
    with ProcessPoolExecutor(jobs) as ex:
        for r in ex.map(roundtrip_one, *zip(*work)):
            res.append(r)
            print(f"[roundtrip] {r['cfg']:10s} {r['task']:42s} {'OK' if r['ok'] else 'MISMATCH'} "
                  f"{r.get('n', '')} {r.get('mismatch') or r.get('error') or ''}", flush=True)
    bad = [r for r in res if not r["ok"]]
    (out.parent / "MTEB-lite_roundtrip.json").write_text(json.dumps(res, indent=1))
    print(f"[roundtrip] {len(res) - len(bad)}/{len(res)} tasks identical; mismatches: {len(bad)}")


# ----------------------------------------------------------------------------- docs
NOTES: dict = {}


def write_docs(out: Path) -> None:
    from mteb_lite_release_docs import readme, selection_md
    st = json.loads((out / "stats.json").read_text()) if (out / "stats.json").exists() else {}
    st = {k: v for k, v in st.items() if k in CONFIGS}
    reps = {cfg: json.loads(r.with_suffix(".json").read_text()) for cfg, (_, _, r, _v) in CONFIGS.items()}
    mans = {cfg: json.loads((out / cfg / "manifest.json").read_text()) for cfg in CONFIGS}
    models = list(csv.DictReader(open(out / "models.csv")))
    cal = {}
    for cfg in CONFIGS:
        rows = list(csv.DictReader(open(out / cfg / "calibration.csv")))
        for r in rows:
            for k in ("fit_pearson_r", "fit_residual_sd"):
                r[k] = float(r[k])
        cal[cfg] = rows
    notes = dict(NOTES)
    if any(c.startswith("ara") for c in CONFIGS):
        notes.setdefault("ara", ARA_NOTE)
    (out / "README.md").write_text(readme(st, reps, mans, models, cal, notes))
    (out / "SELECTION.md").write_text(selection_md(reps, mans))


ARA_NOTE = """
**Arabic configs.** These are the 42 Arabic MMTEB test tasks (7 bitext mining, 14 classification, 2 clustering, 2 pair
classification, 2 reranking, 11 retrieval, 4 STS). Each task is restricted to its Arabic hf_subsets (Arabic, Arabic dialects,
and Arabic-English pairs) and to the split our Arabic MMTEB evaluation uses, and the task score is the mean over subsets.
Texts are capped at 512 tokens. The MIRACLReranking pool was cut to 300 queries (encode cost). The full-task scores of the
8 multilingual public reference models (multilingual-e5 small / base / large, bge-m3, LaBSE, embeddinggemma-300m,
paraphrase-multilingual MiniLM-L12 / mpnet-base) are our own complete runs of all 42 tasks with the same subsets and splits;
the English-only public models enter only the tasks with official full scores. Only `ara-super` (K=20) is released: it beats
uniform random K under family-level leave-one-model-out (macro tau 0.732 vs 0.711, mean tau 0.772 vs 0.764). The K=100 Arabic
selection does not yet beat random K (macro tau 0.769 vs 0.778) and is withheld until it does.
"""


def main() -> None:
    global OUT
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["build", "roundtrip", "stats", "docs"])
    ap.add_argument("--out", default=str(OUT))
    ap.add_argument("--jobs", type=int, default=8)
    ap.add_argument("--configs", default="eng,eng-super", help="any of eng,eng-super,ara,ara-super")
    ap.add_argument("--versions", default="eng=v2,eng-super=v3",
                    help="selection version per config (eng / eng-super: v2 | v3; ara*: v3 | v4)")
    ap.add_argument("--eng-note", default="", help="README sentence on which English selection version is used and why")
    args = ap.parse_args()
    if args.eng_note:
        NOTES["eng"] = args.eng_note.replace("\\`", "`")
    set_configs(args.configs.split(","), dict(kv.split("=") for kv in args.versions.split(",") if kv))
    OUT = Path(args.out)
    if args.cmd == "build":
        build(OUT)
    elif args.cmd == "stats":
        stats()
        write_docs(OUT)
    elif args.cmd == "docs":
        write_docs(OUT)
    else:
        roundtrip(OUT, args.jobs, list(CONFIGS))


if __name__ == "__main__":
    main()