File size: 6,075 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
#!/usr/bin/env python
"""MTEB-lite (eng), step B: per-item scores of one model on the candidate pools.

The model is loaded exactly as scripts/run_mteb_english.py loads it (mteb's native wrapper: the model's
own per-task instructions / prompts), and every text is encoded through model.encode(task_name=...,
prompt_type=query|document|None) the way mteb's evaluators call it.

  python scripts/mteb_lite_score.py --model hf:Qwen/Qwen3-Embedding-0.6B --name qwen3-0.6b
  python scripts/mteb_lite_score.py --model native:<export dir> --name NAME [--tasks A,B] [--shard i/n]
  python scripts/mteb_lite_score.py --model hf:intfloat/multilingual-e5-large-instruct --name me5-large-inst
  python scripts/mteb_lite_score.py --suite ara --model hf:Qwen/Qwen3-Embedding-0.6B --name qwen3-0.6b [--shard i/n]
      (Arabic MMTEB-lite: pools data/mteb_lite_ar/pool, scores outputs/mteb_lite_ar/scores; max length 512 and
      the model's per-task instructions exactly as run_mteb_arabic.py)
Model spec: hf:<mteb model name>[+norm] | native[+tok|+inst_tok]:<export dir>  (as run_mteb_english.py)
Output: outputs/mteb_lite/scores/<NAME>/<task>.json (+ <task>.emb.npy for clustering), resumable per task.
"""
from __future__ import annotations

import os as _os
if _os.environ.get("ADIP_HF_ONLINE") != "1":
    _os.environ.setdefault("HF_HUB_OFFLINE", "1")
    _os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
    _os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")

import argparse
import json
import sys
import time
from pathlib import Path

import numpy as np

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


def load_model(spec: str, max_length: int | None = None):
    """hf:<mteb name>[+norm] (alias mteb:...) | native[+tok|+inst_tok]:<export dir> - mteb's native wrapper
    (the model's own per-task instructions), as run_mteb_english.py / run_mteb_arabic.py load them."""
    from adip.eval import mteb_arabic as ma
    if spec.startswith("mteb:"):
        spec = "hf:" + spec[len("mteb:"):]
    if spec.startswith("hf:"):
        return ma.load_native(spec[3:], max_length=max_length)
    if spec.startswith("native"):
        mode, path = ma.parse_native(spec)
        return ma.load_native_with_export(path, max_length=max_length, prompts=mode)
    raise ValueError(f"model spec {spec!r}: use hf:<name>[+norm] or native[+tok|+inst_tok]:<export dir>")


def shard_names(names: list[str], i: int, n: int) -> list[str]:
    """Balance shards by pool encode size (number of characters)."""
    stats = L.LITE / "pool_stats.json"
    cost = {}
    if stats.exists():
        cost = {r["task"]: r["tokens"] for r in json.loads(stats.read_text())["rows"]}
    loads, buckets = [0.0] * n, [[] for _ in range(n)]
    for t in sorted(names, key=lambda t: -cost.get(t, 1e5)):
        k = min(range(n), key=lambda j: loads[j])
        buckets[k].append(t)
        loads[k] += cost.get(t, 1e5)
    return buckets[i]


def main() -> None:
    L.configure(L.suite_from_argv())
    ap = argparse.ArgumentParser()
    ap.add_argument("--suite", choices=["eng", "ara"], default="eng")
    ap.add_argument("--model", required=True)
    ap.add_argument("--name", required=True)
    ap.add_argument("--tasks", default=None, help="comma list (default: every task with a pool)")
    ap.add_argument("--shard", default=None, help="i/n (balanced by pool tokens)")
    ap.add_argument("--batch-size", type=int, default=64)
    ap.add_argument("--max-length", type=int, default=L.SUITES[L.SUITE]["max_length"],
                    help="model max_seq_length (default: native for eng, 512 for ara as run_mteb_arabic.py)")
    ap.add_argument("--out", default=str(L.SCORES))
    ap.add_argument("--overwrite", action="store_true")
    ap.add_argument("--check-load", action="store_true", help="load the model, encode 2 texts, exit")
    args = ap.parse_args()
    if args.check_load:
        model = load_model(args.model, args.max_length)
        e = L.encode_texts(model, ["a test query", "another text"], "ArguAna" if args.suite == "eng" else "XPQARetrieval",
                           "query")
        print(f"[lite-score] LOAD OK {args.model}: {type(model).__name__} dim={e.shape[1]} "
              f"similarity={L.similarity_name(model)}", flush=True)
        return
    out = Path(args.out) / args.name
    out.mkdir(parents=True, exist_ok=True)
    names = args.tasks.split(",") if args.tasks else [n for n in L.task_names() if L.pool_path(n).exists()]
    if args.shard:
        i, n = map(int, args.shard.split("/"))
        names = shard_names(names, i, n)
    todo = [n for n in names if args.overwrite or not (out / f"{n}.json").exists()]
    if not todo:
        print(f"[lite-score] {args.name}: nothing to do", flush=True)
        return
    model = load_model(args.model, args.max_length)
    (out / "model.json").write_text(json.dumps({"model": args.model, "name": args.name,
                                                "similarity": L.similarity_name(model)}, indent=1))
    t_all = time.time()
    for name in todo:
        t0 = time.time()
        try:
            pool = L.load_pool(name)
            res, emb = L.score_pool(pool, model, batch_size=args.batch_size)
        except Exception as e:
            import traceback
            traceback.print_exc()
            print(f"[lite-score] {args.name} {name}: FAILED {type(e).__name__}: {e}", flush=True)
            continue
        res.update({"model": args.model, "name": args.name, "seconds": time.time() - t0})
        if emb is not None:
            np.save(out / f"{name}.emb.npy", emb)
        tmp = out / f"{name}.json.tmp"
        tmp.write_text(json.dumps(res))
        tmp.replace(out / f"{name}.json")
        print(f"[lite-score] {args.name} {name}: pool {res['pool_score']:.4f} ({res['n_items']} items, "
              f"{time.time() - t0:.0f}s)", flush=True)
    print(f"[lite-score] {args.name}: {len(todo)} tasks in {time.time() - t_all:.0f}s", flush=True)


if __name__ == "__main__":
    main()