File size: 19,862 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
"""
StepProbe: Paper Figure Generation

Generates all figures for the paper:
    1. Step Survival Rate (SSR) curves
    2. Error Type Distribution heatmap
    3. First Failure Step (FFS) distributions
    4. Accuracy vs. bit-width degradation
    5. Error Cascade Rate by model size
    6. Restoration before/after comparison
"""

import json
import os
import sys
import glob
from typing import List, Dict

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({
    "font.family": "sans-serif",
    "font.size": 11,
    "axes.titlesize": 13,
    "axes.labelsize": 12,
    "xtick.labelsize": 10,
    "ytick.labelsize": 10,
    "legend.fontsize": 10,
    "figure.dpi": 150,
    "savefig.dpi": 300,
    "savefig.bbox": "tight",
})

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from stepprobe.utils import load_json


# Color palette (colorblind-friendly)
# Paired palette: the "restored" variant shares a hue with its base so the
# eye can pair them instantly. Base = saturated, restored = desaturated.
COLORS = {
    "fp16":                  "#1F4E79",  # navy — reference
    "awq_w4":                "#A23B72",
    "awq_w4_restored":       "#D9A9C4",
    "gptq_w4":               "#C73E1D",
    "gptq_w4_restored":      "#EFB4A6",
    "bnb_nf4_w4":            "#0B7A75",
    "bnb_nf4_w4_restored":   "#8FC8C5",
}

ERROR_COLORS = {
    "conceptual":    "#2E86AB",
    "methodological": "#A23B72",
    "executional":   "#F18F01",
    "logical":       "#C73E1D",
}

# Canonical ordering so paired (base, restored) bars always sit next to each
# other and colors line up across figures.
QUANT_ORDER = [
    "awq_w4", "awq_w4_restored",
    "gptq_w4", "gptq_w4_restored",
    "bnb_nf4_w4", "bnb_nf4_w4_restored",
]


def _pretty_label(q: str) -> str:
    """Short, lowercase-friendly label: 'gptq_w4_restored' -> 'GPTQ w4 (restored)'."""
    if q.endswith("_restored"):
        base = q[: -len("_restored")]
        return f"{_pretty_label(base)} (restored)"
    if q == "bnb_nf4_w4":
        return "BnB NF4"
    if q == "fp16":
        return "FP16"
    parts = q.split("_w")
    if len(parts) == 2 and parts[1].isdigit():
        return f"{parts[0].upper()} w{parts[1]}"
    return q


def _sorted_results(results):
    """Return results ordered by QUANT_ORDER so figures are consistent."""
    order = {q: i for i, q in enumerate(QUANT_ORDER)}
    return sorted(results, key=lambda r: order.get(r.get("quantization", ""), 999))


BENCHMARKS_KNOWN = ("gsm8k", "math500", "gpqa")


def _benchmark_from_filename(fname: str) -> str:
    """Extract the benchmark from a metrics filename.

    Filenames written by stepprobe.metrics look like
      {model}_{quant}_{benchmark}_run{N}_metrics.json
    and both model and quant contain underscores, so we match the benchmark
    by a known-values list rather than by position.
    """
    import re
    for bench in BENCHMARKS_KNOWN:
        if re.search(rf"_{bench}_run\d+_metrics\.json$", fname):
            return bench
    return "unknown"


def load_all_metrics(metrics_dir: str) -> List[dict]:
    """Load all metrics JSON files from a directory, annotating each with its benchmark."""
    results = []
    for f in sorted(glob.glob(os.path.join(metrics_dir, "*_metrics.json"))):
        data = load_json(f)
        data["benchmark"] = _benchmark_from_filename(os.path.basename(f))
        results.append(data)
    return results


