rileyherchert commited on
Commit
9ef0b4d
·
1 Parent(s): bf81fb3

Update vizualize grid

Browse files
Files changed (1) hide show
  1. visualize_model_grid.py +290 -65
visualize_model_grid.py CHANGED
@@ -14,14 +14,16 @@ Only successful logs are included by default. Repeated/resumed logs with the sam
14
  evaluation id are deduplicated, preferring a successful and then newer log.
15
 
16
  Example:
17
- uv run hf_dataset/visualize_model_grid.py --log-dir hf_dataset/logs
18
  """
19
 
20
  from __future__ import annotations
21
 
22
  import argparse
23
  import math
 
24
  import re
 
25
  from dataclasses import dataclass
26
  from pathlib import Path
27
  from typing import Any
@@ -41,7 +43,6 @@ class ModelInfo:
41
  pretrain_tokens_t: float | None = None
42
 
43
 
44
- # Values are intentionally easy to edit as model documentation is revised.
45
  MODEL_CATALOG = {
46
  "qwen2.5-0.5b-instruct": ModelInfo("Qwen2.5", 0.5, 151_936, "Chinese-English; multilingual", 18),
47
  "qwen2.5-1.5b-instruct": ModelInfo("Qwen2.5", 1.5, 151_936, "Chinese-English; multilingual", 18),
@@ -69,6 +70,16 @@ LANGUAGE_LABELS = {
69
  "ukr": "Ukrainian",
70
  }
71
 
 
 
 
 
 
 
 
 
 
 
72
  FAMILY_COLORS = {
73
  "Qwen2.5": "#7B2CBF",
74
  "Llama 3": "#E76F51",
@@ -143,13 +154,16 @@ def sample_score(sample: Any, scorer: str | None) -> float | None:
143
  scores = sample.scores or {}
144
  if scorer:
145
  return score_to_float(scores.get(scorer)) if scorer in scores else None
 
146
  for preferred in ("math", "pattern"):
147
  if preferred in scores:
148
  return score_to_float(scores[preferred])
 
149
  for score in scores.values():
150
  value = score_to_float(score)
151
  if value is not None:
152
  return value
 
153
  return None
154
 
155
 
@@ -160,73 +174,169 @@ def discover_logs(log_dirs: list[Path]) -> list[Path]:
160
  return sorted(paths)
161
 
162
 
163
- def select_logs(paths: list[Path], include_incomplete: bool) -> list[tuple[Path, Any]]:
 
 
 
 
 
 
 
164
  """Deduplicate log snapshots, preferring successful and newer entries."""
165
  selected: dict[tuple[str, str], tuple[Path, Any]] = {}
166
- for path in paths:
167
- try:
168
- log = read_eval_log(str(path), header_only=True)
169
- except Exception as exc:
170
- print(f"Skipping unreadable log {path.name}: {exc}")
 
 
 
 
 
 
 
 
 
 
171
  continue
 
172
  status = str(log.status)
173
  if not include_incomplete and status != "success":
174
  continue
 
175
  key = (log.eval.eval_id, log.eval.task)
176
- previous = selected.get(key)
177
  rank = (status == "success", path.stat().st_mtime_ns)
 
 
178
  if previous is None:
179
  selected[key] = (path, log)
180
  continue
181
- previous_rank = (str(previous[1].status) == "success", previous[0].stat().st_mtime_ns)
 
 
 
 
182
  if rank > previous_rank:
183
  selected[key] = (path, log)
 
184
  return sorted(selected.values(), key=lambda item: item[0].name)
185
 
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  def load_samples(
188
  selected: list[tuple[Path, Any]],
189
  scorer: str | None,
 
190
  ) -> pd.DataFrame:
191
- rows: list[dict[str, Any]] = []
192
- for index, (path, header) in enumerate(selected, start=1):
193
- parsed_task = parse_task(header.eval.task)
194
- if parsed_task is None:
195
- print(f"Skipping unrecognized task {header.eval.task!r}")
196
- continue
197
- split, task_language = parsed_task
198
- print(f"[{index}/{len(selected)}] {model_name(header.eval.model)} / {task_language} / {split}")
199
- log = read_eval_log(str(path))
200
- if not log.samples:
201
- continue
202
- info = infer_model_info(log.eval.model)
203
- for sample in log.samples:
204
- correct = sample_score(sample, scorer)
205
- if correct is None:
206
- continue
207
- metadata = sample.metadata or {}
208
- rows.append(
209
- {
210
- "eval_id": log.eval.eval_id,
211
- "created": log.eval.created,
212
- "model_raw": log.eval.model,
213
- "model": model_name(log.eval.model),
214
- "family": info.family,
215
- "params_b": info.params_b,
216
- "vocab_size": info.vocab_size,
217
- "training_language": info.training_language,
218
- "pretrain_tokens_t": info.pretrain_tokens_t,
219
- "language": metadata.get("language", task_language),
220
- "split": split,
221
- "sample_id": sample.id,
222
- "source_id": metadata.get("source_id"),
223
- "epoch": sample.epoch,
224
- "correct": correct,
225
- }
226
- )
227
- if not rows:
228
  return pd.DataFrame()
229
- samples = pd.DataFrame(rows)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  problem_keys = [
231
  "model_raw",
232
  "model",
@@ -240,7 +350,14 @@ def load_samples(
240
  "sample_id",
241
  "source_id",
242
  ]
243
- return samples.groupby(problem_keys, dropna=False, as_index=False)["correct"].mean()
 
 
 
 
 
 
 
244
 
245
 
246
  def summarize(samples: pd.DataFrame) -> pd.DataFrame:
@@ -270,6 +387,20 @@ def model_order(summary: pd.DataFrame) -> list[str]:
270
  return models.sort_values(["family_order", "size_order", "model"])["model"].tolist()
271
 
272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  def annotated_heatmap(
274
  ax: plt.Axes,
275
  matrix: pd.DataFrame,
@@ -281,11 +412,34 @@ def annotated_heatmap(
281
  ) -> Any:
282
  values = matrix.to_numpy(dtype=float)
283
  image = ax.imshow(values, aspect="auto", cmap=cmap, vmin=vmin, vmax=vmax)
 
284
  ax.set_xticks(
285
- range(len(matrix.columns)), [LANGUAGE_LABELS.get(x, x) for x in matrix.columns], rotation=40, ha="right"
 
 
 
286
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  ax.set_yticks(range(len(matrix.index)), matrix.index)
288
  ax.set_title(title)
 
289
  for row in range(values.shape[0]):
290
  for col in range(values.shape[1]):
291
  value = values[row, col]
@@ -293,22 +447,32 @@ def annotated_heatmap(
293
  continue
294
  label = f"{value:+.1%}" if signed else f"{value:.1%}"
295
  ax.text(col, row, label, ha="center", va="center", fontsize=7)
 
296
  return image
297
 
298
 
299
  def plot_heatmaps(summary: pd.DataFrame, out: Path) -> None:
300
  order = model_order(summary)
301
- languages = sorted(summary["language"].unique(), key=lambda x: (x != "eng", x))
 
 
 
 
302
  available_splits = [split for split in ("original", "synthetic") if split in set(summary["split"])]
 
303
  matrices: dict[str, pd.DataFrame] = {}
304
  for split in available_splits:
305
  split_rows = summary[summary["split"] == split]
306
- matrices[split] = split_rows.pivot_table(index="model", columns="language", values="accuracy").reindex(
307
- index=order, columns=languages
308
- )
 
 
 
309
  panels: list[tuple[str, pd.DataFrame, str, float, float, bool]] = [
310
  (split.title(), matrices[split], "viridis", 0, 1, False) for split in available_splits
311
  ]
 
312
  if {"original", "synthetic"}.issubset(matrices):
313
  gap = matrices["original"] - matrices["synthetic"]
314
  max_gap = np.nanmax(np.abs(gap.to_numpy())) if gap.notna().any().any() else 0.1
@@ -323,17 +487,24 @@ def plot_heatmaps(summary: pd.DataFrame, out: Path) -> None:
323
  squeeze=False,
324
  )
325
  axes = axes[0]
 
326
  images = [
327
  annotated_heatmap(ax, matrix, title, cmap, vmin, vmax, signed)
328
  for ax, (title, matrix, cmap, vmin, vmax, signed) in zip(axes, panels, strict=True)
329
  ]
 
330
  axes[0].set_ylabel("Model")
331
  fig.suptitle("Accuracy across models, languages, and splits")
332
- fig.subplots_adjust(left=0.2, right=0.92, bottom=0.22, top=0.84, wspace=0.18)
 
 
 
333
  accuracy_axes = [ax for ax, panel in zip(axes, panels, strict=True) if not panel[-1]]
334
  fig.colorbar(images[0], ax=accuracy_axes, shrink=0.8, label="Accuracy")
 
335
  if panels[-1][-1]:
336
  fig.colorbar(images[-1], ax=axes[-1], shrink=0.8, label="Accuracy-point gap")
 
337
  fig.savefig(out, bbox_inches="tight")
338
  plt.close(fig)
339
 
@@ -341,12 +512,18 @@ def plot_heatmaps(summary: pd.DataFrame, out: Path) -> None:
341
  def plot_split_pairs(summary: pd.DataFrame, out: Path) -> bool:
342
  if not {"original", "synthetic"}.issubset(summary["split"].unique()):
343
  return False
344
- paired = summary.pivot_table(index=["model", "family", "language"], columns="split", values="accuracy").dropna(
345
- subset=["original", "synthetic"]
346
- )
 
 
 
 
347
  if paired.empty:
348
  return False
 
349
  fig, ax = plt.subplots(figsize=(6.5, 6))
 
350
  for (model, family, language), row in paired.iterrows():
351
  ax.scatter(
352
  row["original"],
@@ -362,21 +539,27 @@ def plot_split_pairs(summary: pd.DataFrame, out: Path) -> bool:
362
  textcoords="offset points",
363
  fontsize=6.5,
364
  )
 
365
  ax.plot([0, 1], [0, 1], linestyle="--", color="black", linewidth=1, alpha=0.6)
366
  ax.set(xlim=(0, 1), ylim=(0, 1), xlabel="Original accuracy", ylabel="Synthetic accuracy")
367
  ax.set_title("Original versus synthetic performance")
 
368
  fig.tight_layout()
369
  fig.savefig(out, bbox_inches="tight")
370
  plt.close(fig)
 
371
  return True
372
 
373
 
374
  def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
375
  scaled = summary.dropna(subset=["params_b"])
376
  families = [family for family in ("Qwen2.5", "Llama 3", "Gemma 3") if family in set(scaled["family"])]
 
377
  if not families:
378
  return False
 
379
  splits = [split for split in ("original", "synthetic") if split in set(scaled["split"])]
 
380
  fig, axes = plt.subplots(
381
  len(splits),
382
  len(families),
@@ -384,18 +567,22 @@ def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
384
  sharey=True,
385
  squeeze=False,
386
  )
 
387
  markers = ["o", "s", "^", "D", "P", "X", "v", "<", ">"]
388
  languages = sorted(scaled["language"].unique(), key=lambda x: (x != "eng", x))
389
  legend_handles: list[Any] = []
390
  legend_labels: list[str] = []
 
391
  for row_index, split in enumerate(splits):
392
  for col_index, family in enumerate(families):
393
  ax = axes[row_index, col_index]
394
  panel = scaled[(scaled["split"] == split) & (scaled["family"] == family)]
 
395
  for language, marker in zip(languages, markers, strict=False):
396
  line = panel[panel["language"] == language].sort_values("params_b")
397
  if line.empty:
398
  continue
 
399
  ax.errorbar(
400
  line["params_b"],
401
  line["accuracy"],
@@ -405,18 +592,22 @@ def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
405
  capsize=2,
406
  label=LANGUAGE_LABELS.get(language, language),
407
  )
 
408
  ax.set_xscale("log")
409
  ax.set_ylim(0, 1)
410
  ax.grid(alpha=0.2)
411
  ax.set_title(f"{family}: {split}")
412
  ax.set_xlabel("Parameters (billions, log scale)")
 
413
  if col_index == 0:
414
  ax.set_ylabel("Accuracy")
 
415
  handles, labels = ax.get_legend_handles_labels()
416
  for handle, label in zip(handles, labels, strict=True):
417
  if label not in legend_labels:
418
  legend_handles.append(handle)
419
  legend_labels.append(label)
 
420
  if legend_handles:
421
  fig.legend(
422
  legend_handles,
@@ -425,15 +616,18 @@ def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
425
  ncol=min(5, len(legend_labels)),
426
  frameon=False,
427
  )
 
428
  fig.suptitle("Within-family scaling across languages")
429
  fig.tight_layout(rect=(0, 0.06, 1, 0.96))
430
  fig.savefig(out, bbox_inches="tight")
431
  plt.close(fig)
 
432
  return True
433
 
434
 
435
  def main() -> None:
436
  parser = argparse.ArgumentParser(description=__doc__)
 
437
  parser.add_argument(
438
  "--log-dir",
439
  type=Path,
@@ -441,34 +635,65 @@ def main() -> None:
441
  default=[Path(__file__).parent / "logs"],
442
  help="One or more directories searched recursively for .eval logs.",
443
  )
444
- parser.add_argument("--out-dir", type=Path, default=Path(__file__).parent / "figures" / "model_grid")
445
  parser.add_argument(
446
- "--scorer", help="Inspect scorer name to use; defaults to math, pattern, then first numeric score."
 
 
447
  )
448
  parser.add_argument(
449
- "--include-incomplete", action="store_true", help="Include readable samples from non-success logs."
 
450
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  args = parser.parse_args()
452
 
453
  paths = discover_logs(args.log_dir)
454
- selected = select_logs(paths, args.include_incomplete)
 
455
  print(f"Discovered {len(paths)} logs; selected {len(selected)} after status filtering and deduplication.")
456
- samples = load_samples(selected, args.scorer)
 
 
 
457
  if samples.empty:
458
  raise SystemExit("No scored samples found in the selected logs.")
459
 
460
  summary = summarize(samples)
 
461
  args.out_dir.mkdir(parents=True, exist_ok=True)
 
462
  summary_path = args.out_dir / "run_summary.csv"
463
  summary.sort_values(["family", "params_b", "model", "language", "split"]).to_csv(summary_path, index=False)
 
464
  plot_heatmaps(summary, args.out_dir / "accuracy_heatmaps.png")
465
  made_pairs = plot_split_pairs(summary, args.out_dir / "original_vs_synthetic.png")
466
  made_scaling = plot_family_scaling(summary, args.out_dir / "family_scaling.png")
467
 
468
  print(f"Saved {summary_path}")
469
  print(f"Saved {args.out_dir / 'accuracy_heatmaps.png'}")
470
- if not made_pairs:
 
 
 
471
  print("Skipped original_vs_synthetic.png: no model/language has both splits.")
 
472
  if made_scaling:
473
  print(f"Saved {args.out_dir / 'family_scaling.png'}")
474
  else:
@@ -476,4 +701,4 @@ def main() -> None:
476
 
477
 
478
  if __name__ == "__main__":
479
- main()
 
14
  evaluation id are deduplicated, preferring a successful and then newer log.
15
 
16
  Example:
17
+ uv run hf_dataset/visualize_model_grid.py --log-dir hf_dataset/logs --workers 8
18
  """
