Datasets:

ArXiv:
recursive-judge-grpo-study / src /study /visual_summary.py
BurnyCoder's picture
readme-format · 4915b21fb166
17f273c verified
Raw History Blame Contribute Delete
22.5 kB
"""Paper-style overview figures: architecture, X/Twitter summary card, poster, and an animated reward walkthrough.
Global context: `report.figures()` calls `draw_all()` after the per-experiment plots. Every number drawn here
comes from the role-labelled rows of `overview.glance_rows()` or from the verified study data; design constants in
the architecture diagram are the training settings in training.py (TRL GRPOConfig) and records.py.
"""
from textwrap import fill
from .design import GITHUB
from .overview import FAMILIES, group_advantages
ROLE_COLORS = {"Method": "#3f6fb0", "Baseline": "#23796c", "Control": "#6f7d7c", "Ablation": "#8a62a8"}
INK, PAPER, ACCENT = "#173a43", "#f4f8f7", "#b65127"
SHORT = {"base": "Start", "d1-17": "1 judge", "d2-17": "2 judges", "d3-17": "3 judges", "flat-17": "3 votes",
"oracle-17": "Exact", "hybrid-17": "J3 × exact", "shuffle-17": "Shuffled",
"new-judges/winner-d1": "1 judge", "new-judges/winner-d2": "2 judges", "new-judges/winner-d3": "3 judges"}
HEADLINE = {"frozen": ("base", "new-judges/winner-d1", "new-judges/winner-d2", "new-judges/winner-d3"),
"original": ("base", "d1-17", "d2-17", "d3-17", "flat-17", "oracle-17", "hybrid-17", "shuffle-17")}
OUTPUTS = ("architecture.png", "twitter-summary.png", "poster.png", "walkthrough.gif", "walkthrough.mp4")
def pyplot():
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
return plt
def box(ax, x, y, w, h, title, body, face="#e8f3f1", edge=INK, size=10.5):
"""A rounded block with a bold title and wrapped body lines, as in ML architecture figures."""
from matplotlib.patches import FancyBboxPatch
ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=.06,rounding_size=.12", fc=face, ec=edge, lw=1.6))
ax.text(x+w/2, y+h-.28, title, ha="center", va="top", fontsize=size+1.5, weight="bold", color=edge)
ax.text(x+w/2, y+h-.75, body, ha="center", va="top", fontsize=size, color="#1d2b2e", linespacing=1.35)
def arrow(ax, start, end, color=INK, dashed=False, text=None, offset=(0, .18), curve=0):
ax.annotate("", end, start, arrowprops=dict(arrowstyle="-|>", color=color, lw=1.5, ls="--" if dashed else "-",
shrinkA=2, shrinkB=2, connectionstyle=f"arc3,rad={curve}"))
if text:
ax.text((start[0]+end[0])/2+offset[0], (start[1]+end[1])/2+offset[1], text, ha="center", fontsize=9.5,
color=color, bbox=dict(fc="white", ec="none", pad=1.5))
def architecture(path):
"""Training and evaluation loop. Constants: num_generations=4, epsilon=0.2, beta=0, LoRA r=16 (training.py)."""
plt = pyplot()
fig, ax = plt.subplots(figsize=(16, 7.6))
ax.set(xlim=(0, 19), ylim=(0, 8.6))
ax.axis("off")
green = "#3d7a3a"
box(ax, .2, 4.7, 2.6, 2.1, "Problem sampler", "(a ± b) ± c, fresh\nproblem per update\ne.g. (18 − 11) − 3", PAPER)
box(ax, 3.3, 4.7, 3.0, 2.1, "Solver · trained", "Qwen2.5-1.5B-Instruct\nNF4 base + LoRA (r = 16)\nwrites every step: 7,4",
"#fbe9df", ACCENT)
judges = (("Judge 1", "verdict, first wrong\nstep, value\n→ 1,0,4"),
("Judge 2", "audits Judge 1,\nre-grades the solver\n→ 1,0,4,1,0,4"),
("Judge 3", "audits Judge 2,\nre-grades the solver\n→ 1,0,4,1,0,4"))
for i, (title, body) in enumerate(judges):
box(ax, 7.0+2.6*i, 4.7, 2.3, 2.1, title, body, "#e6eef8", ROLE_COLORS["Method"], 10)
ax.text(10.95, 7.35, "Frozen LLM judges: Qwen2.5-1.5B-Instruct or Qwen3.5-4B. Each reads the problem, the "
"solver's trace and every earlier report.", ha="center", fontsize=11, color=ROLE_COLORS["Method"])
ax.plot([7.0, 14.5], [7.1, 7.1], color=ROLE_COLORS["Method"], lw=1.2)
box(ax, 15.1, 3.0, 3.75, 3.8, "Reward rule",
"one rule per arm\nD1 / D2 / D3: last judge's\nsolution verdict (0 or 1)\nflat: majority of three\n"
"independent Judge 1 calls\noracle: exact checker bit\nhybrid: D3 × exact bit\nshuffle: D3, permuted in group",
"#f1ecf7", ROLE_COLORS["Ablation"], 10)
box(ax, 3.3, 2.0, 9.0, 2.05, "GRPO update (TRL GRPOTrainer)",
"4 sampled traces per problem; credit A = (r − mean) / (sd + 0.0001)\n"
"clipped ratio ε = 0.2, no KL term (β = 0); only the LoRA weights change\n"
"identical rewards in a group give zero credit", PAPER)
box(ax, .2, .15, 18.65, 1.45, "Exact integer checker",
"executes every numbered step and labels every solver and judge field · scores every evaluation · "
"is the reward only in the oracle and hybrid arms", "#eef6ec", green)
arrow(ax, (2.85, 5.75), (3.28, 5.75))
arrow(ax, (6.35, 5.75), (6.98, 5.75), text="×4", offset=(0, .2))
for i in range(2):
arrow(ax, (9.33+2.6*i, 5.75), (9.58+2.6*i, 5.75))
arrow(ax, (14.53, 5.75), (15.08, 5.75))
arrow(ax, (15.08, 3.5), (12.33, 3.0), text="rewards r", offset=(0, .25))
arrow(ax, (4.8, 4.08), (4.8, 4.67), text="LoRA update", offset=(-1.05, -.1))
arrow(ax, (17.0, 1.63), (17.0, 2.97), green, dashed=True, text="exact bit", offset=(.75, -.1))
fig.savefig(path, dpi=150, bbox_inches="tight", facecolor="white")
plt.close(fig)
def pick(table, family, keys):
found = {r["key"]: r for r in table if r["family"] == family and r["correct"] is not None}
return [found[k] for k in keys if k in found]
def score_bars(ax, records, title, label_size=10):
"""Vertical bars with Wilson 95% intervals and literal denominators; the axis always starts at zero."""
heights = [100*r["correct"]/r["n"] for r in records]
lows = [h-100*r["interval"][0] for h, r in zip(heights, records, strict=True)]
highs = [100*r["interval"][1]-h for h, r in zip(heights, records, strict=True)]
xs = range(len(records))
ax.bar(xs, heights, color=[ROLE_COLORS[r["role"]] for r in records], yerr=[lows, highs], capsize=4,
error_kw=dict(lw=1.1, color="#33413f"))
for x, r, h, top in zip(xs, records, heights, highs, strict=True):
ax.text(x, h+top+2, f"{r['correct']}/{r['n']}", ha="center", fontsize=label_size, color=INK)
ax.set(xticks=list(xs), ylim=(0, 115), yticks=[0, 25, 50, 75, 100], ylabel="Exact solutions (%)")
ax.set_xticklabels([SHORT.get(r["key"], r["key"]) for r in records], fontsize=label_size)
ax.set_title(title, fontsize=label_size+2, loc="left", color=INK)
ax.spines[["top", "right"]].set_visible(False)
def role_legend(fig, y, size=11):
from matplotlib.patches import Patch
fig.legend(handles=[Patch(color=c, label=role) for role, c in ROLE_COLORS.items()], loc="lower center",
ncol=4, frameon=False, fontsize=size, bbox_to_anchor=(.5, y))
def takeaways(table, data):
"""Three numeric sentences shared by the card and the poster."""
lines = []
contrasts = (data.get("online_solvers") or {}).get("three_depths", {}).get("contrasts", {})
for key, text in (("two_minus_one", "Qwen3.5-4B judges · 2 minus 1 judge"),
("three_minus_two", "Qwen3.5-4B judges · 3 minus 2 judges")):
if key in contrasts:
c = contrasts[key]
lines.append(f"{text}: {100*c['delta']:+.1f} pp, 95% CI [{100*c['interval'][0]:+.1f}, "
f"{100*c['interval'][1]:+.1f}]")
two = pick(table, "original", ("d2-17",))
if two and two[0]["change"]:
# The table stores two minus three; negating the shared bootstrap draws gives three minus two.
c = two[0]["change"]
lines.append(f"Qwen2.5-1.5B judges · 3 minus 2 judges: {-100*c['delta']:+.1f} pp, 95% CI "
f"[{-100*c['interval'][1]:+.1f}, {-100*c['interval'][0]:+.1f}]")
return lines
def cohort(table):
sizes = sorted({r["n"] for r in table if r["n"]})
return f"Single seed · {' or '.join(map(str, sizes))} development problems"
def twitter_card(table, data, path):
plt = pyplot()
fig = plt.figure(figsize=(16, 9), facecolor="white")
fig.text(.04, .93, "Does a third LLM judge improve GRPO rewards?", fontsize=30, weight="bold", color=INK)
fig.text(.04, .875, "Verifying a verifier of a verifier: a solver learns from the verdict of 1, 2 or 3 recursive "
"LLM judges, and an exact checker grades everything.", fontsize=15, color="#355")
axes = [fig.add_axes(rect) for rect in ((.05, .3, .36, .5), (.47, .3, .5, .5))]
for ax, family in zip(axes, ("frozen", "original"), strict=True):
score_bars(ax, pick(table, family, HEADLINE[family]), FAMILIES[family], 12)
role_legend(fig, .205, 13)
for i, line in enumerate(takeaways(table, data)):
fig.text(.05, .16-.04*i, "• "+line, fontsize=14.5, color=INK)
fig.text(.05, .045, cohort(table) + " · error bars: Wilson 95% · differences: paired bootstrap 95% CI",
fontsize=11.5, color="#556")
fig.text(.05, .015, GITHUB.removeprefix("https://"), fontsize=11.5, color="#556")
fig.text(.97, .015, "Libor “Burny” Burian · Hypercurious Lab", fontsize=11.5, color="#556", ha="right")
fig.savefig(path, dpi=100)
plt.close(fig)
def all_original(ax, table):
"""Horizontal bars for every original-judge arm, coloured by role, with Wilson intervals."""
records = pick(table, "original", [r["key"] for r in table if r["family"] == "original"])
ys = range(len(records))
values = [100*r["correct"]/r["n"] for r in records]
errors = [[v-100*r["interval"][0] for v, r in zip(values, records, strict=True)],
[100*r["interval"][1]-v for v, r in zip(values, records, strict=True)]]
ax.barh(ys, values, xerr=errors, color=[ROLE_COLORS[r["role"]] for r in records], capsize=3)
for y, r, v in zip(ys, records, values, strict=True):
ax.text(101, y, f"{r['correct']}/{r['n']}", va="center", fontsize=15, color=INK)
ax.set(yticks=list(ys), xlim=(0, 112), xticks=[0, 25, 50, 75, 100], xlabel="Exact development solutions (%)")
ax.set_yticklabels([r["key"] for r in records], fontsize=15)
ax.invert_yaxis()
ax.spines[["top", "right"]].set_visible(False)
ax.set_title("Every arm with Qwen2.5-1.5B-Instruct judges", loc="left", fontsize=21, color=INK)
def panel(fig, rect, title, text, size=15):
ax = fig.add_axes(rect)
ax.axis("off")
ax.set_title(title, loc="left", fontsize=21, weight="bold", color=INK)
ax.text(0, 1, text, va="top", fontsize=size, color="#1d2b2e", linespacing=1.45, transform=ax.transAxes)
return ax
def example_lines(example):
"""Text rows for the logged update shown in the walkthrough, with TRL advantages for both reward rules."""
second, third = ([s[column] for s in example["samples"]] for column in (2, 3))
a2, a3 = group_advantages(second), group_advantages(third)
rows = [f"{'Answer':8}{'Checker':10}{'J2 r':>6}{'A':>7}{'J3 r':>7}{'A':>7}"]
for (answer, label, *_), r2, x2, r3, x3 in zip(example["samples"], second, a2, third, a3, strict=True):
rows.append(f"{answer:8}{'correct' if label else 'wrong':10}{r2:>6}{x2:>+7.2f}{r3:>7}{x3:>+7.2f}")
return rows
def poster(table, data, path, architecture_png):
"""A landscape poster: question, method, setup, results, training dynamics, evidence audit and a real example."""
plt = pyplot()
style = {"font.size": 16, "axes.labelsize": 17, "xtick.labelsize": 15, "ytick.labelsize": 15}
with plt.rc_context(style):
fig = plt.figure(figsize=(33.1, 23.4), facecolor="white")
fig.patches.append(plt.Rectangle((0, .905), 1, .095, transform=fig.transFigure, color=INK, zorder=-1))
fig.text(.02, .955, "Verifying a verifier of a verifier: does a third LLM judge improve GRPO rewards?",
fontsize=46, weight="bold", color="white", va="center")
fig.text(.02, .92, "Libor “Burny” Burian · Hypercurious Lab · " + GITHUB.removeprefix("https://"),
fontsize=24, color="#d8ecea", va="center")
panel(fig, (.02, .76, .30, .11), "Question",
fill("DeepSeekMath-V2 and others let a second LLM judge check the first. We add a third judge that "
"checks the second and use its verdict as an online GRPO reward for a small solver. Does the extra "
"review make the reward more accurate and the trained solver better? An exact integer checker "
"grades every solver step and every judge field.", 56), 18)
image = fig.add_axes((.015, .44, .315, .29))
image.imshow(plt.imread(architecture_png))
image.axis("off")
image.set_title("Method", loc="left", fontsize=24, weight="bold", color=INK)
panel(fig, (.02, .04, .30, .36), "Setup",
fill("Solver: Qwen2.5-1.5B-Instruct, NF4 base with a rank-16 LoRA adapter. Judges: frozen "
"Qwen2.5-1.5B-Instruct (original study) or frozen Qwen3.5-4B (newer study). Task: two-step "
"addition and subtraction, (a ± b) ± c; a solution counts only when every intermediate value is "
"correct. " + cohort(table) + ".", 56)
+ "\n\n" + fill("GRPO in TRL: four samples per problem, group-scaled advantages, clipped ratio 0.2, no "
"KL term. Every arm uses the same seed, initial adapter, prompt order and update budget; "
"only the reward rule changes. Baselines: one or two judges and three independent votes. "
"Controls: no training, exact reward, shuffled reward. Ablations: checker-gated reward "
"and pre-trained judge stacks.", 56), 18)
score_bars(fig.add_axes((.38, .63, .26, .22)), pick(table, "frozen", HEADLINE["frozen"]),
FAMILIES["frozen"], 17)
all_original(fig.add_axes((.44, .10, .20, .45)), table)
role_legend(fig, .015, 22)
primary = data.get("primary", {})
lines = takeaways(table, data) + ([cohort(table) + "; the preregistered held-out comparison is pending."]
if "delta" not in primary else [])
panel(fig, (.69, .73, .29, .13), "Key results", "\n".join("• "+fill(line, 50) for line in lines), 18)
review = (data.get("depth_review") or [None])[0]
if review:
ax = fig.add_axes((.715, .47, .26, .17))
for arm, color, name in (("two", ROLE_COLORS["Baseline"], "2-judge run"),
("three", ROLE_COLORS["Method"], "3-judge run")):
windows = review[arm]["quarters"]
x = [w["last_update"] for w in windows]
ax.plot(x, [100*w["correct"]/w["n"] for w in windows], "o-", color=color, lw=3, label=name+": exact")
ax.plot(x, [100*(w["rewarded_correct"]+w["rewarded_wrong"])/w["n"] for w in windows], "s--",
color=color, lw=2.5, label=name+": rewarded")
ax.set(ylim=(0, 100), xticks=x, xlabel="Last update in training quarter", ylabel="Sampled answers (%)")
ax.set_title(f"Training quarters · Qwen2.5-1.5B judges · seed {review['seed']}", loc="left",
fontsize=21, color=INK)
ax.legend(fontsize=15, frameon=False, ncol=2, loc="upper center", bbox_to_anchor=(.5, -.2))
ax.spines[["top", "right"]].set_visible(False)
frozen = data.get("newer_judges") or {}
if frozen.get("review"):
records = {r["key"]: r for r in frozen["results"]}
ax = fig.add_axes((.75, .235, .22, .11))
names = [records[k]["model"] for k in ("confirm-winner", "confirm-control")]
twins = [records[k]["metrics"]["twins"] for k in ("confirm-winner", "confirm-control")]
for offset, field, shade in ((-.2, "visible", ROLE_COLORS["Method"]),
(.2, "masked", ROLE_COLORS["Control"])):
ax.barh([i+offset for i in range(2)], [100*t[field]/t["n"] for t in twins], height=.38, color=shade,
label=f"evidence {field}")
for i, t in enumerate(twins):
ax.text(100*t[field]/t["n"]+1, i+offset, f"{t[field]}/{t['n']}", va="center", fontsize=15)
ax.set(yticks=[0, 1], xlim=(0, 100), xlabel="Evidence pairs fully audited by Judge 3 (%)")
ax.set_yticklabels(names)
ax.invert_yaxis()
ax.legend(fontsize=15, frameon=False, loc="lower right")
ax.set_title("Evidence audit: one number in Judge 2's report altered", loc="left", fontsize=21,
color=INK)
ax.spines[["top", "right"]].set_visible(False)
if review and review.get("credit_example"):
e = review["credit_example"]
ax = panel(fig, (.69, .03, .29, .14), f"Logged update {e['update']}: {e['expression']}", "", 16)
ax.text(0, .95, "\n".join(example_lines(e)) + "\nA: TRL group credit under each reward",
va="top", family="monospace", fontsize=17, transform=ax.transAxes)
fig.savefig(path, dpi=90)
plt.close(fig)
def walkthrough(review, gif, mp4):
"""Animate one real logged GRPO group: answers, checker, Judge 2 and Judge 3 rewards, TRL credit, whole run."""
plt = pyplot()
import imageio_ffmpeg
from matplotlib import animation, rcParams
from .domain import Problem
from .learning_review import execute_steps
from .paired_examples import explain_report
example = review["credit_example"]
steps = ",".join(map(str, execute_steps(Problem.from_expression(example["expression"]))))
labels = [int(s[1]) for s in example["samples"]]
second, third = ([s[column] for s in example["samples"]] for column in (2, 3))
advantages = [group_advantages(second), group_advantages(third)]
def paid(bits, wanted):
return f"{sum(b for b, y in zip(bits, labels, strict=True) if y == wanted)}/{labels.count(wanted)}"
stages = ("Problem", "Solver", "Checker", "Judge 2", "Judge 3", "GRPO credit", "Whole run")
captions = (f"Logged GRPO update {example['update']} of the three-judge run with Qwen2.5-1.5B-Instruct judges. "
f"Exact steps: {steps}.",
f"The solver samples {len(labels)} answers to the same problem.",
"The exact integer checker grades every step. It is not the reward in this run.",
f"Judge 2, which reviews Judge 1, rewards {paid(second, 1)} correct and {paid(second, 0)} wrong answers.",
f"Judge 3 reviews Judge 2 and rewards {paid(third, 1)} correct and {paid(third, 0)} wrong answers. "
"Judge 3's verdict is the reward.",
"TRL credit = (r − mean) / (sd + 0.0001) within the group of four.",
fill(f"Across all {review['groups']} updates, Judge 3 fixed {review['fixes']} of Judge 2's verdicts and "
f"spoiled {review['harms']}. Paying Judge 2's verdict instead would have changed the relative "
f"credit in {review['changed_groups']}/{review['groups']} updates.", 110))
headers = ("Solver wrote", "Checker", "Judge 2 says", "Judge 3 says", "Credit if J2 paid", "Credit J3 paid")
columns = (0, 1, 2, 3, 4, 6, 6)
good, bad = "#2f7a39", ACCENT
fig = plt.figure(figsize=(12.8, 7.2), facecolor="white")
def draw(stage):
fig.clear()
fig.text(.04, .92, example["expression"], fontsize=30, weight="bold", color=INK)
fig.text(.04, .855 if stage < 6 else .82, captions[stage], fontsize=14.5, color="#244")
for i, name in enumerate(stages):
fig.text(.04+.135*i, .74, name, fontsize=13, weight="bold",
color=bad if i == stage else ("#9ab" if i > stage else INK))
shown = columns[stage]
for j, header in enumerate(headers[:shown]):
fig.text(.06+.15*j, .65, header, fontsize=13, weight="bold", color=INK)
for i, (answer, label, j2, j3) in enumerate(example["samples"]):
sign = [(a[i] > 0) == bool(label) or abs(a[i]) < 1e-9 for a in advantages]
cells = [(answer, INK), ("correct" if label else "wrong", INK),
(str(j2), good if j2 == label else bad), (str(j3), good if j3 == label else bad),
(f"{advantages[0][i]:+.2f}", good if sign[0] else bad),
(f"{advantages[1][i]:+.2f}", good if sign[1] else bad)]
for j, (value, color) in enumerate(cells[:shown]):
fig.text(.06+.15*j, .55-.1*i, value, fontsize=19, family="monospace", color=color)
if stage in (3, 4):
report = example["reports"][0][stage-3]
meaning = explain_report(report, stage-1, example["samples"][0][stage-1]).split("<br>")[0]
fig.text(.06, .1, fill(f"First answer: Judge {stage-1} wrote {report}. {meaning}", 125),
fontsize=12, color="#355")
if stage >= 3:
fig.text(.06, .035, "Green: agrees with the exact checker (reward) or has the right sign (credit). "
"Orange: disagrees.", fontsize=11.5, color="#556")
sequence = [stage for stage in range(len(stages)) for _ in range(5)] + [len(stages)-1]*5
movie = animation.FuncAnimation(fig, draw, frames=sequence, interval=500)
movie.save(gif, writer=animation.PillowWriter(fps=2))
# imageio-ffmpeg ships a static ffmpeg binary; yuv420p keeps the H.264 file playable in browsers.
rcParams["animation.ffmpeg_path"] = imageio_ffmpeg.get_ffmpeg_exe()
movie.save(mp4, writer=animation.FFMpegWriter(fps=2, codec="libx264", extra_args=["-pix_fmt", "yuv420p"]))
plt.close(fig)
def draw_all(table, data, dest):
"""Draw what the evidence supports and delete outputs whose inputs are absent, so stale media never linger."""
architecture(dest/"architecture.png")
scored = any(r["correct"] is not None for r in table)
if scored:
twitter_card(table, data, dest/"twitter-summary.png")
poster(table, data, dest/"poster.png", dest/"architecture.png")
review = (data.get("depth_review") or [{}])[0] or {}
example = review.get("credit_example")
if example:
walkthrough(review, dest/"walkthrough.gif", dest/"walkthrough.mp4")
for name, available in (("twitter-summary.png", scored), ("poster.png", scored),
("walkthrough.gif", example), ("walkthrough.mp4", example)):
if not available:
(dest/name).unlink(missing_ok=True)