def fig1_ssr_curves(results: List[dict], output_path: str, title_suffix: str = ""):
    """
    Figure 1: Step Survival Rate curves.
    Base quants drawn solid, restored variants drawn dashed in the same hue.
    """
    fig, ax = plt.subplots(figsize=(8.5, 5.2))

    for r in _sorted_results(results):
        quant = r.get("quantization", "")
        ssr = r.get("ssr_curve", [])
        if not ssr:
            continue
        color = COLORS.get(quant, "#888888")
        is_restored = quant.endswith("_restored")
        ax.plot(
            range(len(ssr)), ssr,
            label=_pretty_label(quant),
            color=color,
            linewidth=2.0 if not is_restored else 2.0,
            linestyle="--" if is_restored else "-",
            alpha=0.95,
        )

    ax.set_xlabel("Reasoning step depth")
    ax.set_ylabel("Fraction of runs still correct")
    title = "Step survival — how reasoning degrades with depth"
    if title_suffix:
        title = f"{title}\n{title_suffix}"
    ax.set_title(title)
    ax.set_ylim(0, 1.05)
    ax.legend(loc="upper right", frameon=True, framealpha=0.9, ncol=1)
    ax.grid(True, alpha=0.25)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)

    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 1 saved: {output_path}")


def fig2_error_type_heatmap(results: List[dict], output_path: str, title_suffix: str = ""):
    """
    Figure 2: Error type distribution per quantization.
    Paired base/restored rows so you can read "did restoration reduce the
    conceptual/logical error share?" at a glance.
    """
    error_types = ["conceptual", "methodological", "executional", "logical"]
    sorted_res = _sorted_results([r for r in results if r.get("error_type_dist")])
    if not sorted_res:
        print("  [SKIP] No error distribution data for heatmap")
        return

    quants = [r["quantization"] for r in sorted_res]
    data = np.array([[r["error_type_dist"].get(e, 0) for e in error_types] for r in sorted_res])

    fig, ax = plt.subplots(figsize=(7.5, 0.55 * len(quants) + 1.6))
    im = ax.imshow(data, cmap="YlOrRd", aspect="auto", vmin=0, vmax=max(0.6, data.max()))

    ax.set_xticks(range(len(error_types)))
    ax.set_xticklabels([e.capitalize() for e in error_types])
    ax.set_yticks(range(len(quants)))
    ax.set_yticklabels([_pretty_label(q) for q in quants])

    for i in range(len(quants)):
        for j in range(len(error_types)):
            val = data[i, j]
            color = "white" if val > 0.35 else "black"
            ax.text(j, i, f"{val:.0%}", ha="center", va="center", color=color, fontsize=10)

    title = "Error type distribution by quantization"
    if title_suffix:
        title = f"{title}\n{title_suffix}"
    ax.set_title(title)
    plt.colorbar(im, ax=ax, label="Fraction of errors", fraction=0.04, pad=0.04)
    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 2 saved: {output_path}")


def _plot_paired_bars(ax, results, value_fn, *, ylabel, percent=False):
    """Draw grouped (base, restored) bars for the three quant methods.

    Each method family (awq, gptq, bnb_nf4) gets one group on the x-axis.
    Within a group: two adjacent bars — base (darker) and restored (lighter).
    Bars are annotated with their numeric value.
    """
    families = [("awq_w4", "awq_w4_restored", "AWQ w4"),
                ("gptq_w4", "gptq_w4_restored", "GPTQ w4"),
                ("bnb_nf4_w4", "bnb_nf4_w4_restored", "BnB NF4")]
    by_q = {r.get("quantization", ""): r for r in results}

    x = np.arange(len(families))
    width = 0.36
    base_vals, restored_vals = [], []
    for base_q, rest_q, _ in families:
        base_vals.append(value_fn(by_q.get(base_q)))
        restored_vals.append(value_fn(by_q.get(rest_q)))

    base_colors = [COLORS.get(families[i][0], "#888888") for i in range(len(families))]
    rest_colors = [COLORS.get(families[i][1], "#BBBBBB") for i in range(len(families))]

    b1 = ax.bar(x - width / 2, base_vals, width, color=base_colors,
                edgecolor="white", linewidth=0.6, label="Quantized")
    b2 = ax.bar(x + width / 2, restored_vals, width, color=rest_colors,
                edgecolor="white", linewidth=0.6, label="Restored")

    def fmt(v):
        if v is None or (isinstance(v, float) and (v != v)):
            return ""
        return f"{v:.0%}" if percent else f"{v:.2f}"

    for bars, vals in ((b1, base_vals), (b2, restored_vals)):
        for bar, v in zip(bars, vals):
            if v is None:
                continue
            ax.text(bar.get_x() + bar.get_width() / 2,
                    bar.get_height() + (0.01 if percent else 0.02),
                    fmt(v), ha="center", va="bottom", fontsize=9)

    ax.set_xticks(x)
    ax.set_xticklabels([f[2] for f in families])
    ax.set_ylabel(ylabel)
    ax.grid(True, axis="y", alpha=0.25)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.legend(loc="best", frameon=True, framealpha=0.9)