19
 
20
  from __future__ import annotations
21
 
22
  import argparse
23
  import math
24
+ import os
25
  import re
26
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
27
  from dataclasses import dataclass
28
  from pathlib import Path
29
  from typing import Any
 
43
  pretrain_tokens_t: float | None = None
44
 
45
 
 
46
  MODEL_CATALOG = {
47
  "qwen2.5-0.5b-instruct": ModelInfo("Qwen2.5", 0.5, 151_936, "Chinese-English; multilingual", 18),
48
  "qwen2.5-1.5b-instruct": ModelInfo("Qwen2.5", 1.5, 151_936, "Chinese-English; multilingual", 18),
 
70
  "ukr": "Ukrainian",
71
  }
72
 
73
+ LANGUAGE_SPEAKERS = {
74
+ "eng": 380_000_000,
75
+ "deu": 100_000_000,
76
+ "dan": 6_000_000,
77
+ "nob": 5_000_000,
78
+ "isl": 370_000,
79
+ }
80
+
81
+ HUMAN_VERIFIED_LANGUAGES = {"eng", "dan"}
82
+
83
  FAMILY_COLORS = {
84
  "Qwen2.5": "#7B2CBF",
85
  "Llama 3": "#E76F51",
 
154
  scores = sample.scores or {}
155
  if scorer:
156
  return score_to_float(scores.get(scorer)) if scorer in scores else None
157
+
158
  for preferred in ("math", "pattern"):
159
  if preferred in scores:
160
  return score_to_float(scores[preferred])
161
+
162
  for score in scores.values():
163
  value = score_to_float(score)
164
  if value is not None:
165
  return value
166
+
167
  return None
168
 
169
 
 
174
  return sorted(paths)
175
 
176
 
177
+ def _read_log_header(path: Path) -> tuple[Path, Any | None, str | None]:
178
+ try:
179
+ return path, read_eval_log(str(path), header_only=True), None
180
+ except Exception as exc:
181
+ return path, None, str(exc)
182
+
183
+
184
+ def select_logs(paths: list[Path], include_incomplete: bool, workers: int) -> list[tuple[Path, Any]]:
185
  """Deduplicate log snapshots, preferring successful and newer entries."""
186
  selected: dict[tuple[str, str], tuple[Path, Any]] = {}
187
+
188
+ if not paths:
189
+ return []
190
+
191
+ if workers <= 1:
192
+ results = [_read_log_header(path) for path in paths]
193
+ else:
194
+ max_workers = min(workers, len(paths))
195
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
196
+ futures = [pool.submit(_read_log_header, path) for path in paths]
197
+ results = [future.result() for future in as_completed(futures)]
198
+
199
+ for path, log, error in results:
200
+ if error:
201
+ print(f"Skipping unreadable log {path.name}: {error}")
202
  continue
203
+
204
  status = str(log.status)
205
  if not include_incomplete and status != "success":
206
  continue
207
+
208
  key = (log.eval.eval_id, log.eval.task)
 
209
  rank = (status == "success", path.stat().st_mtime_ns)
210
+
211
+ previous = selected.get(key)
212
  if previous is None:
213
  selected[key] = (path, log)
214
  continue
215
+
216
+ previous_rank = (
217
+ str(previous[1].status) == "success",
218
+ previous[0].stat().st_mtime_ns,
219
+ )
220
  if rank > previous_rank:
221
  selected[key] = (path, log)
222
+
223
  return sorted(selected.values(), key=lambda item: item[0].name)
224
 
225
 
226
+ def _load_one_log(path: Path, scorer: str | None) -> tuple[str, pd.DataFrame | None, str | None]:
227
+ """Load and score one full Inspect log.
228
+
229
+ Returns a partially aggregated dataframe to reduce data copied back from
230
+ worker processes.
231
+ """
232
+ try:
233
+ log = read_eval_log(str(path))
234
+ except Exception as exc:
235
+ return path.name, None, f"Skipping unreadable log {path.name}: {exc}"
236
+
237
+ parsed_task = parse_task(log.eval.task)
238
+ if parsed_task is None:
239
+ return path.name, None, f"Skipping unrecognized task {log.eval.task!r}"
240
+
241
+ split, task_language = parsed_task
242
+ label = f"{model_name(log.eval.model)} / {task_language} / {split}"
243
+
244
+ if not log.samples:
245
+ return label, pd.DataFrame(), None
246
+
247
+ info = infer_model_info(log.eval.model)
248
+ rows: list[dict[str, Any]] = []
249
+
250
+ for sample in log.samples:
251
+ correct = sample_score(sample, scorer)
252
+ if correct is None:
253
+ continue
254
+
255
+ metadata = sample.metadata or {}
256
+ rows.append(
257
+ {
258
+ "model_raw": log.eval.model,
259
+ "model": model_name(log.eval.model),
260
+ "family": info.family,
261
+ "params_b": info.params_b,
262
+ "vocab_size": info.vocab_size,
263
+ "training_language": info.training_language,
264
+ "pretrain_tokens_t": info.pretrain_tokens_t,
265
+ "language": metadata.get("language", task_language),
266
+ "split": split,
267
+ "sample_id": sample.id,
268
+ "source_id": metadata.get("source_id"),
269
+ "correct": correct,
270
+ }
271
+ )
272
+
273
+ if not rows:
274
+ return label, pd.DataFrame(), None
275
+
276
+ samples = pd.DataFrame(rows)
277
+
278
+ problem_keys = [
279
+ "model_raw",
280
+ "model",
281
+ "family",
282
+ "params_b",
283
+ "vocab_size",
284
+ "training_language",
285
+ "pretrain_tokens_t",
286
+ "language",
287
+ "split",
288
+ "sample_id",
289
+ "source_id",
290
+ ]
291
+
292
+ grouped = (
293
+ samples.groupby(problem_keys, dropna=False, as_index=False)["correct"]
294
+ .agg(correct_sum="sum", correct_count="size")
295
+ )
296
+
297
+ return label, grouped, None
298
+
299
+
300
  def load_samples(
301
  selected: list[tuple[Path, Any]],
302
  scorer: str | None,
303
+ workers: int,
304
  ) -> pd.DataFrame:
305
+ """Load selected logs, optionally in parallel."""
306
+ frames: list[pd.DataFrame] = []
307
+ paths = [path for path, _header in selected]
308
+
309
+ if not paths:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  return pd.DataFrame()
311
+
312
+ if workers <= 1:
313
+ for index, path in enumerate(paths, start=1):
314
+ label, frame, warning = _load_one_log(path, scorer)
315
+ if warning:
316
+ print(warning)
317
+ else:
318
+ print(f"[{index}/{len(paths)}] {label}")
319
+ if frame is not None and not frame.empty:
320
+ frames.append(frame)
321
+ else:
322
+ max_workers = min(workers, len(paths))
323
+ with ProcessPoolExecutor(max_workers=max_workers) as pool:
324
+ futures = [pool.submit(_load_one_log, path, scorer) for path in paths]
325
+
326
+ for index, future in enumerate(as_completed(futures), start=1):
327
+ label, frame, warning = future.result()
328
+ if warning:
329
+ print(warning)
330
+ else:
331
+ print(f"[{index}/{len(paths)}] {label}")
332
+ if frame is not None and not frame.empty:
333
+ frames.append(frame)
334
+
335
+ if not frames:
336
+ return pd.DataFrame()
337
+
338
+ combined = pd.concat(frames, ignore_index=True)
339
+
340
  problem_keys = [
341
  "model_raw",
342
  "model",
 
350
  "sample_id",
351
  "source_id",
352
  ]
353
+
354
+ samples = (
355
+ combined.groupby(problem_keys, dropna=False, as_index=False)
356
+ .agg(correct_sum=("correct_sum", "sum"), correct_count=("correct_count", "sum"))
357
+ )
358
+ samples["correct"] = samples["correct_sum"] / samples["correct_count"]
359
+
360
+ return samples.drop(columns=["correct_sum", "correct_count"])
361
 
362
 
363
  def summarize(samples: pd.DataFrame) -> pd.DataFrame:
 
387
  return models.sort_values(["family_order", "size_order", "model"])["model"].tolist()
388
 
389
 
390
+ def format_speaker_count(count: int) -> str:
391
+ if count >= 1_000_000:
392
+ return f"{count / 1_000_000:g}M"
393
+ if count >= 1_000:
394
+ return f"{count / 1_000:g}K"
395
+ return str(count)
396
+
397
+
398
+ def heatmap_language_label(language: str) -> str:
399
+ name = LANGUAGE_LABELS.get(language, language)
400
+ speakers = LANGUAGE_SPEAKERS.get(language)
401
+ return f"{name}\n({format_speaker_count(speakers)} speakers)" if speakers is not None else name
402
+
403
+
404
  def annotated_heatmap(
405
  ax: plt.Axes,
406
  matrix: pd.DataFrame,
 
412
  ) -> Any:
413
  values = matrix.to_numpy(dtype=float)
414
  image = ax.imshow(values, aspect="auto", cmap=cmap, vmin=vmin, vmax=vmax)
415
+
416
  ax.set_xticks(
417
+ range(len(matrix.columns)),
418
+ [heatmap_language_label(x) for x in matrix.columns],
419
+ rotation=40,
420
+ ha="right",
421
  )
422
+
423
+ for col, language in enumerate(matrix.columns):
424
+ if language not in HUMAN_VERIFIED_LANGUAGES:
425
+ continue
426
+ ax.annotate(
427
+ "*",
428
+ xy=(col, 0),
429
+ xycoords=ax.get_xaxis_transform(),
430
+ xytext=(1, -4),
431
+ textcoords="offset points",
432
+ color="#FFC107",
433
+ fontweight="bold",
434
+ rotation=40,
435
+ ha="left",
436
+ va="top",
437
+ annotation_clip=False,
438
+ )
439
+
440
  ax.set_yticks(range(len(matrix.index)), matrix.index)
441
  ax.set_title(title)
442
+
443
  for row in range(values.shape[0]):
444
  for col in range(values.shape[1]):
445
  value = values[row, col]
 
447
  continue
448
  label = f"{value:+.1%}" if signed else f"{value:.1%}"
449
  ax.text(col, row, label, ha="center", va="center", fontsize=7)
450
+
451
  return image
452
 
453
 
454
  def plot_heatmaps(summary: pd.DataFrame, out: Path) -> None:
455
  order = model_order(summary)
456
+ languages = sorted(
457
+ summary["language"].unique(),
458
+ key=lambda language: (-LANGUAGE_SPEAKERS.get(language, -1), language),
459
+ )
460
+
461
  available_splits = [split for split in ("original", "synthetic") if split in set(summary["split"])]
462
+
463
  matrices: dict[str, pd.DataFrame] = {}
464
  for split in available_splits:
465
  split_rows = summary[summary["split"] == split]
466
+ matrices[split] = split_rows.pivot_table(
467
+ index="model",
468
+ columns="language",
469
+ values="accuracy",
470
+ ).reindex(index=order, columns=languages)
471
+
472
  panels: list[tuple[str, pd.DataFrame, str, float, float, bool]] = [
473
  (split.title(), matrices[split], "viridis", 0, 1, False) for split in available_splits
474
  ]
475
+
476
  if {"original", "synthetic"}.issubset(matrices):
477
  gap = matrices["original"] - matrices["synthetic"]
478
  max_gap = np.nanmax(np.abs(gap.to_numpy())) if gap.notna().any().any() else 0.1
 
487
  squeeze=False,
488
  )
