File size: 17,232 Bytes
257b735
56fd675
 
 
 
 
 
 
 
 
 
 
 
 
 
257b735
 
56fd675
257b735
 
56fd675
 
257b735
 
 
 
 
 
56fd675
 
257b735
56fd675
 
 
257b735
56fd675
257b735
56fd675
257b735
56fd675
257b735
56fd675
257b735
56fd675
 
 
 
257b735
 
 
56fd675
257b735
56fd675
 
257b735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56fd675
257b735
56fd675
257b735
 
 
 
 
56fd675
257b735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56fd675
257b735
 
 
 
 
 
 
 
 
 
 
 
 
56fd675
257b735
 
 
 
 
56fd675
257b735
 
56fd675
257b735
56fd675
 
 
257b735
 
 
56fd675
257b735
 
 
 
 
 
 
 
 
 
 
 
 
56fd675
 
 
 
257b735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56fd675
 
 
 
257b735
 
56fd675
257b735
56fd675
257b735
 
 
 
 
 
56fd675
 
 
257b735
 
 
 
 
 
 
 
 
 
 
56fd675
 
 
257b735
56fd675
257b735
 
56fd675
 
257b735
 
 
 
 
 
 
 
 
 
56fd675
 
257b735
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""Compute all metrics and figures for the report from ../data only.

