File size: 38,540 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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
"""MTEB-lite: shared code for the pool builder, the per-item scorer, the selection and the lite eval.

Two suites (configure(suite) / --suite):
  eng  MTEB(eng, v2), 41 tasks            data/mteb_lite/pool, outputs/mteb_lite/scores
  ara  our 42 Arabic MMTEB test tasks     data/mteb_lite_ar/pool, outputs/mteb_lite_ar/scores
       (configs/merge/mmteb_ar_test_tasks.txt; each restricted to its Arabic hf_subsets and test split exactly
       as run_mteb_arabic.py --suite test: adip.eval.mteb_arabic.suite_specs / get_mteb_task)

Pool formats (<pool dir>/<task>.json; common keys: task, type, main_score, eval_split, hf_subset). Items of
multi-subset tasks carry "subset" (retrieval: query_subset {qid: subset}); task scores are means over subsets,
as in mteb:
  Retrieval       queries {qid: text}, corpus {did: text}, qrels {qid: {did: rel}}, candidates {qid: [did]},
                  random_docs [did] (multi-subset: random_docs_by_subset {subset: [did]}), ignore_identical_ids
  Reranking       items [{id, query (str | list[str]), positive [str], negative [str], (candidates [str])}]
  Classification  train {text, label, orig_index}, experiments [[train idx]], items [{id, text, label}]
                  (multi-subset: groups {subset: {train, experiments}})
  PairClassification items [{id, sentence1, sentence2, label}]
  STS             items [{id, sentence1, sentence2, score}]
  Clustering      items [{id, text, labels [level0, level1, ...]}], mteb_ids (mteb's own downsample, if any)
  Summarization   items [{id, machine [str], human [str], relevance [float]}]
  BitextMining    items [{id, subset, sentence1, target}], bitext_texts {key: text},
                  bitext_candidates {subset: [key]} (fixed distractors; an item is correct if its own target
                  is the nearest of distractors + target)

Per-item scores (<scores dir>/<NAME>/<task>.json): {"task", "type", "pool_score", "pool_metrics", "item_key",
"items": [{id, ...}]}; the item field used by the selection is item_key (default ITEM_KEY[type]). Clustering
also writes the pool embeddings (<task>.emb.npy, float16, row order = pool items) so subset scores can
re-cluster exactly as the lite eval does.
"""
from __future__ import annotations

import json
import math
import random
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any, Callable, Optional, Sequence

import numpy as np

REPO = Path(__file__).resolve().parents[1]
SUITE = "eng"
LITE = REPO / "data" / "mteb_lite"
POOL = LITE / "pool"
SCORES = REPO / "outputs" / "mteb_lite" / "scores"
OUT = REPO / "outputs" / "mteb_lite"
BENCHMARK = "MTEB(eng, v2)"
AR_TASKS = REPO / "configs" / "merge" / "mmteb_ar_test_tasks.txt"
SUITES = {
    "eng": {"lite": REPO / "data" / "mteb_lite", "out": REPO / "outputs" / "mteb_lite", "manifest": "MTEB_lite_eng.json",
            "max_length": None},
    "ara": {"lite": REPO / "data" / "mteb_lite_ar", "out": REPO / "outputs" / "mteb_lite_ar",
            "manifest": "MTEB_lite_ara.json", "max_length": 512},     # run_mteb_arabic.py --max-length default
}

# per-item field used for selection; "set" types are scored on item sets by TaskScores.subset
ITEM_KEY = {"Retrieval": "ndcg10", "Reranking": "ap", "Classification": "acc", "PairClassification": "correct",
            "STS": "cos", "Clustering": "agree", "Summarization": "spearman", "BitextMining": "correct"}
SET_TYPES = {"STS", "Clustering", "PairClassification"}
KMEANS_RUNS = 3


def configure(suite: str) -> None:
    """Point the module at a suite's pools / scores (module globals are read at call time)."""
    global SUITE, LITE, POOL, SCORES, OUT
    if suite not in SUITES:
        raise ValueError(f"unknown suite {suite!r} (eng | ara)")
    SUITE = suite
    LITE = SUITES[suite]["lite"]
    POOL = LITE / "pool"
    OUT = SUITES[suite]["out"]
    SCORES = OUT / "scores"
    _TASKS.clear()


def suite_from_argv(argv: Optional[list[str]] = None) -> str:
    """--suite from the command line (before the full parser is built, so defaults follow the suite)."""
    argv = sys.argv[1:] if argv is None else argv
    for i, a in enumerate(argv):
        if a == "--suite" and i + 1 < len(argv):
            return argv[i + 1]
        if a.startswith("--suite="):
            return a.split("=", 1)[1]
    return "eng"


# ----------------------------------------------------------------------------- tasks / pools
_TASKS: dict = {}


def _ar_specs() -> dict:
    sys.path.insert(0, str(REPO / "src"))
    from adip.eval import mteb_arabic as ma
    names = [l.strip() for l in AR_TASKS.read_text().splitlines() if l.strip()]
    return {s["task"]: s for s in ma.suite_specs("test", tasks=names)}