489
  axes = axes[0]
490
+
491
  images = [
492
  annotated_heatmap(ax, matrix, title, cmap, vmin, vmax, signed)
493
  for ax, (title, matrix, cmap, vmin, vmax, signed) in zip(axes, panels, strict=True)
494
  ]
495
+
496
  axes[0].set_ylabel("Model")
497
  fig.suptitle("Accuracy across models, languages, and splits")
498
+ fig.text(0.465, 0.02, "*", color="#FFC107", fontweight="bold", ha="right", fontsize=8)
499
+ fig.text(0.467, 0.02, "Human verified", ha="left", fontsize=8)
500
+ fig.subplots_adjust(left=0.2, right=0.92, bottom=0.28, top=0.84, wspace=0.18)
501
+
502
  accuracy_axes = [ax for ax, panel in zip(axes, panels, strict=True) if not panel[-1]]
503
  fig.colorbar(images[0], ax=accuracy_axes, shrink=0.8, label="Accuracy")
504
+
505
  if panels[-1][-1]:
506
  fig.colorbar(images[-1], ax=axes[-1], shrink=0.8, label="Accuracy-point gap")
507
+
508
  fig.savefig(out, bbox_inches="tight")
509
  plt.close(fig)
510
 
 
512
  def plot_split_pairs(summary: pd.DataFrame, out: Path) -> bool:
