AbstractPhil commited on
Commit
327ed1e
Β·
verified Β·
1 Parent(s): 9bdd151

Create early_eval.py

Browse files
Files changed (1) hide show
  1. early_eval.py +306 -0
early_eval.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # CAPTIONBERT-8192-V2 β€” CAPABILITY + GEOMETRY EVAL (single standalone cell)
3
+ #
4
+ # Self-contained. Pulls the checkpoint from the hub, redefines the encoder
5
+ # inline (no trainer import), runs the capability gauges the training loop
6
+ # cannot see, and measures the baselines IN THE SAME HARNESS so the numbers
7
+ # are comparable rather than cited.
8
+ #
9
+ # WHY THIS EXISTS
10
+ # Training reports student->consensus R@1. That is MIMICRY: how well the
11
+ # student reproduces its target. It says nothing about whether the space
12
+ # means anything. Capability is STS/SICK against models that never saw the
13
+ # consensus. Keep the two on separate lines, always.
14
+ #
15
+ # WHAT IT REPORTS
16
+ # spearman the capability gauge (STS-B, SICK-R, STS12-16 optional)
17
+ # self_cos isotropy. mean-pooled BERT sits in a narrow cone (~0.57);
18
+ # a good sentence encoder is near 0 (MiniLM ~0.02)
19
+ # erank participation ratio = how many directions the embedding
20
+ # actually uses. THE KEY COLUMN. Measured 2026-07-31:
21
+ # consensus target 28.7 / 768
22
+ # v2 in-domain 80.5
23
+ # v2 on STS-B 31.2 <- falls back to the target's rank
24
+ # all-MiniLM-L6-v2 103.1 <- on the SAME sentences
25
+ # Averaging teachers cannot create rank they do not share. If
26
+ # v2's OOD erank stays ~30 while STS stays ~0.55, the ceiling is
27
+ # the consensus construction, not the student.
28
+ #
29
+ # BASELINE (measured, CPU, same harness, 2026-07-31, checkpoint step 3327):
30
+ # bert-base mean-pooled 109.5M STS-B .4729 self_cos .570 erank 34.3
31
+ # captionbert v2 @ 6% 58.3M STS-B .5444 self_cos .139 erank 31.2
32
+ # all-MiniLM-L6-v2 22.7M STS-B .8203 self_cos .023 erank 103.1
33
+ # (bert-base reproduced v1's published .4729073 to 7 digits -> harness valid)
34
+ #
35
+ # L4 (24GB) is plenty; it runs on CPU too, just slower.
36
+ # ============================================================================
37
+
38
+ import subprocess, sys, json, os
39
+ for _p in ("datasets", "transformers", "huggingface_hub", "scipy"):
40
+ try:
41
+ __import__(_p)
42
+ except ImportError:
43
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", _p], check=False)
44
+
45
+ import numpy as np
46
+ import torch
47
+ import torch.nn as nn
48
+ import torch.nn.functional as F
49
+ from scipy.stats import spearmanr, pearsonr
50
+ from huggingface_hub import hf_hub_download
51
+ from transformers import AutoTokenizer, AutoModel
52
+ from datasets import load_dataset
53
+
54
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
55
+
56
+
57
+ # ══════════════════════════════════════════════════════════════════
58
+ # CONFIG
59
+ # ══════════════════════════════════════════════════════════════════
60
+
61
+ REPO = "AbstractPhil/captionbert-8192-v2"
62
+ CKPT = "checkpoints/best_model.pt" # or "checkpoints/model_sNNNN.pt"
63
+ TOKENIZER = "google-bert/bert-base-uncased"
64
+ BASELINES = ["google-bert/bert-base-uncased",
65
+ "sentence-transformers/all-MiniLM-L6-v2"]
66
+ RUN_BASELINES = True # False once you have them; they do not change
67
+ EXTRA_STS = False # STS12-16 as well as STS-B/SICK-R (slower)
68
+ MAX_LEN = 64
69
+ BATCH = 256
70
+ GEOM_N = 1500 # sentences for the isotropy / erank probe
71
+
72
+ # architecture β€” must match config/config.json in the repo
73
+ ARCH = dict(vocab_size=30522, max_len=8192, d_model=512, n_heads=8,
74
+ n_layers=12, d_ff=2048, output_dim=768, dropout=0.1,
75
+ pad_token_id=0, pooling="mean")
76
+
77
+
78
+ # ══════════════════════════════════════════════════════════════════
79
+ # STUDENT (inline copy β€” keys must match the checkpoint exactly)
80
+ # ══════════════════════════════════════════════════════════════════
81
+
82
+ class CaptionEncoder(nn.Module):
83
+ def __init__(self, vocab_size=30522, max_len=8192, d_model=512, n_heads=8,
84
+ n_layers=12, d_ff=2048, output_dim=768, dropout=0.1,
85
+ pad_token_id=0, pooling="mean"):
86
+ super().__init__()
87
+ self.pad_token_id, self.pooling = pad_token_id, pooling
88
+ self.token_emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_token_id)
89
+ self.pos_emb = nn.Embedding(max_len, d_model)
90
+ self.emb_norm = nn.LayerNorm(d_model)
91
+ self.emb_drop = nn.Dropout(dropout)
92
+ layer = nn.TransformerEncoderLayer(
93
+ d_model=d_model, nhead=n_heads, dim_feedforward=d_ff, dropout=dropout,
94
+ activation="gelu", batch_first=True, norm_first=True)
95
+ self.encoder = nn.TransformerEncoder(layer, num_layers=n_layers,
96
+ enable_nested_tensor=False)
97
+ self.output_proj = nn.Sequential(
98
+ nn.Linear(d_model, d_model), nn.GELU(), nn.LayerNorm(d_model),
99
+ nn.Linear(d_model, output_dim))
100
+
101
+ def forward(self, input_ids, attention_mask=None):
102
+ L = input_ids.shape[1]
103
+ pos = torch.arange(L, device=input_ids.device).unsqueeze(0)
104
+ x = self.emb_drop(self.emb_norm(self.token_emb(input_ids) + self.pos_emb(pos)))
105
+ kpm = (~attention_mask.bool()) if attention_mask is not None \
106
+ else (input_ids == self.pad_token_id)
107
+ x = self.encoder(x, src_key_padding_mask=kpm)
108
+ if self.pooling == "cls":
109
+ pooled = x[:, 0]
110
+ else:
111
+ m = (attention_mask.unsqueeze(-1).float() if attention_mask is not None
112
+ else (~kpm).unsqueeze(-1).float())
113
+ pooled = (x * m).sum(1) / m.sum(1).clamp(min=1)
114
+ return F.normalize(self.output_proj(pooled), dim=-1)
115
+
116
+
117
+ # ══════════════════════════════════════════════════════════════════
118
+ # GAUGES
119
+ # ══════════════════════════════════════════════════════════════════
120
+
121
+ def effective_rank(x: torch.Tensor) -> float:
122
+ """Participation ratio of the singular spectrum: how many directions are used."""
123
+ xc = (x - x.mean(0, keepdim=True)).double()
124
+ s2 = torch.linalg.svdvals(xc) ** 2
125
+ return float((s2.sum() ** 2 / (s2 ** 2).sum()).item())
126
+
127
+
128
+ def geometry(E: torch.Tensor) -> dict:
129
+ n = min(GEOM_N, E.shape[0])
130
+ X = E[:n]
131
+ S = X @ X.T
132
+ S.fill_diagonal_(0)
133
+ return {"self_cos": float(S.sum() / (n * n - n)), "erank": effective_rank(X)}
134
+
135
+
136
+ def line(t=""):
137
+ print("-" * 76 if not t else f"-- {t} " + "-" * max(0, 72 - len(t)))
138
+
139
+
140
+ # ══════════════════════════════════════════════════════════════════
141
+ # ENCODERS
142
+ # ══════════════════════════════════════════════════════════════════
143
+
144
+ def load_student():
145
+ line("STUDENT")
146
+ p = hf_hub_download(REPO, CKPT)
147
+ sd = torch.load(p, weights_only=True, map_location="cpu")
148
+ model = CaptionEncoder(**ARCH)
149
+ model.load_state_dict(sd, strict=True) # strict: a silent mismatch is worse
150
+ model.eval().to(DEVICE)
151
+ n = sum(q.numel() for q in model.parameters())
152
+ print(f" {REPO}/{CKPT}")
153
+ print(f" {n:,} params ({n/109_482_240:.2f}x bert-base) | strict load OK | {DEVICE}")
154
+ tok = AutoTokenizer.from_pretrained(TOKENIZER)
155
+
156
+ @torch.no_grad()
157
+ def enc(texts):
158
+ out = []
159
+ for i in range(0, len(texts), BATCH):
160
+ t = tok(list(texts[i:i + BATCH]), max_length=MAX_LEN, padding=True,
161
+ truncation=True, return_tensors="pt").to(DEVICE)
162
+ out.append(model(t["input_ids"], t["attention_mask"]).float().cpu())
163
+ return torch.cat(out)
164
+ return enc, n
165
+
166
+
167
+ def load_baseline(name):
168
+ tok = AutoTokenizer.from_pretrained(name)
169
+ mdl = AutoModel.from_pretrained(name).eval().to(DEVICE)
170
+ n = sum(q.numel() for q in mdl.parameters())
171
+
172
+ @torch.no_grad()
173
+ def enc(texts):
174
+ out = []
175
+ for i in range(0, len(texts), BATCH):
176
+ t = tok(list(texts[i:i + BATCH]), max_length=MAX_LEN, padding=True,
177
+ truncation=True, return_tensors="pt").to(DEVICE)
178
+ h = mdl(**t).last_hidden_state
179
+ m = t["attention_mask"].unsqueeze(-1).float()
180
+ pooled = (h * m).sum(1) / m.sum(1).clamp(min=1) # mean pool, as published
181
+ out.append(F.normalize(pooled, dim=-1).float().cpu())
182
+ return torch.cat(out)
183
+ return enc, n, mdl
184
+
185
+
186
+ # ══════════════════════════════════════════════════════════════════
187
+ # TASKS
188
+ # ══════════════════════════════════════════════════════════════════
189
+
190
+ TASKS = [("STS-B", "mteb/stsbenchmark-sts", "test"),
191
+ ("SICK-R", "mteb/sickr-sts", "test")]
192
+ if EXTRA_STS:
193
+ TASKS += [(f"STS{y}", f"mteb/sts{y}-sts", "test") for y in (12, 13, 14, 15, 16)]
194
+
195
+
196
+ def load_task(path, split):
197
+ ds = load_dataset(path, split=split)
198
+ cols = ds.column_names
199
+ a = "sentence1" if "sentence1" in cols else cols[0]
200
+ b = "sentence2" if "sentence2" in cols else cols[1]
201
+ s = "score" if "score" in cols else ("similarity_score" if "similarity_score" in cols else None)
202
+ return list(ds[a]), list(ds[b]), np.asarray(ds[s], dtype=float)
203
+
204
+
205
+ def score(enc, a, b, gold):
206
+ ea, eb = enc(a), enc(b)
207
+ cos = F.cosine_similarity(ea, eb, dim=-1).numpy()
208
+ return (float(spearmanr(cos, gold).correlation),
209
+ float(pearsonr(cos, gold)[0]),
210
+ torch.cat([ea, eb]))
211
+
212
+
213
+ # ══════════════════════════════════════════════════════════════════
214
+ # RUN
215
+ # ══════════════════════════════════════════════════════════════════
216
+
217
+ def main():
218
+ print("=" * 76)
219
+ print("CAPTIONBERT-8192-V2 - CAPABILITY + GEOMETRY")
220
+ print("=" * 76)
221
+ if DEVICE == "cuda":
222
+ print(f"gpu={torch.cuda.get_device_name()} "
223
+ f"vram={torch.cuda.get_device_properties(0).total_memory/1e9:.0f}GB")
224
+
225
+ results = {}
226
+ data = {}
227
+ for name, path, split in TASKS:
228
+ try:
229
+ data[name] = load_task(path, split)
230
+ print(f" {name}: {len(data[name][2])} pairs")
231
+ except Exception as e:
232
+ print(f" {name}: SKIPPED ({type(e).__name__}: {str(e)[:60]})")
233
+
234
+ enc, n_par = load_student()
235
+ line("STUDENT SCORES")
236
+ results["captionbert-v2"] = {"params": n_par}
237
+ for name in data:
238
+ a, b, g = data[name]
239
+ sp, pe, E = score(enc, a, b, g)
240
+ geo = geometry(E)
241
+ results["captionbert-v2"][name] = {"spearman": sp, "pearson": pe, **geo}
242
+ print(f" {name:8s} spearman {sp:.4f} pearson {pe:.4f} "
243
+ f"self_cos {geo['self_cos']:+.4f} erank {geo['erank']:.1f}/768")
244
+ del enc
245
+ if DEVICE == "cuda":
246
+ torch.cuda.empty_cache()
247
+
248
+ if RUN_BASELINES:
249
+ for bn in BASELINES:
250
+ line(f"BASELINE {bn}")
251
+ benc, bn_par, mdl = load_baseline(bn)
252
+ results[bn] = {"params": bn_par}
253
+ for name in data:
254
+ a, b, g = data[name]
255
+ sp, pe, E = score(benc, a, b, g)
256
+ geo = geometry(E)
257
+ results[bn][name] = {"spearman": sp, "pearson": pe, **geo}
258
+ print(f" {name:8s} spearman {sp:.4f} pearson {pe:.4f} "
259
+ f"self_cos {geo['self_cos']:+.4f} erank {geo['erank']:.1f}")
260
+ del mdl, benc
261
+ if DEVICE == "cuda":
262
+ torch.cuda.empty_cache()
263
+
264
+ # ---- table ----
265
+ print()
266
+ print("=" * 76)
267
+ print("SUMMARY")
268
+ print("=" * 76)
269
+ tasks = list(data.keys())
270
+ hdr = f" {'model':34s}{'params':>10s}" + "".join(f"{t:>10s}" for t in tasks) \
271
+ + f"{'self_cos':>10s}{'erank':>8s}"
272
+ print(hdr)
273
+ for k, v in results.items():
274
+ row = f" {k[-34:]:34s}{v['params']/1e6:>9.1f}M"
275
+ for t in tasks:
276
+ row += f"{v[t]['spearman']:>10.4f}" if t in v else f"{'-':>10s}"
277
+ ref = tasks[0]
278
+ row += f"{v[ref]['self_cos']:>+10.4f}{v[ref]['erank']:>8.1f}" if ref in v else ""
279
+ print(row)
280
+
281
+ # ---- the read ----
282
+ print()
283
+ line("READ")
284
+ cb = results.get("captionbert-v2", {})
285
+ ref = tasks[0] if tasks else None
286
+ if ref and ref in cb:
287
+ er = cb[ref]["erank"]
288
+ print(f" erank on {ref} = {er:.1f}. Consensus target measured 28.7/768;")
289
+ print(f" v2 in-domain (CC12M val) measured 80.5. On out-of-domain text the")
290
+ print(f" student falls back toward its target's intrinsic rank.")
291
+ mini = results.get("sentence-transformers/all-MiniLM-L6-v2")
292
+ if mini and ref in mini:
293
+ print(f" all-MiniLM uses {mini[ref]['erank']:.1f} directions on the SAME "
294
+ f"sentences at {mini['params']/1e6:.1f}M params.")
295
+ print(f" Averaging teachers cannot create rank they do not share -- if this")
296
+ print(f" gap holds, the ceiling is the CONSENSUS, not the student, and the")
297
+ print(f" fix is heterogeneous teachers rather than a bigger model.")
298
+ print(" Training's student->consensus R@1 is MIMICRY. This table is capability.")
299
+
300
+ with open("v2_capability.json", "w") as f:
301
+ json.dump(results, f, indent=2)
302
+ print("\n wrote v2_capability.json")
303
+ return results
304
+
305
+
306
+ RESULTS = main()