File size: 20,753 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
#!/usr/bin/env python
"""MTEB-lite (eng), step C: choose K items per task so the subset ranks models like full MTEB(eng, v2).

Inputs: per-item scores of M models (outputs/mteb_lite/scores/<NAME>/<task>.json, mteb_lite_score.py) and
the FULL main score per task of those models, looked up by NAME in
  outputs/mteb_en/<NAME>/summary_en.json, outputs/merge_sweep/scores*/<NAME>/mteb_en/summary_en.json,
  --full-csv (columns name,task,score; score in [0,1] or [0,100]),
falling back to the model's pool-level score (flagged) if a full score is unknown.

Per task:
  * item outcome across models, discretised into --bins fixed-width bins; zero-entropy items dropped
    (STS: |percentile(cos) - percentile(gold)|, a per-pair rank error; others: their per-item score);
  * relevance = MI(item bin; model full-score rank bin) (or |Spearman| with --relevance spearman);
  * per-item tasks (retrieval, reranking, classification, summarization; task score = mean over items):
    greedy mRMR, score = relevance - mean MI with the already selected items;
  * set-metric tasks (STS Spearman, clustering V-measure, pair-classification AP): greedy forward
    selection maximising Kendall tau (+ 0.1 Pearson as tie-break) between the subset task score and the
    full task score across models, started from the top mRMR items;
  * linear calibration full ~ a + b * subset score, fitted across models.
Validation (--lomo): leave-one-model-out — select + calibrate on M-1 models, predict the held-out model's
full score from its subset score; per task and for the 41-task macro (mean over the 8 types) / mean:
Kendall tau, Pearson, MAE. Baselines: K random items, and the whole pool (both calibrated the same way).

  python scripts/mteb_lite_select.py [--models a,b,c] [--full-csv f.csv] [--K 100] [--lomo] [--jobs 64]
Writes data/mteb_lite/selection/<task>.json, data/mteb_lite/MTEB_lite_eng.json,
outputs/mteb_lite/selection_report.{md,json}.
"""
from __future__ import annotations

import argparse
import csv
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

REPO = L.REPO
SET_TYPES = L.SET_TYPES


# ----------------------------------------------------------------------------- full scores
def full_scores(names: list[str], csv_path: str | None) -> dict[str, dict[str, float]]:
    out: dict[str, dict[str, float]] = defaultdict(dict)
    for n in names:
        cands = [REPO / "outputs" / "mteb_en" / n / "summary_en.json"]
        cands += sorted((REPO / "outputs" / "merge_sweep").glob(f"scores*/{n}/mteb_en/summary_en.json"))
        for p in cands:
            if p.exists():
                for r in json.loads(p.read_text())["rows"]:
                    out[n].setdefault(r["task"], float(r["main_score"]))
    if csv_path:
        with open(csv_path) as f:
            for r in csv.DictReader(f):
                v = float(r["score"])
                out[r["name"]][r["task"]] = v / 100 if v > 1.5 else v
    return out


# ----------------------------------------------------------------------------- information measures
def discretise(Y: np.ndarray, typ: str, bins: int) -> np.ndarray:
    lo, hi = (-1.0, 1.0) if typ == "Summarization" else (0.0, 1.0)
    Z = np.clip((np.nan_to_num(Y, nan=lo) - lo) / (hi - lo), 0, 1)
    return np.minimum((Z * bins).astype(int), bins - 1)


def rank_bins(f: np.ndarray, bins: int) -> np.ndarray:
    from scipy.stats import rankdata
    b = min(bins, len(f))
    r = rankdata(f, method="ordinal") - 1
    return np.minimum((r * b / len(f)).astype(int), b - 1)


def entropy_cols(B: np.ndarray, nb: int) -> np.ndarray:
    P = np.stack([(B == k).mean(0) for k in range(nb)], 1)
    with np.errstate(divide="ignore", invalid="ignore"):
        return -np.nansum(np.where(P > 0, P * np.log(P), 0), 1)


def mi_with(B: np.ndarray, t: np.ndarray, nb: int, nt: int) -> np.ndarray:
    """MI (nats) of every column of B (models x items, ints < nb) with the vector t (ints < nt)."""
    M = B.shape[0]
    OH = np.stack([(B == k) for k in range(nb)], 2).astype(float)       # M x N x nb
    T = np.stack([(t == k) for k in range(nt)], 1).astype(float)        # M x nt
    J = np.einsum("mia,mb->iab", OH, T) / M                             # N x nb x nt
    pa, pb = J.sum(2, keepdims=True), J.sum(1, keepdims=True)
    with np.errstate(divide="ignore", invalid="ignore"):
        v = np.where(J > 0, J * np.log(J / (pa * pb)), 0)
    return v.sum((1, 2))