513
  if not {"original", "synthetic"}.issubset(summary["split"].unique()):
514
  return False
515
+
516
+ paired = summary.pivot_table(
517
+ index=["model", "family", "language"],
518
+ columns="split",
519
+ values="accuracy",
520
+ ).dropna(subset=["original", "synthetic"])
521
+
522
  if paired.empty:
523
  return False
524
+
525
  fig, ax = plt.subplots(figsize=(6.5, 6))
526
+
527
  for (model, family, language), row in paired.iterrows():
528
  ax.scatter(
529
  row["original"],
 
539
  textcoords="offset points",
540
  fontsize=6.5,
541
  )
542
+
543
  ax.plot([0, 1], [0, 1], linestyle="--", color="black", linewidth=1, alpha=0.6)
544
  ax.set(xlim=(0, 1), ylim=(0, 1), xlabel="Original accuracy", ylabel="Synthetic accuracy")
545
  ax.set_title("Original versus synthetic performance")
546
+
547
  fig.tight_layout()
548
  fig.savefig(out, bbox_inches="tight")
549
  plt.close(fig)
550
+
551
  return True
552
 
553
 
554
  def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
555
  scaled = summary.dropna(subset=["params_b"])
556
  families = [family for family in ("Qwen2.5", "Llama 3", "Gemma 3") if family in set(scaled["family"])]
