zaher-m's picture
download
raw
9.99 kB
"""Plain figures built from the CSV tables in results/. One figure per main claim.
Usage: python -m src.figures <results_dir> <figures_dir> [probe_r2.csv]
"""
import csv
import sys
from collections import defaultdict
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
from src.report import LANGS, SYSTEMS, TASKS, VALUE_TASKS, wilson # noqa: E402
TASK_NAMES = {"copy": "Copy", "convert": "Convert", "compare": "Compare", "compute": "Compute", "statement_qa": "Statement QA"}
SYSTEM_NAMES = {"western": "Western", "eastern_arabic": "Eastern Arabic", "persian": "Persian"}
LANG_NAMES = {"en": "English prompts", "ar": "Arabic prompts"}
STYLE = {"western": {"color": "0.0", "marker": "o"}, "eastern_arabic": {"color": "0.35", "marker": "s"},
"persian": {"color": "0.6", "marker": "^"}}
OFFSET = {"western": -0.2, "eastern_arabic": 0.0, "persian": 0.2}
PAIR_OFFSET = {"eastern_arabic": -0.1, "persian": 0.1}
def read(path):
with open(path, encoding="utf-8") as f:
return list(csv.DictReader(f))
def setup_axis(ax, ylabel, ylim=(0, 1.02)):
"""Shared-axis panels keep the label on the first panel only. ylim None keeps autoscaling over all panels."""
if ylim is not None:
ax.set_ylim(*ylim)
if ax.get_subplotspec().is_first_col():
ax.set_ylabel(ylabel)
ax.grid(axis="y", color="0.9", linewidth=0.8)
ax.set_axisbelow(True)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
def errorbar(ax, x, y, lo, hi, system, **kw):
ax.errorbar(x, y, yerr=[[y - lo], [hi - y]], fmt=STYLE[system]["marker"], color=STYLE[system]["color"],
markersize=6, capsize=3, linewidth=1.2, **kw)
def accuracy_by_task(results, out):
rows = read(results / "accuracy_by_cell.csv")
fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
for ax, lang in zip(axes, LANGS):
for system in SYSTEMS:
for i, task in enumerate(TASKS):
r = next(r for r in rows if (r["task"], r["numeral_system"], r["prompt_lang"]) == (task, system, lang))
errorbar(ax, i + OFFSET[system], float(r["accuracy"]), float(r["ci_low"]), float(r["ci_high"]), system,
label=SYSTEM_NAMES[system] if i == 0 else None)
ax.set_xticks(range(len(TASKS)), [TASK_NAMES[t] for t in TASKS])
ax.set_title(LANG_NAMES[lang])
setup_axis(ax, "Accuracy (100 items per point)")
axes[0].legend(frameon=False, loc="lower left")
fig.suptitle("Accuracy by task and numeral system, with 95% Wilson intervals")
return save(fig, out / "accuracy_by_task.png")
def paired_differences(results, out):
rows = read(results / "paired_tests.csv")
fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
for ax, lang in zip(axes, LANGS):
for system in ("eastern_arabic", "persian"):
for i, task in enumerate(TASKS):
r = next(r for r in rows if (r["task"], r["lang_a"], r["system_b"]) == (task, lang, system))
d = 100 * float(r["difference"])
errorbar(ax, i + PAIR_OFFSET[system], d, 100 * float(r["ci_low"]), 100 * float(r["ci_high"]), system,
label=f"Western minus {SYSTEM_NAMES[system]}" if i == 0 else None)
ax.axhline(0, color="0.0", linewidth=0.8)
ax.set_xticks(range(len(TASKS)), [TASK_NAMES[t] for t in TASKS])
ax.set_title(LANG_NAMES[lang])
setup_axis(ax, "Accuracy difference (percentage points)", ylim=None)
axes[0].legend(frameon=False)
fig.suptitle("Accuracy drop when the same items use other digits, with 95% bootstrap intervals (100 pairs)")
return save(fig, out / "paired_differences.png")
def pooled(rows, keys):
"""Sum n and correct over the rows that share keys, and add Wilson intervals."""
sums = defaultdict(lambda: [0, 0])
for r in rows:
k = tuple(r[c] for c in keys)
sums[k][0] += int(r["correct"])
sums[k][1] += int(r["n"])
return {k: (c / n, *wilson(c, n), n) for k, (c, n) in sums.items()}
def accuracy_by_length(results, out):
rows = [r for r in read(results / "accuracy_by_factor.csv") if r["factor"] == "length"]
stats = pooled(rows, ("task", "numeral_system", "level"))
levels = ["short", "medium", "long"]
fig, axes = plt.subplots(1, len(TASKS), figsize=(14, 3.6), sharey=True)
for ax, task in zip(axes, TASKS):
for system in SYSTEMS:
for j, level in enumerate(levels):
acc, lo, hi, _ = stats[(task, system, level)]
errorbar(ax, j + OFFSET[system] / 2, acc, lo, hi, system, label=SYSTEM_NAMES[system] if j == 0 else None)
ax.set_xticks(range(3), ["1 to 4", "5 to 8", "9 to 12"])
ax.set_xlabel("Integer digits")
ax.set_title(TASK_NAMES[task])
setup_axis(ax, "Accuracy, both prompt languages")
axes[0].legend(frameon=False, loc="lower left", fontsize=8)
fig.suptitle("Accuracy by number length and numeral system, with 95% Wilson intervals")
return save(fig, out / "accuracy_by_length.png")
def format_match(results, out):
rows = [r for r in read(results / "secondary_by_cell.csv") if r["metric"] == "format_match"]
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8), sharey=True)
for ax, task in zip(axes, VALUE_TASKS):
for system in SYSTEMS:
for j, lang in enumerate(LANGS):
r = next(r for r in rows if (r["task"], r["numeral_system"], r["prompt_lang"]) == (task, system, lang))
errorbar(ax, j + OFFSET[system], float(r["accuracy"]), float(r["ci_low"]), float(r["ci_high"]), system,
label=SYSTEM_NAMES[system] if j == 0 else None)
ax.set_xticks(range(2), [LANG_NAMES[lang] for lang in LANGS])
ax.set_title(TASK_NAMES[task])
setup_axis(ax, "Share of answers in the question's digits")
axes[0].legend(frameon=False, loc="lower left")
fig.suptitle("Answers written in the same numeral system as the question, with 95% Wilson intervals")
return save(fig, out / "format_match.png")
def error_types(results, out):
rows = read(results / "error_types.csv")
per_system = defaultdict(int)
for r in read(results / "accuracy_by_cell.csv"):
per_system[r["numeral_system"]] += int(r["n"])
if len(set(per_system.values())) != 1:
raise RuntimeError(f"numeral systems have different item counts: {dict(per_system)}")
n_items = next(iter(per_system.values()))
totals = defaultdict(int)
for r in rows:
totals[(r["error_type"], r["numeral_system"])] += int(r["n"])
kinds = sorted({k for k, _ in totals}, key=lambda k: -sum(totals[(k, s)] for s in SYSTEMS))
fig, ax = plt.subplots(figsize=(9, 0.45 * len(kinds) + 1.5))
for system in SYSTEMS:
ys = [i + OFFSET[system] for i in range(len(kinds))]
ax.barh(ys, [totals[(k, system)] for k in kinds], height=0.2, color=STYLE[system]["color"], label=SYSTEM_NAMES[system])
ax.set_yticks(range(len(kinds)), [k.replace("_", " ") for k in kinds])
ax.invert_yaxis()
ax.set_xlabel(f"Wrong answers, all tasks and both prompt languages ({n_items:,} items per numeral system)")
ax.grid(axis="x", color="0.9", linewidth=0.8)
ax.set_axisbelow(True)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
ax.legend(frameon=False)
ax.set_title("Error types by numeral system")
return save(fig, out / "error_types.png")
PROBE_FLOOR = -0.5
CARRIER_NAMES = {"en": "English carrier sentence", "ar": "Arabic carrier sentence"}
def probe_r2(probe_path, out):
rows = read(probe_path)
fig, axes = plt.subplots(2, 2, figsize=(11, 7.5), sharex=True)
lines = [("western", "western", "Trained on Western, tested on Western", "0.0", "-"),
("western", "eastern_arabic", "Trained on Western, tested on Eastern Arabic", "0.35", "-"),
("western", "persian", "Trained on Western, tested on Persian", "0.6", "-"),
("eastern_arabic", "eastern_arabic", "Trained and tested on Eastern Arabic", "0.35", ":"),
("persian", "persian", "Trained and tested on Persian", "0.6", ":")]
titles = {"log10_value": "log10 of the value", "log10_mantissa": "Mantissa (leading digits), exploratory"}
for row_axes, name in zip(axes, ("log10_value", "log10_mantissa")):
for ax, lang in zip(row_axes, LANGS):
for train, test, label, color, style in lines:
pts = sorted((int(r["layer"]), float(r["r2"])) for r in rows
if (r["prompt_lang"], r["train_system"], r["test_system"], r["target"]) == (lang, train, test, name))
ax.plot([p[0] for p in pts], [p[1] for p in pts], color=color, linestyle=style, linewidth=2, label=label)
ax.set_title(f"{titles[name]}, {CARRIER_NAMES[lang]}", fontsize=10)
setup_axis(ax, "R squared on held-out numbers", ylim=(PROBE_FLOOR, 1.02))
for ax in axes[1]:
ax.set_xlabel("Layer (0 is the embedding output)")
axes[0][0].legend(frameon=False, fontsize=8, loc="lower right")
fig.suptitle(f"Linear probes by layer. The axis stops at {PROBE_FLOOR}, lower values leave the frame")
return save(fig, out / "probe_r2.png")
def save(fig, path):
path.parent.mkdir(parents=True, exist_ok=True)
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
return path
def main(results_dir, figures_dir, probe_path="results/probe_r2.csv"):
results, out = Path(results_dir), Path(figures_dir)
made = [accuracy_by_task(results, out), paired_differences(results, out), accuracy_by_length(results, out),
format_match(results, out), error_types(results, out)]
if Path(probe_path).exists():
made.append(probe_r2(Path(probe_path), out))
for path in made:
print("wrote", path)
if __name__ == "__main__":
main(*sys.argv[1:])

Xet Storage Details

Size:
9.99 kB
·
Xet hash:
89bcd197bdadd186592e4bcbdecde7b3cc21e4a1bde9010e64e0c7850f5a1c48

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.