jvonrad commited on
Commit
bcc57b5
·
verified ·
1 Parent(s): 885cd84

Upload src/xscript/eval/bench.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/xscript/eval/bench.py +303 -0
src/xscript/eval/bench.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Downstream multilingual benchmarks via lm-evaluation-harness.
2
+
3
+ Complements the intrinsic BPB eval (eval/bpb.py) and the bespoke
4
+ cross-lingual-transfer/representation analyses (eval/bts.py, eval/alignment.py)
5
+ with real task accuracy: Global-MMLU (knowledge), Belebele (reading
6
+ comprehension), XNLI (natural language inference) -- all covering en/de/fr/ar/zh.
7
+
8
+ By default, evaluation is restricted to the languages in the checkpoint's
9
+ training mixture: three tasks for a monolingual run and six for a bilingual
10
+ run. ``--tasks`` remains an explicit override for targeted/OOD analyses.
11
+
12
+ `XScriptLM` wraps our own Transformer/Tok (not HF-standard) in lm_eval's `LM`
13
+ interface. Scoring follows the exact shifted-LM convention already used in
14
+ eval/bpb.py's score_texts: model(x, y) with x=seq[:-1], y=seq[1:] returns
15
+ logits where logits[:, j] predicts y[j].
16
+ """
17
+ import importlib.metadata
18
+ import json
19
+ from pathlib import Path
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+
24
+ from ..tok.wrapper import BOS_ID, EOS_ID, PAD_ID
25
+
26
+ DEFAULT_TASKS = {
27
+ "global_mmlu": ["global_mmlu_en", "global_mmlu_de", "global_mmlu_fr",
28
+ "global_mmlu_ar", "global_mmlu_zh"],
29
+ "belebele": ["belebele_eng_Latn", "belebele_deu_Latn", "belebele_fra_Latn",
30
+ "belebele_arb_Arab", "belebele_zho_Hans"],
31
+ "xnli": ["xnli_en", "xnli_de", "xnli_fr", "xnli_ar", "xnli_zh"],
32
+ }
33
+
34
+ LANG_ORDER = ("en", "de", "fr", "ar", "zh")
35
+ TASKS_BY_LANG = {
36
+ lang: [DEFAULT_TASKS[family][i] for family in DEFAULT_TASKS]
37
+ for i, lang in enumerate(LANG_ORDER)
38
+ }
39
+
40
+
41
+ def tasks_for_langs(langs: list[str]) -> list[str]:
42
+ """Harness task names for exactly the languages in a run's mixture."""
43
+ unknown = [lang for lang in langs if lang not in TASKS_BY_LANG]
44
+ if unknown:
45
+ raise ValueError(f"no downstream task mapping for languages: {unknown}")
46
+ # Keep benchmark families together in the output, then run language order.
47
+ return [TASKS_BY_LANG[lang][family_i]
48
+ for family_i in range(len(DEFAULT_TASKS)) for lang in langs]
49
+
50
+
51
+ class XScriptLM:
52
+ """lm_eval.api.model.TemplateLM subclass wrapping our Transformer + Tok.
53
+
54
+ Inherits from TemplateLM lazily (import-time, so lm_eval/torch stay
55
+ optional deps of the base package) via _make_lm() below.
56
+ """
57
+
58
+ def __init__(self, model, tok, device, max_seq_len: int, batch_size: int = 4):
59
+ super().__init__()
60
+ self.model = model.eval()
61
+ self.tok = tok
62
+ # lm_eval.api.model.LM exposes `device` as a read-only property backed
63
+ # by `_device`; assigning self.device raises AttributeError.
64
+ self._device = torch.device(device)
65
+ self.max_seq_len = max_seq_len
66
+ self.batch_size = batch_size
67
+ self.tokenizer = None # no chat template support needed for these tasks
68
+
69
+ @property
70
+ def eot_token_id(self) -> int:
71
+ return EOS_ID
72
+
73
+ @property
74
+ def prefix_token_id(self) -> int:
75
+ # our documents are always BOS-prefixed, not EOS-prefixed
76
+ return BOS_ID
77
+
78
+ def tok_encode(self, string: str, add_special_tokens=None, **kwargs) -> list[int]:
79
+ return self.tok.encode(string, bos=False, eos=False)
80
+
81
+ def _prepare(self, context_enc: list[int], continuation_enc: list[int]) -> list[int]:
82
+ """Return a model-ready sequence with one BOS and an intact target.
83
+
84
+ TemplateLM supplies ``[prefix_token_id]`` for an empty string context,
85
+ whereas non-empty contexts contain no special token. Normalize both
86
+ cases here so BOS is added exactly once. Context is left-truncated;
87
+ benchmark answer continuations are never silently truncated.
88
+ """
89
+ if not continuation_enc:
90
+ return []
91
+ has_bos = bool(context_enc) and context_enc[0] == BOS_ID
92
+ context = context_enc[1:] if has_bos else context_enc
93
+ if len(continuation_enc) > self.max_seq_len:
94
+ raise ValueError(
95
+ f"continuation has {len(continuation_enc)} tokens, exceeding "
96
+ f"max_seq_len={self.max_seq_len}"
97
+ )
98
+ budget = self.max_seq_len - len(continuation_enc)
99
+ context = context[-budget:] if budget < len(context) else context
100
+ return [BOS_ID] + context + continuation_enc
101
+
102
+ @torch.no_grad()
103
+ def _score_batch(self, batch) -> list[tuple[float, bool]]:
104
+ """Score variable-length requests with right padding.
105
+
106
+ Padding is strictly after each real sequence, so causal attention
107
+ cannot let it affect any scored position. Passing targets asks our
108
+ Transformer for all-position logits; the returned scalar loss is
109
+ intentionally ignored.
110
+ """
111
+ prepared = [(self._prepare(list(c), list(k)), len(k)) for c, k in batch]
112
+ out: list[tuple[float, bool] | None] = [None] * len(prepared)
113
+ active = [(i, seq, n) for i, (seq, n) in enumerate(prepared) if n]
114
+ for i, (_, n) in enumerate(prepared):
115
+ if not n:
116
+ out[i] = (0.0, True)
117
+ if not active:
118
+ return out # type: ignore[return-value]
119
+
120
+ width = max(len(seq) - 1 for _, seq, _ in active)
121
+ x = torch.full((len(active), width), PAD_ID, dtype=torch.long,
122
+ device=self.device)
123
+ y = torch.full((len(active), width), -100, dtype=torch.long,
124
+ device=self.device)
125
+ lengths = []
126
+ for row, (_, seq, _) in enumerate(active):
127
+ m = len(seq) - 1
128
+ lengths.append(m)
129
+ x[row, :m] = torch.tensor(seq[:-1], device=self.device)
130
+ y[row, :m] = torch.tensor(seq[1:], device=self.device)
131
+
132
+ amp = (torch.autocast("cuda", dtype=torch.bfloat16)
133
+ if self.device.type == "cuda" else _null())
134
+ with amp:
135
+ logits, _ = self.model(x, y)
136
+ for row, (out_i, _, n) in enumerate(active):
137
+ m = lengths[row]
138
+ cont_logits = logits[row, m - n:m, :].float()
139
+ target = y[row, m - n:m]
140
+ logprobs = F.log_softmax(cont_logits, dim=-1)
141
+ token_lp = logprobs.gather(1, target.unsqueeze(1)).squeeze(1)
142
+ greedy = bool((cont_logits.argmax(-1) == target).all().item())
143
+ out[out_i] = (float(token_lp.sum().item()), greedy)
144
+ return out # type: ignore[return-value]
145
+
146
+ def _loglikelihood_tokens(self, requests, disable_tqdm: bool = False):
147
+ from tqdm import tqdm
148
+ out = []
149
+ batches = range(0, len(requests), self.batch_size)
150
+ for st in tqdm(batches, disable=disable_tqdm, desc="[bench] scoring"):
151
+ chunk = requests[st:st + self.batch_size]
152
+ out.extend(self._score_batch([(c, k) for _, c, k in chunk]))
153
+ return out
154
+
155
+ @torch.no_grad()
156
+ def loglikelihood_rolling(self, requests, disable_tqdm: bool = False):
157
+ from lm_eval import utils
158
+ from tqdm import tqdm
159
+ out = []
160
+ for req in tqdm(requests, disable=disable_tqdm, desc="[bench] rolling"):
161
+ (text,) = req.args
162
+ ids = self.tok_encode(text)
163
+ windows = list(utils.get_rolling_token_windows(
164
+ token_list=ids, prefix_token=BOS_ID,
165
+ max_seq_len=self.max_seq_len, context_len=1,
166
+ ))
167
+ # The utility's contexts are already complete windows (the first
168
+ # starts with BOS), so score them without _prepare adding BOS.
169
+ total = 0.0
170
+ for context, target in windows:
171
+ x = torch.tensor(context, device=self.device).unsqueeze(0)
172
+ # Input and prediction windows are aligned by the harness;
173
+ # only the final len(target) logits are part of this window.
174
+ y_ids = [-100] * (len(context) - len(target)) + target
175
+ y = torch.tensor(y_ids, device=self.device).unsqueeze(0)
176
+ logits, _ = self.model(x, y)
177
+ n = len(target)
178
+ lp = F.log_softmax(logits[0, -n:, :].float(), -1)
179
+ total += float(lp.gather(1, y[0, -n:].unsqueeze(1)).sum().item())
180
+ out.append(total)
181
+ return out
182
+
183
+ @torch.no_grad()
184
+ def generate_until(self, requests, disable_tqdm: bool = False):
185
+ from tqdm import tqdm
186
+ out = []
187
+ for req in tqdm(requests, disable=disable_tqdm, desc="[bench] generating"):
188
+ context, gen_kwargs = req.args
189
+ until = gen_kwargs.get("until", []) if isinstance(gen_kwargs, dict) else []
190
+ max_gen = (gen_kwargs.get("max_gen_toks", 256)
191
+ if isinstance(gen_kwargs, dict) else 256)
192
+ ids = [BOS_ID] + self.tok_encode(context)[-(self.max_seq_len - 1):]
193
+ gen = []
194
+ text_so_far = ""
195
+ for _ in range(max_gen):
196
+ x = torch.tensor(ids[-self.max_seq_len:], device=self.device).unsqueeze(0)
197
+ logits = self.model(x) # (1, 1, vocab) -- no targets
198
+ next_id = int(logits[0, -1].argmax(-1).item())
199
+ if next_id == EOS_ID:
200
+ break
201
+ gen.append(next_id)
202
+ ids.append(next_id)
203
+ text_so_far = self.tok.decode(gen)
204
+ if until and any(u in text_so_far for u in until):
205
+ for u in until:
206
+ idx = text_so_far.find(u)
207
+ if idx != -1:
208
+ text_so_far = text_so_far[:idx]
209
+ break
210
+ out.append(text_so_far)
211
+ return out
212
+
213
+
214
+ def _make_lm(model, tok, device, max_seq_len):
215
+ """Bind XScriptLM to lm_eval.api.model.TemplateLM at call time (keeps
216
+ lm_eval/torch optional for anything that only imports xscript.eval.bench
217
+ for DEFAULT_TASKS)."""
218
+ from lm_eval.api.model import TemplateLM
219
+
220
+ class _Bound(XScriptLM, TemplateLM):
221
+ def __init__(self):
222
+ XScriptLM.__init__(self, model, tok, device, max_seq_len)
223
+
224
+ return _Bound()
225
+
226
+
227
+ def run(run_name: str, tok_name: str, tag: str = "final", tasks: list[str] | None = None,
228
+ num_fewshot: int = 0, limit: int | float | None = None,
229
+ out_dir: Path | None = None, log_wandb: bool = True,
230
+ batch_size: int = 4) -> dict:
231
+ """Evaluate a checkpoint on its training languages by default."""
232
+ import lm_eval
233
+ from ..model import ModelConfig, Transformer
234
+ from ..tok.wrapper import Tok
235
+ from ..paths import RUNS, RESULTS, tokenizer_dir, ensure
236
+
237
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
238
+ ck = torch.load(RUNS / run_name / "checkpoints" / f"{tag}.pt",
239
+ map_location="cpu", weights_only=False)
240
+ model = Transformer(ModelConfig(**ck["cfg"]["model"])).to(device).eval()
241
+ model.load_state_dict(ck["model"])
242
+ tok = Tok(tokenizer_dir(tok_name))
243
+ if tok_name != ck["cfg"]["tok_name"]:
244
+ raise ValueError(f"checkpoint uses {ck['cfg']['tok_name']}, not {tok_name}")
245
+
246
+ task_list = tasks if tasks is not None else tasks_for_langs(ck["cfg"]["langs"])
247
+ adapter = _make_lm(model, tok, device, model.cfg.max_seq_len)
248
+ adapter.batch_size = batch_size
249
+
250
+ results = lm_eval.simple_evaluate(
251
+ model=adapter, tasks=task_list, num_fewshot=num_fewshot,
252
+ batch_size=1, limit=limit, log_samples=False, confirm_run_unsafe_code=True,
253
+ )
254
+ def _accuracy(rec):
255
+ # Use ordinary accuracy consistently across all three benchmark
256
+ # families. Belebele additionally reports length-normalized accuracy,
257
+ # which remains available in the preserved raw harness output.
258
+ return rec.get("acc,none", rec.get("acc"))
259
+
260
+ scores = {}
261
+ groups = results.get("groups", {})
262
+ subtasks = results.get("results", {})
263
+ for name in task_list:
264
+ rec = groups.get(name, subtasks.get(name, {}))
265
+ scores[name] = _accuracy(rec)
266
+
267
+ out_dir = ensure(Path(out_dir) if out_dir else RESULTS / "bench")
268
+ payload = {
269
+ "run": run_name, "checkpoint": tag, "tokenizer": tok_name,
270
+ "lm_eval_version": importlib.metadata.version("lm_eval"),
271
+ "num_fewshot": num_fewshot, "limit": limit, "tasks": task_list,
272
+ "scores": scores, "results": results.get("results", {}),
273
+ "groups": groups, "versions": results.get("versions", {}),
274
+ "n-shot": results.get("n-shot", {}),
275
+ }
276
+ (out_dir / f"{run_name}_{tag}.json").write_text(
277
+ json.dumps(payload, indent=2, default=_json_default)
278
+ )
279
+ print(f"[bench] {run_name} ({tag}): " +
280
+ ", ".join(f"{k}={v:.4f}" for k, v in scores.items() if v is not None))
281
+
282
+ if log_wandb:
283
+ try:
284
+ import wandb
285
+ wb = wandb.init(project="XScript-Pretraining", id=run_name, resume="allow")
286
+ wb.log({f"bench/{k}": v for k, v in scores.items() if v is not None})
287
+ wb.finish()
288
+ except Exception as exc:
289
+ print(f"[bench] wandb logging skipped ({exc})")
290
+
291
+ return scores
292
+
293
+
294
+ class _null:
295
+ def __enter__(self): return self
296
+ def __exit__(self, *args): return False
297
+
298
+
299
+ def _json_default(value):
300
+ """Serialize NumPy scalars and other scalar-like harness values."""
301
+ if hasattr(value, "item"):
302
+ return value.item()
303
+ raise TypeError(f"not JSON serializable: {type(value).__name__}")