557
+
558
  if not families:
559
  return False
560
+
561
  splits = [split for split in ("original", "synthetic") if split in set(scaled["split"])]
562
+
563
  fig, axes = plt.subplots(
564
  len(splits),
565
  len(families),
 
567
  sharey=True,
568
  squeeze=False,
569
  )
570
+
571
  markers = ["o", "s", "^", "D", "P", "X", "v", "<", ">"]
572
  languages = sorted(scaled["language"].unique(), key=lambda x: (x != "eng", x))
573
  legend_handles: list[Any] = []
574
  legend_labels: list[str] = []
575
+
576
  for row_index, split in enumerate(splits):
577
  for col_index, family in enumerate(families):
578
  ax = axes[row_index, col_index]
579
  panel = scaled[(scaled["split"] == split) & (scaled["family"] == family)]
580
+
581
  for language, marker in zip(languages, markers, strict=False):
582
  line = panel[panel["language"] == language].sort_values("params_b")
583
  if line.empty:
584
  continue
585
+
586
  ax.errorbar(
587
  line["params_b"],
588
  line["accuracy"],
 
592
  capsize=2,
593
  label=LANGUAGE_LABELS.get(language, language),
594
  )
595
+
596
  ax.set_xscale("log")
597
  ax.set_ylim(0, 1)