def item_outcomes(ts: L.TaskScores) -> np.ndarray:
    """Per-item outcome (models x items) in [0,1] ([-1,1] for summarization) used for entropy / MI."""
    if ts.type == "STS":
        from scipy.stats import rankdata
        pc = (rankdata(ts.Y, axis=1) - 1) / max(ts.N - 1, 1)
        pg = (rankdata(ts.gold) - 1) / max(ts.N - 1, 1)
        return 1 - np.abs(pc - pg[None])
    return ts.Y


def kendall(a, b) -> float:
    from scipy.stats import kendalltau
    a, b = np.asarray(a, float), np.asarray(b, float)
    if len(a) < 2 or np.all(a == a[0]) or np.all(b == b[0]) or np.isnan(a).any():
        return float("nan")
    return float(kendalltau(a, b)[0])


def pearson(a, b) -> float:
    a, b = np.asarray(a, float), np.asarray(b, float)
    if len(a) < 2 or a.std() == 0 or b.std() == 0 or np.isnan(a).any():
        return float("nan")
    return float(np.corrcoef(a, b)[0, 1])


def spearman_cols(Y: np.ndarray, f: np.ndarray) -> np.ndarray:
    from scipy.stats import rankdata
    R = rankdata(np.nan_to_num(Y), axis=0)
    rf = rankdata(f)
    R = R - R.mean(0)
    rf = rf - rf.mean()
    den = np.sqrt((R ** 2).sum(0) * (rf ** 2).sum())
    with np.errstate(divide="ignore", invalid="ignore"):
        return np.where(den > 0, (R * rf[:, None]).sum(0) / den, 0)


# ----------------------------------------------------------------------------- selection
def select(ts: L.TaskScores, f: np.ndarray, models: np.ndarray, K: int, bins: int, relevance: str,
           n_cand: int, seed: int = 0) -> tuple[list[int], dict]:
    """Indices (into ts.ids) of K items chosen using only `models` (rows)."""
    O = item_outcomes(ts)[models]
    fm = f[models]
    B = discretise(O, ts.type, bins)
    H = entropy_cols(B, bins)
    tb = rank_bins(fm, bins)
    nt = int(tb.max()) + 1
    mi = mi_with(B, tb, bins, nt)
    sp = np.abs(spearman_cols(O, fm))
    rel = mi if relevance == "mi" else sp
    rel = rel + 1e-3 * sp                                 # tie-break on |Spearman|
    alive = np.where(H > 1e-12)[0]
    if len(alive) < K:                                    # not enough informative items: pad with the rest
        alive = np.arange(ts.N)
    stats = {"entropy": H, "mi": mi, "spearman": sp}
    if len(alive) <= K and ts.type not in SET_TYPES:
        return sorted(alive.tolist()), stats
    # --- mRMR
    OH = np.stack([(B == k) for k in range(bins)], 2).astype(float)      # Mt x N x bins
    Mt = B.shape[0]
    red = np.zeros(ts.N)
    chosen: list[int] = []
    k_mrmr = K if ts.type not in SET_TYPES else min(10, K)
    avail = np.zeros(ts.N, bool)
    avail[alive] = True
    for step in range(min(k_mrmr, int(avail.sum()))):
        sc = rel - (red / step if step else 0)
        sc = np.where(avail, sc, -np.inf)
        j = int(np.argmax(sc))
        chosen.append(j)
        avail[j] = False
        J = np.einsum("mia,mb->iab", OH, OH[:, j, :]) / Mt                 # N x bins x bins
        pa, pb = J.sum(2, keepdims=True), J.sum(1, keepdims=True)
        with np.errstate(divide="ignore", invalid="ignore"):
            red += np.where(J > 0, J * np.log(J / (pa * pb)), 0).sum((1, 2))
    if ts.type not in SET_TYPES:
        return sorted(chosen), stats
    # --- greedy forward selection on the set metric (rank agreement with the full score)
    rng = np.random.RandomState(seed)
    pool_idx = alive if len(alive) >= K else np.arange(ts.N)
    avail = np.zeros(ts.N, bool)
    avail[pool_idx] = True
    avail[chosen] = False
    while len(chosen) < K and avail.any():
        cands = np.where(avail)[0]
        if len(cands) > n_cand:
            cands = rng.choice(cands, n_cand, replace=False)
        best, bj = -np.inf, None
        for c in cands:
            s = ts.subset(np.array(chosen + [int(c)]), models)
            if np.isnan(s).any():
                continue
            obj = np.nan_to_num(kendall(s, fm)) + 0.1 * np.nan_to_num(pearson(s, fm))
            if obj > best:
                best, bj = obj, int(c)
        if bj is None:
            bj = int(cands[0])
        chosen.append(bj)
        avail[bj] = False
    return sorted(chosen), stats


