#!/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: --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:[+norm] | native[+tok|+inst_tok]: (as run_mteb_english.py) Output: outputs/mteb_lite/scores//.json (+ .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:[+norm] (alias mteb:...) | native[+tok|+inst_tok]: - 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:[+norm] or native[+tok|+inst_tok]:") 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()