598
  ax.grid(alpha=0.2)
599
  ax.set_title(f"{family}: {split}")
600
  ax.set_xlabel("Parameters (billions, log scale)")
601
+
602
  if col_index == 0:
603
  ax.set_ylabel("Accuracy")
604
+
605
  handles, labels = ax.get_legend_handles_labels()
606
  for handle, label in zip(handles, labels, strict=True):
607
  if label not in legend_labels:
608
  legend_handles.append(handle)
609
  legend_labels.append(label)
610
+
611
  if legend_handles:
612
  fig.legend(
613
  legend_handles,
 
616
  ncol=min(5, len(legend_labels)),
617
  frameon=False,
618
  )
619
+
620
  fig.suptitle("Within-family scaling across languages")
621
  fig.tight_layout(rect=(0, 0.06, 1, 0.96))
622
  fig.savefig(out, bbox_inches="tight")
623
  plt.close(fig)
624
+
625
  return True
626
 
627
 
628
  def main() -> None:
629
  parser = argparse.ArgumentParser(description=__doc__)
630
+
631
  parser.add_argument(
632
  "--log-dir",
633
  type=Path,
 
635
  default=[Path(__file__).parent / "logs"],
636
  help="One or more directories searched recursively for .eval logs.",
637
  )
 
638
  parser.add_argument(
639
+ "--out-dir",
640
+ type=Path,
641
+ default=Path(__file__).parent / "figures" / "model_grid",
642
  )
