rileyherchert commited on
Commit
d987d52
·
1 Parent(s): ca8650e

add more visualizations

Browse files
analyze_transfer_features.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = [
3
+ # "lang2vec",
4
+ # "matplotlib",
5
+ # "numpy",
6
+ # "pandas",
7
+ # "pyarrow",
8
+ # "setuptools<81",
9
+ # "transformers",
10
+ # ]
11
+ # ///
12
+ """Collect language features and relate them to cross-lingual transfer.
13
+
14
+ The script combines ``visualize_model_grid.py``'s run summary with:
15
+
16
+ * tokenizer fertility: tokens per non-whitespace Unicode character, normalized
17
+ to English on matched source problems for each model tokenizer;
18
+ * typological distance: cosine distance from English over concatenated
19
+ URIEL/lang2vec ``syntax_knn`` and ``inventory_knn`` vectors;
20
+ * resource quantity: current Wikipedia article count, used as a transparent
21
+ reproducible proxy and plotted on a base-10 log scale.
22
+
23
+ Outputs include the collected feature tables, the joined transfer-analysis
24
+ table, provenance metadata, and one relationship plot per feature.
25
+
26
+ Example:
27
+ uv run hf_dataset/analyze_transfer_features.py
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import math
35
+ import urllib.parse
36
+ import urllib.request
37
+ from datetime import UTC, datetime
38
+ from pathlib import Path
39
+ from typing import Any
40
+
41
+ import lang2vec.lang2vec as l2v
42
+ import matplotlib.pyplot as plt
43
+ import numpy as np
44
+ import pandas as pd
45
+ from transformers import AutoTokenizer
46
+
47
+ LANGUAGE_LABELS = {
48
+ "dan": "Danish",
49
+ "deu": "German",
50
+ "eng": "English",
51
+ "fra": "French",
52
+ "isl": "Icelandic",
53
+ "ita": "Italian",
54
+ "nob": "Norwegian Bokmal",
55
+ "por": "Portuguese",
56
+ "rus": "Russian",
57
+ "spa": "Spanish",
58
+ "ukr": "Ukrainian",
59
+ "zho": "Chinese",
60
+ }
61
+
62
+ WIKIPEDIA_CODES = {
63
+ "dan": "da",
64
+ "deu": "de",
65
+ "eng": "en",
66
+ "fra": "fr",
67
+ "isl": "is",
68
+ "ita": "it",
69
+ "nob": "no",
70
+ "por": "pt",
71
+ "rus": "ru",
72
+ "spa": "es",
73
+ "ukr": "uk",
74
+ "zho": "zh",
75
+ }
76
+
77
+ TOKENIZER_REPOS = {
78
+ "qwen2.5-0.5b-instruct": "Qwen/Qwen2.5-0.5B-Instruct",
79
+ "qwen2.5-1.5b-instruct": "Qwen/Qwen2.5-1.5B-Instruct",
80
+ "qwen2.5-3b-instruct": "Qwen/Qwen2.5-3B-Instruct",
81
+ "qwen2.5-7b-instruct": "Qwen/Qwen2.5-7B-Instruct",
82
+ "llama-3.2-1b-instruct": "meta-llama/Llama-3.2-1B-Instruct",
83
+ "llama-3.2-3b-instruct": "meta-llama/Llama-3.2-3B-Instruct",
84
+ "llama-3.1-8b-instruct": "meta-llama/Llama-3.1-8B-Instruct",
85
+ "gemma-3-1b-it": "google/gemma-3-1b-it",
86
+ "gemma-3-4b-it": "google/gemma-3-4b-it",
87
+ "gemma-3-12b-it": "google/gemma-3-12b-it",
88
+ }
89
+
90
+ FAMILY_COLORS = {
91
+ "Qwen2.5": "#7B2CBF",
92
+ "Llama 3": "#E76F51",
93
+ "Gemma 3": "#2A9D8F",
94
+ "OpenAI": "#457B9D",
95
+ "Other": "#666666",
96
+ }
97
+
98
+ plt.rcParams.update(
99
+ {
100
+ "axes.spines.right": False,
101
+ "axes.spines.top": False,
102
+ "figure.dpi": 160,
103
+ "font.family": "sans-serif",
104
+ }
105
+ )
106
+
107
+
108
+ def wikipedia_statistics(language: str, timeout: float) -> dict[str, Any]:
109
+ """Fetch current article/page counts from a language's MediaWiki API."""
110
+ wiki_code = WIKIPEDIA_CODES.get(language)
111
+ if wiki_code is None:
112
+ raise ValueError(f"No Wikipedia language code configured for {language!r}")
113
+
114
+ query = urllib.parse.urlencode(
115
+ {
116
+ "action": "query",
117
+ "meta": "siteinfo",
118
+ "siprop": "statistics",
119
+ "format": "json",
120
+ "formatversion": 2,
121
+ }
122
+ )
123
+ url = f"https://{wiki_code}.wikipedia.org/w/api.php?{query}"
124
+ request = urllib.request.Request(
125
+ url,
126
+ headers={
127
+ "User-Agent": (
128
+ "multilingual-gsm-symbolic/transfer-feature-analysis "
129
+ "(https://github.com/centre-for-humanities-computing/multilingual-gsm-symbolic)"
130
+ )
131
+ },
132
+ )
133
+ with urllib.request.urlopen(request, timeout=timeout) as response:
134
+ payload = json.load(response)
135
+
136
+ statistics = payload["query"]["statistics"]
137
+ return {
138
+ "wikipedia_code": wiki_code,
139
+ "wikipedia_articles": int(statistics["articles"]),
140
+ "wikipedia_pages": int(statistics["pages"]),
141
+ "resource_source_url": url,
142
+ }
143
+
144
+
145
+ def cosine_distance(left: np.ndarray, right: np.ndarray) -> float:
146
+ denominator = np.linalg.norm(left) * np.linalg.norm(right)
147
+ if denominator == 0:
148
+ return math.nan
149
+ distance = float(1 - np.dot(left, right) / denominator)
150
+ return 0.0 if abs(distance) < 1e-12 else distance
151
+
152
+
153
+ def collect_language_features(
154
+ languages: list[str],
155
+ timeout: float,
156
+ resource_cache: pd.DataFrame | None,
157
+ ) -> pd.DataFrame:
158
+ """Collect URIEL distance and Wikipedia resource counts per language."""
159
+ vectors = l2v.get_features(languages, "syntax_knn+inventory_knn")
160
+ english = np.asarray(vectors["eng"], dtype=float)
161
+ cached = {}
162
+ if resource_cache is not None and not resource_cache.empty:
163
+ cached = resource_cache.set_index("language").to_dict(orient="index")
164
+
165
+ rows: list[dict[str, Any]] = []
166
+ retrieved_at = datetime.now(UTC).isoformat()
167
+ for language in languages:
168
+ try:
169
+ resource = wikipedia_statistics(language, timeout)
170
+ resource["resource_retrieved_at_utc"] = retrieved_at
171
+ except Exception as exc:
172
+ if language not in cached:
173
+ raise RuntimeError(
174
+ f"Could not fetch Wikipedia statistics for {language} and no cache is available"
175
+ ) from exc
176
+ print(f"Using cached Wikipedia statistics for {language}: {exc}")
177
+ resource = {
178
+ key: cached[language][key]
179
+ for key in (
180
+ "wikipedia_code",
181
+ "wikipedia_articles",
182
+ "wikipedia_pages",
183
+ "resource_source_url",
184
+ "resource_retrieved_at_utc",
185
+ )
186
+ }
187
+
188
+ articles = int(resource["wikipedia_articles"])
189
+ rows.append(
190
+ {
191
+ "language": language,
192
+ "language_name": LANGUAGE_LABELS.get(language, language),
193
+ "typological_distance_from_english": cosine_distance(
194
+ np.asarray(vectors[language], dtype=float),
195
+ english,
196
+ ),
197
+ "typological_feature_set": "URIEL syntax_knn + inventory_knn",
198
+ **resource,
199
+ "log10_wikipedia_articles": math.log10(articles) if articles > 0 else math.nan,
200
+ }
201
+ )
202
+
203
+ return pd.DataFrame(rows)
204
+
205
+
206
+ def load_questions(data_dir: Path, languages: list[str]) -> dict[str, pd.DataFrame]:
207
+ """Load original benchmark questions, indexed by matched source id."""
208
+ questions: dict[str, pd.DataFrame] = {}
209
+ for language in languages:
210
+ paths = sorted((data_dir / language).glob("test_original-*.parquet"))
211
+ if not paths:
212
+ raise FileNotFoundError(f"No test_original parquet files found for {language} in {data_dir}")
213
+ frame = pd.concat(pd.read_parquet(path, columns=["question", "source_id"]) for path in paths)
214
+ frame = frame.drop_duplicates("source_id").set_index("source_id").sort_index()
215
+ questions[language] = frame
216
+ return questions
217
+
218
+
219
+ def tokenizer_repo(model: str, model_raw: str) -> str | None:
220
+ known = TOKENIZER_REPOS.get(model.lower())
221
+ if known:
222
+ return known
223
+
224
+ raw = model_raw.rstrip("/")
225
+ for prefix in ("vllm/", "hf/", "transformers/"):
226
+ if raw.lower().startswith(prefix):
227
+ return raw[len(prefix) :]
228
+ if raw.lower().startswith("openai/"):
229
+ return None
230
+ return raw if "/" in raw else None
231
+
232
+
233
+ def text_fertility(tokenizer: Any, texts: list[str]) -> tuple[float, int, int]:
234
+ """Return corpus tokens/non-whitespace-character ratio and its totals."""
235
+ encoded = tokenizer(
236
+ texts,
237
+ add_special_tokens=False,
238
+ truncation=False,
239
+ return_attention_mask=False,
240
+ return_token_type_ids=False,
241
+ )
242
+ token_count = sum(len(input_ids) for input_ids in encoded["input_ids"])
243
+ character_count = sum(sum(not character.isspace() for character in text) for text in texts)
244
+ if character_count == 0:
245
+ return math.nan, token_count, character_count
246
+ return token_count / character_count, token_count, character_count
247
+
248
+
249
+ def collect_tokenizer_fertility(
250
+ summary: pd.DataFrame,
251
+ questions: dict[str, pd.DataFrame],
252
+ local_files_only: bool,
253
+ ) -> pd.DataFrame:
254
+ """Calculate model-specific fertility on source-matched translated questions."""
255
+ if "eng" not in questions:
256
+ raise ValueError("English questions are required as the fertility reference")
257
+
258
+ models = summary[["model_raw", "model", "family"]].drop_duplicates()
259
+ rows: list[dict[str, Any]] = []
260
+
261
+ for model_row in models.itertuples(index=False):
262
+ repo = tokenizer_repo(model_row.model, model_row.model_raw)
263
+ if repo is None:
264
+ print(f"Skipping tokenizer fertility for {model_row.model}: no open tokenizer repository")
265
+ continue
266
+
267
+ print(f"Loading tokenizer for {model_row.model} from {repo}")
268
+ try:
269
+ tokenizer = AutoTokenizer.from_pretrained(
270
+ repo,
271
+ local_files_only=local_files_only,
272
+ trust_remote_code=False,
273
+ )
274
+ except Exception as exc:
275
+ print(f"Skipping tokenizer fertility for {model_row.model}: {exc}")
276
+ continue
277
+
278
+ for language, language_questions in questions.items():
279
+ common_ids = questions["eng"].index.intersection(language_questions.index)
280
+ if common_ids.empty:
281
+ print(f"Skipping {model_row.model}/{language}: no source ids match English")
282
+ continue
283
+
284
+ english_texts = questions["eng"].loc[common_ids, "question"].astype(str).tolist()
285
+ language_texts = language_questions.loc[common_ids, "question"].astype(str).tolist()
286
+ english_fertility, english_tokens, english_characters = text_fertility(
287
+ tokenizer,
288
+ english_texts,
289
+ )
290
+ fertility, token_count, character_count = text_fertility(tokenizer, language_texts)
291
+
292
+ rows.append(
293
+ {
294
+ "model_raw": model_row.model_raw,
295
+ "model": model_row.model,
296
+ "family": model_row.family,
297
+ "tokenizer_repo": repo,
298
+ "language": language,
299
+ "fertility_tokens_per_character": fertility,
300
+ "english_fertility_tokens_per_character": english_fertility,
301
+ "normalized_fertility": fertility / english_fertility,
302
+ "n_matched_questions": len(common_ids),
303
+ "token_count": token_count,
304
+ "non_whitespace_character_count": character_count,
305
+ "english_token_count": english_tokens,
306
+ "english_non_whitespace_character_count": english_characters,
307
+ }
308
+ )
309
+
310
+ return pd.DataFrame(rows)
311
+
312
+
313
+ def build_transfer_table(
314
+ summary: pd.DataFrame,
315
+ language_features: pd.DataFrame,
316
+ fertility: pd.DataFrame,
317
+ ) -> pd.DataFrame:
318
+ """Join English-relative accuracy penalties to collected language features."""
319
+ index_columns = ["model_raw", "model", "family", "params_b", "language", "split"]
320
+ values = summary[index_columns + ["accuracy", "stderr", "n_problems"]].copy()
321
+ english = (
322
+ values[values["language"] == "eng"]
323
+ .drop(columns="language")
324
+ .rename(
325
+ columns={
326
+ "accuracy": "english_accuracy",
327
+ "stderr": "english_stderr",
328
+ "n_problems": "english_n_problems",
329
+ }
330
+ )
331
+ )
332
+ transfer = values[values["language"] != "eng"].merge(
333
+ english,
334
+ on=["model_raw", "model", "family", "params_b", "split"],
335
+ how="inner",
336
+ validate="many_to_one",
337
+ )
338
+ transfer["transfer_gap"] = transfer["english_accuracy"] - transfer["accuracy"]
339
+ transfer["transfer_gap_stderr"] = np.sqrt(
340
+ transfer["stderr"].fillna(0) ** 2 + transfer["english_stderr"].fillna(0) ** 2
341
+ )
342
+
343
+ transfer = transfer.merge(
344
+ language_features,
345
+ on="language",
346
+ how="left",
347
+ validate="many_to_one",
348
+ )
349
+ if not fertility.empty:
350
+ transfer = transfer.merge(
351
+ fertility.drop(columns=["family"]),
352
+ on=["model_raw", "model", "language"],
353
+ how="left",
354
+ validate="many_to_one",
355
+ )
356
+ return transfer
357
+
358
+
359
+ def relationship_plot(
360
+ data: pd.DataFrame,
361
+ x_column: str,
362
+ xlabel: str,
363
+ title: str,
364
+ out: Path,
365
+ ) -> bool:
366
+ """Plot a descriptive feature relationship separately for each split."""
367
+ plot_data = data.dropna(subset=[x_column, "transfer_gap"])
368
+ if plot_data.empty:
369
+ return False
370
+
371
+ splits = [split for split in ("original", "synthetic") if split in set(plot_data["split"])]
372
+ fig, axes = plt.subplots(1, len(splits), figsize=(6.5 * len(splits), 5), squeeze=False)
373
+ axes = axes[0]
374
+
375
+ for ax, split in zip(axes, splits, strict=True):
376
+ panel = plot_data[plot_data["split"] == split]
377
+ for family, family_rows in panel.groupby("family"):
378
+ ax.errorbar(
379
+ family_rows[x_column],
380
+ family_rows["transfer_gap"],
381
+ yerr=family_rows["transfer_gap_stderr"],
382
+ fmt="o",
383
+ markersize=6,
384
+ capsize=2,
385
+ alpha=0.8,
386
+ color=FAMILY_COLORS.get(family, FAMILY_COLORS["Other"]),
387
+ label=family,
388
+ )
389
+
390
+ label_positions = (
391
+ panel.groupby(["family", "language"], as_index=False)
392
+ .agg(x=(x_column, "mean"), y=("transfer_gap", "mean"))
393
+ )
394
+ for row in label_positions.itertuples(index=False):
395
+ ax.annotate(
396
+ row.language,
397
+ (row.x, row.y),
398
+ xytext=(4, 3),
399
+ textcoords="offset points",
400
+ fontsize=7,
401
+ color=FAMILY_COLORS.get(row.family, FAMILY_COLORS["Other"]),
402
+ )
403
+
404
+ unique_x = panel[x_column].nunique()
405
+ if len(panel) >= 3 and unique_x >= 2:
406
+ slope, intercept = np.polyfit(panel[x_column], panel["transfer_gap"], 1)
407
+ x_line = np.linspace(panel[x_column].min(), panel[x_column].max(), 100)
408
+ ax.plot(x_line, slope * x_line + intercept, color="black", linestyle="--", linewidth=1)
409
+ correlation = panel[[x_column, "transfer_gap"]].corr().iloc[0, 1]
410
+ ax.text(
411
+ 0.02,
412
+ 0.98,
413
+ f"Descriptive Pearson r = {correlation:.2f}",
414
+ transform=ax.transAxes,
415
+ ha="left",
416
+ va="top",
417
+ fontsize=8,
418
+ )
419
+
420
+ ax.axhline(0, color="black", linewidth=0.8, alpha=0.4)
421
+ ax.grid(alpha=0.2)
422
+ ax.set_xlabel(xlabel)
423
+ ax.set_ylabel("Transfer gap (English - language accuracy)")
424
+ ax.set_title(split.title())
425
+
426
+ handles, labels = axes[0].get_legend_handles_labels()
427
+ if handles:
428
+ fig.legend(handles, labels, loc="lower center", ncol=len(labels), frameon=False)
429
+ fig.suptitle(title)
430
+ fig.tight_layout(rect=(0, 0.07, 1, 0.94))
431
+ fig.savefig(out, bbox_inches="tight")
432
+ plt.close(fig)
433
+ return True
434
+
435
+
436
+ def source_metadata() -> dict[str, Any]:
437
+ return {
438
+ "definitions": {
439
+ "transfer_gap": "English accuracy minus target-language accuracy for the same model and split",
440
+ "tokenizer_fertility": (
441
+ "Tokenizer tokens divided by non-whitespace Unicode characters, with no special tokens"
442
+ ),
443
+ "normalized_fertility": (
444
+ "Target-language fertility divided by English fertility on matched source_id questions"
445
+ ),
446
+ "typological_distance": (
447
+ "Cosine distance from English over concatenated URIEL/lang2vec "
448
+ "syntax_knn and inventory_knn vectors"
449
+ ),
450
+ "resource_quantity": "Wikipedia article count; plots use log10(article count)",
451
+ },
452
+ "sources": {
453
+ "tokenizers": "https://huggingface.co/docs/transformers/en/model_doc/auto",
454
+ "uriel_lang2vec": "https://github.com/antonisa/lang2vec",
455
+ "uriel_paper": "https://aclanthology.org/E17-2002/",
456
+ "mediawiki_siteinfo": "https://www.mediawiki.org/wiki/API:Siteinfo",
457
+ },
458
+ }
459
+
460
+
461
+ def main() -> None:
462
+ parser = argparse.ArgumentParser(description=__doc__)
463
+ script_dir = Path(__file__).parent
464
+ default_out = script_dir / "figures" / "transfer_features"
465
+ parser.add_argument(
466
+ "--summary",
467
+ type=Path,
468
+ default=script_dir / "figures" / "model_grid" / "run_summary.csv",
469
+ )
470
+ parser.add_argument("--data-dir", type=Path, default=script_dir / "data")
471
+ parser.add_argument("--out-dir", type=Path, default=default_out)
472
+ parser.add_argument(
473
+ "--local-files-only",
474
+ action="store_true",
475
+ help="Do not download tokenizer files; use the Hugging Face cache only.",
476
+ )
477
+ parser.add_argument(
478
+ "--resource-timeout",
479
+ type=float,
480
+ default=30,
481
+ help="Seconds allowed for each Wikipedia statistics request.",
482
+ )
483
+ args = parser.parse_args()
484
+
485
+ summary = pd.read_csv(args.summary)
486
+ if "eng" not in set(summary["language"]):
487
+ raise SystemExit("English results are required to calculate transfer gaps.")
488
+ languages = sorted(set(summary["language"]))
489
+
490
+ args.out_dir.mkdir(parents=True, exist_ok=True)
491
+ language_features_path = args.out_dir / "language_features.csv"
492
+ resource_cache = pd.read_csv(language_features_path) if language_features_path.exists() else None
493
+
494
+ print(f"Collecting language features for: {', '.join(languages)}")
495
+ language_features = collect_language_features(
496
+ languages,
497
+ timeout=args.resource_timeout,
498
+ resource_cache=resource_cache,
499
+ )
500
+ language_features.to_csv(language_features_path, index=False)
501
+
502
+ questions = load_questions(args.data_dir, languages)
503
+ fertility = collect_tokenizer_fertility(
504
+ summary,
505
+ questions,
506
+ local_files_only=args.local_files_only,
507
+ )
508
+ fertility_path = args.out_dir / "tokenizer_fertility.csv"
509
+ fertility.to_csv(fertility_path, index=False)
510
+
511
+ transfer = build_transfer_table(summary, language_features, fertility)
512
+ transfer_path = args.out_dir / "transfer_feature_data.csv"
513
+ transfer.to_csv(transfer_path, index=False)
514
+
515
+ metadata_path = args.out_dir / "feature_sources.json"
516
+ metadata_path.write_text(json.dumps(source_metadata(), indent=2) + "\n", encoding="utf-8")
517
+
518
+ plots = [
519
+ (
520
+ "normalized_fertility",
521
+ "Tokenizer fertility relative to English",
522
+ "Transfer gap versus tokenizer fertility",
523
+ args.out_dir / "tokenizer_fertility_vs_transfer.png",
524
+ ),
525
+ (
526
+ "typological_distance_from_english",
527
+ "URIEL typological distance from English",
528
+ "Transfer gap versus typological distance",
529
+ args.out_dir / "typological_distance_vs_transfer.png",
530
+ ),
531
+ (
532
+ "log10_wikipedia_articles",
533
+ "Language resources: log10 Wikipedia articles",
534
+ "Resource quantity versus transfer",
535
+ args.out_dir / "resource_quantity_vs_transfer.png",
536
+ ),
537
+ ]
538
+ for column, xlabel, title, path in plots:
539
+ if relationship_plot(transfer, column, xlabel, title, path):
540
+ print(f"Saved {path}")
541
+ else:
542
+ print(f"Skipped {path.name}: no paired transfer observations with this feature.")
543
+
544
+ print(f"Saved {language_features_path}")
545
+ print(f"Saved {fertility_path}")
546
+ print(f"Saved {transfer_path}")
547
+ print(f"Saved {metadata_path}")
548
+
549
+
550
+ if __name__ == "__main__":
551
+ main()
figures/model_grid/english_normalized_transfer.png ADDED

Git LFS Details

  • SHA256: 097038ed6efeb4443706523010748c63a849b9e05993b7311e20b00d8d414695
  • Pointer size: 131 Bytes
  • Size of remote file: 159 kB
visualize_model_grid.py CHANGED
@@ -9,6 +9,9 @@ The script reads Inspect ``.eval`` logs and writes:
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.
@@ -21,7 +24,6 @@ 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
@@ -413,6 +415,16 @@ def annotated_heatmap(
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],
@@ -551,6 +563,221 @@ def plot_split_pairs(summary: pd.DataFrame, out: Path) -> bool:
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"])]
@@ -685,6 +912,18 @@ def main() -> None:
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'}")
@@ -699,6 +938,21 @@ def main() -> None:
699
  else:
700
  print("Skipped family_scaling.png: no recognized model parameter counts.")
701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
 
703
  if __name__ == "__main__":
704
- main()
 
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
+ * ``english_normalized_transfer.png``: language accuracy relative to English.
13
+ * ``transfer_robustness.png``: transfer penalty and cross-language dispersion by size.
14
+ * ``split_degradation_heatmaps.png``: absolute and relative original-to-synthetic drop.
15
 
16
  Only successful logs are included by default. Repeated/resumed logs with the same
17
  evaluation id are deduplicated, preferring a successful and then newer log.
 
24
 
25
  import argparse
26
  import math
 
27
  import re
28
  from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
29
  from dataclasses import dataclass
 
415
  values = matrix.to_numpy(dtype=float)
416
  image = ax.imshow(values, aspect="auto", cmap=cmap, vmin=vmin, vmax=vmax)
417
 
418
+ families = [infer_model_info(model).family for model in matrix.index]
419
+ for row in range(1, len(families)):
420
+ if families[row] != families[row - 1]:
421
+ ax.axhline(
422
+ row - 0.5,
423
+ color="white",
424
+ linewidth=1.5,
425
+ alpha=0.9,
426
+ )
427
+
428
  ax.set_xticks(
429
  range(len(matrix.columns)),
430
  [heatmap_language_label(x) for x in matrix.columns],
 
563
  return True
564
 
565
 
566
+ def plot_english_normalized_transfer(summary: pd.DataFrame, out: Path) -> bool:
567
+ """Plot each language's accuracy difference from the same model's English score."""
568
+ order = model_order(summary)
569
+ splits = [split for split in ("original", "synthetic") if split in set(summary["split"])]
570
+ languages = sorted(
571
+ (language for language in summary["language"].unique() if language != "eng"),
572
+ key=lambda language: (-LANGUAGE_SPEAKERS.get(language, -1), language),
573
+ )
574
+
575
+ panels: list[tuple[str, pd.DataFrame]] = []
576
+ for split in splits:
577
+ matrix = (
578
+ summary[summary["split"] == split]
579
+ .pivot_table(index="model", columns="language", values="accuracy")
580
+ .reindex(index=order)
581
+ )
582
+ if "eng" not in matrix or not languages:
583
+ continue
584
+ transfer = matrix.reindex(columns=languages).sub(matrix["eng"], axis=0)
585
+ if transfer.notna().any().any():
586
+ panels.append((split.title(), transfer))
587
+
588
+ if not panels:
589
+ return False
590
+
591
+ max_gap = max(
592
+ np.nanmax(np.abs(matrix.to_numpy()))
593
+ for _title, matrix in panels
594
+ if matrix.notna().any().any()
595
+ )
596
+ max_gap = max(max_gap, 0.05)
597
+ height = max(4.0, 0.42 * len(order) + 1.5)
598
+ fig, axes = plt.subplots(
599
+ 1,
600
+ len(panels),
601
+ figsize=(max(7, 2.8 * len(languages) * len(panels)), height),
602
+ sharey=True,
603
+ squeeze=False,
604
+ )
605
+ axes = axes[0]
606
+
607
+ images = [
608
+ annotated_heatmap(
609
+ ax,
610
+ matrix,
611
+ title,
612
+ "RdBu",
613
+ -max_gap,
614
+ max_gap,
615
+ signed=True,
616
+ )
617
+ for ax, (title, matrix) in zip(axes, panels, strict=True)
618
+ ]
619
+
620
+ axes[0].set_ylabel("Model")
621
+ fig.suptitle("Cross-lingual transfer relative to English")
622
+ fig.subplots_adjust(left=0.2, right=0.89, bottom=0.27, top=0.84, wspace=0.18)
623
+ colorbar_axis = fig.add_axes([0.91, 0.25, 0.012, 0.55])
624
+ fig.colorbar(
625
+ images[0],
626
+ cax=colorbar_axis,
627
+ label="Accuracy difference (language - English)",
628
+ )
629
+ fig.savefig(out, bbox_inches="tight")
630
+ plt.close(fig)
631
+ return True
632
+
633
+
634
+ def transfer_robustness_summary(summary: pd.DataFrame) -> pd.DataFrame:
635
+ """Summarize the English transfer penalty across non-English languages."""
636
+ indexed = summary.pivot_table(
637
+ index=["model", "family", "params_b", "split"],
638
+ columns="language",
639
+ values="accuracy",
640
+ )
641
+ non_english = [column for column in indexed.columns if column != "eng"]
642
+ if "eng" not in indexed or not non_english:
643
+ return pd.DataFrame()
644
+
645
+ penalties = indexed[non_english].rsub(indexed["eng"], axis=0)
646
+ result = indexed.reset_index()[["model", "family", "params_b", "split"]].copy()
647
+ result["mean_transfer_penalty"] = penalties.mean(axis=1, skipna=True).to_numpy()
648
+ result["language_dispersion"] = indexed[non_english].std(axis=1, ddof=0, skipna=True).to_numpy()
649
+ result["n_transfer_languages"] = penalties.notna().sum(axis=1).to_numpy()
650
+ return result[result["n_transfer_languages"] > 0]
651
+
652
+
653
+ def plot_transfer_robustness(summary: pd.DataFrame, out: Path) -> bool:
654
+ robust = transfer_robustness_summary(summary).dropna(subset=["params_b"])
655
+ if robust.empty:
656
+ return False
657
+
658
+ splits = [split for split in ("original", "synthetic") if split in set(robust["split"])]
659
+ metrics = [
660
+ ("mean_transfer_penalty", "Mean transfer penalty\n(English - non-English)"),
661
+ ("language_dispersion", "Cross-language accuracy SD"),
662
+ ]
663
+ fig, axes = plt.subplots(
664
+ len(splits),
665
+ len(metrics),
666
+ figsize=(11, 4 * len(splits)),
667
+ squeeze=False,
668
+ )
669
+
670
+ for row_index, split in enumerate(splits):
671
+ split_rows = robust[robust["split"] == split]
672
+ for col_index, (metric, label) in enumerate(metrics):
673
+ ax = axes[row_index, col_index]
674
+ for family, family_rows in split_rows.groupby("family"):
675
+ family_rows = family_rows.sort_values("params_b")
676
+ ax.plot(
677
+ family_rows["params_b"],
678
+ family_rows[metric],
679
+ marker="o",
680
+ linewidth=1.7,
681
+ color=FAMILY_COLORS.get(family, FAMILY_COLORS["Other"]),
682
+ label=family,
683
+ )
684
+ for row in family_rows.itertuples():
685
+ ax.annotate(
686
+ row.model,
687
+ (row.params_b, getattr(row, metric)),
688
+ xytext=(4, 4),
689
+ textcoords="offset points",
690
+ fontsize=6.5,
691
+ )
692
+
693
+ ax.axhline(0, color="black", linewidth=0.8, alpha=0.4)
694
+ ax.set_xscale("log")
695
+ ax.grid(alpha=0.2)
696
+ ax.set_xlabel("Parameters (billions, log scale)")
697
+ ax.set_ylabel(label)
698
+ ax.set_title(split.title())
699
+
700
+ handles, labels = axes[0, 0].get_legend_handles_labels()
701
+ if handles:
702
+ fig.legend(handles, labels, loc="lower center", ncol=len(labels), frameon=False)
703
+ fig.suptitle("Cross-lingual transfer robustness with model scale")
704
+ fig.tight_layout(rect=(0, 0.05, 1, 0.96))
705
+ fig.savefig(out, bbox_inches="tight")
706
+ plt.close(fig)
707
+ return True
708
+
709
+
710
+ def plot_split_degradation(summary: pd.DataFrame, out: Path) -> bool:
711
+ if not {"original", "synthetic"}.issubset(summary["split"].unique()):
712
+ return False
713
+
714
+ order = model_order(summary)
715
+ languages = sorted(
716
+ summary["language"].unique(),
717
+ key=lambda language: (-LANGUAGE_SPEAKERS.get(language, -1), language),
718
+ )
719
+ paired = summary.pivot_table(
720
+ index="model",
721
+ columns=["split", "language"],
722
+ values="accuracy",
723
+ )
724
+ original = paired["original"].reindex(index=order, columns=languages)
725
+ synthetic = paired["synthetic"].reindex(index=order, columns=languages)
726
+ absolute = original - synthetic
727
+ relative = absolute.div(original.where(original != 0))
728
+
729
+ if not absolute.notna().any().any():
730
+ return False
731
+
732
+ absolute_limit = max(float(np.nanmax(np.abs(absolute.to_numpy()))), 0.05)
733
+ finite_relative = relative.to_numpy()[np.isfinite(relative.to_numpy())]
734
+ relative_limit = max(float(np.max(np.abs(finite_relative))) if finite_relative.size else 0, 0.05)
735
+
736
+ height = max(4.0, 0.42 * len(order) + 1.5)
737
+ fig, axes = plt.subplots(
738
+ 1,
739
+ 2,
740
+ figsize=(max(12, 5 * len(languages)), height),
741
+ sharey=True,
742
+ )
743
+ absolute_image = annotated_heatmap(
744
+ axes[0],
745
+ absolute,
746
+ "Absolute degradation",
747
+ "RdBu_r",
748
+ -absolute_limit,
749
+ absolute_limit,
750
+ signed=True,
751
+ )
752
+ relative_image = annotated_heatmap(
753
+ axes[1],
754
+ relative,
755
+ "Relative degradation",
756
+ "RdBu_r",
757
+ -relative_limit,
758
+ relative_limit,
759
+ signed=True,
760
+ )
761
+ axes[0].set_ylabel("Model")
762
+ fig.suptitle("Performance degradation from original to synthetic")
763
+ fig.colorbar(
764
+ absolute_image,
765
+ ax=axes[0],
766
+ shrink=0.8,
767
+ label="Original - synthetic accuracy",
768
+ )
769
+ fig.colorbar(
770
+ relative_image,
771
+ ax=axes[1],
772
+ shrink=0.8,
773
+ label="(Original - synthetic) / original",
774
+ )
775
+ fig.subplots_adjust(left=0.2, right=0.92, bottom=0.27, top=0.84, wspace=0.18)
776
+ fig.savefig(out, bbox_inches="tight")
777
+ plt.close(fig)
778
+ return True
779
+
780
+
781
  def plot_family_scaling(summary: pd.DataFrame, out: Path) -> bool:
782
  scaled = summary.dropna(subset=["params_b"])
783
  families = [family for family in ("Qwen2.5", "Llama 3", "Gemma 3") if family in set(scaled["family"])]
 
912
  plot_heatmaps(summary, args.out_dir / "accuracy_heatmaps.png")
913
  made_pairs = plot_split_pairs(summary, args.out_dir / "original_vs_synthetic.png")
914
  made_scaling = plot_family_scaling(summary, args.out_dir / "family_scaling.png")
915
+ made_transfer = plot_english_normalized_transfer(
916
+ summary,
917
+ args.out_dir / "english_normalized_transfer.png",
918
+ )
919
+ made_robustness = plot_transfer_robustness(
920
+ summary,
921
+ args.out_dir / "transfer_robustness.png",
922
+ )
923
+ made_degradation = plot_split_degradation(
924
+ summary,
925
+ args.out_dir / "split_degradation_heatmaps.png",
926
+ )
927
 
928
  print(f"Saved {summary_path}")
929
  print(f"Saved {args.out_dir / 'accuracy_heatmaps.png'}")
 
938
  else:
939
  print("Skipped family_scaling.png: no recognized model parameter counts.")
940
 
941
+ if made_transfer:
942
+ print(f"Saved {args.out_dir / 'english_normalized_transfer.png'}")
943
+ else:
944
+ print("Skipped english_normalized_transfer.png: paired English/non-English results are required.")
945
+
946
+ if made_robustness:
947
+ print(f"Saved {args.out_dir / 'transfer_robustness.png'}")
948
+ else:
949
+ print("Skipped transfer_robustness.png: paired transfer results with model sizes are required.")
950
+
951
+ if made_degradation:
952
+ print(f"Saved {args.out_dir / 'split_degradation_heatmaps.png'}")
953
+ else:
954
+ print("Skipped split_degradation_heatmaps.png: paired original/synthetic results are required.")
955
+
956
 
957
  if __name__ == "__main__":
958
+ main()