def calibrate(s: np.ndarray, f: np.ndarray) -> tuple[float, float]:
    ok = ~(np.isnan(s) | np.isnan(f))
    s, f = s[ok], f[ok]
    if len(s) >= 3 and s.std() > 1e-9:
        b, a = np.polyfit(s, f, 1)
        return float(a), float(b)
    return float(np.mean(f - s)) if len(s) else 0.0, 1.0


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


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


def run_job(task: str, names: list[str], f: list[float], src: list[str], holdout: int | None, args) -> dict:
    ts = task_scores(task, names)
    f = np.asarray(f, float)
    M = ts.M
    # fit only on models with a real full score (pool-score fallback only if fewer than 3 have one)
    real = [m for m in range(M) if src[m] == "full" and m != holdout]
    train = np.array(real if len(real) >= 3 else [m for m in range(M) if m != holdout])
    t0 = time.time()
    sel, stats = select(ts, f, train, args.K, args.bins, args.relevance, args.n_cand)
    out = {"task": task, "holdout": holdout, "sel": sel, "seconds": time.time() - t0}
    exact = ts.type == "Clustering"
    s_all = ts.subset(np.array(sel), exact=exact)
    a, b = calibrate(s_all[train], f[train])
    out.update({"subset": s_all.tolist(), "cal": [a, b], "pred": (a + b * s_all).tolist()})
    if holdout is None:
        out["stats"] = {k: v.tolist() for k, v in stats.items()}
    else:
        rng = np.random.RandomState(1000 + holdout)
        preds = []
        for _ in range(args.n_random_baseline):
            cols = np.sort(rng.choice(ts.N, min(args.K, ts.N), replace=False))
            s = ts.subset(cols, exact=exact)
            ar, br = calibrate(s[train], f[train])
            preds.append(ar + br * s[holdout])
        out["pred_random"] = float(np.nanmean(preds))
        ap_, bp_ = calibrate(ts.pool_scores[train], f[train])
        out["pred_pool"] = float(ap_ + bp_ * ts.pool_scores[holdout])
    return out


def metrics(pred: np.ndarray, true: np.ndarray) -> dict:
    ok = ~(np.isnan(pred) | np.isnan(true))
    p, t = pred[ok], true[ok]
    return {"kendall": kendall(p, t), "pearson": pearson(p, t),
            "mae": float(np.mean(np.abs(p - t))) if len(p) else float("nan"), "n": int(ok.sum())}


