Download make_paper_figures.py from MikeDd2025/ProseOnlyRepair_Codes: direct link, hf CLI and curl.
- Browser
- Download file 9.89 kB
-
https://huggingface.co/datasets/MikeDd2025/ProseOnlyRepair_Codes/resolve/main/make_paper_figures.py
- Command line
-
hf download hf://datasets/MikeDd2025/ProseOnlyRepair_Codes/make_paper_figures.py
-
curl -L -o make_paper_figures.py https://huggingface.co/datasets/MikeDd2025/ProseOnlyRepair_Codes/resolve/main/make_paper_figures.py
9.89 kB
| #!/usr/bin/env python3 | |
| """Generate Figures 1 and 2 for the paper. | |
| Figure 1 — Repair effect (POST+UP − PRE) by tier on five robust benchmarks. | |
| Figure 2 — Per-corpus Paloma BPB delta under repair (heatmap). | |
| Outputs PDF (vector, for LaTeX inclusion) and PNG (for previewing). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import glob | |
| import statistics | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as mpatches | |
| from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm | |
| import numpy as np | |
| BASE = './eval_results' | |
| OUTDIR = './figures' | |
| import os | |
| os.makedirs(OUTDIR, exist_ok=True) | |
| def load(suite, label): | |
| f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json') | |
| return json.load(open(f[0]))['results'] if f else {} | |
| # Variant lookup → anonymized display label (cluster A = Cluster A, cluster B = Cluster B) | |
| PAIRS = { | |
| 'LQ-A': None, # no Cluster A LQ runs | |
| 'LQ-B': ('clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'), | |
| 'MQ-A': ('clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'), | |
| 'MQ-B': ('clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'), | |
| 'HQ-A': None, | |
| 'HQ-B': ('clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'), | |
| } | |
| def task_value(results, task, key=None): | |
| """Get accuracy in [0,1] for a task. Handles mmlu_/blimp_ aggregation.""" | |
| if task == 'mmlu_mean': | |
| accs = [v.get('acc,none') for k, v in results.items() if k.startswith('mmlu_') and k != 'mmlu'] | |
| accs = [a for a in accs if isinstance(a, (int, float))] | |
| return statistics.mean(accs) if accs else None | |
| if task == 'blimp_mean': | |
| accs = [v.get('acc,none') for k, v in results.items() if k.startswith('blimp_') and k != 'blimp'] | |
| accs = [a for a in accs if isinstance(a, (int, float))] | |
| return statistics.mean(accs) if accs else None | |
| if key is None: | |
| key_map = { | |
| 'hellaswag': 'acc_norm,none', 'piqa': 'acc_norm,none', 'winogrande': 'acc,none', | |
| 'commonsense_qa': 'acc,none', 'social_iqa': 'acc,none', 'openbookqa': 'acc_norm,none', | |
| 'sciq': 'acc_norm,none', 'arc_easy': 'acc_norm,none', 'arc_challenge': 'acc_norm,none', | |
| 'boolq': 'acc,none', 'race': 'acc,none', 'lambada_openai': 'acc,none', | |
| } | |
| key = key_map.get(task) | |
| if key is None or task not in results: | |
| return None | |
| v = results[task].get(key) | |
| return v if isinstance(v, (int, float)) else None | |
| # ============================================================================ | |
| # FIGURE 1 — Repair effect by tier on five robust benchmarks | |
| # ============================================================================ | |
| print("[fig1] computing repair-effect deltas by tier ...") | |
| # 5 benchmarks (the S/N >= 4× headline set) | |
| BENCHMARKS = [ | |
| ('lambada_openai', 'LAMBADA-OpenAI'), | |
| ('boolq', 'BoolQ'), | |
| ('race', 'RACE'), | |
| ('hellaswag', 'HellaSwag'), | |
| ('openbookqa', 'OpenBookQA'), | |
| ] | |
| # 4 tier × cluster bars per benchmark, in the visual order LQ → MQ-A → MQ-B → HQ | |
| BAR_KEYS = [('LQ-B', 'LQ'), ('MQ-A', 'MQ-A'), ('MQ-B', 'MQ-B'), ('HQ-B', 'HQ')] | |
| SIGMA_SEED = 0.6 # per-task noise floor in pp (median from Table 2) | |
| # Load all data once | |
| RAW = {} | |
| for k, pair in PAIRS.items(): | |
| if pair is None: | |
| continue | |
| pre_lab, ups_lab = pair | |
| RAW[k] = { | |
| 'pre': load('prose', pre_lab), | |
| 'ups': load('prose', ups_lab), | |
| } | |
| fig, axes = plt.subplots(1, 5, figsize=(14, 3.4), sharey=False) | |
| colors_per_tier = {'LQ-B':'#c0392b', 'MQ-A':'#f39c12', 'MQ-B':'#27ae60', 'HQ-B':'#2980b9'} | |
| tier_labels = {'LQ-B':'LQ', 'MQ-A':'MQ-A', 'MQ-B':'MQ-B', 'HQ-B':'HQ'} | |
| for ax, (task_id, task_disp) in zip(axes, BENCHMARKS): | |
| deltas = [] | |
| bar_colors = [] | |
| bar_labels = [] | |
| for k, lab in BAR_KEYS: | |
| if k not in RAW: | |
| deltas.append(0.0); bar_colors.append('#cccccc'); bar_labels.append(lab); continue | |
| pv = task_value(RAW[k]['pre'], task_id) | |
| uv = task_value(RAW[k]['ups'], task_id) | |
| if pv is None or uv is None: | |
| deltas.append(0.0) | |
| else: | |
| deltas.append((uv - pv) * 100) | |
| bar_colors.append(colors_per_tier[k]) | |
| bar_labels.append(tier_labels[k]) | |
| x = np.arange(len(deltas)) | |
| bars = ax.bar(x, deltas, color=bar_colors, edgecolor='black', linewidth=0.4, width=0.7) | |
| ax.errorbar(x, deltas, yerr=SIGMA_SEED, fmt='none', ecolor='black', lw=0.7, capsize=2) | |
| # ±3σ significance lines | |
| ax.axhline(y= 3*SIGMA_SEED, ls='--', lw=0.5, color='gray') | |
| ax.axhline(y=-3*SIGMA_SEED, ls='--', lw=0.5, color='gray') | |
| ax.axhline(y=0, color='black', lw=0.5) | |
| ax.set_xticks(x); ax.set_xticklabels(bar_labels, fontsize=8) | |
| ax.set_title(task_disp, fontsize=10) | |
| ax.tick_params(axis='y', labelsize=8) | |
| # annotate bars with delta values | |
| for xi, di in zip(x, deltas): | |
| ax.text(xi, di + (0.15 if di >= 0 else -0.45), f'{di:+.1f}', | |
| ha='center', va='bottom' if di >= 0 else 'top', fontsize=7) | |
| ax.set_ylim(min(min(deltas) - 1.0, -4.0), max(max(deltas) + 1.0, 6.0)) | |
| axes[0].set_ylabel('Δ accuracy (POST+UP − PRE), pp', fontsize=9) | |
| fig.suptitle('Repair effect by tier on the five robust benchmarks (S/N ≥ 4×)', | |
| fontsize=11, y=1.00) | |
| # Add legend below figures | |
| proxies = [mpatches.Patch(color=c, label=tier_labels[k]) for k, c in colors_per_tier.items()] | |
| proxies.append(mpatches.Patch(color='gray', alpha=0.3, label=f'±3σ noise (={3*SIGMA_SEED:.1f} pp)')) | |
| fig.legend(handles=proxies, loc='lower center', ncol=5, fontsize=8, frameon=False, | |
| bbox_to_anchor=(0.5, -0.05)) | |
| plt.tight_layout() | |
| plt.subplots_adjust(bottom=0.15) | |
| plt.savefig(f'{OUTDIR}/fig1_repair_by_tier.pdf', bbox_inches='tight', dpi=300) | |
| plt.savefig(f'{OUTDIR}/fig1_repair_by_tier.png', bbox_inches='tight', dpi=200) | |
| print(f"[fig1] saved to {OUTDIR}/fig1_repair_by_tier.{{pdf,png}}") | |
| plt.close() | |
| # ============================================================================ | |
| # FIGURE 2 — Paloma per-corpus BPB delta heatmap | |
| # ============================================================================ | |
| print("[fig2] computing Paloma per-corpus deltas ...") | |
| ROWS = [ | |
| ('LQ-B', 'LQ', 'clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'), | |
| ('MQ-A', 'MQ-A', 'clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'), | |
| ('MQ-B', 'MQ-B', 'clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'), | |
| ('HQ-B', 'HQ', 'clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'), | |
| ] | |
| # Web → mixed → literary column ordering | |
| COL_ORDER = [ | |
| ('paloma_c4_100_domains', 'C4-100', 'web'), | |
| ('paloma_c4_en', 'C4-en', 'web'), | |
| ('paloma_falcon-refinedweb', 'Falcon', 'web'), | |
| ('paloma_mc4', 'mC4', 'web'), | |
| ('paloma_m2d2_s2orc_unsplit', 'S2ORC', 'mixed'), | |
| ('paloma_m2d2_wikipedia_unsplit', 'M2D2-Wiki', 'mixed'), | |
| ('paloma_dolma_100_subreddits', 'Subreddit', 'mixed'), | |
| ('paloma_dolma-v1_5', 'Dolma', 'lit'), | |
| ('paloma_wikitext_103', 'WikiText','lit'), | |
| ('paloma_redpajama', 'RedPajama','lit'), | |
| ('paloma_ptb', 'PTB', 'lit'), | |
| ] | |
| # Compute delta matrix | |
| matrix = np.zeros((len(ROWS), len(COL_ORDER))) | |
| for i, (key, _label, pre_lab, ups_lab) in enumerate(ROWS): | |
| pre_palo = load('paloma', pre_lab) | |
| ups_palo = load('paloma', ups_lab) | |
| for j, (corpus, _name, _kind) in enumerate(COL_ORDER): | |
| p = pre_palo[corpus]['bits_per_byte,none'] | |
| u = ups_palo[corpus]['bits_per_byte,none'] | |
| matrix[i, j] = u - p | |
| fig2, ax2 = plt.subplots(figsize=(9.5, 3.0)) | |
| # Diverging colormap: red for positive (regression), blue for negative (improvement) | |
| vmax = max(abs(matrix.min()), abs(matrix.max())) | |
| cmap = plt.get_cmap('RdBu_r') | |
| norm = TwoSlopeNorm(vmin=-vmax, vcenter=0.0, vmax=vmax) | |
| im = ax2.imshow(matrix, cmap=cmap, norm=norm, aspect='auto') | |
| # Tick labels | |
| ax2.set_xticks(range(len(COL_ORDER))) | |
| ax2.set_xticklabels([n[1] for n in COL_ORDER], rotation=25, ha='right', fontsize=8) | |
| ax2.set_yticks(range(len(ROWS))) | |
| ax2.set_yticklabels([r[1] for r in ROWS], fontsize=9) | |
| # Annotate cells | |
| for i in range(matrix.shape[0]): | |
| for j in range(matrix.shape[1]): | |
| v = matrix[i, j] | |
| col = 'white' if abs(v) > 0.06 else 'black' | |
| ax2.text(j, i, f'{v:+.3f}', ha='center', va='center', fontsize=7, color=col) | |
| # Vertical dividers between web/mixed/literary blocks | |
| boundary_indices = [] | |
| kinds = [c[2] for c in COL_ORDER] | |
| for j in range(1, len(kinds)): | |
| if kinds[j] != kinds[j-1]: | |
| boundary_indices.append(j - 0.5) | |
| for x in boundary_indices: | |
| ax2.axvline(x=x, color='black', lw=1.2) | |
| # Region annotations under x-axis | |
| kind_labels = {'web':'WEB (improvement)', 'mixed':'NEUTRAL', 'lit':'LITERARY (regression)'} | |
| # Find midpoints of each block | |
| from itertools import groupby | |
| groups = [] | |
| idx = 0 | |
| for kind, group in groupby(kinds): | |
| g = list(group) | |
| groups.append((kind, idx, idx + len(g) - 1)) | |
| idx += len(g) | |
| for kind, lo, hi in groups: | |
| mid = (lo + hi) / 2 | |
| ax2.text(mid, len(ROWS) + 0.15, kind_labels[kind], | |
| ha='center', va='top', fontsize=8, style='italic', | |
| transform=ax2.transData) | |
| # Colorbar | |
| cbar = fig2.colorbar(im, ax=ax2, fraction=0.025, pad=0.02) | |
| cbar.set_label('Δ BPB (POST+UP − PRE)', fontsize=8) | |
| cbar.ax.tick_params(labelsize=7) | |
| ax2.set_title('Paloma-11 per-corpus repair Δ — universal web/literary split across tiers', | |
| fontsize=10, pad=10) | |
| plt.tight_layout() | |
| plt.subplots_adjust(bottom=0.30, right=0.92) | |
| plt.savefig(f'{OUTDIR}/fig2_paloma_split.pdf', bbox_inches='tight', dpi=300) | |
| plt.savefig(f'{OUTDIR}/fig2_paloma_split.png', bbox_inches='tight', dpi=200) | |
| print(f"[fig2] saved to {OUTDIR}/fig2_paloma_split.{{pdf,png}}") | |
| plt.close() | |
| print("Done.") | |