"""Generate all result figures for the paper from results.py.""" import os import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib import gridspec from matplotlib.colors import TwoSlopeNorm from decimal import Decimal, ROUND_HALF_UP from results import (RESULTS, TASK_LABEL, TASK_GROUPS, PALOMA_LABEL, PALOMA_ORDER, PALOMA_FAMILY, tally, verdict, paloma_verdict, RECOVERY_YIELD, REPAIR_OPS) OUT = os.path.join(os.path.dirname(__file__), "..", "figures") os.makedirs(OUT, exist_ok=True) plt.rcParams.update({ "font.family": "STIXGeneral", "mathtext.fontset": "stix", "font.size": 8.5, "axes.titlesize": 9, "axes.labelsize": 8.5, "xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 7.5, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42, }) TIERS = ["LQ", "MQ", "HQ"] C_V1 = "#9ecae1" # light blue (surface repair only) C_V2 = "#08519c" # dark blue (surface + linguistic) C_NEG = "#cb181d" C_POS = "#238b45" def hu(x, nd=1, sign=True): """Round half-up (away from zero) at nd decimals, as the reported tables do; Python's float formatting would turn e.g. -6.35 into -6.3.""" q = Decimal(str(x)).quantize(Decimal(1).scaleb(-nd), rounding=ROUND_HALF_UP) if q == 0: return f"{abs(q):.{nd}f}" out = f"{q:+.{nd}f}" if sign else f"{q:.{nd}f}" return out.replace("-", "\u2212") # typographic minus sign def get(tier, cfg, task): ds, pal = RESULTS[(tier, cfg)] for r in ds: if r[0] == task: return r for r in pal: if r[0] == task: return r raise KeyError(task) # -------------------------------------------------------------------------- # Figure 1: teaser -- (a) LAMBADA gain by tier, (b) robust win/loss, (c) PTB tax # -------------------------------------------------------------------------- def fig_teaser(): fig = plt.figure(figsize=(7.0, 1.8)) gs = gridspec.GridSpec(1, 3, width_ratios=[1.0, 1.1, 1.0], wspace=0.45) x = np.arange(len(TIERS)) w = 0.36 # (a) LAMBADA delta ax = fig.add_subplot(gs[0]) v1 = [get(t, "V1", "lambada_openai")[7] for t in TIERS] v2 = [get(t, "V2", "lambada_openai")[7] for t in TIERS] z1 = [get(t, "V1", "lambada_openai")[9] for t in TIERS] z2 = [get(t, "V2", "lambada_openai")[9] for t in TIERS] ax.bar(x - w / 2, v1, w, color=C_V1, edgecolor="black", linewidth=0.4, label="V1: surface repair") ax.bar(x + w / 2, v2, w, color=C_V2, edgecolor="black", linewidth=0.4, label="V2: surface + linguistic repair") for xi, (a, b, za, zb) in enumerate(zip(v1, v2, z1, z2)): nudge = 0.06 if abs(a - b) < 0.5 else 0.0 # keep adjacent labels apart ax.text(xi - w / 2 - nudge, a + 0.1, hu(a), ha="center", va="bottom", fontsize=6.2) ax.text(xi + w / 2 + nudge, b + 0.1, hu(b), ha="center", va="bottom", fontsize=6.2) ax.text(xi - w / 2, 0.15, f"$z$\n{hu(za, 0)}", ha="center", va="bottom", fontsize=5.8, color="black") ax.text(xi + w / 2, 0.15, f"$z$\n{hu(zb, 0)}", ha="center", va="bottom", fontsize=5.8, color="white") ax.set_xticks(x, TIERS) ax.set_ylabel("LAMBADA $\\Delta$ vs. Raw (pp)") ax.set_ylim(0, 6.6) ax.axhline(0, color="black", lw=0.6) ax.set_title("(a) LAMBADA gain by input tier", fontsize=8, loc="left") # (b) robust win / loss ax = fig.add_subplot(gs[1]) for i, cfg in enumerate(["V1", "V2"]): col = C_V1 if cfg == "V1" else C_V2 off = -w / 2 if cfg == "V1" else w / 2 for xi, t in enumerate(TIERS): tl = tally(t, cfg) ax.bar(xi + off, tl["W"], w, color=col, edgecolor="black", linewidth=0.4) ax.bar(xi + off, -tl["L"], w, color="white", edgecolor=col, hatch="////", linewidth=0.8) ax.text(xi + off, tl["W"] + 0.3, f"{tl['W']}", ha="center", va="bottom", fontsize=6.5) ax.text(xi + off, -tl["L"] - 0.3, f"{tl['L']}", ha="center", va="top", fontsize=6.5) for xi, t in enumerate(TIERS): n1, n2 = tally(t, "V1")["net"], tally(t, "V2")["net"] sgn = lambda n: f"{n:+d}".replace("-", "\u2212") ax.text(xi, 14.6, f"{sgn(n1)} $\\rightarrow$ {sgn(n2)}", ha="center", va="bottom", fontsize=6.5, color=C_POS, fontweight="bold") ax.axhline(0, color="black", lw=0.6) ax.set_xticks(x, TIERS) ax.set_yticks([-10, -5, 0, 5, 10, 15], ["10", "5", "0", "5", "10", "15"]) ax.set_ylim(-11.5, 18.0) ax.set_ylabel("robust losses | robust wins") ax.set_title("(b) Robust verdicts ($|z|\\geq 2$), net V1$\\rightarrow$V2", fontsize=8, loc="left") # (c) PTB BPB change ax = fig.add_subplot(gs[2]) v1 = [get(t, "V1", "paloma_ptb")[7] for t in TIERS] v2 = [get(t, "V2", "paloma_ptb")[7] for t in TIERS] ax.bar(x - w / 2, v1, w, color=C_V1, edgecolor="black", linewidth=0.4) ax.bar(x + w / 2, v2, w, color=C_V2, edgecolor="black", linewidth=0.4) for xi, (a, b) in enumerate(zip(v1, v2)): ax.text(xi - w / 2, a + 0.25, hu(a) + "%", ha="center", va="bottom", fontsize=6.2) ax.text(xi + w / 2 + 0.07, max(b, 0) + 0.25, hu(b) + "%", ha="center", va="bottom", fontsize=6.2) ax.axhline(0, color="black", lw=0.6) ax.set_xticks(x, TIERS) ax.set_ylabel("PTB BPB $\\Delta_{rel}$ vs. Raw (%)\n(lower is better)") ax.set_ylim(-1.8, 14.0) ax.set_title("(c) Penn Treebank BPB change", fontsize=8, loc="left") fig.legend(loc="upper center", bbox_to_anchor=(0.5, 1.10), ncol=2, frameon=False, handlelength=1.4, columnspacing=2.0) fig.savefig(os.path.join(OUT, "fig1_teaser.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) # -------------------------------------------------------------------------- # Figure 3: heat-maps of all 38 evaluations x 6 configurations # -------------------------------------------------------------------------- COLS = [("LQ", "V1"), ("LQ", "V2"), ("MQ", "V1"), ("MQ", "V2"), ("HQ", "V1"), ("HQ", "V2")] COL_LABELS = ["LQ\nV1", "LQ\nV2", "MQ\nV1", "MQ\nV2", "HQ\nV1", "HQ\nV2"] def _draw_block(ax, rows, get_delta, get_z, labels, is_paloma, title, group_bounds=None, group_names=None, cols=None, col_labels=None, seps=(1.5, 3.5), fs_cell=6.2, fs_tick=7, fs_title=8): COLS_ = cols or COLS COLL_ = col_labels or COL_LABELS n = len(rows) Z = np.zeros((n, len(COLS_))) D = np.zeros((n, len(COLS_))) for i, task in enumerate(rows): for j, (t, c) in enumerate(COLS_): r = get(t, c, task) Z[i, j] = get_z(r) D[i, j] = get_delta(r) # colour: signed detectability; sign flipped for BPB so that blue = better S = -Z if is_paloma else Z S = np.clip(S, -6, 6) # SQuAD v2 is recorded on a composite scale whose direction is not interpreted: draw it neutral neutral = [i for i, task in enumerate(rows) if task == "squadv2"] for i in neutral: S[i, :] = 0.0 norm = TwoSlopeNorm(vmin=-6, vcenter=0, vmax=6) ax.imshow(S, cmap="RdBu", norm=norm, aspect="auto") for i in neutral: ax.add_patch(plt.Rectangle((-0.5, i - 0.5), len(COLS_), 1, facecolor="#e6e6e6", edgecolor="none", zorder=1.5)) for i in range(n): for j in range(len(COLS_)): z = Z[i, j] d = D[i, j] txt = hu(d) col = "white" if abs(S[i, j]) >= 4.2 else "black" if i in neutral: col = "#555555" fs = fs_cell - 0.8 if abs(d) >= 9.95 else fs_cell # two-digit values: smaller so cells do not run together ax.text(j, i, txt, ha="center", va="center", fontsize=fs, color=col, zorder=2, fontweight="bold" if (abs(z) >= 2 and i not in neutral) else "normal") ax.set_xticks(range(len(COLS_)), COLL_, fontsize=fs_tick) ax.set_yticks(range(n), labels, fontsize=fs_tick) ax.tick_params(length=0) for s in ax.spines.values(): s.set_visible(False) ax.set_title(title, fontsize=fs_title, loc="left", pad=4) # vertical separators between tiers for xline in seps: ax.axvline(xline, color="white", lw=2.0) if group_bounds: for gb in group_bounds[1:]: ax.axhline(gb - 0.5, color="white", lw=2.0) def fig_teaser_full(): """Main-text Figure 1: effect of the full repair pipeline (V2) against Raw.""" from results import PALOMA_FAMILY fig = plt.figure(figsize=(7.0, 1.95)) gs = gridspec.GridSpec(1, 3, width_ratios=[0.8, 0.8, 1.55], wspace=0.42) x = np.arange(len(TIERS)) # (a) LAMBADA gain of the full pipeline ax = fig.add_subplot(gs[0]) v2 = [get(t, "V2", "lambada_openai")[7] for t in TIERS] z2 = [get(t, "V2", "lambada_openai")[9] for t in TIERS] ax.bar(x, v2, 0.55, color=C_V2, edgecolor="black", linewidth=0.4) for xi, v, z in zip(x, v2, z2): ax.text(xi, v + 0.15, hu(v), ha="center", va="bottom", fontsize=7) ax.text(xi, 0.25, f"$z$={z:.0f}", ha="center", va="bottom", fontsize=6, color="white") ax.set_xticks(x, TIERS) ax.set_ylim(0, 6.4) ax.set_ylabel("$\\Delta$ vs. Raw (pp)") ax.set_title("(a) LAMBADA gain", fontsize=8, loc="left") # (b) robust wins vs losses of the full pipeline ax = fig.add_subplot(gs[1]) W, L = [], [] for t in TIERS: ds, pal = RESULTS[(t, "V2")] W.append(sum(1 for r in ds if r[9] >= 2) + sum(1 for r in pal if r[8] <= -2)) L.append(sum(1 for r in ds if r[9] <= -2) + sum(1 for r in pal if r[8] >= 2)) ax.bar(x, W, 0.55, color=C_V2, edgecolor="black", linewidth=0.4) ax.bar(x, [-l for l in L], 0.55, color="#d6604d", edgecolor="black", linewidth=0.4) for xi, w_, l_ in zip(x, W, L): ax.text(xi, w_ + 0.3, str(w_), ha="center", va="bottom", fontsize=7) ax.text(xi, -l_ - 0.3, str(l_), ha="center", va="top", fontsize=7) ax.axhline(0, color="black", lw=0.6) ax.set_xticks(x, TIERS) ax.set_ylim(-10.5, 15.5) ax.set_yticks([-8, -4, 0, 4, 8, 12], ["8", "4", "0", "4", "8", "12"]) ax.set_ylabel("losses $|$ wins") ax.set_title("(b) Robust wins/losses", fontsize=8, loc="left") # (c) Paloma: per-corpus change, replicated across tiers ax = fig.add_subplot(gs[2]) order = PALOMA_ORDER short = {"Falcon-RefinedWeb": "Falcon-RW", "Dolma-100-subreddits": "Dolma-Reddit", "M2D2-Wikipedia": "M2D2-Wiki", "Penn Treebank": "PTB", "C4-100-domains": "C4-100dom", "M2D2-S2ORC": "S2ORC", "WikiText-103": "WikiText"} xs = np.arange(len(order)) means = [] for i, c in enumerate(order): vals = [get(t, "V2", c)[7] for t in TIERS] m = float(np.mean(vals)); means.append(m) col = {"web": C_V2, "mixed": "#4292c6", "curated": "#bdbdbd"}[PALOMA_FAMILY[c]] ax.bar(i, m, 0.7, color=col, edgecolor="black", linewidth=0.3) for j, v in enumerate(vals): ax.plot(i + (j - 1) * 0.16, v, marker="o", ms=2.2, color="black", lw=0) ax.axhline(0, color="black", lw=0.6) ax.set_xticks(xs, [short.get(PALOMA_LABEL[c], PALOMA_LABEL[c]) for c in order], rotation=55, ha="right", fontsize=6.2) ax.set_ylabel("BPB $\\Delta_{rel}$ (%)") ax.set_ylim(-7.5, 3.3) ax.set_title("(c) Paloma BPB, bar = mean, dots = LQ/MQ/HQ", fontsize=8, loc="left") fig.savefig(os.path.join(OUT, "fig1_teaser_full.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) def fig_heatmaps(): task_order = [t for _, ts in TASK_GROUPS for t in ts] bounds, names, acc = [], [], 0 for gname, ts in TASK_GROUPS: bounds.append(acc) names.append(gname) acc += len(ts) # split into two blocks of 14 / 13 while keeping groups intact where possible blockA = task_order[:14] blockB = task_order[14:] fig = plt.figure(figsize=(7.0, 2.40)) gs = gridspec.GridSpec(1, 3, width_ratios=[1, 1, 1.12], wspace=0.95, right=0.90) axA = fig.add_subplot(gs[0]) axB = fig.add_subplot(gs[1]) axC = fig.add_subplot(gs[2]) _draw_block(axA, blockA, lambda r: r[7], lambda r: r[9], [TASK_LABEL[t] for t in blockA], False, "(a) Downstream score, $\\Delta$ vs. Raw (pp)", group_bounds=[0, 2, 7], group_names=None) _draw_block(axB, blockB, lambda r: r[7], lambda r: r[9], [TASK_LABEL[t] for t in blockB], False, "(b) Downstream score, $\\Delta$ vs. Raw (pp)", group_bounds=[0, 8], group_names=None) pal_rows = PALOMA_ORDER short = {"Falcon-RefinedWeb": "Falcon-RW", "Dolma-100-subreddits": "Dolma-Reddit", "M2D2-Wikipedia": "M2D2-Wiki", "Penn Treebank": "PTB", "C4-100-domains": "C4-100dom"} _draw_block(axC, pal_rows, lambda r: r[7], lambda r: r[8], [short.get(PALOMA_LABEL[c], PALOMA_LABEL[c]) for c in pal_rows], True, "(c) Paloma BPB, $\\Delta_{rel}$ vs. Raw (%)", group_bounds=[0, 5, 7], group_names=None) # colour bar cax = fig.add_axes([0.925, 0.50, 0.012, 0.32]) sm = plt.cm.ScalarMappable(cmap="RdBu", norm=TwoSlopeNorm(vmin=-6, vcenter=0, vmax=6)) cb = fig.colorbar(sm, cax=cax) cb.set_ticks([-6, -2, 0, 2, 6]) cb.set_ticklabels(["$\\leq$$-$6", "$-$2", "0", "+2", "$\\geq$+6"], fontsize=6.5) cb.set_label("signed $z$ (blue = better)", fontsize=6.8) cb.outline.set_visible(False) fig.savefig(os.path.join(OUT, "fig3_heatmaps.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) def fig_heatmaps_v2(): """Main-text version: full repair (V2) only, larger type; the 6-column map is in the appendix.""" task_order = [t for _, ts in TASK_GROUPS for t in ts] blockA = task_order[:14] blockB = task_order[14:] cols = [("LQ", "V2"), ("MQ", "V2"), ("HQ", "V2")] labs = ["LQ", "MQ", "HQ"] fig = plt.figure(figsize=(5.2, 2.05)) gs = gridspec.GridSpec(1, 3, width_ratios=[1, 1, 1.05], wspace=1.25, right=0.88) axA = fig.add_subplot(gs[0]); axB = fig.add_subplot(gs[1]); axC = fig.add_subplot(gs[2]) kw = dict(cols=cols, col_labels=labs, seps=(0.5, 1.5), fs_cell=6.6, fs_tick=6.8, fs_title=7.2) _draw_block(axA, blockA, lambda r: r[7], lambda r: r[9], [TASK_LABEL[t] for t in blockA], False, "(a) Tasks, $\\Delta$ (pp)", group_bounds=[0, 2, 7], **kw) _draw_block(axB, blockB, lambda r: r[7], lambda r: r[9], [TASK_LABEL[t] for t in blockB], False, "(b) Tasks, $\\Delta$ (pp)", group_bounds=[0, 8], **kw) short = {"Falcon-RefinedWeb": "Falcon-RW", "Dolma-100-subreddits": "Dolma-Reddit", "M2D2-Wikipedia": "M2D2-Wiki", "Penn Treebank": "PTB", "C4-100-domains": "C4-100dom"} _draw_block(axC, PALOMA_ORDER, lambda r: r[7], lambda r: r[8], [short.get(PALOMA_LABEL[c], PALOMA_LABEL[c]) for c in PALOMA_ORDER], True, "(c) Paloma BPB, $\\Delta_{rel}$ (%)", group_bounds=[0, 5, 7], **kw) cax = fig.add_axes([0.915, 0.48, 0.014, 0.34]) sm = plt.cm.ScalarMappable(cmap="RdBu", norm=TwoSlopeNorm(vmin=-6, vcenter=0, vmax=6)) cb = fig.colorbar(sm, cax=cax) cb.set_ticks([-6, -2, 0, 2, 6]) cb.set_ticklabels(["$\\leq$$-$6", "$-$2", "0", "+2", "$\\geq$+6"], fontsize=6.3) cb.set_label("signed $z$ (blue = better)", fontsize=6.5) cb.outline.set_visible(False) fig.savefig(os.path.join(OUT, "fig3_heatmaps_v2.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) # -------------------------------------------------------------------------- # Figure 4: Paloma web vs. curated split, V1 vs V2 (mean delta_rel per family) # -------------------------------------------------------------------------- def fig_paloma_split(): fig, axes = plt.subplots(1, 3, figsize=(7.0, 1.9), sharey=True) web = [c for c in PALOMA_ORDER if PALOMA_FAMILY[c] == "web"] mix = [c for c in PALOMA_ORDER if PALOMA_FAMILY[c] == "mixed"] cur = [c for c in PALOMA_ORDER if PALOMA_FAMILY[c] == "curated"] for ax, tier in zip(axes, TIERS): rows = web + mix + cur x = np.arange(len(rows)) v1 = [get(tier, "V1", c)[7] for c in rows] v2 = [get(tier, "V2", c)[7] for c in rows] w = 0.38 ax.bar(x - w / 2, v1, w, color=C_V1, edgecolor="black", linewidth=0.3, label="V1") ax.bar(x + w / 2, v2, w, color=C_V2, edgecolor="black", linewidth=0.3, label="V2") ax.axhline(0, color="black", lw=0.6) ax.axvline(len(web) - 0.5, color="grey", lw=0.6, ls="--") ax.axvline(len(web) + len(mix) - 0.5, color="grey", lw=0.6, ls="--") ax.set_xticks(x, [PALOMA_LABEL[c].replace("Dolma-100-subreddits", "Dolma-Reddit") .replace("M2D2-", "").replace("Falcon-RefinedWeb", "Falcon-RW") .replace("Penn Treebank", "PTB").replace("C4-100-domains", "C4-100dom") for c in rows], rotation=60, ha="right", fontsize=6.3) ax.set_title(f"{tier}", fontsize=8.5) ax.text(len(web) / 2 - 0.5, 11.2, "web", ha="center", fontsize=6.5, color="grey") ax.text(len(web) + len(mix) / 2 - 0.5, 11.2, "mixed", ha="center", fontsize=6.5, color="grey") ax.text(len(web) + len(mix) + len(cur) / 2 - 0.5, 11.2, "curated", ha="center", fontsize=6.5, color="grey") ax.set_ylim(-8, 13) axes[0].set_ylabel("BPB $\\Delta_{rel}$ vs. Raw (%)\n(lower is better)") h, l = axes[0].get_legend_handles_labels() fig.legend(h, ["V1 (surface)", "V2 (surface + linguistic)"], loc="upper center", bbox_to_anchor=(0.5, 1.10), ncol=2, frameon=False, handlelength=1.0, columnspacing=1.2, borderpad=0.2) fig.subplots_adjust(wspace=0.08) fig.savefig(os.path.join(OUT, "fig4_paloma_split.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) # -------------------------------------------------------------------------- # Figure 5 (appendix): repair-operation composition and recovery yield # -------------------------------------------------------------------------- def fig_ops(): fig, ax = plt.subplots(figsize=(5.4, 1.9)) keys = ["ftfy", "artifact", "line", "char_noise", "grammar_syntax"] names = ["ftfy atomic\n(stage 2)", "artifact strip\n(stage 4)", "line-level\n(stage 5)", "char. cleanup\n(stage 6)", "grammar/syntax\n(stage 8)"] x = np.arange(len(keys)) w = 0.26 cols = {"LQ": "#cb181d", "MQ": "#fd8d3c", "HQ": "#08519c"} for i, t in enumerate(TIERS): vals = [REPAIR_OPS[t][k] for k in keys] ax.bar(x + (i - 1) * w, vals, w, color=cols[t], edgecolor="black", linewidth=0.3, label=f"{t} (repair coverage {hu(RECOVERY_YIELD[t], 1, sign=False)}%)") ax.set_xticks(x, names, fontsize=7) ax.set_ylabel("share (%)") ax.legend(frameon=False) fig.savefig(os.path.join(OUT, "fig5_ops.pdf"), bbox_inches="tight", pad_inches=0.02) plt.close(fig) if __name__ == "__main__": fig_teaser() fig_heatmaps() fig_heatmaps_v2() fig_teaser_full() fig_paloma_split() fig_ops() print("figures written to", OUT)