643
  parser.add_argument(
644
+ "--scorer",
645
+ help="Inspect scorer name to use; defaults to math, pattern, then first numeric score.",
646
  )
647
+ parser.add_argument(
648
+ "--include-incomplete",
649
+ action="store_true",
650
+ help="Include readable samples from non-success logs.",
651
+ )
652
+ parser.add_argument(
653
+ "--workers",
654
+ type=int,
655
+ default=32,
656
+ help="Processes used for full log loading. Use 1 to disable multiprocessing.",
657
+ )
658
+ parser.add_argument(
659
+ "--header-workers",
660
+ type=int,
661
+ default=32,
662
+ help="Threads used for the header-only deduplication pass.",
663
+ )
664
+
665
  args = parser.parse_args()
666
 
667
  paths = discover_logs(args.log_dir)
668
+ selected = select_logs(paths, args.include_incomplete, workers=args.header_workers)
669
+
670
  print(f"Discovered {len(paths)} logs; selected {len(selected)} after status filtering and deduplication.")
671
+ print(f"Loading selected logs with {args.workers} worker(s).")
672
+
673
+ samples = load_samples(selected, args.scorer, workers=args.workers)
674
+
675
  if samples.empty:
676
  raise SystemExit("No scored samples found in the selected logs.")
677
 
678
  summary = summarize(samples)
679
+
680
  args.out_dir.mkdir(parents=True, exist_ok=True)
681
+
682
  summary_path = args.out_dir / "run_summary.csv"
683
  summary.sort_values(["family", "params_b", "model", "language", "split"]).to_csv(summary_path, index=False)
684
+
685
  plot_heatmaps(summary, args.out_dir / "accuracy_heatmaps.png")
686
  made_pairs = plot_split_pairs(summary, args.out_dir / "original_vs_synthetic.png")
687
  made_scaling = plot_family_scaling(summary, args.out_dir / "family_scaling.png")
688
 
689
  print(f"Saved {summary_path}")
690
  print(f"Saved {args.out_dir / 'accuracy_heatmaps.png'}")
691
+
692
+ if made_pairs:
693
+ print(f"Saved {args.out_dir / 'original_vs_synthetic.png'}")
694
+ else:
695
  print("Skipped original_vs_synthetic.png: no model/language has both splits.")
696
+
697
  if made_scaling:
698
  print(f"Saved {args.out_dir / 'family_scaling.png'}")
699
  else:
 
701
 
702
 
703
  if __name__ == "__main__":
704
+ main()