def benchmark_tasks():
    """{name: mteb task} of the current suite (ara: restricted to the Arabic hf_subsets, with the split the
    Arabic eval uses in task._lite_split)."""
    if not _TASKS:
        if SUITE == "eng":
            import mteb
            for t in mteb.get_benchmark(BENCHMARK).tasks:
                t._lite_split = t.eval_splits[0]
                _TASKS[t.metadata.name] = t
        else:
            specs = _ar_specs()                   # also puts src/ on sys.path
            from adip.eval import mteb_arabic as ma
            for n, s in specs.items():
                t = ma.get_mteb_task(s)
                t._lite_split = s["split"]
                t._lite_spec = s
                _TASKS[n] = t
    return _TASKS


def task_names() -> list[str]:
    if SUITE == "ara":
        return [l.strip() for l in AR_TASKS.read_text().splitlines() if l.strip()]
    return list(benchmark_tasks())


def get_task(name: str):
    return benchmark_tasks()[name]


def task_type(name: str) -> str:
    return get_task(name).metadata.type


def pool_path(name: str) -> Path:
    return POOL / f"{name}.json"


def save_pool(pool: dict) -> None:
    POOL.mkdir(parents=True, exist_ok=True)
    p = pool_path(pool["task"])
    tmp = p.with_suffix(".tmp")
    tmp.write_text(json.dumps(pool, ensure_ascii=False))
    tmp.replace(p)


def load_pool(name: str) -> dict:
    return json.loads(pool_path(name).read_text())


def doc_text(v: Any) -> str:
    """mteb's corpus_to_str: title + ' ' + text, stripped."""
    if isinstance(v, str):
        return v.strip()
    if "title" in v and v.get("title"):
        return (v["title"] + " " + v["text"]).strip()
    return v["text"].strip()


def item_ids(pool: dict) -> list[str]:
    if pool["type"] == "Retrieval":
        return list(pool["queries"])
    return [x["id"] for x in pool["items"]]


def item_groups(pool: dict) -> dict[str, str]:
    """{item id: hf_subset} ('' for single-subset tasks)."""
    if pool["type"] == "Retrieval":
        qs = pool.get("query_subset", {})
        return {q: qs.get(q, "") for q in pool["queries"]}
    return {x["id"]: x.get("subset", "") for x in pool["items"]}


def pool_size_str(pool: dict) -> str:
    t = pool["type"]
    if t == "Retrieval":
        return (f"{len(pool['queries'])} queries, {len(pool['corpus'])} docs "
                f"(full {pool['full_sizes']['queries']} q / {pool['full_sizes']['corpus']} docs)")
    if t == "Reranking":
        n = sum(len(x.get("candidates") or (x["positive"] + x["negative"])) for x in pool["items"])
        return f"{len(pool['items'])} queries, {n} candidates (full {pool['full_sizes']['queries']} q)"
    if t == "Classification":
        ntr = (sum(len(g["train"]["text"]) for g in pool["groups"].values()) if "groups" in pool
               else len(pool["train"]["text"]))
        return f"{len(pool['items'])} test, {ntr} train texts (full {pool['full_sizes']})"
    if t == "Summarization":
        return f"{len(pool['items'])} documents"
    if t == "BitextMining":
        return (f"{len(pool['items'])} pairs, {len(pool['bitext_texts'])} target texts "
                f"({len(pool['bitext_candidates'])} subsets; full {pool['full_sizes']})")
    return f"{len(pool['items'])} items (full {pool['full_sizes']})"


def texts_to_encode(pool: dict) -> list[tuple[str, Optional[str]]]:
    """(text, role) pairs a model has to encode for this pool; role: query | document | None."""
    t = pool["type"]
    if t == "Retrieval":
        return [(q, "query") for q in pool["queries"].values()] + [(d, "document") for d in pool["corpus"].values()]
    if t == "Reranking":
        out = []
        for x in pool["items"]:
            qs = x["query"] if isinstance(x["query"], list) else [x["query"]]
            docs = x.get("candidates") or (x["positive"] + x["negative"])
            out += [(q, "query") for q in qs] + [(d, "document") for d in docs]
        return out
    if t == "Classification":
        trs = ([s for g in pool["groups"].values() for s in g["train"]["text"]] if "groups" in pool
               else pool["train"]["text"])
        return [(s, None) for s in trs] + [(x["text"], None) for x in pool["items"]]
    if t in ("PairClassification", "STS"):
        return [(x[k], None) for x in pool["items"] for k in ("sentence1", "sentence2")]
    if t == "Clustering":
        return [(x["text"], None) for x in pool["items"]]
    if t == "Summarization":
        return [(s, None) for x in pool["items"] for s in x["machine"] + x["human"]]
    if t == "BitextMining":
        return [(x["sentence1"], None) for x in pool["items"]] + [(v, None) for v in pool["bitext_texts"].values()]
    raise ValueError(t)