def aggregate(scores: dict[str, float], types: dict[str, str]) -> tuple[float, float]:
    by = defaultdict(list)
    for t, v in scores.items():
        by[types[t]].append(100 * v)
    macro = float(np.mean([np.mean(v) for v in by.values()]))
    mean = float(np.mean([100 * v for v in scores.values()]))
    return macro, mean


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--scores-dir", default=str(L.SCORES))
    ap.add_argument("--models", default=None, help="comma list of score dirs (default: all)")
    ap.add_argument("--tasks", default=None)
    ap.add_argument("--full-csv", default=None)
    ap.add_argument("--K", type=int, default=100)
    ap.add_argument("--bins", type=int, default=5)
    ap.add_argument("--relevance", choices=["mi", "spearman"], default="mi")
    ap.add_argument("--n-cand", type=int, default=200, help="set-metric greedy: candidates tried per step")
    ap.add_argument("--n-random-baseline", type=int, default=5)
    ap.add_argument("--lomo", action="store_true")
    ap.add_argument("--jobs", type=int, default=1)
    ap.add_argument("--out", default=str(L.LITE))
    ap.add_argument("--report", default=str(REPO / "outputs" / "mteb_lite" / "selection_report"))
    args = ap.parse_args()
    L.SCORES = Path(args.scores_dir)
    names = sorted(args.models.split(",")) if args.models else sorted(
        p.name for p in L.SCORES.iterdir() if p.is_dir())
    types = {n: L.get_task(n).metadata.type for n in L.task_names()}
    tasks = args.tasks.split(",") if args.tasks else [t for t in L.task_names() if L.pool_path(t).exists()]
    fulls = full_scores(names, args.full_csv)
    jobs, info = [], {}
    for t in tasks:
        have = [n for n in names if (L.SCORES / n / f"{t}.json").exists()]
        if len(have) < 3:
            print(f"[select] {t}: only {len(have)} models scored - skipped", flush=True)
            continue
        f, src = [], []
        for n in have:
            if t in fulls.get(n, {}):
                f.append(fulls[n][t])
                src.append("full")
            else:
                f.append(json.loads((L.SCORES / n / f"{t}.json").read_text())["pool_score"])
                src.append("pool")
        info[t] = {"names": have, "f": f, "src": src}
        jobs.append((t, have, f, src, None))
        if args.lomo and src.count("full") >= 4:
            jobs += [(t, have, f, src, m) for m in range(len(have)) if src[m] == "full"]
    print(f"[select] {len(info)} tasks, {len(names)} models, {len(jobs)} jobs", flush=True)
    results = []
    if args.jobs > 1:
        from concurrent.futures import ProcessPoolExecutor
        jobs.sort(key=lambda j: (types[j[0]] not in SET_TYPES, j[0]))
        with ProcessPoolExecutor(args.jobs) as ex:
            futs = [ex.submit(run_job, *j, args) for j in jobs]
            for fu in futs:
                results.append(fu.result())
    else:
        results = [run_job(*j, args) for j in jobs]
    final = {r["task"]: r for r in results if r["holdout"] is None}
    lomo = defaultdict(dict)
    for r in results:
        if r["holdout"] is not None:
            lomo[r["task"]][r["holdout"]] = r

    out = Path(args.out)
    (out / "selection").mkdir(parents=True, exist_ok=True)
    manifest = {"benchmark": "MTEB-lite (eng)", "source_benchmark": L.BENCHMARK, "K": args.K,
                "models": names, "method": {"bins": args.bins, "relevance": args.relevance,
                                            "per_item": "mRMR", "set_metric": "greedy Kendall tau"},
                "tasks": {}}
    report = {"per_task": {}, "aggregate": {}, "args": vars(args)}
    for t, r in final.items():
        ts = task_scores(t, info[t]["names"])
        ids = [ts.ids[j] for j in r["sel"]]
        st = r["stats"]
        sel_doc = {"task": t, "type": types[t], "K": len(ids), "ids": ids, "calibration": r["cal"],
                   "n_pool_items": ts.N, "n_informative": int(np.sum(np.array(st["entropy"]) > 1e-12)),
                   "items": [{"id": ts.ids[j], "entropy": st["entropy"][j], "mi": st["mi"][j],
                              "abs_spearman": st["spearman"][j]} for j in r["sel"]],
                   "models": info[t]["names"], "full_score_source": info[t]["src"]}
        (out / "selection" / f"{t}.json").write_text(json.dumps(sel_doc, indent=1))
        manifest["tasks"][t] = {"type": types[t], "main_score": L.get_task(t).metadata.main_score,
                                "ids": ids, "calibration": {"a": r["cal"][0], "b": r["cal"][1]},
                                "subset_metric": "re-clustered V-measure" if types[t] == "Clustering" else
                                ("Spearman(cos, gold)" if types[t] == "STS" else
                                 ("weighted AP(cos)" if types[t] == "PairClassification" else
                                  f"mean {L.ITEM_KEY[types[t]]}"))}
        f = np.array(info[t]["f"])
        real = np.array([x == "full" for x in info[t]["src"]])
        row = {"type": types[t], "n_models": len(f), "n_full": int(real.sum()),
               "in_sample": metrics(np.array(r["pred"])[real], f[real]) if real.sum() >= 2 else {},
               "subset_vs_full_raw": {"kendall": kendall(np.array(r["subset"])[real], f[real]),
                                      "pearson": pearson(np.array(r["subset"])[real], f[real])},
               "pool_vs_full_raw": {"kendall": kendall(ts.pool_scores[real], f[real]),
                                    "pearson": pearson(ts.pool_scores[real], f[real])}}
        if lomo.get(t):
            hs = sorted(lomo[t])
            pt = np.array([lomo[t][m]["pred"][m] for m in hs])
            tt = f[hs]
            row["lomo"] = metrics(pt, tt)
            row["lomo_random"] = metrics(np.array([lomo[t][m]["pred_random"] for m in hs]), tt)
            row["lomo_pool"] = metrics(np.array([lomo[t][m]["pred_pool"] for m in hs]), tt)
        report["per_task"][t] = row
    (out / "MTEB_lite_eng.json").write_text(json.dumps(manifest, indent=1))

    # aggregate (models with LOMO predictions on every task)
    if lomo and len(final) == len(info):
        agg = {"lomo": defaultdict(list), "lomo_random": defaultdict(list), "lomo_pool": defaultdict(list),
               "true": defaultdict(list)}
        for n in names:
            if not all(n in info[t]["names"] for t in final):
                continue
            idx = {t: info[t]["names"].index(n) for t in final}
            if not all(idx[t] in lomo[t] for t in final):
                continue
            tru = {t: info[t]["f"][idx[t]] for t in final}
            for key, fn in (("lomo", lambda t: lomo[t][idx[t]]["pred"][idx[t]]),
                            ("lomo_random", lambda t: lomo[t][idx[t]]["pred_random"]),
                            ("lomo_pool", lambda t: lomo[t][idx[t]]["pred_pool"])):
                ma, me = aggregate({t: fn(t) for t in final}, types)
                agg[key]["macro"].append(ma)
                agg[key]["mean"].append(me)
            ma, me = aggregate(tru, types)
            agg["true"]["macro"].append(ma)
            agg["true"]["mean"].append(me)
            agg["true"]["names"].append(n)
        for key in ("lomo", "lomo_random", "lomo_pool"):
            report["aggregate"][key] = {k: metrics(np.array(agg[key][k]), np.array(agg["true"][k]))
                                        for k in ("macro", "mean")} if agg["true"]["macro"] else {}
        report["aggregate"]["models"] = agg["true"]["names"]
    rp = Path(args.report)
    rp.parent.mkdir(parents=True, exist_ok=True)
    rp.with_suffix(".json").write_text(json.dumps(report, indent=1, default=float))
    rp.with_suffix(".md").write_text(render(report, manifest))
    print(render(report, manifest))