def fig3_ffs_distribution(results: List[dict], output_path: str, title_suffix: str = ""):
    """Figure 3: First Failure Step — grouped (base, restored) bars per method."""
    fig, ax = plt.subplots(figsize=(8, 5))

    def get_ffs(r):
        if not r:
            return None
        v = r.get("avg_ffs", None)
        if v is None or v == float("inf"):
            return None
        return v

    _plot_paired_bars(ax, results, get_ffs, ylabel="Avg first failure step")

    title = "Where does reasoning first break? (higher = better)"
    if title_suffix:
        title = f"{title}\n{title_suffix}"
    ax.set_title(title)

    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 3 saved: {output_path}")


def fig4_accuracy_degradation(results: List[dict], fp16_acc: float, output_path: str, title_suffix: str = ""):
    """Figure 4: Accuracy — grouped (base, restored) bars per method, with FP16 line."""
    fig, ax = plt.subplots(figsize=(8, 5))

    def get_acc(r):
        return r.get("accuracy") if r else None

    _plot_paired_bars(ax, results, get_acc, ylabel="Accuracy", percent=True)

    if fp16_acc is not None:
        ax.axhline(y=fp16_acc, color=COLORS["fp16"], linestyle="--",
                   linewidth=1.5, alpha=0.8, label="FP16 reference")
        # Re-draw legend so the FP16 line is included.
        ax.legend(loc="best", frameon=True, framealpha=0.9)

    ax.set_ylim(0, max(1.0, (ax.get_ylim()[1] or 0) + 0.05))

    title = "Accuracy — quantized vs restored (higher = better)"
    if title_suffix:
        title = f"{title}\n{title_suffix}"
    ax.set_title(title)

    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 4 saved: {output_path}")


def fig5_cascade_rate(results: List[dict], output_path: str, title_suffix: str = ""):
    """Figure 5: Error Cascade Rate — grouped (base, restored) bars per method."""
    fig, ax = plt.subplots(figsize=(8, 5))

    def get_ecr(r):
        return r.get("ecr") if r else None

    _plot_paired_bars(ax, results, get_ecr, ylabel="Error cascade rate", percent=True)
    ax.set_ylim(0, 1.05)

    title = "Once reasoning breaks, how badly does it cascade? (lower = better)"
    if title_suffix:
        title = f"{title}\n{title_suffix}"
    ax.set_title(title)

    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 5 saved: {output_path}")


def fig6_restoration_comparison(before: dict, after: dict, output_path: str):
    """
    Figure 6: Before/after restoration for a single quantization method.
    Uses the paired colors from COLORS so the "before" and "after" bars match
    the hue used for that method in figs 3/4/5.
    """
    metrics = ["accuracy", "avg_ffs", "ecr"]
    labels = ["Accuracy", "Avg FFS\n(higher = better)", "ECR\n(lower = better)"]

    before_vals = [before.get(m, 0) for m in metrics]
    after_vals = [after.get(m, 0) for m in metrics]

    base_q = before.get("quantization", "gptq_w4")
    rest_q = after.get("quantization", f"{base_q}_restored")
    bar_colors = [COLORS.get(base_q, "#888888"), COLORS.get(rest_q, "#BBBBBB")]

    fig, axes = plt.subplots(1, 3, figsize=(12, 4))

    for i, (ax, label, bv, av) in enumerate(zip(axes, labels, before_vals, after_vals)):
        vals = [bv, av]
        bars = ax.bar([0, 1], vals, color=bar_colors, width=0.55, edgecolor="white")

        ax.set_xticks([0, 1])
        ax.set_xticklabels([_pretty_label(base_q), _pretty_label(rest_q)])
        ax.set_title(label)
        ax.grid(True, axis="y", alpha=0.25)
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)

        for bar, v in zip(bars, vals):
            fmt = f"{v:.1%}" if i != 1 else f"{v:.2f}"
            ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.01,
                    fmt, ha="center", va="bottom", fontsize=10)

    plt.suptitle(f"Restoration effect: {_pretty_label(base_q)}{_pretty_label(rest_q)}",
                 fontsize=13, y=1.02)
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"  Fig 6 saved: {output_path}")


