"""Generate auto-populated LaTeX tables for the paper. Emits two supplementary tables from whatever data currently exists on disk: table_ablation.tex — Silver-bullet dataset-size ablation numerics (companion to fig_paper_6_ablation.pdf). table_baselines.tex — Sampling-strategy baseline comparison (silver_bullet vs failed_only vs random; companion to fig_paper_7). table_interventions.tex — Prompt-prefix vs QLoRA comparison (companion to fig_paper_10), if prefix runs have completed. Each file is safe to \\input{} from paper/main.tex; if the underlying experiment hasn't run yet, the script writes a minimal placeholder table with a \\textit{(not yet computed)} note so LaTeX still compiles. """ import argparse import glob import json import os import re import sys from typing import List, Optional, Tuple import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # --------------------------------------------------------------------------- # Shared helpers # --------------------------------------------------------------------------- def _bootstrap_acc(jsonl_path: str, n_boot: int = 5000) -> Optional[Tuple[float, float, float]]: if not os.path.exists(jsonl_path): return None v = [] with open(jsonl_path) as f: for line in f: t = json.loads(line) v.append(1.0 if t.get("is_correct_final") else 0.0) if not v: return None v = np.array(v) rng = np.random.default_rng(0) s = np.empty(n_boot) for i in range(n_boot): idx = rng.integers(0, len(v), size=len(v)) s[i] = v[idx].mean() return float(v.mean()), float(np.percentile(s, 2.5)), float(np.percentile(s, 97.5)) def _paired_p(base_out, rest_out, n_boot=5000) -> Optional[float]: common = sorted(set(base_out) & set(rest_out)) if not common: return None b = np.array([base_out[k] for k in common]) r = np.array([rest_out[k] for k in common]) rng = np.random.default_rng(0) deltas = np.empty(n_boot) for i in range(n_boot): idx = rng.integers(0, len(common), size=len(common)) deltas[i] = r[idx].mean() - b[idx].mean() return float(2 * min((deltas <= 0).mean(), (deltas >= 0).mean())) def _load_outcomes(jsonl_path: str): if not os.path.exists(jsonl_path): return None out = {} with open(jsonl_path) as f: for line in f: t = json.loads(line) out[t.get("problem_id")] = 1.0 if t.get("is_correct_final") else 0.0 return out def _stars(p: Optional[float]) -> str: if p is None: return "" if p < 0.001: return "$^{***}$" if p < 0.01: return "$^{**}$" if p < 0.05: return "$^{*}$" return "" def _placeholder(label: str, caption: str, note: str) -> str: return ( "\\begin{table}[t]\n\\centering\\small\n" f"\\caption{{{caption}}}\n\\label{{{label}}}\n" "\\begin{tabular}{l}\n\\toprule\n" f"\\textit{{{note}}} \\\\\n" "\\bottomrule\n\\end{tabular}\n\\end{table}\n" ) # --------------------------------------------------------------------------- # Table: dataset-size ablation # --------------------------------------------------------------------------- def table_ablation(ablation_root: str, benchmark: str, baseline_acc: Optional[float], output: str) -> None: rows = [] if os.path.isdir(ablation_root): for entry in sorted(os.listdir(ablation_root)): m = re.match(r"n(\d+)$", entry) if not m: continue N = int(m.group(1)) diag = os.path.join(ablation_root, entry, "diagnosis", f"{benchmark}_run0.jsonl") ci = _bootstrap_acc(diag) if ci is None: continue rows.append((N, ci)) if not rows: with open(output, "w") as f: f.write(_placeholder("tab:ablation", "Silver-bullet dataset-size ablation on primary cell.", "(not yet computed — run \\texttt{bash run\\_ablation.sh})")) print(f" placeholder written: {output}") return rows.sort() with open(output, "w") as f: f.write("\\begin{table}[t]\n\\centering\\small\n") f.write("\\caption{Dataset-size ablation. Accuracy (\\%) of the restored " "model on MATH-500 under the primary configuration " "(\\texttt{qwen25-7b} / GPTQ w4) as the silver-bullet dataset size " "$N$ varies. 95\\% bootstrap CIs in brackets. $\\Delta$ is " "restored $-$ quantized baseline.}\n\\label{tab:ablation}\n") f.write("\\begin{tabular}{@{}rccc@{}}\n\\toprule\n") f.write("$N$ & Acc (\\%) & 95\\% CI & $\\Delta$ vs.\\ baseline (pp) \\\\\n\\midrule\n") for N, (acc, lo, hi) in rows: delta = (acc - baseline_acc) * 100 if baseline_acc is not None else None delta_str = "--" if delta is None else f"{delta:+.1f}" f.write(f"{N} & {acc*100:.1f} & [{lo*100:.1f}, {hi*100:.1f}] & {delta_str} \\\\\n") f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n") print(f" wrote: {output}") # --------------------------------------------------------------------------- # Table: sampling-strategy baseline comparison # --------------------------------------------------------------------------- def table_baselines(baseline_root: str, model: str, quant: str, benchmark: str, baseline_acc: Optional[float], output: str) -> None: strategies = ["silver_bullet", "failed_only", "random"] rows = [] if os.path.isdir(baseline_root): base_out = _load_outcomes(os.path.join( "results", "diagnosis", quant, model, f"{benchmark}_run0.jsonl")) for strat in strategies: diag = os.path.join(baseline_root, strat, "diagnosis", f"{benchmark}_run0.jsonl") ci = _bootstrap_acc(diag) if ci is None: continue rest_out = _load_outcomes(diag) p = _paired_p(base_out, rest_out) if base_out and rest_out else None rows.append((strat, ci, p)) if not rows: with open(output, "w") as f: f.write(_placeholder("tab:baselines", "Sampling-strategy baseline comparison.", "(not yet computed — run \\texttt{bash run\\_baselines.sh})")) print(f" placeholder written: {output}") return pretty_strat = { "silver_bullet": "\\textbf{Silver bullet} (ours)", "failed_only": "Failed only (no type balancing)", "random": "Random (no diagnosis)", } with open(output, "w") as f: f.write("\\begin{table}[t]\n\\centering\\small\n") f.write("\\caption{Sampling-strategy baselines. All three adapters are " "trained with identical QLoRA hyperparameters on the same " "underlying problem set; the only difference is which problems " "are drawn. Accuracy in \\%; 95\\% bootstrap CI in brackets; " "$p$-value from paired bootstrap against the quantized baseline.}\n" "\\label{tab:baselines}\n") f.write("\\begin{tabular}{@{}lccc@{}}\n\\toprule\n") f.write("Sampling strategy & Acc (\\%) & 95\\% CI & $p$ \\\\\n\\midrule\n") for strat, (acc, lo, hi), p in rows: p_str = "--" if p is None else f"{p:.3f}{_stars(p)}" f.write(f"{pretty_strat.get(strat, strat)} & {acc*100:.1f} " f"& [{lo*100:.1f}, {hi*100:.1f}] & {p_str} \\\\\n") if baseline_acc is not None: f.write("\\midrule\n") f.write(f"\\textit{{Quantized baseline (no restoration)}} " f"& {baseline_acc*100:.1f} & -- & -- \\\\\n") f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n") print(f" wrote: {output}") # --------------------------------------------------------------------------- # Table: intervention comparison (prompt-prefix vs QLoRA) # --------------------------------------------------------------------------- def table_interventions(prefix_root: str, model: str, quant: str, benchmark: str, baseline_acc: Optional[float], metrics_dir: str, output: str) -> None: rest_path = os.path.join(metrics_dir, f"{model}_{quant}_restored_{benchmark}_run0_metrics.json") rest_acc = (json.load(open(rest_path))["accuracy"] if os.path.exists(rest_path) else None) rows = [] if os.path.isdir(prefix_root): for entry in sorted(os.listdir(prefix_root)): m = re.match(r"k(\d+)$", entry) if not m: continue k = int(m.group(1)) diag = os.path.join(prefix_root, entry, "diagnosis", f"{benchmark}_run0.jsonl") ci = _bootstrap_acc(diag) if ci is None: continue rows.append((k, ci)) rows.sort() if not rows and rest_acc is None: with open(output, "w") as f: f.write(_placeholder("tab:interventions", "Training-free vs. training-based interventions.", "(not yet computed — run \\texttt{bash run\\_prompt\\_prefix.sh})")) print(f" placeholder written: {output}") return with open(output, "w") as f: f.write("\\begin{table}[t]\n\\centering\\small\n") f.write("\\caption{Diagnosis-enabled interventions on the primary cell " "(\\texttt{qwen25-7b} / GPTQ w4 / MATH-500). " "\\emph{Prompt-prefix $k$} prepends the first $k$ FP16 reference " "steps to the quantized model's prompt (no training). " "\\emph{QLoRA restored} is the adapter from \\S\\ref{sec:results-restoration}. " "Accuracy in \\%, 95\\% bootstrap CIs in brackets.}\n" "\\label{tab:interventions}\n") f.write("\\begin{tabular}{@{}lcc@{}}\n\\toprule\n") f.write("Intervention & Acc (\\%) & 95\\% CI \\\\\n\\midrule\n") if baseline_acc is not None: f.write(f"Quantized baseline & {baseline_acc*100:.1f} & -- \\\\\n") for k, (acc, lo, hi) in rows: label = f"Prompt-prefix $k={k}$" f.write(f"{label} & {acc*100:.1f} & [{lo*100:.1f}, {hi*100:.1f}] \\\\\n") if rest_acc is not None: f.write(f"\\textbf{{QLoRA restored (ours)}} & {rest_acc*100:.1f} & -- \\\\\n") f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n") print(f" wrote: {output}") # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser() parser.add_argument("--model", default="qwen25-7b") parser.add_argument("--quant", default="gptq_w4") parser.add_argument("--benchmark", default="math500") parser.add_argument("--metrics-dir", default="results/metrics") parser.add_argument("--ablation-root", default=None, help="Default: results/ablation/_") parser.add_argument("--baselines-root", default=None, help="Default: results/baselines/_") parser.add_argument("--prefix-root", default=None, help="Default: results/prefix_injection/_") parser.add_argument("--output-dir", default="figures/paper", help="Where to drop the .tex files") args = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) # Quantized baseline accuracy (read from metrics file). base_path = os.path.join(args.metrics_dir, f"{args.model}_{args.quant}_{args.benchmark}_run0_metrics.json") base_acc = (json.load(open(base_path))["accuracy"] if os.path.exists(base_path) else None) ablation_root = args.ablation_root or f"results/ablation/{args.model}_{args.quant}" baselines_root = args.baselines_root or f"results/baselines/{args.model}_{args.quant}" prefix_root = args.prefix_root or f"results/prefix_injection/{args.model}_{args.quant}" table_ablation(ablation_root, args.benchmark, base_acc, os.path.join(args.output_dir, "table_ablation.tex")) table_baselines(baselines_root, args.model, args.quant, args.benchmark, base_acc, os.path.join(args.output_dir, "table_baselines.tex")) table_interventions(prefix_root, args.model, args.quant, args.benchmark, base_acc, args.metrics_dir, os.path.join(args.output_dir, "table_interventions.tex")) if __name__ == "__main__": main()