def render(report: dict, manifest: dict) -> str:
    def f3(x):
        return "-" if x is None or (isinstance(x, float) and np.isnan(x)) else f"{x:.3f}"
    lines = [f"# MTEB-lite (eng) selection report", "",
             f"K={manifest['K']} items/task, {len(manifest['models'])} models: {', '.join(manifest['models'])}", "",
             "| task | type | models (full) | LOMO tau | LOMO r | LOMO MAE | random tau | random MAE | pool tau | pool MAE | in-sample tau |",
             "|---|---|---|---|---|---|---|---|---|---|---|"]
    for t, r in report["per_task"].items():
        lo, ra, po = r.get("lomo", {}), r.get("lomo_random", {}), r.get("lomo_pool", {})
        lines.append(f"| {t} | {r['type']} | {r['n_models']} ({r['n_full']}) | {f3(lo.get('kendall'))} | "
                     f"{f3(lo.get('pearson'))} | {f3(lo.get('mae'))} | {f3(ra.get('kendall'))} | {f3(ra.get('mae'))} | "
                     f"{f3(po.get('kendall'))} | {f3(po.get('mae'))} | {f3(r['in_sample'].get('kendall'))} |")
    if report["aggregate"]:
        lines += ["", f"## {len(report['per_task'])}-task aggregate (leave-one-model-out; scores x100)", "",
                  "| estimate | macro tau | macro r | macro MAE | mean tau | mean r | mean MAE |", "|---|---|---|---|---|---|---|"]
        for key in ("lomo", "lomo_random", "lomo_pool"):
            a = report["aggregate"].get(key) or {}
            if a:
                lines.append(f"| {key} | {f3(a['macro']['kendall'])} | {f3(a['macro']['pearson'])} | "
                             f"{f3(a['macro']['mae'])} | {f3(a['mean']['kendall'])} | {f3(a['mean']['pearson'])} | "
                             f"{f3(a['mean']['mae'])} |")
    return "\n".join(lines) + "\n"


if __name__ == "__main__":
    main()