def restrict_pool(pool: dict, ids: Sequence[str]) -> dict:
    """The pool restricted to the given items (what the lite eval encodes)."""
    keep = set(ids)
    p = dict(pool)
    if pool["type"] == "Retrieval":
        qs = [q for q in pool["queries"] if q in keep]
        if "random_docs_by_subset" in pool:
            subs = {pool["query_subset"][q] for q in qs}
            docs = {d for sub in subs for d in pool["random_docs_by_subset"][sub]}
            p["random_docs_by_subset"] = {sub: pool["random_docs_by_subset"][sub] for sub in subs}
            p["query_subset"] = {q: pool["query_subset"][q] for q in qs}
        else:
            docs = set(pool["random_docs"])
        for q in qs:
            docs.update(pool["candidates"][q])
        p["queries"] = {q: pool["queries"][q] for q in qs}
        p["candidates"] = {q: pool["candidates"][q] for q in qs}
        p["qrels"] = {q: pool["qrels"][q] for q in qs}
        p["corpus"] = {d: v for d, v in pool["corpus"].items() if d in docs}
    else:
        p["items"] = [x for x in pool["items"] if x["id"] in keep]
        if "mteb_ids" in p:
            p["mteb_ids"] = [i for i in p["mteb_ids"] if i in keep]
        if pool["type"] == "BitextMining":
            subs = {x["subset"] for x in p["items"]}
            p["bitext_candidates"] = {k: v for k, v in pool["bitext_candidates"].items() if k in subs}
            need = {k for v in p["bitext_candidates"].values() for k in v} | {x["target"] for x in p["items"]}
            p["bitext_texts"] = {k: v for k, v in pool["bitext_texts"].items() if k in need}
    return p


def group_mean(values: np.ndarray, groups: Sequence[str]) -> float:
    """Mean over hf_subsets of the per-subset nanmean (mteb's aggregation); plain nanmean for one subset."""
    values = np.asarray(values, dtype=float)
    gs = np.asarray(list(groups))
    uniq = list(dict.fromkeys(gs.tolist()))
    if len(uniq) <= 1:
        return float(np.nanmean(values)) if len(values) else float("nan")
    with np.errstate(all="ignore"):
        per = [np.nanmean(values[gs == g]) for g in uniq]
    return float(np.nanmean(per))


