rileyherchert commited on
Commit ·
bf81fb3
1
Parent(s): 5536cb0
Update eval script and add visualization
Browse files- ucloudeval +36 -6
- visualize_model_grid.py +479 -0
ucloudeval
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
from __future__ import annotations
|
| 5 |
|
| 6 |
import argparse
|
|
|
|
| 7 |
import subprocess
|
| 8 |
import sys
|
| 9 |
from collections.abc import Sequence
|
|
@@ -24,7 +25,9 @@ MODELS = (
|
|
| 24 |
"google/gemma-3-4b-it",
|
| 25 |
"google/gemma-3-12b-it",
|
| 26 |
)
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
HERE = Path(__file__).resolve().parent
|
| 30 |
EVAL_YAML, LOG_DIR = HERE / "eval.yaml", HERE / "logs"
|
|
@@ -56,7 +59,10 @@ def load_tasks(path: Path = EVAL_YAML) -> list[Task]:
|
|
| 56 |
|
| 57 |
def build_parser(languages: Sequence[str], splits: Sequence[str]) -> argparse.ArgumentParser:
|
| 58 |
parser = argparse.ArgumentParser(
|
| 59 |
-
description=
|
|
|
|
|
|
|
|
|
|
| 60 |
)
|
| 61 |
options = (
|
| 62 |
("model", MODELS, "HF_MODEL_ID", "curated Hugging Face model id"),
|
|
@@ -109,13 +115,35 @@ def select_tasks(
|
|
| 109 |
|
| 110 |
|
| 111 |
def inspect_command(model: str, tasks: Sequence[Task]) -> list[str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
return [
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
]
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def show_command(message: str, command: Sequence[str]) -> None:
|
| 120 |
print(f"{message}\n {' '.join(command)}")
|
| 121 |
|
|
@@ -124,11 +152,13 @@ def run_inspect(model: str, tasks: Sequence[Task]) -> None:
|
|
| 124 |
command = inspect_command(model, tasks)
|
| 125 |
show_command(f"Running {len(tasks)} Inspect task(s) for {model}", command)
|
| 126 |
try:
|
| 127 |
-
subprocess.run(command, check=True)
|
| 128 |
except subprocess.CalledProcessError as error:
|
| 129 |
raise RunnerError(f"Inspect failed for {model} with status {error.returncode}") from error
|
| 130 |
except OSError as error:
|
| 131 |
raise RunnerError(f"Could not start Inspect for {model}: {error}") from error
|
|
|
|
|
|
|
| 132 |
def main(argv: Sequence[str] | None = None) -> int:
|
| 133 |
try:
|
| 134 |
tasks = load_tasks()
|
|
|
|
| 4 |
from __future__ import annotations
|
| 5 |
|
| 6 |
import argparse
|
| 7 |
+
import os
|
| 8 |
import subprocess
|
| 9 |
import sys
|
| 10 |
from collections.abc import Sequence
|
|
|
|
| 25 |
"google/gemma-3-4b-it",
|
| 26 |
"google/gemma-3-12b-it",
|
| 27 |
)
|
| 28 |
+
# Repository id (no revision) and optional revision to apply to each task
|
| 29 |
+
DATASET = "danish-foundation-models/multilingual-gsm-symbolic"
|
| 30 |
+
REVISION = "refs/pr/4"
|
| 31 |
|
| 32 |
HERE = Path(__file__).resolve().parent
|
| 33 |
EVAL_YAML, LOG_DIR = HERE / "eval.yaml", HERE / "logs"
|
|
|
|
| 59 |
|
| 60 |
def build_parser(languages: Sequence[str], splits: Sequence[str]) -> argparse.ArgumentParser:
|
| 61 |
parser = argparse.ArgumentParser(
|
| 62 |
+
description=(
|
| 63 |
+
"Evaluate multilingual GSM-Symbolic tasks against one local vLLM model at a time, "
|
| 64 |
+
"resuming completed and interrupted work from the log directory."
|
| 65 |
+
)
|
| 66 |
)
|
| 67 |
options = (
|
| 68 |
("model", MODELS, "HF_MODEL_ID", "curated Hugging Face model id"),
|
|
|
|
| 115 |
|
| 116 |
|
| 117 |
def inspect_command(model: str, tasks: Sequence[Task]) -> list[str]:
|
| 118 |
+
# place the revision after the task id so the HF loader parses it correctly
|
| 119 |
+
specs = [
|
| 120 |
+
f"hf/{DATASET}/{task.task_id}@{REVISION}" if REVISION else f"hf/{DATASET}/{task.task_id}" for task in tasks
|
| 121 |
+
]
|
| 122 |
return [
|
| 123 |
+
# Eval sets use the log directory to skip successful tasks and retry
|
| 124 |
+
# interrupted tasks without repeating their completed samples.
|
| 125 |
+
"inspect", "eval-set", *specs,
|
| 126 |
+
"--model", f"vllm/{model}",
|
| 127 |
+
"-M", "dtype=auto",
|
| 128 |
+
"-M", "attention_backend=FLASH_ATTN",
|
| 129 |
+
"-M", "max_num_seqs=512",
|
| 130 |
+
"--max-connections", "128",
|
| 131 |
+
"--max-samples", "128",
|
| 132 |
+
"--max-tasks", "8",
|
| 133 |
+
"--log-dir", str(LOG_DIR),
|
| 134 |
+
"--log-dir-allow-dirty",
|
| 135 |
]
|
| 136 |
|
| 137 |
|
| 138 |
+
def vllm_environment() -> dict[str, str]:
|
| 139 |
+
env = os.environ.copy()
|
| 140 |
+
# The CUDA 13 packages in this environment have mismatched nvcc/headers.
|
| 141 |
+
# Avoid vLLM paths that require FlashInfer or DeepGEMM runtime compilation.
|
| 142 |
+
env.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 143 |
+
env.setdefault("VLLM_USE_DEEP_GEMM", "0")
|
| 144 |
+
return env
|
| 145 |
+
|
| 146 |
+
|
| 147 |
def show_command(message: str, command: Sequence[str]) -> None:
|
| 148 |
print(f"{message}\n {' '.join(command)}")
|
| 149 |
|
|
|
|
| 152 |
command = inspect_command(model, tasks)
|
| 153 |
show_command(f"Running {len(tasks)} Inspect task(s) for {model}", command)
|
| 154 |
try:
|
| 155 |
+
subprocess.run(command, check=True, env=vllm_environment())
|
| 156 |
except subprocess.CalledProcessError as error:
|
| 157 |
raise RunnerError(f"Inspect failed for {model} with status {error.returncode}") from error
|
| 158 |
except OSError as error:
|
| 159 |
raise RunnerError(f"Could not start Inspect for {model}: {error}") from error
|
| 160 |
+
|
| 161 |
+
|
| 162 |
def main(argv: Sequence[str] | None = None) -> int:
|
| 163 |
try:
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# dependencies = ["inspect-ai", "matplotlib", "numpy", "pandas"]
|
| 3 |
+
# ///
|
| 4 |
+
"""Visualize multilingual GSM evaluation logs across models and splits.
|
| 5 |
+
|
| 6 |
+
The script reads Inspect ``.eval`` logs and writes:
|
| 7 |
+
|
| 8 |
+
* ``run_summary.csv``: tidy accuracy table for downstream analysis.
|
| 9 |
+
* ``accuracy_heatmaps.png``: original, synthetic, and original-minus-synthetic.
|
| 10 |
+
* ``original_vs_synthetic.png``: paired split performance for each model/language.
|
| 11 |
+
* ``family_scaling.png``: within-family accuracy as a function of parameter count.
|
| 12 |
+
|
| 13 |
+
Only successful logs are included by default. Repeated/resumed logs with the same
|
| 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
|
| 28 |
+
|
| 29 |
+
import matplotlib.pyplot as plt
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 32 |
+
from inspect_ai.log import read_eval_log
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass(frozen=True)
|
| 36 |
+
class ModelInfo:
|
| 37 |
+
family: str
|
| 38 |
+
params_b: float | None
|
| 39 |
+
vocab_size: int | None = None
|
| 40 |
+
training_language: str = ""
|
| 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),
|
| 48 |
+
"qwen2.5-3b-instruct": ModelInfo("Qwen2.5", 3, 151_936, "Chinese-English; multilingual", 18),
|
| 49 |
+
"qwen2.5-7b-instruct": ModelInfo("Qwen2.5", 7, 151_936, "Chinese-English; multilingual", 18),
|
| 50 |
+
"llama-3.2-1b-instruct": ModelInfo("Llama 3", 1, 128_256, "English-centric", 9),
|
| 51 |
+
"llama-3.2-3b-instruct": ModelInfo("Llama 3", 3, 128_256, "English-centric", 9),
|
| 52 |
+
"llama-3.1-8b-instruct": ModelInfo("Llama 3", 8, 128_256, "English-centric", 15),
|
| 53 |
+
"gemma-3-1b-it": ModelInfo("Gemma 3", 1, 262_144, "English-oriented", 2),
|
| 54 |
+
"gemma-3-4b-it": ModelInfo("Gemma 3", 4, 262_144, "Multilingual; 140+ languages", 4),
|
| 55 |
+
"gemma-3-12b-it": ModelInfo("Gemma 3", 12, 262_144, "Multilingual; 140+ languages", 12),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
LANGUAGE_LABELS = {
|
| 59 |
+
"dan": "Danish",
|
| 60 |
+
"deu": "German",
|
| 61 |
+
"eng": "English",
|
| 62 |
+
"fra": "French",
|
| 63 |
+
"isl": "Icelandic",
|
| 64 |
+
"ita": "Italian",
|
| 65 |
+
"nob": "Norwegian Bokmal",
|
| 66 |
+
"por": "Portuguese",
|
| 67 |
+
"rus": "Russian",
|
| 68 |
+
"spa": "Spanish",
|
| 69 |
+
"ukr": "Ukrainian",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
FAMILY_COLORS = {
|
| 73 |
+
"Qwen2.5": "#7B2CBF",
|
| 74 |
+
"Llama 3": "#E76F51",
|
| 75 |
+
"Gemma 3": "#2A9D8F",
|
| 76 |
+
"OpenAI": "#457B9D",
|
| 77 |
+
"Other": "#666666",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
plt.rcParams.update(
|
| 81 |
+
{
|
| 82 |
+
"axes.spines.right": False,
|
| 83 |
+
"axes.spines.top": False,
|
| 84 |
+
"figure.dpi": 160,
|
| 85 |
+
"font.family": "sans-serif",
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def model_name(raw_model: str) -> str:
|
| 91 |
+
"""Drop provider/organization prefixes while preserving the model id."""
|
| 92 |
+
return raw_model.rstrip("/").split("/")[-1]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def infer_model_info(raw_model: str) -> ModelInfo:
|
| 96 |
+
name = model_name(raw_model)
|
| 97 |
+
catalog_info = MODEL_CATALOG.get(name.lower())
|
| 98 |
+
if catalog_info:
|
| 99 |
+
return catalog_info
|
| 100 |
+
|
| 101 |
+
lower = name.lower()
|
| 102 |
+
if "qwen" in lower:
|
| 103 |
+
family = "Qwen2.5" if "2.5" in lower else "Qwen"
|
| 104 |
+
elif "llama" in lower:
|
| 105 |
+
family = "Llama 3" if re.search(r"llama[-_. ]?3", lower) else "Llama"
|
| 106 |
+
elif "gemma" in lower:
|
| 107 |
+
family = "Gemma 3" if re.search(r"gemma[-_. ]?3", lower) else "Gemma"
|
| 108 |
+
elif raw_model.lower().startswith("openai/") or lower.startswith(("gpt-", "o1", "o3", "o4")):
|
| 109 |
+
family = "OpenAI"
|
| 110 |
+
else:
|
| 111 |
+
family = "Other"
|
| 112 |
+
|
| 113 |
+
size_match = re.search(r"(?<![\d.])(\d+(?:\.\d+)?)\s*b(?:\b|[-_])", lower)
|
| 114 |
+
params_b = float(size_match.group(1)) if size_match else None
|
| 115 |
+
return ModelInfo(family, params_b)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def parse_task(task: str) -> tuple[str, str] | None:
|
| 119 |
+
matches = re.findall(r"(original|synthetic)[_-]([a-z]{3})", task.lower())
|
| 120 |
+
return matches[-1] if matches else None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def score_to_float(score: Any) -> float | None:
|
| 124 |
+
value = getattr(score, "value", score)
|
| 125 |
+
if isinstance(value, bool):
|
| 126 |
+
return float(value)
|
| 127 |
+
if isinstance(value, (int, float)):
|
| 128 |
+
return float(value)
|
| 129 |
+
if isinstance(value, str):
|
| 130 |
+
normalized = value.strip().upper()
|
| 131 |
+
if normalized in {"C", "CORRECT", "TRUE"}:
|
| 132 |
+
return 1.0
|
| 133 |
+
if normalized in {"I", "INCORRECT", "FALSE"}:
|
| 134 |
+
return 0.0
|
| 135 |
+
try:
|
| 136 |
+
return float(normalized)
|
| 137 |
+
except ValueError:
|
| 138 |
+
return None
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
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 |
+
|
| 156 |
+
def discover_logs(log_dirs: list[Path]) -> list[Path]:
|
| 157 |
+
paths: set[Path] = set()
|
| 158 |
+
for log_dir in log_dirs:
|
| 159 |
+
paths.update(path for path in log_dir.rglob("*.eval") if path.stat().st_size >= 1_000)
|
| 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",
|
| 233 |
+
"family",
|
| 234 |
+
"params_b",
|
| 235 |
+
"vocab_size",
|
| 236 |
+
"training_language",
|
| 237 |
+
"pretrain_tokens_t",
|
| 238 |
+
"language",
|
| 239 |
+
"split",
|
| 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:
|
| 247 |
+
group_cols = [
|
| 248 |
+
"model_raw",
|
| 249 |
+
"model",
|
| 250 |
+
"family",
|
| 251 |
+
"params_b",
|
| 252 |
+
"vocab_size",
|
| 253 |
+
"training_language",
|
| 254 |
+
"pretrain_tokens_t",
|
| 255 |
+
"language",
|
| 256 |
+
"split",
|
| 257 |
+
]
|
| 258 |
+
return (
|
| 259 |
+
samples.groupby(group_cols, dropna=False)["correct"]
|
| 260 |
+
.agg(accuracy="mean", n_problems="size", stderr="sem")
|
| 261 |
+
.reset_index()
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def model_order(summary: pd.DataFrame) -> list[str]:
|
| 266 |
+
models = summary[["model", "family", "params_b"]].drop_duplicates().copy()
|
| 267 |
+
family_order = {"Qwen2.5": 0, "Llama 3": 1, "Gemma 3": 2, "OpenAI": 3, "Other": 4}
|
| 268 |
+
models["family_order"] = models["family"].map(family_order).fillna(99)
|
| 269 |
+
models["size_order"] = models["params_b"].fillna(math.inf)
|
| 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,
|
| 276 |
+
title: str,
|
| 277 |
+
cmap: str,
|
| 278 |
+
vmin: float,
|
| 279 |
+
vmax: float,
|
| 280 |
+
signed: bool = False,
|
| 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]
|
| 292 |
+
if np.isnan(value):
|
| 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
|
| 315 |
+
panels.append(("Original - synthetic", gap, "RdBu_r", -max_gap, max_gap, True))
|
| 316 |
+
|
| 317 |
+
height = max(4.0, 0.42 * len(order) + 1.5)
|
| 318 |
+
fig, axes = plt.subplots(
|
| 319 |
+
1,
|
| 320 |
+
len(panels),
|
| 321 |
+
figsize=(max(6, 2.5 * len(languages) * len(panels)), height),
|
| 322 |
+
sharey=True,
|
| 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 |
+
|
| 340 |
+
|
| 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"],
|
| 353 |
+
row["synthetic"],
|
| 354 |
+
color=FAMILY_COLORS.get(family, FAMILY_COLORS["Other"]),
|
| 355 |
+
s=50,
|
| 356 |
+
alpha=0.85,
|
| 357 |
+
)
|
| 358 |
+
ax.annotate(
|
| 359 |
+
f"{model} / {language}",
|
| 360 |
+
(row["original"], row["synthetic"]),
|
| 361 |
+
xytext=(4, 3),
|
| 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),
|
| 383 |
+
figsize=(5 * len(families), 4 * len(splits)),
|
| 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"],
|
| 402 |
+
yerr=line["stderr"].fillna(0),
|
| 403 |
+
marker=marker,
|
| 404 |
+
linewidth=1.5,
|
| 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,
|
| 423 |
+
legend_labels,
|
| 424 |
+
loc="lower center",
|
| 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,
|
| 440 |
+
nargs="+",
|
| 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:
|
| 475 |
+
print("Skipped family_scaling.png: no recognized model parameter counts.")
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
if __name__ == "__main__":
|
| 479 |
+
main()
|