Spaces:
Sleeping
Sleeping
File size: 17,260 Bytes
3040767 | 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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | """
eval/plot_reliability.py β Publication-quality reliability / calibration diagrams.
Usage:
python eval/plot_reliability.py # uses baseline_results.json
python eval/plot_reliability.py --results path/to.json # custom results file
python eval/plot_reliability.py --prefix after_rl # changes output file prefix
Comparison helper (importable):
from eval.plot_reliability import plot_comparison
plot_comparison("eval/baseline_results.json", "eval/after_rl_results.json")
"""
import argparse
import json
import os
from pathlib import Path
from typing import Optional
import matplotlib
matplotlib.use("Agg") # non-interactive backend β works without a display
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import seaborn as sns
# ---------------------------------------------------------------------------
# Styling
# ---------------------------------------------------------------------------
sns.set_theme(style="whitegrid", context="paper", font_scale=1.2)
PALETTE = {
"bar": "#4C72B0", # Seaborn blue
"perfect": "#DD8452", # Warm orange diagonal
"gap_pos": "#55A868", # Green β overconfidentundershoot
"gap_neg": "#C44E52", # Red β underconfident
"bg": "#F8F9FA",
}
BIN_EDGES = np.linspace(0.0, 1.0, 11) # 10 bins: [0,.1), [.1,.2), β¦, [.9,1]
BIN_CENTRES = (BIN_EDGES[:-1] + BIN_EDGES[1:]) / 2
BIN_WIDTH = 0.09 # slightly narrower than the 0.1 spacing for readability
# ---------------------------------------------------------------------------
# Core: build calibration bins from a flat list of (confidence, correct) pairs
# ---------------------------------------------------------------------------
def build_bins(confidences: list, correctness: list) -> dict:
"""Return per-bin stats used by the reliability diagram."""
conf = np.array(confidences, dtype=float)
corr = np.array(correctness, dtype=float)
bin_acc, bin_conf, bin_count = [], [], []
for lo, hi in zip(BIN_EDGES[:-1], BIN_EDGES[1:]):
mask = (conf >= lo) & (conf < hi)
# last bin is inclusive on the right
if hi == 1.0:
mask = (conf >= lo) & (conf <= hi)
n = mask.sum()
bin_count.append(int(n))
bin_acc.append(float(corr[mask].mean()) if n > 0 else np.nan)
bin_conf.append(float(conf[mask].mean()) if n > 0 else np.nan)
return {
"bin_acc": np.array(bin_acc),
"bin_conf": np.array(bin_conf),
"bin_count": np.array(bin_count),
}
def compute_ece_from_bins(bins: dict) -> float:
counts = bins["bin_count"]
accs = bins["bin_acc"]
confs = bins["bin_conf"]
total = counts.sum()
if total == 0:
return float("nan")
ece = 0.0
for n, a, c in zip(counts, accs, confs):
if n > 0 and not np.isnan(a):
ece += (n / total) * abs(a - c)
return ece
# ---------------------------------------------------------------------------
# Single reliability diagram
# ---------------------------------------------------------------------------
def _draw_reliability(
ax: plt.Axes,
bins: dict,
ece: float,
title: str,
show_counts: bool = True,
):
"""Draw a reliability diagram onto ax."""
acc = bins["bin_acc"]
count = bins["bin_count"]
# ββ background & reference diagonal βββββββββββββββββββββββββββββββββββββ
ax.set_facecolor(PALETTE["bg"])
ax.plot([0, 1], [0, 1], "--", color=PALETTE["perfect"],
linewidth=1.8, label="Perfect calibration", zorder=3)
# ββ gap fill (miscalibration region) ββββββββββββββββββββββββββββββββββββ
for i, (c, a, n) in enumerate(zip(BIN_CENTRES, acc, count)):
if np.isnan(a) or n == 0:
continue
lo, hi = min(c, a), max(c, a)
color = PALETTE["gap_neg"] if a < c else PALETTE["gap_pos"]
ax.bar(c, hi - lo, bottom=lo, width=BIN_WIDTH * 0.98,
color=color, alpha=0.25, zorder=1)
# ββ accuracy bars ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
valid = ~np.isnan(acc)
bars = ax.bar(
BIN_CENTRES[valid], acc[valid],
width=BIN_WIDTH, color=PALETTE["bar"],
edgecolor="white", linewidth=0.6,
label="Observed accuracy", alpha=0.85, zorder=2,
)
# ββ count annotations on bars ββββββββββββββββββββββββββββββββββββββββββββ
if show_counts:
for bar, n in zip(bars, count[valid]):
h = bar.get_height()
if h > 0.05:
ax.text(bar.get_x() + bar.get_width() / 2,
h / 2, f"n={n}",
ha="center", va="center",
fontsize=7.5, color="white", fontweight="bold", zorder=5)
# ββ ECE badge ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ece_text = f"ECE = {ece:.4f}" if not np.isnan(ece) else "ECE = n/a"
ax.text(0.97, 0.04, ece_text,
transform=ax.transAxes,
ha="right", va="bottom",
fontsize=11, fontweight="bold",
bbox=dict(boxstyle="round,pad=0.35", fc="white", ec="#CCCCCC", alpha=0.9))
# ββ axes formatting βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ax.set_xlim(-0.02, 1.02)
ax.set_ylim(-0.02, 1.12)
ax.set_xlabel("Confidence (predicted probability)", fontsize=11)
ax.set_ylabel("Accuracy (fraction correct)", fontsize=11)
ax.set_title(title, fontsize=13, fontweight="bold", pad=10)
ax.set_xticks(BIN_EDGES)
ax.set_xticklabels([f"{e:.1f}" for e in BIN_EDGES], fontsize=8, rotation=45)
ax.legend(loc="upper left", fontsize=9, framealpha=0.9)
# ---------------------------------------------------------------------------
# High-level: single-results plotting
# ---------------------------------------------------------------------------
def extract_pairs(samples: list) -> tuple:
"""Return (confidences, correctness) from a list of sample dicts."""
confs, corrs = [], []
for s in samples:
if s.get("confidence") is not None and s.get("correct") is not None:
confs.append(float(s["confidence"]))
corrs.append(1 if s["correct"] else 0)
return confs, corrs
def plot_domain(
domain: str,
conditions: dict,
out_dir: Path,
prefix: str = "baseline",
):
"""One 2Γ3 sub-grid showing each difficulty level + aggregate for a domain."""
domain_conditions = {
k: v for k, v in conditions.items() if k.startswith(domain + "_")
}
if not domain_conditions:
print(f" ! No conditions found for domain '{domain}' β skipping.")
return
# collect aggregate pairs for the domain
agg_conf, agg_corr = [], []
per_diff = {}
for key, cond in sorted(domain_conditions.items()):
diff = int(key.split("_")[-1])
cf, cr = extract_pairs(cond.get("samples", []))
per_diff[diff] = (cf, cr)
agg_conf.extend(cf)
agg_corr.extend(cr)
n_diffs = len(per_diff)
# layout: difficulties in a row + 1 aggregate panel
ncols = n_diffs + 1
fig, axes = plt.subplots(1, ncols, figsize=(4 * ncols, 4.5))
fig.patch.set_facecolor("white")
for idx, (diff, (cf, cr)) in enumerate(sorted(per_diff.items())):
bins = build_bins(cf, cr)
ece = compute_ece_from_bins(bins)
_draw_reliability(
axes[idx], bins, ece,
title=f"{domain.capitalize()} β Difficulty {diff}",
)
# aggregate panel (last)
agg_bins = build_bins(agg_conf, agg_corr)
agg_ece = compute_ece_from_bins(agg_bins)
_draw_reliability(
axes[-1], agg_bins, agg_ece,
title=f"{domain.capitalize()} β All Difficulties",
)
fig.suptitle(
f"Baseline Calibration - {domain.capitalize()}",
fontsize=15, fontweight="bold", y=1.02,
)
fig.tight_layout()
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{prefix}_{domain}.png"
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f" β Saved {out_path}")
def plot_overall(
conditions: dict,
overall: dict,
out_dir: Path,
prefix: str = "baseline",
):
"""Aggregate diagram across ALL domains and a per-domain summary bar."""
all_conf, all_corr = [], []
domain_eces = {}
domain_accs = {}
for domain in ["math", "code", "logic"]:
d_conf, d_corr = [], []
for key, cond in conditions.items():
if key.startswith(domain + "_"):
cf, cr = extract_pairs(cond.get("samples", []))
d_conf.extend(cf)
d_corr.extend(cr)
all_conf.extend(cf)
all_corr.extend(cr)
if d_conf:
bins = build_bins(d_conf, d_corr)
domain_eces[domain] = compute_ece_from_bins(bins)
domain_accs[domain] = float(np.mean(d_corr)) if d_corr else 0.0
fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(14, 5))
fig.patch.set_facecolor("white")
# ββ left: overall reliability diagram βββββββββββββββββββββββββββββββββββ
overall_bins = build_bins(all_conf, all_corr)
overall_ece = compute_ece_from_bins(overall_bins)
_draw_reliability(ax_left, overall_bins, overall_ece,
title="Overall Reliability Diagram")
# ββ right: per-domain ECE + accuracy summary bar chart ββββββββββββββββββ
domains = list(domain_eces.keys())
x = np.arange(len(domains))
width = 0.35
ece_vals = [domain_eces[d] for d in domains]
acc_vals = [domain_accs[d] for d in domains]
bars1 = ax_right.bar(x - width / 2, acc_vals, width,
label="Accuracy", color="#4C72B0", alpha=0.85, edgecolor="white")
bars2 = ax_right.bar(x + width / 2, ece_vals, width,
label="ECE (lower=better)", color="#C44E52", alpha=0.85, edgecolor="white")
for bar, val in zip(list(bars1) + list(bars2), acc_vals + ece_vals):
ax_right.text(bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.01, f"{val:.2f}",
ha="center", fontsize=9, fontweight="bold")
ax_right.set_xticks(x)
ax_right.set_xticklabels([d.capitalize() for d in domains], fontsize=11)
ax_right.set_ylim(0, 1.15)
ax_right.set_ylabel("Score", fontsize=11)
ax_right.set_title("Per-Domain Summary: Accuracy vs ECE", fontsize=13,
fontweight="bold")
ax_right.legend(fontsize=10)
ax_right.set_facecolor(PALETTE["bg"])
fig.suptitle("Baseline Calibration - Overall", fontsize=15,
fontweight="bold", y=1.02)
fig.tight_layout()
out_path = out_dir / f"{prefix}_overall.png"
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f" β Saved {out_path}")
# ---------------------------------------------------------------------------
# Comparison: before vs after RL/SFT
# ---------------------------------------------------------------------------
def _collect_conditions_any_schema(results: dict) -> dict:
"""Return a flat ``{condition_key: condition_dict}`` regardless of which
schema the JSON uses.
Supported shapes:
* ``baseline_eval.py`` β ``{"conditions": {"math_1": {...}, ...}}``
* ``full_eval.py`` β ``{"in_distribution": {...}, "ood": {...}}``
(each value is a ``{condition_key: cond}`` map)
Keys from in-distribution conditions stay verbatim
(``math_1`` / ``code_3`` / β¦); OOD condition keys are prefixed with
``ood_`` so they don't collide with the math/code/logic namespace.
"""
out: dict = {}
if isinstance(results.get("conditions"), dict):
out.update(results["conditions"])
if isinstance(results.get("in_distribution"), dict):
out.update(results["in_distribution"])
if isinstance(results.get("ood"), dict):
for k, v in results["ood"].items():
out[f"ood_{k}"] = v
return out
def plot_comparison(
before_path: str,
after_path: str,
out_dir: Optional[str] = None,
output_path: Optional[str] = None,
label_before: str = "Before Training",
label_after: str = "After Training",
):
"""
Generate side-by-side overall reliability diagrams from two result JSON files.
Typically called after RL training to visualise improvement.
Robust to both ``baseline_results.json`` (top-level ``conditions``) and
``full_results.json`` (top-level ``in_distribution`` + ``ood``) schemas β
samples from any/all sections are aggregated for the diagram.
Args:
before_path: Baseline JSON.
after_path: Trained JSON.
out_dir: Optional directory; ignored if ``output_path`` is given.
output_path: Explicit PNG path. Takes precedence over ``out_dir``.
label_before/label_after: Panel titles.
Returns:
str: Path of the saved PNG.
"""
with open(before_path) as f:
before = json.load(f)
with open(after_path) as f:
after = json.load(f)
def _collect(results):
confs, corrs = [], []
for cond in _collect_conditions_any_schema(results).values():
cf, cr = extract_pairs(cond.get("samples", []))
confs.extend(cf)
corrs.extend(cr)
return confs, corrs
b_conf, b_corr = _collect(before)
a_conf, a_corr = _collect(after)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))
fig.patch.set_facecolor("white")
b_bins = build_bins(b_conf, b_corr)
a_bins = build_bins(a_conf, a_corr)
_draw_reliability(ax1, b_bins, compute_ece_from_bins(b_bins),
title=label_before, show_counts=False)
_draw_reliability(ax2, a_bins, compute_ece_from_bins(a_bins),
title=label_after, show_counts=False)
b_ece = compute_ece_from_bins(b_bins)
a_ece = compute_ece_from_bins(a_bins)
delta = b_ece - a_ece
sign = "β" if delta > 0 else "β"
fig.suptitle(
f"Calibration Comparison | ECE: {b_ece:.4f} β {a_ece:.4f} ({sign} {abs(delta):.4f})",
fontsize=13, fontweight="bold", y=1.02,
)
fig.tight_layout()
if output_path is not None:
out_path = Path(output_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
else:
_out_dir = Path(out_dir) if out_dir else Path(before_path).parent / "plots"
_out_dir.mkdir(parents=True, exist_ok=True)
out_path = _out_dir / "comparison.png"
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Comparison plot saved to {out_path}")
return str(out_path)
# ---------------------------------------------------------------------------
# CLI entry-point
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Generate reliability / calibration diagrams from eval results."
)
parser.add_argument(
"--results", default="eval/baseline_results.json",
help="Path to the results JSON (default: eval/baseline_results.json)",
)
parser.add_argument(
"--out-dir", default="eval/plots",
help="Output directory for PNG files (default: eval/plots)",
)
parser.add_argument(
"--prefix", default="baseline",
help="Filename prefix for output PNGs (default: baseline)",
)
args = parser.parse_args()
results_path = Path(args.results)
if not results_path.exists():
print(f"ERROR: {results_path} not found. Run baseline_eval.py first.")
return
with open(results_path) as f:
data = json.load(f)
conditions = _collect_conditions_any_schema(data)
if not conditions:
print(f"ERROR: {results_path} has no `conditions`, `in_distribution`, "
f"or `ood` sections to plot.")
return
overall = data.get("overall", {})
out_dir = Path(args.out_dir)
print(f"\nGenerating reliability diagrams from: {results_path}")
print(f"Output directory: {out_dir}\n")
domains = sorted({k.rsplit("_", 1)[0] for k in conditions})
for domain in domains:
print(f"Domain: {domain}")
plot_domain(domain, conditions, out_dir, prefix=args.prefix)
print("\nOverall:")
plot_overall(conditions, overall, out_dir, prefix=args.prefix)
print(f"\nDone! {len(domains) + 1} plots saved to {out_dir}/")
if __name__ == "__main__":
main()
|