def generate_all_figures(metrics_dir: str, output_dir: str, fp16_acc: float = 0.85,
                         model_filter: str = None, benchmark_filter: str = None):
    """Generate figures grouped by (model, benchmark).

    Each group produces one set of figures under output_dir/<model>/<benchmark>/
    so that the quantization lines/bars on each plot compare apples-to-apples
    (same model, same benchmark).

    If model_filter/benchmark_filter are set, only matching groups are rendered.
    """
    from collections import defaultdict

    os.makedirs(output_dir, exist_ok=True)

    results = load_all_metrics(metrics_dir)
    if not results:
        print("No metrics found. Run the evaluation pipeline first.")
        print(f"  Expected: {metrics_dir}/*_metrics.json")
        return

    print(f"Loaded {len(results)} metric files")

    # Group by (model, benchmark). Without grouping, a single figure mixed
    # together entries from every model and every benchmark and was unreadable.
    groups = defaultdict(list)
    for r in results:
        model = r.get("model", "unknown") or "unknown"
        bench = r.get("benchmark", "unknown") or "unknown"
        if model_filter and model != model_filter:
            continue
        if benchmark_filter and bench != benchmark_filter:
            continue
        groups[(model, bench)].append(r)

    if not groups:
        print("No metric files matched the given --model/--benchmark filters.")
        return

    for (model, bench), group in sorted(groups.items()):
        subdir = os.path.join(output_dir, model, bench)
        os.makedirs(subdir, exist_ok=True)
        suffix = f"{model} · {bench}"
        print(f"\n[{model} / {bench}] {len(group)} quant variants")

        fig1_ssr_curves(group, os.path.join(subdir, "fig1_ssr_curves.pdf"), title_suffix=suffix)
        fig2_error_type_heatmap(group, os.path.join(subdir, "fig2_error_heatmap.pdf"), title_suffix=suffix)
        fig3_ffs_distribution(group, os.path.join(subdir, "fig3_ffs_distribution.pdf"), title_suffix=suffix)
        fig4_accuracy_degradation(group, fp16_acc, os.path.join(subdir, "fig4_accuracy_degradation.pdf"), title_suffix=suffix)
        fig5_cascade_rate(group, os.path.join(subdir, "fig5_cascade_rate.pdf"), title_suffix=suffix)

        # Fig 6: before/after restoration within this (model, benchmark).
        for r in group:
            q = r.get("quantization", "")
            if not q.endswith("_restored"):
                continue
            base_q = q[: -len("_restored")]
            before = next((x for x in group if x.get("quantization") == base_q), None)
            if before:
                out = os.path.join(subdir, f"fig6_restoration_{base_q}.pdf")
                fig6_restoration_comparison(before, r, out)

    print(f"\nAll figures saved under {output_dir}/<model>/<benchmark>/")


# ============================================================
# Demo with synthetic data (for testing)
# ============================================================

