delivered-sooner / code /figure1.py
Boesgaard's picture
Retitle to Delivered Sooner; six-panel Figure 1; follow-up experiments
5dc1ed5 verified
Raw History Blame Contribute Delete
18 kB
"""Figure 1: the six-panel front figure, drawn from the files in this package.
uv run --no-project --with matplotlib python code/figure1.py
Writes figures/figure1.pdf. Every plotted value is read from a package file and checked against the printed value.
The sans-serif face is TeX Gyre Heros, taken from the Tectonic bundle when Tectonic is installed; otherwise the
script falls back to Helvetica or Arial.
"""
import json
import subprocess
import tempfile
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
import matplotlib
matplotlib.use("pdf")
import matplotlib.pyplot as plt # noqa: E402
from matplotlib import font_manager # noqa: E402
from matplotlib.patches import FancyArrowPatch, Patch, Rectangle # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "figures" / "figure1.pdf"
def r2(v, places=2):
"""Round halves away from zero, the paper's convention (0.495 prints as 0.50)."""
q = Decimal(1).scaleb(-places)
return str(Decimal(repr(v)).quantize(q, rounding=ROUND_HALF_UP))
def load(rel):
return json.loads((ROOT / rel).read_text())
# ----------------------------------------------------------------------------------------------- data
# (a) Mean sampled tokens per question in the four cells of the 256-question panel (Table 2) and the two transplant
# fractions (83.31% of the donor's saving recovered, 76.59% undone).
recip = load("stats/main256/reciprocal_four_cell.json")["all_questions"]["actual_sampled_tokens"]
cells = {k: recip["cell_means"][k]["estimate"] for k in "BFRC"}
undone = recip["fractions_of_full_training_gap"]["paired_ratios_of_means"]["reciprocal_MLP_undo_on_trained"]
recovered = load("stats/main256/all32_fraction_of_donor_saving.json")["result"]["generated"][
"edit_fraction_of_real_donor_saving"
]
assert [round(cells[k]) for k in "BFRC"] == [15932, 11961, 14816, 11165]
assert round(100 * recovered["point"], 2) == 83.31 and round(100 * undone["estimate"], 2) == 76.59
# (b) By 8,192 tokens, on the main panel and the first 256 questions of the replication panel pooled (512 questions):
# questions with a correct answer available in a forced readout or the final response, and correct answers delivered.
pooled = load("records/paper_provenance_20261130/available_delivered_8k.json")["outcomes"]["pooled"]["results"]
AVAILABLE = {"parent": pooled["ever_correct_observed"]["base"], "transplant": pooled["ever_correct_observed"]["edit"]}
DELIVERED = {"parent": pooled["natural_correct_delivered"]["base"], "transplant": pooled["natural_correct_delivered"]["edit"]}
assert (AVAILABLE, DELIVERED) == ({"parent": 367, "transplant": 366}, {"parent": 144, "transplant": 232})
# (c) Reconsideration and verification markers per 1,000 thinking tokens, with 95% intervals (Table 6), and the
# registered 512-question replication.
markers = load("stats/audit/recheck_markers.json")
replication = load("markers/registration/MARKER_REPLICATION_RESULT.json")
assert replication["H1_pass"] and replication["H2_pass"] and replication["H3_pass"]
ratio = replication["H2_reconsideration_rate_ratio"]
# (d) Final accuracy, all-layer transplant minus parent, percentage points with 95% intervals: the 256 questions
# alone and the registered 768-question test (-2-point margin), with the test's token saving.
acc = load("records/joined768/RESULTS.json")["estimates"]["base_mlp_all_vs_base"]
c256 = acc["cohorts"]["confirmation256"]["contrast"]["final"]
c768 = acc["all768"]["contrast"]
def pp(v):
return float(r2(v, 2))
ACC = [
("256 questions", pp(c256["difference_pp"]), *map(pp, c256["difference_pp_95ci"]), False),
("768 questions,\nregistered test", pp(c768["final"]["difference_pp"]), *map(pp, c768["final"]["difference_pp_95ci"]), True),
]
assert [a[1:4] for a in ACC] == [(1.56, -2.34, 5.47), (1.69, -0.52, 3.91)]
saving = [100 * (1 - c768["generated_ratio"])] + [100 * (1 - x) for x in reversed(c768["generated_ratio_ci95"])]
TOKENS_768 = tuple(pp(x) for x in saving)
assert TOKENS_768 == (24.35, 22.49, 26.26)
MARGIN = -2.0
# ---------------------------------------------------------------------------------------------- style
INK, MUTED, CAP, RULE, GRID, PANEL = "#1D1D1B", "#6B6A66", "#55544F", "#BDBCB6", "#E3E2DD", "#F1F0EC"
# Hue follows the MLP weights: warm = the parent's MLPs, cool = Concise-9B's MLPs. Validated as a
# categorical palette (lightness band, chroma floor, CVD and normal-vision separation, all pairs).
COL = {
"parent": "#A65E1E", # Qwen3.5-9B
"transplant": "#008C80", # parent + Concise MLPs
"reverse": "#D9A04E", # Concise-9B + parent MLPs
"donor": "#4250C8", # Concise-9B
}
NAME = {
"parent": "Parent",
"transplant": "Parent + Concise MLPs",
"reverse": "Concise-9B + parent MLPs",
"donor": "Concise-9B",
}
def heros():
"""Register TeX Gyre Heros from the Tectonic bundle; return the family name to use."""
tmp = Path(tempfile.mkdtemp(prefix="heros_"))
try:
for face in ("regular", "bold", "italic"):
path = tmp / f"texgyreheros-{face}.otf"
data = subprocess.run(
["tectonic", "-X", "bundle", "cat", path.name], capture_output=True, check=True
).stdout
if len(data) < 10_000:
raise RuntimeError("font not found")
path.write_bytes(data)
font_manager.fontManager.addfont(str(path))
return "TeX Gyre Heros"
except (OSError, subprocess.CalledProcessError, RuntimeError):
return "Helvetica"
plt.rcParams.update(
{
"font.family": "sans-serif",
"font.sans-serif": [heros(), "Helvetica", "Arial", "DejaVu Sans"],
"font.size": 7.5,
"pdf.fonttype": 3,
"axes.edgecolor": RULE,
"axes.linewidth": 0.6,
"axes.labelcolor": CAP,
"axes.labelsize": 7.2,
"xtick.color": MUTED,
"ytick.color": MUTED,
"xtick.labelcolor": CAP,
"ytick.labelcolor": CAP,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"xtick.major.width": 0.6,
"ytick.major.width": 0.6,
"xtick.major.size": 2.5,
"ytick.major.size": 2.5,
"svg.fonttype": "none",
}
)
fig = plt.figure(figsize=(6.1, 6.9)) # three rows; each panel keeps its 4.75-inch-layout physical size
L0, R0 = 0.085, 0.615 # left edges of the two columns of axes
TOP_Y, BOT_Y, ROW3_Y, H = 0.726, 0.396, 0.066, 0.2065 # bottoms of the three rows and the axes height
TITLE_X = {"left": 0.008, "right": 0.545}
def clean(ax, left=True):
for side in ("top", "right"):
ax.spines[side].set_visible(False)
ax.spines["left"].set_visible(left)
ax.tick_params(axis="both", which="both", length=2.5 if left else 0)
ax.set_axisbelow(True)
def title(ax, letter, text, column):
top = ax.get_position().y1
fig.text(TITLE_X[column], top + 0.0207, f"({letter}) {text}", ha="left", va="bottom", fontsize=8.6,
fontweight="bold", color=INK)
def hgrid(ax, ys):
for y in ys:
ax.axhline(y, color=GRID, lw=0.5, zorder=0)
def minus(text):
return text.replace("-", "−")
# ------------------------------------------------------------------------------- legend across the top
handles = [Patch(facecolor=COL[k], edgecolor="none", label=NAME[k]) for k in ("parent", "transplant", "reverse", "donor")]
fig.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.5, 0.998), ncol=4, frameon=False,
fontsize=7.4, handlelength=1.1, handleheight=0.9, handletextpad=0.45, columnspacing=1.6,
labelcolor=INK)
# ------------------------------------------------------------------------- (a) two-way MLP transplant
ax = fig.add_axes([L0, TOP_Y, 0.425, H])
clean(ax)
order = [("parent", "B"), ("transplant", "F"), ("donor", "C"), ("reverse", "R")]
xs = [0, 1, 2.4, 3.4]
for x, (key, cell) in zip(xs, order):
v = cells[cell]
ax.add_patch(Rectangle((x - 0.34, 0), 0.68, v, facecolor=COL[key], edgecolor="none", zorder=2))
ink = INK if key == "reverse" else "white" # the light bar takes dark text
ax.text(x, v - 450, f"{round(v):,}", ha="center", va="top", fontsize=7.2, fontweight="bold", color=ink,
zorder=3)
ax.set_xlim(-0.55, 3.95)
ax.set_ylim(0, 27000)
ax.set_yticks([0, 5000, 10000, 15000, 20000])
ax.set_yticklabels(["0", "5k", "10k", "15k", "20k"])
hgrid(ax, [5000, 10000, 15000, 20000])
ax.set_ylabel("Tokens per question", labelpad=3)
ax.yaxis.set_label_coords(-0.115, 0.37)
ax.set_xticks(xs)
ax.set_xticklabels(["Parent", "+ Concise\nMLPs", "Concise-9B", "+ parent\nMLPs"], fontsize=7)
ax.tick_params(axis="x", length=0, pad=3)
def arc(x0, y0, x1, y1, head, value, rad):
ax.add_patch(FancyArrowPatch((x0, y0), (x1, y1), connectionstyle=f"arc3,rad={rad}",
arrowstyle="-|>,head_length=3.2,head_width=1.8", lw=0.9, color=INK,
zorder=4, shrinkA=0, shrinkB=0))
xm = (x0 + x1) / 2
ax.text(xm, 21900, head, ha="center", va="bottom", fontsize=6.9, color=CAP)
ax.text(xm, 23700, value, ha="center", va="bottom", fontsize=7.6, fontweight="bold", color=INK)
lab = 450 # clearance above the bar top
arc(xs[0], cells["B"] + lab, xs[1], cells["F"] + lab, "Concise MLPs in", f"{100 * recovered['point']:.1f}% recovered", -0.35)
arc(xs[2], cells["C"] + lab, xs[3], cells["R"] + lab, "parent MLPs back", f"{100 * undone['estimate']:.1f}% undone", -0.35)
title(ax, "a", "Two-way transplant", "left")
# ----------------------------------------------------------------- (b) available vs delivered by 8K
ax = fig.add_axes([R0, TOP_Y, 0.36, H])
clean(ax)
groups = [("Correct answer available\n(readout or response)", AVAILABLE),
("Correct answer\ndelivered", DELIVERED)]
w = 0.36
for g, (label, vals) in enumerate(groups):
for j, key in enumerate(("parent", "transplant")):
x = g + (j - 0.5) * (w + 0.04)
v = vals[key]
ax.add_patch(Rectangle((x - w / 2, 0), w, v, facecolor=COL[key], edgecolor="none", zorder=2))
ax.text(x, v + 10, f"{v}", ha="center", va="bottom", fontsize=10.5, fontweight="bold", color=INK)
ax.text(x, 14, "Parent" if key == "parent" else "Transplant", rotation=90, ha="center",
va="bottom", fontsize=6.8, color="white", zorder=3)
ax.set_xlim(-0.55, 1.55)
ax.set_ylim(0, 530)
ax.set_xticks([0, 1])
ax.set_xticklabels([g[0] for g in groups], fontsize=7.2)
ax.tick_params(axis="x", length=0, pad=3)
ax.set_yticks([0, 100, 200, 300, 400])
hgrid(ax, [100, 200, 300, 400])
ax.set_ylabel("Questions (of 512)", labelpad=3)
ax.text(0, 440, "available almost\nequally often", ha="center", va="bottom", fontsize=7.2, color=CAP, style="italic",
linespacing=1.1)
ax.text(1, 440, "delivered\nfar more often", ha="center", va="bottom", fontsize=7.2, color=CAP,
style="italic", linespacing=1.1)
title(ax, "b", "Available vs delivered by 8,192 tokens", "right")
# ----------------------------------------------------------------- (c) reopening, not checking
EXACT = load("stats/audit/markers_exact_rates.json")["rates"] # labels from exact rates (0.4948 prints as 0.49)
ax = fig.add_axes([L0, BOT_Y, 0.425, H])
clean(ax)
keys = ("parent", "transplant", "reverse", "donor")
w = 0.19
for g, field in enumerate(("rc_per_1k_thinking", "vf_per_1k_thinking")):
for j, key in enumerate(keys):
point, lo, hi = markers[field][{"transplant": "forward"}.get(key, key)]
x = g + (j - 1.5) * (w + 0.02)
ax.add_patch(Rectangle((x - w / 2, 0), w, point, facecolor=COL[key], edgecolor="none", zorder=2))
ax.plot([x, x], [lo, hi], color=INK, lw=0.7, zorder=3)
exact = EXACT[{"transplant": "forward"}.get(key, key)]["rc_per_1k" if field.startswith("rc") else "vf_per_1k"]
assert abs(exact - point) < 0.0051, (key, field, exact, point)
ax.text(x, hi + 0.05, f"{exact:.2f}", ha="center", va="bottom", fontsize=6.6, color=INK)
ax.set_xlim(-0.55, 1.55)
ax.set_ylim(0, 2.95)
ax.set_xticks([0, 1])
ax.set_xticklabels(["Reconsideration\n(Wait, Hmm, Alternatively, ...)", "Verification\n(verify, double-check, ...)"],
fontsize=7.0)
ax.tick_params(axis="x", length=0, pad=3)
ax.set_yticks([0, 0.5, 1, 1.5, 2, 2.5])
ax.set_yticklabels(["0", "0.5", "1.0", "1.5", "2.0", "2.5"])
hgrid(ax, [0.5, 1, 1.5, 2, 2.5])
ax.set_ylabel("Markers per 1,000 thinking tokens", labelpad=3)
ax.yaxis.set_label_coords(-0.115, 0.45)
ax.text(1.03, 2.82,
"Registered replication,\n512 new questions\n"
"reconsideration rate ratio\n"
f"{r2(ratio['estimate'], 3)} [{r2(ratio['ci'][0], 3)}, {r2(ratio['ci'][1], 3)}]\n"
"verification rate: equivalent",
ha="center", va="top", fontsize=6.5, color=INK, linespacing=1.3,
bbox=dict(boxstyle="round,pad=0.4,rounding_size=0.15", facecolor="#FAFAF7", edgecolor=GRID, lw=0.6))
title(ax, "c", "Reconsideration falls, verification holds", "left")
# ------------------------------------------------------------------------------- (d) accuracy holds
ax = fig.add_axes([R0, BOT_Y, 0.36, H])
clean(ax, left=False)
ax.set_xlim(-4, 7)
ax.set_ylim(-0.25, 2.65)
ax.axvspan(-4, MARGIN, color=PANEL, zorder=0, lw=0)
ax.axvline(0, color=RULE, lw=0.7, zorder=1)
ax.axvline(MARGIN, color=INK, lw=0.8, ls=(0, (3, 2)), zorder=1)
ax.text(MARGIN - 0.2, 2.62, "\u22122-point\nmargin", ha="right", va="top", fontsize=6.8, color=CAP,
linespacing=1.15)
for i, (label, m, lo, hi, main) in enumerate(ACC):
y = 0.45 + 1.05 * i
col = COL["transplant"] if main else MUTED
ax.plot([lo, hi], [y, y], color=col, lw=1.6 if main else 1.0, solid_capstyle="butt", zorder=3)
for e in (lo, hi):
ax.plot([e, e], [y - 0.09, y + 0.09], color=col, lw=1.0 if main else 0.8, zorder=3)
ax.plot([m], [y], marker="o", ms=5.2 if main else 4.2, color=col, mec="white", mew=0.8, zorder=4)
ax.text(m + 0.6, y + 0.15, minus(f"{m:+.2f} [{lo:+.2f}, {hi:+.2f}]"), ha="center", va="bottom",
fontsize=7.2 if main else 6.8, color=INK, fontweight="bold" if main else "normal")
ax.text(7, y - 0.17, label, ha="right", va="top", fontsize=6.6, color=CAP, linespacing=1.1)
ax.set_yticks([])
ax.set_xticks([-4, -2, 0, 2, 4, 6])
ax.set_xticklabels(["−4", "−2", "0", "+2", "+4", "+6"])
ax.set_xlabel("Final accuracy, transplant − parent (points)", labelpad=3)
ax.text(7, 2.62, f"{TOKENS_768[0]:.2f}% fewer tokens", ha="right", va="top", fontsize=7.2, fontweight="bold",
color=INK)
ax.text(7, 2.36, f"[{TOKENS_768[1]:.2f}, {TOKENS_768[2]:.2f}] on the 768", ha="right", va="top", fontsize=6.8,
color=CAP)
title(ax, "d", "Accuracy holds", "right")
OUT.parent.mkdir(exist_ok=True)
# ------------------------------------------------------- (e), (f) identical histories (96 saved histories x 4 seeds)
ih = load("stats/identical_histories/conditional_native_prefixes.json")["groups"]
IC, IW = ih["initial_correct"]["endpoints"], ih["initial_explicit_wrong"]["endpoints"]
REM = {"correct": (IC["thinking"]["base_mean"], IC["thinking"]["edited_mean"], IC["thinking"]["relative_saved"]),
"wrong": (IW["thinking"]["base_mean"], IW["thinking"]["edited_mean"], IW["thinking"]["relative_saved"])}
assert [round(v) for v in (*REM["correct"][:2], *REM["wrong"][:2])] == [7924, 5040, 12410, 9978]
assert round(100 * REM["correct"][2], 1) == 36.4 and round(100 * REM["wrong"][2], 1) == 19.6
REPAIR = {"natural": (int(IW["natural_correct"]["base_sum"]), int(IW["natural_correct"]["edited_sum"])),
"final": (int(IW["final_correct"]["base_sum"]), int(IW["final_correct"]["edited_sum"]))}
assert REPAIR == {"natural": (30, 56), "final": (75, 81)}
ax = fig.add_axes([L0, ROW3_Y, 0.425, H])
clean(ax)
w = 0.36
for g, key in enumerate(("correct", "wrong")):
base, edit, rel = REM[key]
for j, (who, v) in enumerate((("parent", base), ("transplant", edit))):
x = g + (j - 0.5) * (w + 0.04)
ax.add_patch(Rectangle((x - w / 2, 0), w, v, facecolor=COL[who], edgecolor="none", zorder=2))
ax.text(x, v + 250, f"{round(v):,}", ha="center", va="bottom", fontsize=7.6, fontweight="bold", color=INK)
ax.text(g + 0.5 * (w + 0.04), 600, minus(f"-{round(base - edit):,}\n(-{100 * rel:.1f}%)"), ha="center",
va="bottom", fontsize=6.6, color="white", fontweight="bold", zorder=3, linespacing=1.1)
ax.set_xlim(-0.55, 1.55)
ax.set_ylim(0, 15000)
ax.set_xticks([0, 1])
ax.set_xticklabels(["Answer correct\nat the cut", "Answer wrong\nat the cut"], fontsize=7.2)
ax.tick_params(axis="x", length=0, pad=3)
ax.set_yticks([0, 5000, 10000, 15000])
ax.set_yticklabels(["0", "5k", "10k", "15k"])
hgrid(ax, [5000, 10000])
ax.set_ylabel("Remaining thinking tokens", labelpad=3)
title(ax, "e", "Same history: less thinking after the cut", "left")
ax = fig.add_axes([R0, ROW3_Y, 0.36, H])
clean(ax)
w = 0.5
for j, who in enumerate(("parent", "transplant")):
nat, fin = REPAIR["natural"][j], REPAIR["final"][j]
ax.add_patch(Rectangle((j - w / 2, 0), w, nat, facecolor=COL[who], edgecolor="none", zorder=2))
ax.add_patch(Rectangle((j - w / 2, nat), w, fin - nat, facecolor=COL[who], alpha=0.3, edgecolor="none", zorder=2))
ax.text(j, nat / 2, f"{nat}", ha="center", va="center", fontsize=10, fontweight="bold", color="white", zorder=3)
ax.text(j, fin + 3, f"{fin} with forced", ha="center", va="bottom", fontsize=6.8, color=CAP)
ax.set_xlim(-0.6, 1.6)
ax.set_ylim(0, 128)
ax.set_xticks([0, 1])
ax.set_xticklabels(["Parent", "Transplant"], fontsize=7.2)
ax.tick_params(axis="x", length=0, pad=3)
ax.set_yticks([0, 25, 50, 75, 100, 125])
hgrid(ax, [25, 50, 75, 100, 125])
ax.set_ylabel("Correct repairs (of 192)", labelpad=3)
ax.text(1.55, 127, "all 28 new repairs where\nthe parent ran out of budget", ha="right", va="top", fontsize=6.5,
color=CAP, style="italic", linespacing=1.1)
title(ax, "f", "Repairs delivered after a wrong answer", "right")
fig.savefig(OUT, metadata={"Title": "Figure 1", "Creator": "figure1.py", "CreationDate": None})
print(f"wrote {OUT}")