Usage: python scripts/make_figures.py   ->  ../figures/*.png  and  ../figures/metrics.json
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

HERE = Path(__file__).resolve().parent.parent
DATA, FIG = HERE / "data", HERE / "figures"
FIG.mkdir(exist_ok=True)
for old in FIG.glob("*.png"):
    old.unlink()
BUDGETS = [10, 20, 30, 40, 50, 80, 100, 150, 200, 300, 500, 800, 1200, 2000, 4000, 8000]
MODELS = ["Llama-3.2-3B", "Qwen2.5-Math-1.5B"]
COL = {"Llama-3.2-3B": "#1f77b4", "Qwen2.5-Math-1.5B": "#ff7f0e", "Qwen3-4B-Thinking": "#2ca02c", "Qwen3-30B-A3B": "#7f7f7f", "Qwen3-235B": "#17becf"}
M = {}


def wilson(k, n, z=1.96):
    if n == 0: return (np.nan, np.nan)
    p = k / n; d = 1 + z * z / n; c = p + z * z / (2 * n); h = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
    return ((c - h) / d, (c + h) / d)


def flip_stats(A):
    """A: (n, 16) graded scores, NaN where a budget was not run."""
    n_b = A.shape[1]
    ever = np.nanmax(np.where(np.isnan(A), -1, A), axis=1) >= 1.0
    perfect_flip = np.zeros(len(A), bool); hard_flip = np.zeros(len(A), bool)
    first_off = []; surv = np.zeros(n_b); cnt = np.zeros(n_b)
    for i in np.where(ever)[0]:
        row = A[i]; valid = ~np.isnan(row)
        fs = int(np.argmax((row >= 1.0) & valid))
        later = row[fs + 1:]; lv = ~np.isnan(later)
        if lv.any():
            perfect_flip[i] = np.any(later[lv] < 1.0); hard_flip[i] = np.any(later[lv] <= 0.0)
            idx = np.where(lv & (later < 1.0))[0]
            if len(idx): first_off.append(int(idx[0]) + 1)
        alive = True
        for k in range(1, n_b - fs):
            v = row[fs + k]
            if np.isnan(v): continue
            alive = alive and v >= 1.0; surv[k] += alive; cnt[k] += 1
    fo = np.array(first_off)
    return dict(n_ever_solved=int(ever.sum()), perfect_flip_pct=round(100 * perfect_flip[ever].mean(), 1),
                hard_flip_pct=round(100 * hard_flip[ever].mean(), 1),
                pct_first_flip_at_next_level=round(100 * (fo == 1).mean(), 1) if len(fo) else None,
                survival_by_offset=[1.0] + [round(float(surv[k] / cnt[k]), 3) if cnt[k] else None for k in range(1, n_b)])


def oracle_vs_fixed(A, bud):
    """Oracle = per query, cheapest budget that is fully correct (else the cheapest budget, scored 0)."""
    full = (np.nan_to_num(A, nan=-1) >= 1.0)
    per_b = full.mean(axis=0) * 100
    valid = ~np.all(np.isnan(A), axis=0)
    bi = int(np.nanargmax(np.where(valid, per_b, -1)))
    ever = full.any(axis=1)
    first = np.argmax(full, axis=1)
    oracle_cost = np.where(ever, np.array(bud)[first], bud[0]).mean()
    solved_at_best = full[:, bi]
    cheaper = np.array([full[i, :bi].any() for i in range(len(A))])
    return dict(best_fixed_budget=int(bud[bi]), best_fixed_fully_correct_pct=round(float(per_b[bi]), 1),
                oracle_fully_correct_pct=round(float(ever.mean() * 100), 1),
                oracle_mean_tokens=round(float(oracle_cost)), best_fixed_tokens=int(bud[bi]),
                pct_of_best_fixed_solves_already_solved_cheaper=round(float(cheaper[solved_at_best].mean() * 100), 1),
                pct_all_queries_right_cheaper_but_wrong_at_best_fixed=round(float((cheaper & ~solved_at_best).mean() * 100), 1),
                fixed_curve={int(b): round(float(p), 2) for b, p, v in zip(bud, per_b, valid) if v})


# ============================================================ R2-Bench small models
sc = pd.read_parquet(DATA / "r2bench_small_models_scores_by_budget.parquet")
cols = [f"score@{b}" for b in BUDGETS]
M["r2bench"] = {}
fig, ax = plt.subplots(1, 3, figsize=(15, 4))
for m in MODELS:
    d = sc[sc.model == m]; A = d[cols].to_numpy(dtype=float)
    valid = ~np.all(np.isnan(A), axis=0); bv = np.array(BUDGETS)[valid]
    perfect = np.nanmean(A >= 1.0, axis=0)[valid] * 100
    graded = np.nanmean(A, axis=0)[valid] * 100
    closed = np.maximum.accumulate(np.nan_to_num(A, nan=-1) >= 1.0, axis=1).mean(axis=0)[valid] * 100
    fs = flip_stats(A)
    fs.update(perfect_rate_by_budget={int(b): round(float(p), 2) for b, p in zip(bv, perfect)},
              mean_graded_by_budget={int(b): round(float(g), 2) for b, g in zip(bv, graded)},
              closure_inflation_pp_by_budget={int(b): round(float(c - p), 1) for b, c, p in zip(bv, closed, perfect)},
              peak_budget=int(bv[np.argmax(perfect)]))
    drops = [(bv[i], bv[j], perfect[i] - perfect[j]) for i in range(len(bv)) for j in range(i + 1, len(bv))]
    f, t, pp = max(drops, key=lambda x: x[2]); fs["max_aggregate_drop"] = {"from": int(f), "to": int(t), "pp": round(float(pp), 2)}
    fs["oracle_vs_fixed"] = oracle_vs_fixed(A, BUDGETS)
    # by question type
    fs["by_qtype"] = {}
    for qt in sorted(d.qtype.unique()):
        Aq = d.loc[d.qtype == qt, cols].to_numpy(dtype=float)
        if len(Aq) < 50: continue
        q = flip_stats(Aq); q["n_queries"] = int(len(Aq)); q.pop("survival_by_offset")
        q["oracle_vs_fixed"] = {k: v for k, v in oracle_vs_fixed(Aq, BUDGETS).items() if k != "fixed_curve"}
        fs["by_qtype"][qt] = q
    M["r2bench"][m] = fs
    ax[0].plot(bv, perfect, "o-", color=COL[m], label=m); ax[0].plot(bv, closed, "--", color=COL[m], alpha=.5)
    ax[1].plot(bv, graded, "o-", color=COL[m], label=m)
    ax[2].plot(bv, closed - perfect, "o-", color=COL[m], label=m)
ax[0].set_title("Fully-correct rate (%)\nsolid = at that budget, dashed = 'solved at any budget <= x'", fontsize=9)
ax[1].set_title("Mean graded score (%)", fontsize=10)
ax[2].set_title("Gap between the two (pp): what a pass@budget\nleaderboard overstates", fontsize=9)
for a in ax:
    a.set_xscale("log"); a.set_xlabel("response budget (words in prompt; hard cap = budget+10 tokens)", fontsize=8); a.grid(alpha=.3); a.legend(fontsize=8)
fig.suptitle("R2-Bench, 30,968 queries, single sample per cell", fontsize=11)
fig.tight_layout(); fig.savefig(FIG / "fig1_accuracy_vs_budget.png", dpi=150); plt.close(fig)

# flips
fig, ax = plt.subplots(figsize=(6.5, 4))
for m in MODELS:
    sv = M["r2bench"][m]["survival_by_offset"]
    ax.plot(range(len(sv)), [v if v is not None else np.nan for v in sv], "o-", color=COL[m], label=f"{m} (hard flip {M['r2bench'][m]['hard_flip_pct']}%)")
ax.set_xlabel("budget levels above the first budget that solved it"); ax.set_ylabel("P(still fully correct)"); ax.set_ylim(0, 1.02)
ax.set_title("Survival of a correct answer as budget grows (single sample per cell: upper bound on flipping)", fontsize=9); ax.grid(alpha=.3); ax.legend(fontsize=8)
fig.tight_layout(); fig.savefig(FIG / "fig2_flips.png", dpi=150); plt.close(fig)

# raster, Llama
A = sc.loc[sc.model == "Llama-3.2-3B", cols].to_numpy(dtype=float)
ever = np.nanmax(np.nan_to_num(A, nan=-1), axis=1) >= 1
rng = np.random.default_rng(0); idx = rng.choice(np.where(ever)[0], 120, replace=False); sub = A[idx]
order = np.argsort(np.argmax(sub >= 1, axis=1))
fig, ax = plt.subplots(figsize=(8, 7))
im = ax.imshow(sub[order], aspect="auto", cmap="RdYlGn", vmin=0, vmax=1, interpolation="nearest")
ax.set_xticks(range(16)); ax.set_xticklabels(BUDGETS, rotation=60, fontsize=8); ax.set_xlabel("budget"); ax.set_ylabel("120 random queries Llama-3.2-3B solves at least once (sorted by first solve)")
ax.set_title("Llama-3.2-3B: correctness is not monotone in budget (green = 1.0, red = 0.0)\nrows sorted by first solve, so the left edge is construction; the red to its right is the finding", fontsize=9)
fig.colorbar(im, ax=ax, label="graded score"); fig.tight_layout(); fig.savefig(FIG / "fig3_llama3b_raster.png", dpi=150); plt.close(fig)

# oracle vs fixed: cost-accuracy pareto
fig, ax = plt.subplots(figsize=(7, 4.5))
for m in MODELS:
    o = M["r2bench"][m]["oracle_vs_fixed"]
    xs = list(o["fixed_curve"].keys()); ys = list(o["fixed_curve"].values())
    ax.plot(xs, ys, "o-", color=COL[m], label=f"{m}: fixed budget")
    ax.scatter([o["oracle_mean_tokens"]], [o["oracle_fully_correct_pct"]], marker="*", s=250, color=COL[m], edgecolor="k", zorder=5, label=f"{m}: per-query cheapest correct budget (oracle)")
    ax.annotate("", xy=(o["oracle_mean_tokens"], o["oracle_fully_correct_pct"]), xytext=(o["best_fixed_budget"], o["best_fixed_fully_correct_pct"]), arrowprops=dict(arrowstyle="->", color=COL[m], lw=1.2, ls="--"))
ax.set_xscale("log"); ax.set_xlabel("mean budget spent per query (tokens)"); ax.set_ylabel("fully-correct rate (%)"); ax.grid(alpha=.3); ax.legend(fontsize=7, loc="lower right"); ax.set_ylim(0, 62)
ax.set_title("What knowing how long to think is worth: fixed budgets vs. per-query oracle\n(oracle is an n=1 upper bound; see report)", fontsize=9)
fig.tight_layout(); fig.savefig(FIG / "fig4_oracle_vs_fixed.png", dpi=150); plt.close(fig)

# ============================================================ obedience (Llama only)
ob = pd.read_parquet(DATA / "r2bench_budget_obedience_compact.parquet")
M["obedience"] = {}
fig, ax = plt.subplots(1, 3, figsize=(13, 3.8))
for i, b in enumerate((50, 200, 800)):
    d = ob[(ob.model == "Llama-3.2-3B") & (ob.budget_words == b)]
    M["obedience"][f"Llama-3.2-3B@{b}"] = dict(n=int(len(d)), mean_tokens=round(float(d.actual_token_count.mean()), 1), median_tokens=float(d.actual_token_count.median()),
                                            frac_hit_cap=round(float(d.hit_cap.mean()), 3), frac_at_most_N_tokens=round(float((d.actual_token_count <= b).mean()), 3),
                                            frac_at_most_1p3N_tokens=round(float((d.actual_token_count <= 1.3 * b).mean()), 3),
                                            frac_under_15_tokens=round(float((d.actual_token_count < 15).mean()), 3),
                                            mean_score=round(float(d.correctness_score.mean()), 3), perfect_rate=round(float((d.correctness_score >= 1).mean()), 3))
    ax[i].hist(d.actual_token_count, bins=40, color=COL["Llama-3.2-3B"], range=(0, b + 20))
    ax[i].axvline(b, color="k", ls="--", lw=1); ax[i].set_title(f'prompt: "strict budget of {b} words"  |  {100*d.hit_cap.mean():.0f}% hit the hard cap', fontsize=9); ax[i].set_xlabel("tokens actually generated")
fig.suptitle("Llama-3.2-3B: a budget stated in the prompt is obeyed only when it is already slack (the spike near 10 tokens = bare MCQ letter answers)", fontsize=10)
fig.tight_layout(); fig.savefig(FIG / "fig5_budget_obedience.png", dpi=150); plt.close(fig)

# ============================================================ natural length vs difficulty (Llama, 8k cap, no budget sentence)
H = json.load(open(DATA / "r2bench_llama3b_length_vs_hardness.json"))["Llama-3.2-3B"]
M["length_vs_difficulty_llama3b"] = dict(mean_tokens_by_n_models_solving=H["mean_tokens_by_hardness"], cv=H["cv_by_hardness"],
                                         kendall_tau_len_vs_n_models_solving=H["kendall_tau_len_vs_hardness"],
                                         mean_min_budget_by_n_models_solving=H["mean_minbudget_by_hardness"], mean_overspend_tokens=H["mean_overspend_tokens"])
fig, ax = plt.subplots(figsize=(7, 4))
xs = np.arange(11); mt = np.array(H["mean_tokens_by_hardness"]); mb = np.array([np.nan if v is None else v for v in H["mean_minbudget_by_hardness"]])
sd = np.array(H["std_tokens_by_hardness"]); n = np.array(H["n_by_hardness"]); se = sd / np.sqrt(n)
ax.errorbar(xs, mt, yerr=se, fmt="o-", capsize=3, color=COL["Llama-3.2-3B"], label=f"tokens spent at the slack 8000-word level (mean ± s.e., n={int(n.sum()):,})")
ax.plot(xs, mb, "s--", color="k", alpha=.7, label="cheapest budget that gets it fully right")
ax.set_xlabel("number of the 10 reference models that solve the query (0 = hardest, 10 = easiest)", fontsize=9)
ax.set_ylabel("tokens (mean)"); ax.grid(alpha=.3); ax.legend(fontsize=8)
ax.set_title(f"Llama-3.2-3B spends about the same on the hardest and the easiest questions\n(Kendall tau length vs. ease = {H['kendall_tau_len_vs_hardness']:+.2f}; within-level CV {min(H['cv_by_hardness']):.1f}-{max(H['cv_by_hardness']):.1f})", fontsize=9); fig.subplots_adjust(bottom=0.18)
fig.tight_layout(); fig.savefig(FIG / "fig6_length_vs_difficulty.png", dpi=150); plt.close(fig)

# ============================================================ Qwen3-4B-Thinking on GPQA-Diamond
g = pd.read_json(DATA / "gpqa_diamond_qwen3_4b_thinking_per_question.jsonl", lines=True)
c, w = g[g.correct].gen_tokens, g[~g.correct].gen_tokens
g["q"] = pd.qcut(g.gen_tokens, 5)
byq = g.groupby("q", observed=True).correct.agg(["sum", "size"])
from itertools import product
auc = float(np.mean([(a < b) + 0.5 * (a == b) for a, b in product(c.to_numpy(), w.to_numpy())]))
M["gpqa_qwen3_4b"] = dict(n=int(len(g)), accuracy=round(float(g.correct.mean()), 3),
                          tokens_correct=dict(mean=round(float(c.mean())), median=float(c.median()), p10=round(float(c.quantile(.1))), p90=round(float(c.quantile(.9)))),
                          tokens_wrong=dict(mean=round(float(w.mean())), median=float(w.median()), p10=round(float(w.quantile(.1))), p90=round(float(w.quantile(.9)))),
                          wrong_costs_pct_more_tokens=round(float(100 * (w.mean() / c.mean() - 1)), 1),
                          cv_across_questions=round(float(g.gen_tokens.std() / g.gen_tokens.mean()), 3), max_tokens=int(g.gen_tokens.max()),
                          auc_shorter_is_correct=round(auc, 3),
                          accuracy_by_length_quintile={f"{int(i.left)}-{int(i.right)}": dict(acc=round(float(r["sum"] / r["size"]), 3), n=int(r["size"]), ci95=[round(v, 3) for v in wilson(r["sum"], r["size"])]) for i, r in byq.iterrows()})
ec = json.load(open(DATA / "qwen3_4b_phase0_early_commit.json"))
ks = [r["k"] for r in ec["rows"]]; acc = [r["A_k_accuracy"] for r in ec["rows"]]; stab = [r["stability_rate"] for r in ec["rows"]]
M["gpqa_qwen3_4b"]["early_commit"] = {str(k): dict(acc_forced_answer=round(a, 3), agrees_with_own_final_answer=round(s, 3)) for k, a, s in zip(ks, acc, stab)}
M["gpqa_qwen3_4b"]["early_commit"]["full"] = dict(acc_forced_answer=round(ec["a_base_acc"], 3), mean_tokens=8651)
# chance agreement with the final answer if the early pick were independent of it: sum_p p_final(l)^2 ~ use marginal of final preds
pf = g.pred.value_counts(normalize=True); M["gpqa_qwen3_4b"]["early_commit"]["chance_agreement_if_independent"] = round(float((pf ** 2).sum()), 3)
sc_j = json.load(open(DATA / "qwen3_4b_phase0_sc.json")); M["gpqa_qwen3_4b"]["self_consistency_raw"] = sc_j

fig, ax = plt.subplots(1, 3, figsize=(14, 4))
ax[0].hist([c, w], bins=25, label=[f"correct (n={len(c)}, mean {c.mean():.0f})", f"wrong (n={len(w)}, mean {w.mean():.0f})"], color=["#2ca02c", "#d62728"], alpha=.7)
ax[0].set_xlabel("tokens generated (thinking + answer; cap 32,768 never hit)"); ax[0].set_title("Qwen3-4B-Thinking, GPQA-Diamond:\nthe answers that cost most are the wrong ones", fontsize=9); ax[0].legend(fontsize=8)
qi = np.arange(len(byq)); accs = byq["sum"] / byq["size"]; ci = np.array([wilson(r["sum"], r["size"]) for _, r in byq.iterrows()])
ax[1].bar(qi, accs, color="#2ca02c", yerr=[accs - ci[:, 0], ci[:, 1] - accs], capsize=3)
ax[1].set_xticks(qi); ax[1].set_xticklabels([f"{int(i.left/1000)}-{int(i.right/1000)}k" for i in byq.index], fontsize=8); ax[1].set_xlabel("trace length quintile"); ax[1].set_ylabel("accuracy (95% CI)"); ax[1].set_ylim(0, 1); ax[1].set_title("Accuracy by trace-length quintile (n≈40 each)", fontsize=9)
xs = np.arange(len(ks) + 1)
ax[2].bar(xs - .2, acc + [ec["a_base_acc"]], .4, label="accuracy when forced to answer at k", color="#2ca02c")
ax[2].bar(xs[:-1] + .2, stab, .4, label="forced answer == its own final answer", color="grey")
ax[2].axhline(0.25, color="k", ls=":", lw=1); ax[2].text(2.45, 0.265, "chance (4-way) for both bars", fontsize=7)
ax[2].set_xticks(xs); ax[2].set_xticklabels([f"k={k}" for k in ks] + ["full\n(~8.7k)"]); ax[2].set_ylim(0, 1); ax[2].legend(fontsize=7)
ax[2].set_title("Stop thinking at k tokens, inject </think> and force an answer", fontsize=9)
fig.tight_layout(w_pad=1.5); fig.savefig(FIG / "fig7_qwen3_4b_gpqa.png", dpi=150); plt.close(fig)

mm = json.load(open(DATA / "qwen3_4b_mmlu_pro_cascade.json"))
M["mmlu_pro_qwen3_4b"] = dict(n=mm["n"], accuracy_4b=mm["a_accuracy"], mean_tokens_4b=mm["mean_a_gen_tokens"], accuracy_30b_a3b=mm["b_accuracy"], mean_tokens_30b_a3b=mm["mean_b_gen_tokens"],
                              pct_more_tokens_4b_vs_30b=round(100 * (mm["mean_a_gen_tokens"] / mm["mean_b_gen_tokens"] - 1), 1), a_only_router_auc=round(mm["a_only_router_auc"], 3))

# ============================================================ transfer: larger reference models, same benchmark
lg = pd.read_parquet(DATA / "r2bench_large_reference_scores_by_budget.parquet")
M["transfer_large_models"] = {}
for m in sorted(lg.model.unique()):
    A = lg.loc[lg.model == m, cols].to_numpy(dtype=float); f = flip_stats(A); f.pop("survival_by_offset")
    f["oracle_vs_fixed"] = {k: v for k, v in oracle_vs_fixed(A, BUDGETS).items() if k != "fixed_curve"}
    M["transfer_large_models"][m] = f

json.dump(M, open(FIG / "metrics.json", "w"), indent=1, default=str)
print(json.dumps({k: v for k, v in M.items()}, indent=1, default=str)[:6000])