def generate_demo_figures(output_dir: str):
    """Generate demo figures with synthetic data for testing the visualization."""
    os.makedirs(output_dir, exist_ok=True)

    # Synthetic results
    demo_results = [
        {
            "model": "DeepSeek-R1-Distill-Qwen-7B",
            "quantization": "awq_w4",
            "accuracy": 0.72,
            "accuracy_delta": -0.13,
            "avg_ffs": 3.2,
            "median_ffs": 3.0,
            "ffs_std": 1.8,
            "ecr": 0.78,
            "ssr_curve": [0.95, 0.88, 0.79, 0.68, 0.55, 0.45, 0.38, 0.32, 0.28, 0.25,
                          0.23, 0.21, 0.20, 0.19, 0.18, 0.17, 0.16, 0.15, 0.14, 0.13],
            "error_type_dist": {"conceptual": 0.12, "methodological": 0.25, "executional": 0.48, "logical": 0.15},
        },
        {
            "model": "DeepSeek-R1-Distill-Qwen-7B",
            "quantization": "awq_w3",
            "accuracy": 0.58,
            "accuracy_delta": -0.27,
            "avg_ffs": 2.1,
            "median_ffs": 2.0,
            "ffs_std": 1.3,
            "ecr": 0.89,
            "ssr_curve": [0.90, 0.75, 0.58, 0.42, 0.30, 0.22, 0.17, 0.14, 0.12, 0.10,
                          0.09, 0.08, 0.07, 0.06, 0.05, 0.05, 0.04, 0.04, 0.03, 0.03],
            "error_type_dist": {"conceptual": 0.28, "methodological": 0.22, "executional": 0.35, "logical": 0.15},
        },
        {
            "model": "DeepSeek-R1-Distill-Qwen-7B",
            "quantization": "gptq_w4",
            "accuracy": 0.74,
            "accuracy_delta": -0.11,
            "avg_ffs": 3.5,
            "median_ffs": 3.0,
            "ffs_std": 2.0,
            "ecr": 0.75,
            "ssr_curve": [0.96, 0.90, 0.82, 0.72, 0.60, 0.50, 0.42, 0.36, 0.31, 0.27,
                          0.24, 0.22, 0.20, 0.19, 0.18, 0.17, 0.16, 0.15, 0.14, 0.13],
            "error_type_dist": {"conceptual": 0.10, "methodological": 0.20, "executional": 0.55, "logical": 0.15},
        },
        {
            "model": "DeepSeek-R1-Distill-Qwen-7B",
            "quantization": "bnb_nf4",
            "accuracy": 0.70,
            "accuracy_delta": -0.15,
            "avg_ffs": 3.0,
            "median_ffs": 3.0,
            "ffs_std": 1.9,
            "ecr": 0.80,
            "ssr_curve": [0.94, 0.86, 0.76, 0.64, 0.52, 0.42, 0.35, 0.30, 0.26, 0.23,
                          0.21, 0.19, 0.18, 0.17, 0.16, 0.15, 0.14, 0.13, 0.12, 0.11],
            "error_type_dist": {"conceptual": 0.15, "methodological": 0.23, "executional": 0.45, "logical": 0.17},
        },
    ]

    fig1_ssr_curves(demo_results, os.path.join(output_dir, "fig1_ssr_curves.png"))
    fig2_error_type_heatmap(demo_results, os.path.join(output_dir, "fig2_error_heatmap.png"))
    fig3_ffs_distribution(demo_results, os.path.join(output_dir, "fig3_ffs_distribution.png"))
    fig4_accuracy_degradation(demo_results, 0.85, os.path.join(output_dir, "fig4_accuracy_degradation.png"))
    fig5_cascade_rate(demo_results, os.path.join(output_dir, "fig5_cascade_rate.png"))

    # Demo restoration
    before = demo_results[2]  # gptq_w4
    after = {"accuracy": 0.82, "avg_ffs": 5.1, "ecr": 0.45}
    fig6_restoration_comparison(before, after, os.path.join(output_dir, "fig6_restoration.png"))

    print(f"\nDemo figures saved to {output_dir}")


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Generate paper figures")
    parser.add_argument("--metrics", default=None, help="Metrics directory")
    parser.add_argument("--output", default="figures/", help="Output directory")
    parser.add_argument("--fp16-acc", type=float, default=0.85)
    parser.add_argument("--model", default=None, help="Only render figures for this model tag")
    parser.add_argument("--benchmark", default=None, help="Only render figures for this benchmark")
    parser.add_argument("--demo", action="store_true", help="Generate demo figures with synthetic data")
    args = parser.parse_args()

    if args.demo:
        generate_demo_figures(args.output)
    elif args.metrics:
        generate_all_figures(args.metrics, args.output, fp16_acc=args.fp16_acc,
                             model_filter=args.model, benchmark_filter=args.benchmark)
    else:
        print("Specify --metrics <dir> or --demo")