File size: 30,632 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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#!/usr/bin/env python
"""MTEB-lite v2: IRT / anchor-point item selection on a DIVERSE reference set, validated by family-level LOMO.

Why v2: with 33 of 42 reference models being near-identical Qwen merges, v1's "discriminative" items (binned MI,
mRMR) chased noise and lost to random K under leave-one-model-out. v2:
  1. Reference models are grouped into families (by merge recipe; every public / base model is its own family)
     and thinned to a diverse set: <= --per-family models per family (best / median / worst by full score).
  2. Per task, item outcomes are modelled against the known model ability theta (= full-task score standardised
     over the training models):
       continuous items  linear-Gaussian factor model  y_im = a_i theta_m + b_i + e,  e ~ N(0, s_i^2)
       binary items      2PL  P(y_im = 1) = sigmoid(a_i (theta_m - d_i))  (L2-regularised, vectorised Newton)
     Selection (per-item tasks: retrieval, reranking, classification, bitext, summarization):
       anchor   tinyBenchmarks anchor points: k-means (K clusters) of the items' outcome vectors over the training
                models; anchor = item nearest each centroid, weight = the cluster's share of the pool (subset-aware)
       fisher   greedy max of sum_m log(eps + I_S(theta_m)) (information spread over the reference abilities)
     Estimators of the full score (all finally mapped by a linear calibration fitted on the training models):
       mean     (anchor-weighted) subset mean
       pirt     p-IRT: MAP theta from the selected items, pool score = observed items + model-predicted rest
       gp       0.5 * (mean + pirt)
     Set-metric tasks (STS Spearman, clustering V-measure, pair-classification AP): no per-item IRT applies (the
     metric is not a sum over items) -> stratified random K (gold-score bins / labels / classes, per subset) +
     calibration.
  3. Validation: family-level LOMO (hold out a whole family; the honest generalisation test) and distinct-model
     LOMO (hold out one model of the diverse set), K=--K; baselines: uniform random K (metrics averaged over
     --n-random single draws - NOT averaged predictions, which v1 did and which made "random" an ensemble of
     5K items) and the whole pool.

  python scripts/mteb_lite_select_v2.py --K 100 [--suite eng|ara] [--jobs 128] [--full-csv data/mteb_lite/public_full.csv]
Writes <out>/selection/<task>.json, <out>/<manifest> and <report>.{md,json}
(defaults: data/mteb_lite_v2, outputs/mteb_lite/selection_report_v2; ara: data/mteb_lite_ar_v2, ...).
"""
from __future__ import annotations

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))
import mteb_lite_lib as L  # noqa: E402
import mteb_lite_select as S1  # noqa: E402  (full scores, metrics)

REPO = L.REPO
PER_ITEM = {"Retrieval", "Reranking", "Classification", "BitextMining", "Summarization"}
METHODS = ("anchor", "fisher")
ESTIMATORS = ("mean", "pirt", "gp")


# ----------------------------------------------------------------------------- reference models
def family(name: str) -> str:
    """Merge recipe family (base / public models: their own family)."""
    if name.startswith("qwen3-0.6b"):
        return "qwen3-0.6b"
    for pre, fam in (("AS3-", "AS3"), ("AV2-", "AV2"), ("V5-", "v5"), ("S5-", "v5"), ("FV-", "FV"), ("Vq-", "Vq"),
                     ("F-", "v1-F/P"),
                     ("P-", "v1-F/P"), ("A-", "A-v3@6750"), ("W-", "W"), ("V-", "v4"), ("S-", "v4")):
        if name.startswith(pre):
            return fam
    return name