# ----------------------------------------------------------------------------- encoding
def encode_texts(model, texts: list[str], task_name: str, role: Optional[str], batch_size: int = 64) -> np.ndarray:
    """model.encode exactly as mteb's evaluators call it (task_name + prompt_type); dedupes texts;
    halves the batch on CUDA OOM."""
    from mteb.encoder_interface import PromptType
    pt = {"query": PromptType.query, "document": PromptType.document, None: None}[role]
    uniq = list(dict.fromkeys(texts))
    if not uniq:
        return np.zeros((0, 1), dtype=np.float32)
    bs = batch_size
    while True:
        try:
            emb = model.encode(uniq, task_name=task_name, prompt_type=pt, batch_size=bs)
            break
        except Exception as e:  # torch.cuda.OutOfMemoryError
            if "out of memory" not in str(e).lower() or bs == 1:
                raise
            import torch
            torch.cuda.empty_cache()
            bs = max(1, bs // 2)
            print(f"[encode] OOM -> batch {bs}", flush=True)
    if hasattr(emb, "detach"):
        emb = emb.detach().cpu().float().numpy()
    emb = np.asarray(emb, dtype=np.float32)
    pos = {s: i for i, s in enumerate(uniq)}
    return emb[[pos[s] for s in texts]]


def similarity_name(model) -> str:
    meta = getattr(model, "mteb_model_meta", None) or getattr(model, "model_meta", None)
    name = getattr(meta, "similarity_fn_name", None) or "cosine"
    return str(getattr(name, "value", name)).lower()


def sim_matrix(a: np.ndarray, b: np.ndarray, sim: str = "cosine") -> np.ndarray:
    if sim.startswith("cos"):
        a = a / np.maximum(np.linalg.norm(a, axis=1, keepdims=True), 1e-12)
        b = b / np.maximum(np.linalg.norm(b, axis=1, keepdims=True), 1e-12)
    return a @ b.T


def cos_pairs(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    a = a / np.maximum(np.linalg.norm(a, axis=1, keepdims=True), 1e-12)
    b = b / np.maximum(np.linalg.norm(b, axis=1, keepdims=True), 1e-12)
    return (a * b).sum(1)


# ----------------------------------------------------------------------------- metrics
def ndcg_at_k(ranked: Sequence[str], qrel: dict, k: int = 10) -> float:
    """pytrec_eval ndcg_cut (gain = relevance grade, log2 discount)."""
    dcg = sum(max(qrel.get(d, 0), 0) / math.log2(i + 2) for i, d in enumerate(ranked[:k]))
    ideal = sorted((v for v in qrel.values() if v > 0), reverse=True)[:k]
    idcg = sum(v / math.log2(i + 2) for i, v in enumerate(ideal))
    return dcg / idcg if idcg > 0 else 0.0


def recall_at_k(ranked: Sequence[str], qrel: dict, k: int = 10) -> float:
    rel = {d for d, v in qrel.items() if v > 0}
    return len(rel & set(ranked[:k])) / len(rel) if rel else 0.0


def average_precision(y: np.ndarray, s: np.ndarray, w: Optional[np.ndarray] = None) -> float:
    from sklearn.metrics import average_precision_score
    y = np.asarray(y)
    if y.sum() == 0 or y.sum() == len(y):
        return float("nan")
    return float(average_precision_score(y, s, sample_weight=w))


def pair_weights(pool: dict, labels: np.ndarray) -> Optional[np.ndarray]:
    lw = pool.get("label_weights")
    return None if not lw else np.array([lw[str(int(v))] for v in labels], dtype=float)


def spearman(x, y) -> float:
    from scipy.stats import spearmanr
    x, y = np.asarray(x, float), np.asarray(y, float)
    if len(x) < 3 or np.all(x == x[0]) or np.all(y == y[0]):
        return float("nan")
    return float(spearmanr(x, y).statistic if hasattr(spearmanr(x, y), "statistic") else spearmanr(x, y)[0])


def v_measure_fast(labels: np.ndarray, clusters: np.ndarray) -> float:
    """sklearn's v_measure_score (beta=1) with numpy only (labels / clusters: non-negative ints)."""
    n = len(labels)
    if n == 0:
        return float("nan")
    _, li = np.unique(labels, return_inverse=True)
    _, ci = np.unique(clusters, return_inverse=True)
    nl, nc = li.max() + 1, ci.max() + 1
    if nl == 1 or nc == 1:
        return 1.0 if nl == nc else 0.0
    cont = np.bincount(li * nc + ci, minlength=nl * nc).reshape(nl, nc).astype(float)
    pl, pc, pj = cont.sum(1) / n, cont.sum(0) / n, cont / n
    h_l = -(pl * np.log(pl)).sum()
    h_c = -(pc * np.log(pc)).sum()
    nz = pj > 0
    mi = (pj[nz] * np.log(pj[nz] / (pl[:, None] * pc[None, :])[nz])).sum()
    hom, com = mi / h_l, mi / h_c
    return float(2 * hom * com / (hom + com)) if hom + com > 0 else 0.0


def level_labels(items: list[dict], level: int) -> tuple[np.ndarray, np.ndarray]:
    """(valid mask, int labels) of one hierarchy level."""
    lab = [x["labels"][level] if len(x["labels"]) > level else None for x in items]
    mask = np.array([v is not None for v in lab])
    vocab = {v: i for i, v in enumerate(sorted({v for v in lab if v is not None}))}
    return mask, np.array([vocab[v] for v in lab if v is not None], dtype=int)


def _group_index(items: list[dict]) -> list[np.ndarray]:
    gs = np.array([x.get("subset", "") for x in items])
    return [np.where(gs == g)[0] for g in dict.fromkeys(gs.tolist())]


def kmeans_runs(emb: np.ndarray, items: list[dict], n_levels: int, runs: int = KMEANS_RUNS) -> list[list[np.ndarray]]:
    """Cluster ids [run][level] (k = number of gold labels at that level, -1 for items without the level);
    k-means runs separately inside every hf_subset (cluster ids are only comparable within a subset)."""
    from sklearn.cluster import KMeans
    x = emb / np.maximum(np.linalg.norm(emb, axis=1, keepdims=True), 1e-12)
    groups = _group_index(items)
    out = []
    for r in range(runs):
        per = []
        for lv in range(n_levels):
            ids = np.full(len(items), -1, dtype=int)
            for gi in groups:
                its = [items[i] for i in gi]
                mask, lab = level_labels(its, lv)
                k = len(np.unique(lab))
                gids = np.full(len(gi), -1, dtype=int)
                if mask.sum() >= 2 and k >= 2:
                    km = KMeans(n_clusters=min(k, int(mask.sum())), n_init=1, random_state=r, max_iter=100)
                    gids[mask] = km.fit_predict(x[gi][mask])
                elif mask.any():
                    gids[mask] = 0
                ids[gi] = gids
            per.append(ids)
        out.append(per)
    return out


def cluster_score(emb: np.ndarray, items: list[dict], n_levels: int, runs: int = KMEANS_RUNS) -> float:
    """Lite clustering score of a set of items: mean over k-means runs and levels of the V-measure of
    k-means (k = #gold labels present) on exactly these items (per hf_subset, then averaged over subsets).
    Used by the scorer (pool), the selection (subsets, from stored embeddings) and the lite eval alike."""
    cl = kmeans_runs(emb, items, n_levels, runs)
    per_group = []
    for gi in _group_index(items):
        its = [items[i] for i in gi]
        vals = []
        for per in cl:
            for lv in range(n_levels):
                mask, lab = level_labels(its, lv)
                if mask.sum() >= 2:
                    vals.append(v_measure_fast(lab, per[lv][gi][mask]))
        if vals:
            per_group.append(float(np.nanmean(vals)))
    return float(np.nanmean(per_group)) if per_group else float("nan")


# ----------------------------------------------------------------------------- per-task scoring
def score_pool(pool: dict, model, batch_size: int = 64, log: Callable = print) -> tuple[dict, Optional[np.ndarray]]:
    """Encode the pool with the model (mteb's prompts for this task) and compute per-item + pool scores.
    Returns (result json, embeddings to save or None). Pool scores of multi-subset tasks are means over
    hf_subsets (mteb's aggregation)."""
    t, name = pool["type"], pool["task"]
    sim = similarity_name(model)
    enc = lambda texts, role: encode_texts(model, texts, name, role, batch_size)  # noqa: E731
    emb_out = None
    grp = item_groups(pool)
    item_key = ITEM_KEY[t]
    if t == "Retrieval":
        qids, dids = list(pool["queries"]), list(pool["corpus"])
        Q = enc([pool["queries"][q] for q in qids], "query")
        D = enc([pool["corpus"][d] for d in dids], "document")
        dpos = {d: i for i, d in enumerate(dids)}
        multi = "random_docs_by_subset" in pool
        if multi:       # docs of a subset: its namespaced ids "<subset>|<doc id>"
            dsub = np.array([d.split("|", 1)[0] for d in dids])
            rnd_by = {k: [dpos[d] for d in v] for k, v in pool["random_docs_by_subset"].items()}
        else:
            rnd = [dpos[d] for d in pool["random_docs"]]
        ign = pool.get("ignore_identical_ids", False)
        items, pool_ndcg, pool_rec = [], [], []
        for s in range(0, len(qids), 256):
            S = sim_matrix(Q[s:s + 256], D, sim)
            for r, q in enumerate(qids[s:s + 256]):
                row = S[r].copy()
                if multi:
                    row[dsub != pool["query_subset"][q]] = -np.inf
                if ign and q in dpos:
                    row[dpos[q]] = -np.inf
                top = np.argpartition(-row, min(10, len(row) - 1))[:11]
                top = top[np.argsort(-row[top])]
                ranked = [dids[i] for i in top if not (ign and dids[i] == q) and np.isfinite(row[i])][:10]
                qrel = pool["qrels"][q]
                pool_ndcg.append(ndcg_at_k(ranked, qrel))
                pool_rec.append(recall_at_k(ranked, qrel))
                rr = rnd_by[pool["query_subset"][q]] if multi else rnd
                cand = sorted(set(dpos[d] for d in pool["candidates"][q]) | set(rr))
                if ign:
                    cand = [i for i in cand if dids[i] != q]
                cs = S[r, cand]
                order = np.argsort(-cs)[:10]
                lr = [dids[cand[i]] for i in order]
                items.append({"id": q, "ndcg10": ndcg_at_k(lr, qrel), "recall10": recall_at_k(lr, qrel),
                              "ndcg10_pool": pool_ndcg[-1], "n_cand": len(cand)})
        g = [grp[q] for q in qids]
        res = {"pool_score": group_mean(pool_ndcg, g),
               "pool_metrics": {"ndcg_at_10_pool_corpus": group_mean(pool_ndcg, g),
                                "recall_at_10_pool_corpus": group_mean(pool_rec, g),
                                "ndcg_at_10_local": group_mean([x["ndcg10"] for x in items], g),
                                "recall_at_10_local": group_mean([x["recall10"] for x in items], g)}}
    elif t == "Reranking":
        qtexts, qown, dtexts, down = [], [], [], []
        for i, x in enumerate(pool["items"]):
            qs = x["query"] if isinstance(x["query"], list) else [x["query"]]
            qtexts += qs
            qown += [i] * len(qs)
            ds = x.get("candidates") or (x["positive"] + x["negative"])
            dtexts += ds
            down += [i] * len(ds)
        Q, D = enc(qtexts, "query"), enc(dtexts, "document")
        qown, down = np.array(qown), np.array(down)
        items = []
        for i, x in enumerate(pool["items"]):
            S = sim_matrix(Q[qown == i], D[down == i], sim).max(0)
            if x.get("candidates"):            # MIRACL format: relevance = candidate is a positive
                pos = set(x["positive"])
                y = np.array([int(d in pos) for d in x["candidates"]])
            else:
                y = np.array([1] * len(x["positive"]) + [0] * len(x["negative"]))
            order = np.argsort(-S)
            first = int(np.argmax(y[order])) + 1 if y.any() else 10 ** 9
            items.append({"id": x["id"], "ap": average_precision(y, S),
                          "mrr10": 1.0 / first if first <= 10 else 0.0,
                          "ndcg10": ndcg_at_k([str(j) for j in order], {str(j): int(v) for j, v in enumerate(y)})})
        if "ndcg" in str(pool["main_score"]).lower():
            item_key = "ndcg10"
        g = [x.get("subset", "") for x in pool["items"]]
        res = {"pool_score": group_mean([x[item_key] for x in items], g),
               "pool_metrics": {"map": group_mean([x["ap"] for x in items], g),
                                "mrr_at_10": group_mean([x["mrr10"] for x in items], g),
                                "ndcg_at_10": group_mean([x["ndcg10"] for x in items], g)}}
    elif t == "Classification":
        from sklearn.linear_model import LogisticRegression
        groups = pool["groups"] if "groups" in pool else {"": {"train": pool["train"],
                                                                "experiments": pool["experiments"]}}
        Xte = enc([x["text"] for x in pool["items"]], None)
        yte = np.array([str(x["label"]) for x in pool["items"]])
        gte = np.array([x.get("subset", "") for x in pool["items"]])
        n_exp = max(len(g["experiments"]) for g in groups.values())
        correct = np.full((n_exp, len(yte)), np.nan)
        per_exp = defaultdict(list)
        for sub, gd in groups.items():
            cols = np.where(gte == sub)[0] if "groups" in pool else np.arange(len(yte))
            if not len(cols):
                continue
            Xtr = enc(gd["train"]["text"], None)
            ytr = np.array([str(v) for v in gd["train"]["label"]])
            for e, idx in enumerate(gd["experiments"]):
                clf = LogisticRegression(random_state=42, n_jobs=-1, max_iter=100)
                clf.fit(Xtr[idx], ytr[idx])
                correct[e, cols] = clf.predict(Xte[cols]) == yte[cols]
                per_exp[e].append(float(np.mean(correct[e, cols])))
        acc = np.nanmean(correct, 0)
        items = [{"id": x["id"], "acc": float(a)} for x, a in zip(pool["items"], acc)]
        sc = group_mean(acc, gte)
        res = {"pool_score": sc,
               "pool_metrics": {"accuracy": sc,
                                "accuracy_per_experiment": [float(np.mean(per_exp[e])) for e in sorted(per_exp)]}}
    elif t == "PairClassification":
        A = enc([x["sentence1"] for x in pool["items"]], None)
        B = enc([x["sentence2"] for x in pool["items"]], None)
        y = np.array([x["label"] for x in pool["items"]])
        cos = cos_pairs(A, B)
        scores = {"cosine": cos, "dot": (A * B).sum(1), "euclidean": -np.linalg.norm(A - B, axis=1),
                  "manhattan": -np.abs(A - B).sum(1)}
        w = pair_weights(pool, y)
        gs = np.array([x.get("subset", "") for x in pool["items"]])

        def gap(v, wt):
            return float(np.nanmean([average_precision(y[gs == g], v[gs == g], None if wt is None else wt[gs == g])
                                     for g in dict.fromkeys(gs.tolist())]))
        aps = {k: gap(v, w) for k, v in scores.items()}
        aps_bal = {f"{k}_ap_balanced": gap(v, None) for k, v in scores.items()}
        thr, best = best_accuracy_threshold(cos, y)
        items = [{"id": x["id"], "cos": float(c), "correct": int((c >= thr) == bool(l))}
                 for x, c, l in zip(pool["items"], cos, y)]
        res = {"pool_score": float(np.nanmax(list(aps.values()))),
               "pool_metrics": {**{f"{k}_ap": v for k, v in aps.items()}, **aps_bal, "cosine_accuracy": best,
                                "cosine_threshold": thr}}
    elif t == "STS":
        A = enc([x["sentence1"] for x in pool["items"]], None)
        B = enc([x["sentence2"] for x in pool["items"]], None)
        cos = cos_pairs(A, B)
        items = [{"id": x["id"], "cos": float(c), "gold": x["score"]} for x, c in zip(pool["items"], cos)]
        gold = np.array([x["score"] for x in pool["items"]], dtype=float)
        gs = np.array([x.get("subset", "") for x in pool["items"]])
        sp = float(np.nanmean([spearman(cos[gs == g], gold[gs == g]) for g in dict.fromkeys(gs.tolist())]))
        res = {"pool_score": sp, "pool_metrics": {"cosine_spearman": sp}}
    elif t == "Clustering":
        X = enc([x["text"] for x in pool["items"]], None)
        nl = pool["n_levels"]
        cl = kmeans_runs(X, pool["items"], nl)
        agree = np.zeros(len(pool["items"]))
        cnt = np.zeros(len(pool["items"]))
        for gi in _group_index(pool["items"]):
            its = [pool["items"][i] for i in gi]
            for per in cl:
                for lv in range(nl):
                    mask, lab = level_labels(its, lv)
                    ids = per[lv][gi][mask]
                    maj = {}
                    for c in np.unique(ids):
                        maj[c] = np.bincount(lab[ids == c]).argmax()
                    hit = np.array([maj[c] == g for c, g in zip(ids, lab)], dtype=float)
                    agree[gi[mask]] += hit
                    cnt[gi[mask]] += 1
        agree /= np.maximum(cnt, 1)
        items = [{"id": x["id"], "agree": float(a), "clusters": [[int(per[lv][i]) for lv in range(nl)] for per in cl]}
                 for i, (x, a) in enumerate(zip(pool["items"], agree))]
        vm = cluster_score(X, pool["items"], nl)
        metrics = {"v_measure_kmeans": vm}
        if pool.get("mteb_ids"):          # mteb's own protocol on its downsampled documents (if all in pool)
            metrics["v_measure_mteb_protocol"] = mteb_cluster_protocol(X, pool)
        res = {"pool_score": vm, "pool_metrics": metrics}
        emb_out = X.astype(np.float16)
    elif t == "Summarization":
        mt = [s for x in pool["items"] for s in x["machine"]]
        ht = [s for x in pool["items"] for s in x["human"]]
        M, H = enc(mt, None), enc(ht, None)
        items, mi, hi = [], 0, 0
        for x in pool["items"]:
            m, h = M[mi:mi + len(x["machine"])], H[hi:hi + len(x["human"])]
            mi += len(x["machine"])
            hi += len(x["human"])
            pred = sim_matrix(m, h, "cosine").max(1)
            sp = spearman(x["relevance"], pred) if len(set(x["relevance"])) > 1 else float("nan")
            items.append({"id": x["id"], "spearman": sp, "pred": pred.tolist()})
        sc = float(np.nanmean([x["spearman"] for x in items]))
        res = {"pool_score": sc, "pool_metrics": {"cosine_spearman": sc}}
    elif t == "BitextMining":
        S1 = enc([x["sentence1"] for x in pool["items"]], None)
        keys = list(pool["bitext_texts"])
        T = enc([pool["bitext_texts"][k] for k in keys], None)
        kpos = {k: i for i, k in enumerate(keys)}
        cand_by = {sub: [kpos[k] for k in v] for sub, v in pool["bitext_candidates"].items()}
        items = []
        for i, x in enumerate(pool["items"]):
            tgt = kpos[x["target"]]
            cand = sorted(set(cand_by[x["subset"]]) | {tgt})
            sc = sim_matrix(S1[i:i + 1], T[cand], sim)[0]
            gold = sc[cand.index(tgt)]
            rank = int((sc > gold).sum()) + 1
            items.append({"id": x["id"], "correct": int(rank == 1), "rank": rank, "n_cand": len(cand)})
        g = [x["subset"] for x in pool["items"]]
        acc = group_mean([x["correct"] for x in items], g)
        res = {"pool_score": acc, "pool_metrics": {"accuracy": acc,
                                                    "mrr": group_mean([1 / x["rank"] for x in items], g)}}
    else:
        raise ValueError(t)
    res.update({"task": name, "type": t, "main_score": pool["main_score"], "n_items": len(items),
                "similarity": sim, "item_key": item_key, "items": items})
    return res, emb_out


def best_accuracy_threshold(s: np.ndarray, y: np.ndarray) -> tuple[float, float]:
    order = np.argsort(-s)
    ss, yy = s[order], y[order]
    tp = np.cumsum(yy)
    tn = (len(yy) - yy.sum()) - (np.arange(1, len(yy) + 1) - tp)
    acc = (tp + tn) / len(yy)
    j = int(np.argmax(acc))
    thr = float(ss[j]) if j + 1 >= len(ss) else float((ss[j] + ss[j + 1]) / 2)
    base = max(yy.mean(), 1 - yy.mean())
    if acc[j] < base:          # predicting all-negative is better
        return float(ss[0] + 1), float(base)
    return thr, float(acc[j])


def mteb_cluster_protocol(X: np.ndarray, pool: dict) -> Optional[float]:
    """mteb's ClusteringFast protocol (bootstrapped MiniBatchKMeans V-measure) on its own downsample."""
    try:
        from mteb.abstasks.AbsTaskClusteringFast import evaluate_clustering_bootstrapped
    except Exception:
        return None
    pos = {x["id"]: i for i, x in enumerate(pool["items"])}
    ids = [pos[i] for i in pool["mteb_ids"] if i in pos]
    if len(ids) < len(pool["mteb_ids"]) or len(ids) < 4:
        return None
    rng = random.Random(42)
    v = evaluate_clustering_bootstrapped(X[ids], [pool["items"][i]["labels"] for i in ids], n_clusters=10,
                                         cluster_size=pool.get("mteb_cluster_size", 16384), kmean_batch_size=512,
                                         max_depth=None, rng_state=rng)
    vals = [x for lv in v.values() for x in lv]
    return float(np.mean(vals))


# ----------------------------------------------------------------------------- subset scores (selection / eval)
class TaskScores:
    """Per-item scores of one task for M models, aligned on the pool's item ids."""

    def __init__(self, task: str, results: list[dict], embs: Optional[list[Optional[np.ndarray]]] = None,
                 pool: Optional[dict] = None):
        self.task, self.type = task, results[0]["type"]
        ids = [x["id"] for x in results[0]["items"]]
        for r in results[1:]:
            have = {x["id"] for x in r["items"]}
            ids = [i for i in ids if i in have]
        self.ids = ids
        self.M, self.N = len(results), len(ids)
        key = results[0].get("item_key") or ITEM_KEY[self.type]
        self.Y = np.zeros((self.M, self.N))
        for m, r in enumerate(results):
            byid = {x["id"]: x for x in r["items"]}
            for j, i in enumerate(ids):
                v = byid[i].get(key)
                self.Y[m, j] = np.nan if v is None else v
        self.pool_scores = np.array([r["pool_score"] for r in results], dtype=float)
        g = item_groups(pool) if pool is not None else {}
        self.group = np.array([g.get(i, "") for i in ids])
        self.multi = len(set(self.group.tolist())) > 1
        if self.type == "STS":
            b0 = {x["id"]: x for x in results[0]["items"]}
            self.gold = np.array([b0[i]["gold"] for i in ids], dtype=float)
        if self.type == "PairClassification":
            self.cos = np.zeros((self.M, self.N))
            for m, r in enumerate(results):
                byid = {x["id"]: x for x in r["items"]}
                self.cos[m] = [byid[i]["cos"] for i in ids]
            b0 = {x["id"]: x for x in pool["items"]} if pool else None
            self.label = np.array([b0[i]["label"] for i in ids]) if b0 else None
            self.w = pair_weights(pool, self.label) if b0 else None
        if self.type == "Clustering":
            self.clusters = []           # [m] -> array N x runs x levels
            for r in results:
                byid = {x["id"]: x for x in r["items"]}
                self.clusters.append(np.array([byid[i]["clusters"] for i in ids]))
            pitems = {x["id"]: x for x in pool["items"]}
            self.items = [pitems[i] for i in ids]
            self.n_levels = pool["n_levels"]
            self.labels = []
            for lv in range(self.n_levels):
                vocab = {}
                self.labels.append(np.array([vocab.setdefault(x["labels"][lv], len(vocab)) if len(x["labels"]) > lv
                                             else -1 for x in self.items]))
            self.embs = None
            if embs is not None and all(e is not None for e in embs):
                rows = {x["id"]: k for k, x in enumerate(pool["items"])}
                sel = [rows[i] for i in ids]
                self.embs = [e[sel].astype(np.float32) for e in embs]

    def _groups(self, cols: np.ndarray) -> list[np.ndarray]:
        if not self.multi:
            return [cols]
        gs = self.group[cols]
        return [cols[gs == g] for g in dict.fromkeys(gs.tolist())]

    def _sts(self, cols: np.ndarray, ms: np.ndarray) -> np.ndarray:
        from scipy.stats import rankdata
        g = rankdata(self.gold[cols])
        c = rankdata(self.Y[np.ix_(ms, cols)], axis=1)
        g = (g - g.mean()) / (g.std() + 1e-12)
        c = (c - c.mean(1, keepdims=True)) / (c.std(1, keepdims=True) + 1e-12)
        return (c * g).mean(1)

    def subset(self, cols: np.ndarray, models: Optional[np.ndarray] = None, exact: bool = False) -> np.ndarray:
        """Task score of an item subset for every model (cols: indices into self.ids); multi-subset tasks:
        mean over the hf_subsets present (set metrics: subsets with too few items are skipped, falling back
        to the pooled metric if none qualifies).
        exact=True: clustering re-clusters the subset (what the lite eval does); else the fast proxy
        (V-measure of the pool clusterings restricted to the subset)."""
        ms = np.arange(self.M) if models is None else np.asarray(models)
        cols = np.asarray(cols, dtype=int)
        t = self.type
        if t == "STS":
            if not self.multi:
                return self._sts(cols, ms)
            per = [self._sts(gc, ms) for gc in self._groups(cols) if len(gc) >= 3]
            return np.mean(per, 0) if per else self._sts(cols, ms)
        if t == "PairClassification":
            def ap(cc):
                w = None if self.w is None else self.w[cc]
                return np.array([average_precision(self.label[cc], self.cos[m, cc], w) for m in ms])
            if not self.multi:
                return ap(cols)
            per = [ap(gc) for gc in self._groups(cols)]
            per = [p for p in per if not np.isnan(p).any()]
            return np.mean(per, 0) if per else ap(cols)
        if t == "Clustering":
            if exact and self.embs is not None:
                its = [self.items[j] for j in cols]
                return np.array([cluster_score(self.embs[m][cols], its, self.n_levels) for m in ms])
            out = []
            for m in ms:
                cl = self.clusters[m]
                per_group = []
                for gc in self._groups(cols):
                    vals = []
                    for r in range(cl.shape[1]):
                        for lv in range(self.n_levels):
                            lab = self.labels[lv][gc]
                            ok = lab >= 0
                            if ok.sum() >= 2:
                                vals.append(v_measure_fast(lab[ok], cl[gc, r, lv][ok]))
                    if vals:
                        per_group.append(np.nanmean(vals))
                out.append(np.nanmean(per_group) if per_group else np.nan)
            return np.array(out)
        if not self.multi:
            return np.nanmean(self.Y[np.ix_(ms, cols)], axis=1)
        with np.errstate(all="ignore"):
            per = [np.nanmean(self.Y[np.ix_(ms, gc)], axis=1) for gc in self._groups(cols)]
        return np.nanmean(per, 0)


def load_scores(name: str, task: str) -> tuple[Optional[dict], Optional[np.ndarray]]:
    p = SCORES / name / f"{task}.json"
    if not p.exists():
        return None, None
    e = SCORES / name / f"{task}.emb.npy"
    return json.loads(p.read_text()), (np.load(e) if e.exists() else None)