AbstractPhil commited on
Commit
289b976
Β·
verified Β·
1 Parent(s): 17625c8

Create full_benchmark.py

Browse files
Files changed (1) hide show
  1. full_benchmark.py +542 -0
full_benchmark.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # CAPTIONBERT FULL BENCHMARK -- teachers, MiniLM, both trunks, arms
3
+ #
4
+ # One harness, one pass, every model measured on the SAME eight tasks with the
5
+ # SAME pooling and normalization. The card tables so far mixed sources: the
6
+ # teacher numbers came from a 2-task run, the trunk numbers from an 8-task run,
7
+ # and MiniLM was quoted for scale from a different pass. That is not a fair
8
+ # comparison and it is not defensible in a writeup.
9
+ #
10
+ # WHAT IS MEASURED
11
+ # 5 teachers bert-base, ModernBERT-base, roberta-base, albert-base-v2,
12
+ # distilbert -- the exact models the consensus was built from
13
+ # reference all-MiniLM-L6-v2 (contrastive, 1B+ curated pairs: a
14
+ # DIFFERENT comparison class, labelled as such)
15
+ # 2 trunks captionbert-8192-v2 (54 chunks) and -b (66 chunks)
16
+ # 2 arm sets each trunk with ITS OWN native arms -- anchors are
17
+ # trunk-bound (v2 arms on -b cost 31% of their gain)
18
+ #
19
+ # 8 TASKS: STS-B, SICK-R, STS12-16, BIOSSES. BIOSSES is 100 rows and is the only
20
+ # genuinely out-of-domain gauge; it is reported but never used alone.
21
+ #
22
+ # EVERY MODEL IS MEAN-POOLED AND L2-NORMALIZED. That is the honest setting for
23
+ # an untuned encoder and it is what the teachers were consensus-averaged in.
24
+ # It is also why bert-base scores low here: raw mean-pooled BERT is a known-weak
25
+ # sentence encoder, which is the entire reason Sentence-BERT exists. Beating it
26
+ # is a real efficiency result, not a competitive sentence-embedding result --
27
+ # the card should say so and the MiniLM row is there to keep that honest.
28
+ #
29
+ # Config at the top, functionality in the body, run logic at the base.
30
+ # ============================================================================
31
+
32
+ import gc
33
+ import json
34
+ import os
35
+ import subprocess
36
+ import sys
37
+ from dataclasses import dataclass, asdict
38
+ from typing import Dict, List, Optional, Tuple
39
+
40
+ for _p, _i in [("datasets", "datasets"), ("transformers", "transformers"),
41
+ ("scipy", "scipy"), ("huggingface_hub", "huggingface_hub"),
42
+ ("amoe-lora @ git+https://github.com/AbstractEyes/amoe-lora", "amoe")]:
43
+ try:
44
+ __import__(_i)
45
+ except ImportError:
46
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", _p], check=False)
47
+
48
+ import numpy as np
49
+ import torch
50
+ import torch.nn.functional as F
51
+ from scipy.stats import spearmanr
52
+ from huggingface_hub import hf_hub_download
53
+ from transformers import AutoModel, AutoTokenizer
54
+ from datasets import load_dataset
55
+
56
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
57
+
58
+
59
+ # ══════════════════════════════════════════════════════════════════
60
+ # BASE CONFIG
61
+ # ══════════════════════════════════════════════════════════════════
62
+
63
+ @dataclass
64
+ class BaseConfig:
65
+ # ---- the five teachers the consensus was built from ----
66
+ teachers: tuple = (
67
+ ("bert-base", "google-bert/bert-base-uncased"),
68
+ ("ModernBERT-base", "answerdotai/ModernBERT-base"),
69
+ ("roberta-base", "FacebookAI/roberta-base"),
70
+ ("albert-base-v2", "albert/albert-base-v2"),
71
+ ("distilbert", "distilbert/distilbert-base-uncased"),
72
+ )
73
+ # ---- reference point, NOT a teacher ----
74
+ references: tuple = (
75
+ ("all-MiniLM-L6-v2", "sentence-transformers/all-MiniLM-L6-v2"),
76
+ )
77
+ # ---- (label, repo, ckpt, arm_dir|None, dispatch|None) ----
78
+ # Arm locations are EXPLICIT. Earlier versions resolved them through
79
+ # modeling_captionbert.py, which meant the benchmark broke whenever that
80
+ # file was mid-update: BOTH repos currently carry a pre-patch copy that
81
+ # searches amoe/collective/ and amoe/moe/, so -b 404s. A benchmark should
82
+ # not depend on an artifact it is measuring.
83
+ trunks: tuple = (
84
+ ("captionbert-v2", "AbstractPhil/captionbert-8192-v2",
85
+ "checkpoints/best_model.pt", "amoe/collective",
86
+ "amoe/collective/captionbert-v2-collective.dispatch.pt"),
87
+ ("captionbert-b", "AbstractPhil/captionbert-8192-v2-B",
88
+ "checkpoints/final_model.pt", "amoe/b-collective",
89
+ "amoe/b-collective/captionbert-b-arms-native.dispatch.pt"),
90
+ )
91
+ # architecture, so the trunk class is local and needs no remote code
92
+ vocab_size: int = 30522
93
+ d_model: int = 512
94
+ n_heads: int = 12 - 4
95
+ n_layers: int = 12
96
+ d_ff: int = 2048
97
+ output_dim: int = 768
98
+ max_len: int = 8192
99
+ pooling: str = "mean"
100
+ # anchor spec -- the certified campaign defaults every anchor was built with
101
+ n_slots: int = 16
102
+ K: int = 64
103
+ D: int = 4
104
+ tau: float = 0.1
105
+ hidden: int = 178
106
+ gate_init: float = -3.0
107
+ align_emb: int = 64
108
+
109
+ tasks: tuple = (
110
+ ("STS-B", "mteb/stsbenchmark-sts"),
111
+ ("SICK-R", "mteb/sickr-sts"),
112
+ ("STS12", "mteb/sts12-sts"),
113
+ ("STS13", "mteb/sts13-sts"),
114
+ ("STS14", "mteb/sts14-sts"),
115
+ ("STS15", "mteb/sts15-sts"),
116
+ ("STS16", "mteb/sts16-sts"),
117
+ ("BIOSSES", "mteb/biosses-sts"),
118
+ )
119
+
120
+ batch_size: int = 256
121
+ max_tokens: int = 64
122
+ geom_n: int = 2000
123
+ seed: int = 0
124
+
125
+ out_json: str = "full_benchmark.json"
126
+ out_md: str = "benchmark_tables.md"
127
+ hf_push: bool = False
128
+ hf_repos: tuple = ("AbstractPhil/captionbert-8192-v2",
129
+ "AbstractPhil/captionbert-8192-v2-B")
130
+ hf_path: str = "eval"
131
+
132
+
133
+ CFG = BaseConfig()
134
+
135
+
136
+ def free_model(*objs):
137
+ """Drop refs, collect, empty the cache, and report if VRAM is not coming back."""
138
+ for o in objs:
139
+ try:
140
+ if o is not None and hasattr(o, "to"):
141
+ o.to("cpu")
142
+ except Exception:
143
+ pass
144
+ del objs
145
+ gc.collect()
146
+ if DEVICE == "cuda":
147
+ torch.cuda.empty_cache()
148
+ torch.cuda.synchronize()
149
+ held = torch.cuda.memory_allocated() / 1e9
150
+ if held > 2.0:
151
+ print(f" [mem] {held:.1f} GB still allocated after teardown -- "
152
+ f"something is holding a reference")
153
+
154
+
155
+ def line(t=""):
156
+ print("-" * 96 if not t else f"-- {t} " + "-" * max(0, 92 - len(t)))
157
+
158
+
159
+ # ══════════════════════════════════════════════════════════════════
160
+ # GAUGES
161
+ # ══════════════════════════════════════════════════════════════════
162
+
163
+ def effective_rank(x):
164
+ xc = (x - x.mean(0, keepdim=True)).double()
165
+ s2 = torch.linalg.svdvals(xc) ** 2
166
+ return float((s2.sum() ** 2 / (s2 ** 2).sum()).item())
167
+
168
+
169
+ @torch.no_grad()
170
+ def score(enc, task, cfg):
171
+ a, b, g = task
172
+ ea, eb = enc(a), enc(b)
173
+ cos = F.cosine_similarity(ea, eb, dim=-1).numpy()
174
+ E = torch.cat([ea, eb])
175
+ n = min(cfg.geom_n, E.shape[0])
176
+ S = E[:n] @ E[:n].T
177
+ S.fill_diagonal_(0)
178
+ return {"spearman": float(spearmanr(cos, g).correlation),
179
+ "self_cos": float(S.sum() / (n * n - n)),
180
+ "erank": effective_rank(E[:n])}
181
+
182
+
183
+ def load_tasks(cfg):
184
+ out = {}
185
+ for nm, path in cfg.tasks:
186
+ try:
187
+ d = load_dataset(path, split="test")
188
+ c = d.column_names
189
+ a = "sentence1" if "sentence1" in c else c[0]
190
+ b = "sentence2" if "sentence2" in c else c[1]
191
+ sc = "score" if "score" in c else "similarity_score"
192
+ out[nm] = (list(d[a]), list(d[b]), np.asarray(d[sc], dtype=float))
193
+ print(f" {nm:8s} {len(out[nm][2]):>6,d} pairs")
194
+ except Exception as e:
195
+ print(f" {nm:8s} SKIPPED ({type(e).__name__})")
196
+ return out
197
+
198
+
199
+ def hf_encoder(name, cfg):
200
+ """
201
+ Mean-pooled + L2-normalized. The same treatment every teacher gets.
202
+
203
+ NOTE the decorator placement. A previous version put @torch.no_grad() on
204
+ THIS function, which only covered from_pretrained -- the returned closure
205
+ ran outside it, built an autograd graph on every batch, and exhausted a
206
+ 96 GB card (it failed to allocate 16 MiB). It also made the embeddings
207
+ carry requires_grad, which broke .numpy() downstream. The guard belongs on
208
+ the thing that runs per batch.
209
+ """
210
+ tok = AutoTokenizer.from_pretrained(name)
211
+ mdl = AutoModel.from_pretrained(name).to(DEVICE).eval()
212
+ for q in mdl.parameters():
213
+ q.requires_grad_(False)
214
+
215
+ n_par = sum(q.numel() for q in mdl.parameters())
216
+
217
+ @torch.no_grad()
218
+ def enc(texts):
219
+ out = []
220
+ for i in range(0, len(texts), cfg.batch_size):
221
+ t = tok(list(texts[i:i + cfg.batch_size]), max_length=cfg.max_tokens,
222
+ padding=True, truncation=True, return_tensors="pt").to(DEVICE)
223
+ h = mdl(**t).last_hidden_state
224
+ m = t["attention_mask"].unsqueeze(-1).float()
225
+ out.append(F.normalize((h * m).sum(1) / m.sum(1).clamp(min=1),
226
+ dim=-1).float().cpu())
227
+ return torch.cat(out)
228
+ return enc, n_par, mdl
229
+
230
+
231
+ class CaptionEncoder(torch.nn.Module):
232
+ """Local, key-compatible with every captionbert-v2-family checkpoint."""
233
+
234
+ def __init__(self, cfg):
235
+ super().__init__()
236
+ import torch.nn as nn
237
+ d = cfg.d_model
238
+ self.pad_token_id, self.pooling = 0, cfg.pooling
239
+ self.token_emb = nn.Embedding(cfg.vocab_size, d, padding_idx=0)
240
+ self.pos_emb = nn.Embedding(cfg.max_len, d)
241
+ self.emb_norm = nn.LayerNorm(d)
242
+ self.emb_drop = nn.Dropout(0.1)
243
+ layer = nn.TransformerEncoderLayer(
244
+ d_model=d, nhead=cfg.n_heads, dim_feedforward=cfg.d_ff, dropout=0.1,
245
+ activation="gelu", batch_first=True, norm_first=True)
246
+ self.encoder = nn.TransformerEncoder(layer, num_layers=cfg.n_layers,
247
+ enable_nested_tensor=False)
248
+ self.output_proj = nn.Sequential(
249
+ nn.Linear(d, d), nn.GELU(), nn.LayerNorm(d), nn.Linear(d, cfg.output_dim))
250
+
251
+ def forward(self, input_ids, attention_mask=None):
252
+ L = input_ids.shape[1]
253
+ pos = torch.arange(L, device=input_ids.device).unsqueeze(0)
254
+ x = self.emb_drop(self.emb_norm(self.token_emb(input_ids) + self.pos_emb(pos)))
255
+ kpm = (~attention_mask.bool()) if attention_mask is not None \
256
+ else (input_ids == self.pad_token_id)
257
+ for mod in self.encoder.layers:
258
+ x = mod(x, src_key_padding_mask=kpm)
259
+ if self.encoder.norm is not None:
260
+ x = self.encoder.norm(x)
261
+ if self.pooling == "cls":
262
+ pooled = x[:, 0]
263
+ else:
264
+ m = (attention_mask.unsqueeze(-1).to(x.dtype) if attention_mask is not None
265
+ else (~kpm).unsqueeze(-1).to(x.dtype))
266
+ pooled = (x * m).sum(1) / m.sum(1).clamp(min=1)
267
+ return F.normalize(self.output_proj(pooled), dim=-1)
268
+
269
+
270
+ def trunk_encoder(cfg, repo, ckpt, tok):
271
+ m = CaptionEncoder(cfg)
272
+ sd = torch.load(hf_hub_download(repo, ckpt), weights_only=True, map_location="cpu")
273
+ m.load_state_dict(sd, strict=True)
274
+ m = m.to(DEVICE).eval()
275
+ for q in m.parameters():
276
+ q.requires_grad_(False)
277
+ n_par = sum(q.numel() for q in m.parameters())
278
+
279
+ @torch.no_grad()
280
+ def enc(texts):
281
+ out = []
282
+ for i in range(0, len(texts), cfg.batch_size):
283
+ t = tok(list(texts[i:i + cfg.batch_size]), max_length=cfg.max_tokens,
284
+ padding=True, truncation=True, return_tensors="pt").to(DEVICE)
285
+ out.append(m(t["input_ids"], t["attention_mask"]).float().cpu())
286
+ return torch.cat(out)
287
+ return enc, n_par, m
288
+
289
+
290
+ def attach_arms(cfg, model, repo, arm_dir, dispatch_path):
291
+ """
292
+ Inline attach: anchors and dispatch come from EXPLICIT paths in `repo`.
293
+ No modeling_captionbert.py, no AMOE_FALLBACKS, nothing that can go stale.
294
+ Returns (dispatch modules, arm names) and leaves every arm enabled.
295
+ """
296
+ import torch.nn as nn
297
+ from amoe.core.adapter import AdapterSpec, RelayPatchwork
298
+ from amoe.core.dispatch import AnchorDispatch, BlockWithDispatch
299
+ from amoe.io.checkpoint import load_anchor, load_dispatch
300
+
301
+ dck = load_dispatch(hf_hub_download(repo, dispatch_path))
302
+ names = list(dck.meta.get("anchors", []))
303
+ tau = float(dck.meta.get("tau", cfg.tau))
304
+ cks = [load_anchor(hf_hub_download(repo, f"{arm_dir}/{n}.anchor.pt")) for n in names]
305
+ spec = AdapterSpec(n_slots=cfg.n_slots, K=cfg.K, D=cfg.D, tau=cfg.tau,
306
+ hidden=cfg.hidden, gate_init=cfg.gate_init, zero_init_head=True)
307
+ layers = list(model.encoder.layers)
308
+ model._orig_layers = layers
309
+ new, disps = [], []
310
+ for i, layer in enumerate(layers):
311
+ stack = nn.ModuleList()
312
+ for ck in cks:
313
+ a = RelayPatchwork(cfg.d_model, spec)
314
+ a.load_state_dict({k[len(f"{i}."):]: v for k, v in ck.adapters.items()
315
+ if k.startswith(f"{i}.")})
316
+ for q in a.parameters():
317
+ q.requires_grad_(False)
318
+ stack.append(a)
319
+ dp = AnchorDispatch(stack.to(DEVICE), cfg.d_model,
320
+ emb=int(dck.meta.get("emb", cfg.align_emb)),
321
+ tau=tau).to(DEVICE)
322
+ with torch.no_grad():
323
+ dp.dispatch.copy_(dck.dispatch[i]["dispatch"].to(DEVICE))
324
+ dp.key_proj.copy_(dck.dispatch[i]["key_proj"].to(DEVICE))
325
+ for q in dp.parameters():
326
+ q.requires_grad_(False)
327
+ disps.append(dp)
328
+ new.append(BlockWithDispatch(layer, dp))
329
+ model.encoder.layers = nn.ModuleList(new)
330
+ return disps, names
331
+
332
+
333
+ def detach_arms(model):
334
+ import torch.nn as nn
335
+ if getattr(model, "_orig_layers", None) is not None:
336
+ model.encoder.layers = nn.ModuleList(model._orig_layers)
337
+ model._orig_layers = None
338
+
339
+
340
+ # ══════════════════════════════════════════════════════════════════
341
+ # TABLES
342
+ # ══════════════════════════════════════════════════════════════════
343
+
344
+ def render(rows, tasks, title, params=None):
345
+ tk = list(tasks)
346
+ line(title)
347
+ print(f" {'model':26s}{'params':>10s}" + "".join(f"{t:>9s}" for t in tk)
348
+ + f"{'mean':>9s}")
349
+ for label, r in rows.items():
350
+ vals = [r[t]["spearman"] for t in tk]
351
+ p = params.get(label) if params else None
352
+ ps = f"{p/1e6:>9.1f}M" if p else f"{'':>10s}"
353
+ print(f" {label:26s}{ps}" + "".join(f"{v:>9.4f}" for v in vals)
354
+ + f"{np.mean(vals):>9.4f}")
355
+
356
+
357
+ def markdown(rows, tasks, params, note=""):
358
+ tk = list(tasks)
359
+ out = ["| model | params | " + " | ".join(tk) + " | mean |",
360
+ "|---" * (len(tk) + 3) + "|"]
361
+ for label, r in rows.items():
362
+ vals = [r[t]["spearman"] for t in tk]
363
+ p = params.get(label)
364
+ out.append(f"| {label} | {f'{p/1e6:.1f}M' if p else '--'} | "
365
+ + " | ".join(f"{v:.4f}" for v in vals)
366
+ + f" | **{np.mean(vals):.4f}** |")
367
+ return "\n".join(out) + ("\n\n" + note if note else "")
368
+
369
+
370
+ # ══════════════════════════════════════════════════════════════════
371
+ # RUN
372
+ # ══════════════════════════════════════════════════════════════════
373
+
374
+ def run(cfg: BaseConfig = CFG):
375
+ print("=" * 96)
376
+ print("CAPTIONBERT FULL BENCHMARK -- one harness, every model, eight tasks")
377
+ print("=" * 96)
378
+ if DEVICE == "cuda":
379
+ print(f"gpu={torch.cuda.get_device_name()} "
380
+ f"vram={torch.cuda.get_device_properties(0).total_memory/1e9:.0f}GB")
381
+ torch.manual_seed(cfg.seed)
382
+ line("TASKS")
383
+ tasks = load_tasks(cfg)
384
+ if not tasks:
385
+ raise RuntimeError("no tasks loaded")
386
+ tok = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
387
+
388
+ rows, params, geom, groups = {}, {}, {}, {"teachers": [], "reference": [],
389
+ "trunks": [], "arms": []}
390
+
391
+ # ---- teachers ----
392
+ for label, name in cfg.teachers:
393
+ line(f"TEACHER {label}")
394
+ try:
395
+ enc, n_par, mdl = hf_encoder(name, cfg)
396
+ rows[label] = {k: score(enc, v, cfg) for k, v in tasks.items()}
397
+ params[label] = n_par
398
+ groups["teachers"].append(label)
399
+ ref = list(tasks)[0]
400
+ geom[label] = {k: rows[label][ref][k] for k in ("self_cos", "erank")}
401
+ print(f" {n_par:,} params | {ref} {rows[label][ref]['spearman']:.4f} "
402
+ f"| self_cos {rows[label][ref]['self_cos']:+.4f} "
403
+ f"| erank {rows[label][ref]['erank']:.1f}")
404
+ free_model(mdl, enc)
405
+ except Exception as e:
406
+ print(f" FAILED: {type(e).__name__}: {str(e)[:110]}")
407
+ free_model(locals().get("mdl"), locals().get("enc"))
408
+
409
+ # ---- reference ----
410
+ for label, name in cfg.references:
411
+ line(f"REFERENCE {label} (contrastive, 1B+ pairs -- different class)")
412
+ try:
413
+ enc, n_par, mdl = hf_encoder(name, cfg)
414
+ rows[label] = {k: score(enc, v, cfg) for k, v in tasks.items()}
415
+ params[label] = n_par
416
+ groups["reference"].append(label)
417
+ ref = list(tasks)[0]
418
+ geom[label] = {k: rows[label][ref][k] for k in ("self_cos", "erank")}
419
+ print(f" {n_par:,} params | {ref} {rows[label][ref]['spearman']:.4f} "
420
+ f"| self_cos {rows[label][ref]['self_cos']:+.4f} "
421
+ f"| erank {rows[label][ref]['erank']:.1f}")
422
+ free_model(mdl, enc)
423
+ except Exception as e:
424
+ print(f" FAILED: {type(e).__name__}: {str(e)[:110]}")
425
+ free_model(locals().get("mdl"), locals().get("enc"))
426
+
427
+ # ---- trunks, bare and with their OWN arms ----
428
+ for label, repo, ckpt, arm_dir, dispatch_path in cfg.trunks:
429
+ line(f"TRUNK {label}")
430
+ enc, n_par, m = trunk_encoder(cfg, repo, ckpt, tok)
431
+ rows[label] = {k: score(enc, v, cfg) for k, v in tasks.items()}
432
+ params[label] = n_par
433
+ groups["trunks"].append(label)
434
+ ref = list(tasks)[0]
435
+ geom[label] = {k: rows[label][ref][k] for k in ("self_cos", "erank")}
436
+ print(f" {n_par:,} params | {ref} {rows[label][ref]['spearman']:.4f} "
437
+ f"| self_cos {rows[label][ref]['self_cos']:+.4f} "
438
+ f"| erank {rows[label][ref]['erank']:.1f}")
439
+
440
+ if arm_dir:
441
+ try:
442
+ # EXPLICIT paths in THIS trunk's repo. Anchors are trunk-bound:
443
+ # v2's arms on -b cost 31% of their gain, so each trunk gets its own.
444
+ disps, anames = attach_arms(cfg, m, repo, arm_dir, dispatch_path)
445
+ al = f"{label} + arms"
446
+ rows[al] = {k: score(enc, v, cfg) for k, v in tasks.items()}
447
+ params[al] = n_par + sum(p.numel() for d in disps
448
+ for a in d.anchors for p in a.parameters())
449
+ groups["arms"].append(al)
450
+ geom[al] = {k: rows[al][ref][k] for k in ("self_cos", "erank")}
451
+ print(f" + arms {anames} from {repo}/{arm_dir}: "
452
+ f"{ref} {rows[al][ref]['spearman']:.4f}")
453
+ detach_arms(m)
454
+ except Exception as e:
455
+ msg = str(e)[:110]
456
+ print(f" arms FAILED: {type(e).__name__}: {msg}")
457
+ if "404" in msg or "NotFound" in type(e).__name__:
458
+ print(f" !! 404: check that {repo}/{arm_dir}/ and")
459
+ print(f" !! {repo}/{dispatch_path} exist.")
460
+ detach_arms(m)
461
+ free_model(m, enc)
462
+
463
+ # ---- tables ----
464
+ order = groups["teachers"] + groups["trunks"] + groups["arms"] + groups["reference"]
465
+ ordered = {k: rows[k] for k in order if k in rows}
466
+ render(ordered, tasks, "FULL BENCHMARK -- every model, mean-pooled, L2-normalized",
467
+ params)
468
+
469
+ tk = list(tasks)
470
+ line("READ")
471
+ tmeans = {k: np.mean([rows[k][t]["spearman"] for t in tk])
472
+ for k in groups["teachers"] if k in rows}
473
+ if tmeans:
474
+ bt = max(tmeans, key=tmeans.get)
475
+ print(f" best teacher: {bt} {tmeans[bt]:.4f} "
476
+ f"({params[bt]/1e6:.1f}M)")
477
+ tot = sum(params[k] for k in tmeans)
478
+ for k in groups["trunks"]:
479
+ if k in rows:
480
+ mv = np.mean([rows[k][t]["spearman"] for t in tk])
481
+ print(f" {k:26s} {mv:.4f} ({mv-tmeans[bt]:+.4f} vs best teacher) "
482
+ f"at {params[k]/tot*100:.0f}% of the teachers' combined params")
483
+ for k in groups["arms"]:
484
+ if k in rows:
485
+ mv = np.mean([rows[k][t]["spearman"] for t in tk])
486
+ print(f" {k:26s} {mv:.4f} ({mv-tmeans[bt]:+.4f} vs best teacher)")
487
+ for k in groups["reference"]:
488
+ if k in rows:
489
+ mv = np.mean([rows[k][t]["spearman"] for t in tk])
490
+ print(f" {k:26s} {mv:.4f} <- 1B+ curated pairs, a DIFFERENT class")
491
+
492
+ line("GEOMETRY (first task)")
493
+ print(f" {'model':26s}{'self_cos':>11s}{'erank':>9s}")
494
+ for k in order:
495
+ if k in geom:
496
+ print(f" {k:26s}{geom[k]['self_cos']:>+11.4f}{geom[k]['erank']:>9.1f}")
497
+ print()
498
+ print(" self_cos is the isotropy gauge: mean-pooled BERT-family embeddings sit")
499
+ print(" in a narrow cone. Low is better and it is the mechanism behind the")
500
+ print(" trunks' advantage -- cosine discriminates poorly inside a cone.")
501
+
502
+ # ---- markdown for the cards ----
503
+ note = ("All models mean-pooled and L2-normalized, no task tuning, one harness. "
504
+ "`all-MiniLM-L6-v2` was contrastively trained on 1B+ curated pairs and is "
505
+ "listed for scale, not as a peer.")
506
+ md = ["## Benchmark\n", markdown(ordered, tasks, params, note), "",
507
+ "### Geometry\n",
508
+ "| model | self_cos | erank |", "|---|---|---|"]
509
+ for k in order:
510
+ if k in geom:
511
+ md.append(f"| {k} | {geom[k]['self_cos']:+.4f} | {geom[k]['erank']:.1f} |")
512
+ open(cfg.out_md, "w").write("\n".join(md) + "\n")
513
+ json.dump({"rows": rows, "params": params, "geometry": geom,
514
+ "groups": groups, "config": asdict(cfg)},
515
+ open(cfg.out_json, "w"), indent=2, default=float)
516
+ print(f"\n wrote {cfg.out_json} and {cfg.out_md} (paste-ready card tables)")
517
+
518
+ if cfg.hf_push:
519
+ tokn = os.environ.get("HF_TOKEN")
520
+ if not tokn:
521
+ try:
522
+ from google.colab import userdata
523
+ tokn = userdata.get("HF_TOKEN")
524
+ except Exception:
525
+ tokn = None
526
+ if tokn:
527
+ from huggingface_hub import HfApi
528
+ api = HfApi(token=tokn)
529
+ for r in cfg.hf_repos:
530
+ for f in (cfg.out_json, cfg.out_md):
531
+ try:
532
+ api.upload_file(path_or_fileobj=f,
533
+ path_in_repo=f"{cfg.hf_path}/{f}",
534
+ repo_id=r, commit_message="full benchmark")
535
+ except Exception as e:
536
+ print(f" push {r} failed: {str(e)[:60]}")
537
+ print(f" pushed to {list(cfg.hf_repos)}")
538
+ return rows
539
+
540
+
541
+ if "get_ipython" in globals() or __name__ == "__main__":
542
+ RESULTS = run(CFG)