def diverse_set(names: list[str], fulls: dict, tasks: list[str], per_family: int) -> tuple[list[str], dict]:
    fam = defaultdict(list)
    for n in names:
        fam[family(n)].append(n)
    keep, info = [], {}
    for f, ms in sorted(fam.items()):
        common = [t for t in tasks if all(t in fulls.get(m, {}) for m in ms)]

        def q(m):
            return float(np.mean([fulls[m][t] for t in common])) if common else 0.0
        ms = sorted(ms, key=q)
        if len(ms) > per_family:
            idx = sorted({0, len(ms) // 2, len(ms) - 1} if per_family >= 3 else {0, len(ms) - 1})
            pick = [ms[i] for i in idx][:per_family]
        else:
            pick = ms
        keep += pick
        info[f] = {"members": ms, "kept": pick}
    return sorted(keep), info


# ----------------------------------------------------------------------------- item models
def is_binary(Y: np.ndarray) -> bool:
    v = Y[~np.isnan(Y)]
    return bool(len(v)) and bool(np.all((v == 0) | (v == 1)))


def fit_linear(Y: np.ndarray, th: np.ndarray) -> dict:
    """Per-item OLS y = a*theta + b (theta standardised), residual variance (floored)."""
    tc = th - th.mean()
    a = (tc[:, None] * (Y - Y.mean(0))).sum(0) / max((tc ** 2).sum(), 1e-12)
    b = Y.mean(0) - a * th.mean()
    r = Y - (a[None] * th[:, None] + b[None])
    s2 = np.maximum((r ** 2).mean(0), 1e-4 + 1e-2 * Y.var(0).mean())
    return {"kind": "linear", "a": a, "b": b, "s2": s2}


def fit_2pl(Y: np.ndarray, th: np.ndarray, l2: float = 1.0, iters: int = 30) -> dict:
    """Per-item logistic y ~ sigmoid(alpha*theta + beta), L2 on (alpha, beta); a = alpha, d = -beta/alpha."""
    N = Y.shape[1]
    al, be = np.zeros(N), np.zeros(N)
    X = np.stack([th, np.ones_like(th)], 1)                       # M x 2
    for _ in range(iters):
        z = th[:, None] * al[None] + be[None]
        p = 1 / (1 + np.exp(-z))
        w = p * (1 - p)
        g0 = (X[:, 0:1] * (Y - p)).sum(0) - l2 * al
        g1 = (X[:, 1:2] * (Y - p)).sum(0) - l2 * be
        h00 = -(w * th[:, None] ** 2).sum(0) - l2
        h01 = -(w * th[:, None]).sum(0)
        h11 = -w.sum(0) - l2
        det = h00 * h11 - h01 ** 2
        da = (h11 * g0 - h01 * g1) / det
        db = (-h01 * g0 + h00 * g1) / det
        al, be = al - da, be - db
    return {"kind": "2pl", "alpha": al, "beta": be}


def item_info(model: dict, th: np.ndarray) -> np.ndarray:
    """Fisher information I_i(theta_m): M x N."""
    if model["kind"] == "linear":
        return np.broadcast_to(model["a"] ** 2 / model["s2"], (len(th), len(model["a"]))).copy()
    p = 1 / (1 + np.exp(-(th[:, None] * model["alpha"][None] + model["beta"][None])))
    return model["alpha"][None] ** 2 * p * (1 - p)


def predict_items(model: dict, theta: float) -> np.ndarray:
    if model["kind"] == "linear":
        return model["a"] * theta + model["b"]
    return 1 / (1 + np.exp(-(theta * model["alpha"] + model["beta"])))


def map_theta(model: dict, y: np.ndarray, cols: np.ndarray) -> float:
    """MAP ability (N(0,1) prior) from the observed selected items."""
    ok = ~np.isnan(y)
    cols, y = cols[ok], y[ok]
    if model["kind"] == "linear":
        a, b, s2 = model["a"][cols], model["b"][cols], model["s2"][cols]
        return float((a * (y - b) / s2).sum() / ((a ** 2 / s2).sum() + 1.0))
    al, be = model["alpha"][cols], model["beta"][cols]
    t = 0.0
    for _ in range(30):
        p = 1 / (1 + np.exp(-(t * al + be)))
        g = (al * (y - p)).sum() - t
        h = -(al ** 2 * p * (1 - p)).sum() - 1
        t -= g / h
    return float(t)


def weights_of(ts: L.TaskScores) -> np.ndarray:
    """Per-item weight in the pool score (1/N; multi-subset: 1/(G * n_subset))."""
    if not ts.multi:
        return np.full(ts.N, 1.0 / ts.N)
    gs = ts.group
    uniq = list(dict.fromkeys(gs.tolist()))
    cnt = {g: int((gs == g).sum()) for g in uniq}
    return np.array([1.0 / (len(uniq) * cnt[g]) for g in gs])


# ----------------------------------------------------------------------------- selection
def select_anchor(Yt: np.ndarray, K: int, u: np.ndarray, seed: int = 0) -> tuple[np.ndarray, np.ndarray]:
    from sklearn.cluster import KMeans
    N = Yt.shape[1]
    if K >= N:
        return np.arange(N), u.copy()
    X = Yt.T                                                          # N x M
    km = KMeans(n_clusters=K, n_init=3, random_state=seed, max_iter=200).fit(X, sample_weight=u)
    sel, w = [], []
    for k in range(K):
        mem = np.where(km.labels_ == k)[0]
        if not len(mem):
            continue
        d = ((X[mem] - km.cluster_centers_[k]) ** 2).sum(1)
        sel.append(int(mem[np.argmin(d)]))
        w.append(float(u[mem].sum()))
    return np.array(sel), np.array(w)


def select_fisher(info: np.ndarray, K: int, u: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    M, N = info.shape
    if K >= N:
        return np.arange(N), u.copy()
    tot = np.zeros(M)
    chosen = []
    avail = np.ones(N, bool)
    eps = 1e-3 + 1e-3 * info.mean()
    for _ in range(K):
        gain = np.log(eps + tot[:, None] + info).sum(0) - np.log(eps + tot).sum()
        gain[~avail] = -np.inf
        j = int(np.argmax(gain))
        chosen.append(j)
        avail[j] = False
        tot += info[:, j]
    sel = np.array(sorted(chosen))
    return sel, u[sel] / u[sel].sum()


def stratified_random(ts: L.TaskScores, pool: dict, K: int, rng: np.random.RandomState) -> np.ndarray:
    """Stratified random K for set-metric tasks: strata = subset x (gold-score bin | label | class)."""
    N = ts.N
    if K >= N:
        return np.arange(N)
    byid = {x["id"]: x for x in pool["items"]}
    keys = []
    for j, i in enumerate(ts.ids):
        x = byid[i]
        if ts.type == "STS":
            k = str(min(4, int(5 * (x["score"] - pool.get("min_score", 0)) /
                               max(pool.get("max_score", 5) - pool.get("min_score", 0), 1e-9))))
        elif ts.type == "Clustering":
            k = str(x["labels"][0])
        else:
            k = str(x["label"])
        keys.append(f"{x.get('subset', '')}/{k}")
    groups = defaultdict(list)
    for j, k in enumerate(keys):
        groups[k].append(j)
    alloc = {k: len(v) * K / N for k, v in groups.items()}
    base = {k: int(np.floor(a)) for k, a in alloc.items()}
    rest = K - sum(base.values())
    frac = sorted(groups, key=lambda k: -(alloc[k] - base[k]) + rng.rand() * 1e-6)
    for k in frac[:rest]:
        base[k] += 1
    out = []
    for k, v in groups.items():
        out += rng.choice(v, size=min(base[k], len(v)), replace=False).tolist()
    return np.array(sorted(out))


# ----------------------------------------------------------------------------- one fold
def fold(ts: L.TaskScores, pool: dict, f: np.ndarray, train: np.ndarray, test: np.ndarray, K: int,
         n_random: int, methods=METHODS) -> dict:
    """Predictions of the test models' full score for every (method, estimator), random K and the pool."""
    out = {"test": test.tolist()}
    ft = f[train]
    mu, sd = ft.mean(), ft.std() + 1e-12
    th_t = (ft - mu) / sd
    u = weights_of(ts)
    exact = ts.type == "Clustering"

    def cal(s_all):
        a, b = S1.calibrate(s_all[train], ft)
        return (a + b * s_all)[test]
    # pool baseline
    out["pool"] = cal(ts.pool_scores).tolist()
    # random baseline: single draws (metrics averaged later)
    rng = np.random.RandomState(12345)
    rnd = []
    for _ in range(n_random):
        cols = np.sort(rng.choice(ts.N, min(K, ts.N), replace=False))
        rnd.append(cal(ts.subset(cols, exact=exact)).tolist())
    out["random"] = rnd
    if ts.type not in PER_ITEM:
        rng = np.random.RandomState(777)
        draws, sels = [], []
        for r in range(n_random):
            cols = stratified_random(ts, pool, K, rng)
            draws.append(cal(ts.subset(cols, exact=exact)).tolist())
            sels.append(cols.tolist())
        out["strat"] = draws
        out["strat_sel0"] = sels[0]
        # anchor points on the per-item outcomes (STS: per-pair rank agreement), unweighted set metric
        O = S1.item_outcomes(ts)
        O = np.where(np.isnan(O), np.nan_to_num(np.nanmean(O, 0))[None], O)
        sel, _ = select_anchor(O[train], K, weights_of(ts))
        out["anchorset"] = cal(ts.subset(np.sort(sel), exact=exact)).tolist()
        out["anchorset_sel"] = np.sort(sel).tolist()
        return out
    Y = ts.Y.copy()
    colmean = np.nanmean(Y, 0)
    Y = np.where(np.isnan(Y), np.nan_to_num(colmean)[None], Y)
    Yt = Y[train]
    binary = is_binary(Yt)
    model = fit_2pl(Yt, th_t) if binary else fit_linear(Yt, th_t)
    info = item_info(model, th_t)
    pool_est_obs = (Y * u[None]).sum(1)                                  # == the pool score (decomposable)
    for meth in methods:
        sel, w = select_anchor(Yt, K, u) if meth == "anchor" else select_fisher(info, K, u)
        w = w / w.sum()
        est_mean = (Y[:, sel] * w[None]).sum(1)
        est_pirt = np.zeros(ts.M)
        rest = np.ones(ts.N, bool)
        rest[sel] = False
        for m in range(ts.M):
            th = map_theta(model, Y[m, sel], sel)
            pred = predict_items(model, th)
            est_pirt[m] = (u[sel] * Y[m, sel]).sum() + (u[rest] * pred[rest]).sum()
        ests = {"mean": est_mean, "pirt": est_pirt, "gp": 0.5 * (est_mean + est_pirt)}
        for e, v in ests.items():
            out[f"{meth}/{e}"] = cal(v).tolist()
        out[f"{meth}/sel"] = sel.tolist()
        out[f"{meth}/w"] = w.tolist()
    out["binary"] = binary
    out["pool_obs_check"] = float(np.nanmax(np.abs(pool_est_obs - ts.pool_scores))) if not ts.multi else None
    return out


# ----------------------------------------------------------------------------- jobs
_CACHE: dict = {}


def load_task(task: str, names: tuple) -> tuple[L.TaskScores, dict]:
    if (task, names) not in _CACHE:
        _CACHE.clear()
        res, embs = [], []
        for n in names:
            r, e = L.load_scores(n, task)
            res.append(r)
            embs.append(e)
        pool = L.load_pool(task)
        _CACHE[(task, names)] = (L.TaskScores(task, res, embs, pool), pool)
    return _CACHE[(task, names)]


def run_job(suite, scores_dir, task, names, f, train, test, K, n_random, tag):
    L.configure(suite)
    L.SCORES = Path(scores_dir)
    ts, pool = load_task(task, tuple(names))
    t0 = time.time()
    o = fold(ts, pool, np.asarray(f, float), np.asarray(train), np.asarray(test), K, n_random)
    o.update({"task": task, "tag": tag, "seconds": time.time() - t0})
    return o


def main() -> None:
    L.configure(L.suite_from_argv())
    ap = argparse.ArgumentParser()
    ap.add_argument("--suite", choices=["eng", "ara"], default="eng")
    ap.add_argument("--scores-dir", default=str(L.SCORES))
    ap.add_argument("--models", default=None, help="comma list (default: every scored model)")
    ap.add_argument("--exclude", default="", help="comma list of score dirs to ignore")
    ap.add_argument("--tasks", default=None)
    ap.add_argument("--full-csv", default=None, help="name,task,score (default: <lite>/public_full.csv if present)")
    ap.add_argument("--extra-full-csv", default=None, help="another CSV (e.g. our models' Arabic full scores)")
    ap.add_argument("--K", type=int, default=100)
    ap.add_argument("--K-set", type=int, default=None,
                    help="K for set-metric tasks (STS / clustering / pair classification); default = --K")
    ap.add_argument("--set-method", choices=["auto", "strat", "anchorset"], default="anchorset",
                    help="set-metric selection (anchorset beat strat on tau for every set type at K=100 and K=20)")
    ap.add_argument("--per-family", type=int, default=3)
    ap.add_argument("--all-models", action="store_true", help="no family thinning (v1-style reference set)")
    ap.add_argument("--n-random", type=int, default=10)
    ap.add_argument("--choose-by", default="family", choices=["family", "distinct"],
                    help="validation protocol used to choose the per-item method/estimator")
    ap.add_argument("--jobs", type=int, default=1)
    ap.add_argument("--out", default=None)
    ap.add_argument("--report", default=None)
    args = ap.parse_args()
    L.SCORES = Path(args.scores_dir)
    sfx = ("" if args.K > 20 else "_super") + (f"_kset{args.K_set}" if args.K_set and args.K_set != args.K else "")
    out = Path(args.out) if args.out else REPO / "data" / (("mteb_lite" if args.suite == "eng" else "mteb_lite_ar")
                                                           + sfx + "_v2")
    report = Path(args.report) if args.report else L.OUT / f"selection_report_v2{sfx}"
    manifest_name = L.SUITES[args.suite]["manifest"]
    excl = set(filter(None, args.exclude.split(",")))
    names = sorted(args.models.split(",")) if args.models else sorted(
        p.name for p in L.SCORES.iterdir() if p.is_dir() and p.name not in excl)
    tasks = args.tasks.split(",") if args.tasks else [t for t in L.task_names() if L.pool_path(t).exists()]
    types = {t: L.task_type(t) for t in tasks}
    csv_path = args.full_csv or (str(L.LITE / "public_full.csv") if (L.LITE / "public_full.csv").exists() else None)
    fulls = S1.full_scores(names, csv_path) if args.suite == "eng" else ara_full_scores(names, csv_path)
    if args.extra_full_csv:
        for k, v in S1.full_scores([], args.extra_full_csv).items():
            fulls[k].update(v)
    names = [n for n in names if fulls.get(n)]
    ref, fam_info = (names, {}) if args.all_models else diverse_set(names, fulls, tasks, args.per_family)
    fams = defaultdict(list)
    for n in ref:
        fams[family(n)].append(n)
    print(f"[v2] {len(names)} models with full scores -> reference set {len(ref)} in {len(fams)} families", flush=True)

    jobs, info = [], {}
    k_set = args.K_set or args.K
    for t in tasks:
        Kt = args.K if types[t] in PER_ITEM else k_set
        have = [n for n in ref if (L.SCORES / n / f"{t}.json").exists() and t in fulls[n]]
        if len(have) < 4:
            print(f"[v2] {t}: {len(have)} reference models - skipped", flush=True)
            continue
        f = [fulls[n][t] for n in have]
        info[t] = {"names": have, "f": f}
        idx = np.arange(len(have))
        jobs.append((args.suite, str(L.SCORES), t, have, f, idx.tolist(), idx.tolist(), Kt, args.n_random, "final"))
        for m in idx:
            jobs.append((args.suite, str(L.SCORES), t, have, f, [j for j in idx if j != m], [int(m)], Kt,
                         args.n_random, f"distinct:{have[m]}"))
        for fam in sorted({family(n) for n in have}):
            te = [j for j in idx if family(have[j]) == fam]
            tr = [j for j in idx if family(have[j]) != fam]
            if len(tr) >= 4:
                jobs.append((args.suite, str(L.SCORES), t, have, f, tr, te, Kt, args.n_random, f"family:{fam}"))
    print(f"[v2] {len(info)} tasks, {len(jobs)} jobs", flush=True)
    results = []
    if args.jobs > 1:
        from concurrent.futures import ProcessPoolExecutor
        with ProcessPoolExecutor(args.jobs) as ex:
            for r in ex.map(run_job, *zip(*jobs), chunksize=1):
                results.append(r)
    else:
        results = [run_job(*j) for j in jobs]
    by = defaultdict(lambda: defaultdict(dict))        # task -> protocol -> {model idx: {key: pred}}
    final = {}
    for r in results:
        if r["tag"] == "final":
            final[r["task"]] = r
            continue
        proto = r["tag"].split(":")[0]
        for k, v in r.items():
            if k in ("test", "task", "tag", "seconds", "binary", "pool_obs_check") or k.endswith("/sel") \
                    or k.endswith("/w") or k in ("strat_sel0", "anchorset_sel"):
                continue
            for pos, m in enumerate(r["test"]):
                if k in ("random", "strat"):
                    by[r["task"]][proto].setdefault(m, {})[k] = [d[pos] for d in v]
                else:
                    by[r["task"]][proto].setdefault(m, {})[k] = v[pos]
    keys_item = [f"{m}/{e}" for m in METHODS for e in ESTIMATORS]
    rep = {"args": vars(args), "reference": ref, "families": {k: v for k, v in fam_info.items()},
           "per_task": {}, "aggregate": {}, "choice": {}}

    def task_metrics(t, proto, key):
        d = by[t][proto]
        ms = sorted(d)
        tru = np.array([info[t]["f"][m] for m in ms])
        if key in ("random", "strat"):
            nd = len(d[ms[0]][key]) if ms else 0
            per = [S1.metrics(np.array([d[m][key][r] for m in ms]), tru) for r in range(nd)]
            o = {k: float(np.nanmean([p[k] for p in per])) for k in ("kendall", "pearson", "mae")}
            o["n"] = len(ms)
            return o
        return S1.metrics(np.array([d[m][key] for m in ms]), tru)
    # choose one per-item method/estimator for all per-item tasks by the aggregate of the chosen protocol
    for proto in ("family", "distinct"):
        for t in info:
            row = rep["per_task"].setdefault(t, {"type": types[t], "n_ref": len(info[t]["names"])})
            keys = (keys_item if types[t] in PER_ITEM else ["strat", "anchorset"]) + ["random", "pool"]
            row[proto] = {k: task_metrics(t, proto, k) for k in keys if by[t][proto]}

    def agg(proto, key_of):
        """Aggregate over tasks for the models predicted in every task: macro (mean of the type means) and mean,
        x100. Keys holding single random draws are scored per draw and the metrics averaged."""
        models = None
        for t in info:
            ms = {info[t]["names"][m] for m in by[t][proto]}
            models = ms if models is None else models & ms
        models = sorted(models or [])
        if len(models) < 3:
            return {}
        draws = any(key_of(types[t]) in ("random", "strat") for t in info)
        res = []
        for r in range(args.n_random if draws else 1):
            pm, pmean, tm, tmean = [], [], [], []
            for n in models:
                pred, tru = {}, {}
                for t in info:
                    m = info[t]["names"].index(n)
                    v = by[t][proto][m][key_of(types[t])]
                    pred[t] = v[r % len(v)] if isinstance(v, list) else v
                    tru[t] = info[t]["f"][m]
                a_, b_ = S1.aggregate(pred, types), S1.aggregate(tru, types)
                pm.append(a_[0]); pmean.append(a_[1]); tm.append(b_[0]); tmean.append(b_[1])
            res.append({"macro": S1.metrics(np.array(pm), np.array(tm)) | {"tau_resolvable": res_tau(pm, tm)},
                        "mean": S1.metrics(np.array(pmean), np.array(tmean)) | {"tau_resolvable": res_tau(pmean, tmean)},
                        "pred": {"macro": pm, "mean": pmean}})
        out_ = {w: {k: float(np.nanmean([x[w][k] for x in res])) for k in ("kendall", "pearson", "mae", "tau_resolvable")}
                for w in ("macro", "mean")}
        for w in out_:
            out_[w]["n"] = len(models)
        out_["models"] = models
        out_["true"] = {"macro": tm, "mean": tmean}
        out_["pred_draw0"] = res[0]["pred"]
        return out_
    for proto in ("family", "distinct"):
        A = {}
        for k in keys_item:
            for sm in ("strat", "anchorset"):
                A[f"{k}+{sm}"] = agg(proto, lambda ty, k=k, sm=sm: k if ty in PER_ITEM else sm)
        A["random"] = agg(proto, lambda ty: "random")
        A["pool"] = agg(proto, lambda ty: "pool")
        rep["aggregate"][proto] = A
    cands = {k: v for k, v in rep["aggregate"][args.choose_by].items() if "+" in k and v
             and (args.set_method == "auto" or k.endswith("+" + args.set_method))}
    best = (max(cands, key=lambda k: (cands[k]["macro"]["kendall"], -cands[k]["macro"]["mae"])) if cands
            else "anchor/mean+strat")
    best_item, best_set = best.split("+")
    rep["choice"] = {"combo": best, "per_item": best_item, "set_metric": best_set, "chosen_by": args.choose_by}
    meth, est = best_item.split("/")

    # final selection on the whole reference set
    (out / "selection").mkdir(parents=True, exist_ok=True)
    man = {"benchmark": f"MTEB-lite v2 ({args.suite})", "K": args.K, "K_set": args.K_set or args.K, "reference_models": ref,
           "method": {"per_item": best_item, "set_metric": f"{best_set} + calibration",
                      "item_model": "linear-Gaussian (continuous) / 2PL (binary)"}, "tasks": {}}
    for t, r in final.items():
        ts, pool = load_task(t, tuple(info[t]["names"]))
        f = np.array(info[t]["f"])
        doc = {"task": t, "type": types[t], "K": None, "reference_models": info[t]["names"]}
        if types[t] in PER_ITEM:
            sel, w = np.array(r[f"{meth}/sel"]), np.array(r[f"{meth}/w"])
            Y = np.where(np.isnan(ts.Y), np.nan_to_num(np.nanmean(ts.Y, 0))[None], ts.Y)
            th = (f - f.mean()) / (f.std() + 1e-12)
            model = fit_2pl(Y, th) if r["binary"] else fit_linear(Y, th)
            est_vals = {"mean": (Y[:, sel] * w[None]).sum(1)}
            u = weights_of(ts)
            rest = np.ones(ts.N, bool)
            rest[sel] = False
            pir = []
            for m in range(ts.M):
                tm_ = map_theta(model, Y[m, sel], sel)
                pir.append((u[sel] * Y[m, sel]).sum() + (u[rest] * predict_items(model, tm_)[rest]).sum())
            est_vals["pirt"] = np.array(pir)
            est_vals["gp"] = 0.5 * (est_vals["mean"] + est_vals["pirt"])
            a, b = S1.calibrate(est_vals[est], f)
            params = ({"kind": "linear", "a": model["a"].tolist(), "b": model["b"].tolist(), "s2": model["s2"].tolist()}
                      if model["kind"] == "linear" else
                      {"kind": "2pl", "alpha": model["alpha"].tolist(), "beta": model["beta"].tolist()})
            doc.update({"ids": [ts.ids[j] for j in sel], "weights": w.tolist(), "estimator": est,
                        "theta_scale": {"mu": float(f.mean()), "sd": float(f.std() + 1e-12)},
                        "pool_ids": ts.ids, "pool_weights": u.tolist(), "item_model": params,
                        "calibration": {"a": a, "b": b}})
        else:
            sel = np.array(r["strat_sel0"] if best_set == "strat" else r["anchorset_sel"])
            exact = types[t] == "Clustering"
            a, b = S1.calibrate(ts.subset(sel, exact=exact), f)
            doc.update({"ids": [ts.ids[j] for j in sel], "estimator": "set_metric", "set_selection": best_set,
                        "calibration": {"a": a, "b": b}})
        doc["K"] = len(doc["ids"])
        (out / "selection" / f"{t}.json").write_text(json.dumps(doc))
        man["tasks"][t] = {"type": types[t], "main_score": L.get_task(t).metadata.main_score,
                           "selection": f"selection/{t}.json", "K": doc["K"], "estimator": doc["estimator"]}
    (out / manifest_name).write_text(json.dumps(man, indent=1))
    report.parent.mkdir(parents=True, exist_ok=True)
    report.with_suffix(".json").write_text(json.dumps(rep, indent=1, default=float))
    md = render(rep, args, best, fams)
    report.with_suffix(".md").write_text(md)
    print(md)


def res_tau(pred, true, thr: float = 0.5) -> float:
    """Kendall-style agreement on the 'resolvable' pairs only (true scores differ by >= thr points)."""
    p, t = np.asarray(pred, float), np.asarray(true, float)
    c = d = 0
    for i in range(len(t)):
        for j in range(i + 1, len(t)):
            if abs(t[i] - t[j]) >= thr:
                if np.sign(p[i] - p[j]) == np.sign(t[i] - t[j]):
                    c += 1
                else:
                    d += 1
    return (c - d) / (c + d) if c + d else float("nan")


def ara_full_scores(names: list[str], csv_path) -> dict:
    """Arabic: our models from <lite>/ours_full.csv (mteb_lite_ara_full.py) + public CSV."""
    fulls = defaultdict(dict)
    for p in [L.LITE / "ours_full.csv", csv_path]:
        if p and Path(p).exists():
            for k, v in S1.full_scores([], str(p)).items():
                fulls[k].update(v)
    return fulls


def render(rep: dict, args, best: str, fams: dict) -> str:
    def f3(x):
        return "-" if x is None or (isinstance(x, float) and np.isnan(x)) else f"{x:.3f}"
    L_ = [f"# MTEB-lite v2 selection report ({args.suite}, K={args.K})", "",
          f"Reference set ({len(rep['reference'])} models, {len(fams)} families, <= {args.per_family} per family): "
          + "; ".join(f"**{k}**: {', '.join(v)}" for k, v in sorted(fams.items())), "",
          f"K={args.K} for per-item tasks, K={args.K_set or args.K} for set-metric tasks. "
          f"Chosen: **{best}** (per-item method/estimator by the {rep['choice']['chosen_by']}"
          f"-level LOMO macro tau among {{anchor, fisher}} x {{mean, pirt, gp}}; set-metric selection: {args.set_method}). Set-metric "
          "tasks (STS, clustering, pair classification): no per-item IRT (the metric is not a sum over items) -> "
          "stratified random K ('strat') or unweighted anchor points on per-item outcomes ('anchorset'), + "
          f"calibration. Random = uniform K, metrics averaged over {args.n_random} single draws. tau_res = tau on "
          "the pairs whose true score differs by >= 0.5 points.", ""]
    for proto in ("family", "distinct"):
        A = rep["aggregate"].get(proto, {})
        if not A:
            continue
        n = next((v["macro"]["n"] for v in A.values() if v), 0)
        L_ += [f"## Aggregate, {proto}-level LOMO ({n} held-out models with all tasks; scores x100)", "",
               "| estimate | macro tau | macro tau_res | macro r | macro MAE | mean tau | mean tau_res | mean r | mean MAE |",
               "|---|---|---|---|---|---|---|---|---|"]
        for k, v in A.items():
            if v:
                L_.append(f"| {k}{' (chosen)' if k == best else ''} | {f3(v['macro']['kendall'])} | "
                          f"{f3(v['macro']['tau_resolvable'])} | {f3(v['macro']['pearson'])} | "
                          f"{f3(v['macro']['mae'])} | {f3(v['mean']['kendall'])} | {f3(v['mean']['tau_resolvable'])} | "
                          f"{f3(v['mean']['pearson'])} | {f3(v['mean']['mae'])} |")
        L_.append("")
    L_ += ["## Per task (family-level LOMO; chosen estimator vs random K vs pool)", "",
           "| task | type | ref | chosen tau | chosen r | chosen MAE | random tau | random MAE | pool tau | pool MAE |",
           "|---|---|---|---|---|---|---|---|---|---|"]
    for t, r in rep["per_task"].items():
        fam = r.get("family", {})
        k = best.split("+")[0] if r["type"] in PER_ITEM else best.split("+")[1]
        c, ra, po = fam.get(k, {}), fam.get("random", {}), fam.get("pool", {})
        L_.append(f"| {t} | {r['type']} | {r['n_ref']} | {f3(c.get('kendall'))} | {f3(c.get('pearson'))} | "
                  f"{f3(c.get('mae'))} | {f3(ra.get('kendall'))} | {f3(ra.get('mae'))} | {f3(po.get('kendall'))} | "
                  f"{f3(po.get('mae'))} |")
    return "\n".join(L_) + "\n"


if __name__ == "__main__":
    main()