File size: 5,991 Bytes
d428e08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render the Llama LR sweep figure (paper fig 8).

ΔAccuracy of the restored adapter vs the quantized baseline, per learning
rate. Zero line is the "no effect" reference — below zero = restoration
made it worse. The figure is laid out so the story ("lower LR recovers
more of the gap") reads in one pass.
"""

import argparse
import json
import os
import re
import sys

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

mpl.rcParams.update({
    "font.family": "sans-serif",
    "font.sans-serif": ["Inter", "Helvetica Neue", "Arial", "DejaVu Sans"],
    "font.size": 9,
    "axes.labelsize": 10,
    "xtick.labelsize": 8.5,
    "ytick.labelsize": 8.5,
    "legend.fontsize": 8,
    "legend.frameon": False,
    "figure.dpi": 200,
    "savefig.dpi": 400,
    "savefig.bbox": "tight",
    "pdf.fonttype": 42,
    "ps.fonttype": 42,
    "axes.linewidth": 0.7,
    "axes.spines.top": False,
    "axes.spines.right": False,
})

LR_PARSE = re.compile(r"^lr(.+)$")
METHOD_COLOR = {"awq_w4": "#4E79A7", "gptq_w4": "#E15759", "bnb_nf4_w4": "#59A14F"}
GAIN = "#2E7D32"
LOSS = "#C03A2B"


def _load_outcomes(jsonl):
    if not os.path.exists(jsonl):
        return None
    out = {}
    with open(jsonl) as f:
        for line in f:
            t = json.loads(line)
            out[t["problem_id"]] = 1.0 if t.get("is_correct_final") else 0.0
    return out


def paired_delta_ci(base_out, rest_out, n_boot=5000):
    ids = sorted(set(base_out) & set(rest_out))
    if not ids:
        return None
    b = np.array([base_out[i] for i in ids])
    r = np.array([rest_out[i] for i in ids])
    n = len(ids)
    rng = np.random.default_rng(0)
    deltas = np.empty(n_boot)
    for i in range(n_boot):
        idx = rng.integers(0, n, size=n)
        deltas[i] = r[idx].mean() - b[idx].mean()
    obs = float(r.mean() - b.mean())
    return obs * 100, float(np.percentile(deltas, 2.5)) * 100, float(np.percentile(deltas, 97.5)) * 100


def _tag_to_lr(tag: str) -> float:
    # lr5e_5 -> 5e-5 etc. The sweep script encodes "." as "_" and "-" as "_".
    s = tag.replace("__", "-").replace("_", "-")
    try:
        return float(s)
    except ValueError:
        return float("nan")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--sweep-root", required=True)
    parser.add_argument("--model", required=True)
    parser.add_argument("--quant", required=True)
    parser.add_argument("--benchmark", required=True)
    parser.add_argument("--metrics", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    base_diag = os.path.join("results", "diagnosis", args.quant, args.model,
                              f"{args.benchmark}_run0.jsonl")
    base_out = _load_outcomes(base_diag)
    if base_out is None:
        print(f"  [ERROR] base diagnosed jsonl missing: {base_diag}")
        return

    rows = []
    for entry in sorted(os.listdir(args.sweep_root)):
        m = LR_PARSE.match(entry)
        if not m:
            continue
        diag = os.path.join(args.sweep_root, entry, "diagnosis",
                            f"{args.benchmark}_run0.jsonl")
        rest_out = _load_outcomes(diag)
        if rest_out is None:
            continue
        ci = paired_delta_ci(base_out, rest_out)
        if ci is None:
            continue
        lr_val = _tag_to_lr(m.group(1))
        rows.append((lr_val, ci))

    if not rows:
        print("No LR sweep data found.")
        return

    rows.sort(key=lambda r: r[0])
    lrs    = [r[0] for r in rows]
    deltas = [r[1][0] for r in rows]
    los    = [r[1][1] for r in rows]
    his    = [r[1][2] for r in rows]

    fig, ax = plt.subplots(figsize=(5.3, 3.2), constrained_layout=True)

    # Shade the "below-zero = regression" region in a faint red.
    ys_needed = deltas + los + his + [0]
    ymin, ymax = min(ys_needed) - 3, max(ys_needed) + 4
    ax.axhspan(ymin, 0, color=LOSS, alpha=0.06, zorder=0)
    ax.axhspan(0, ymax, color=GAIN, alpha=0.06, zorder=0)

    # Zero reference line.
    ax.axhline(0, color="#555555", linewidth=0.8, zorder=1)

    x = np.arange(len(lrs))
    for i, (d, lo, hi) in enumerate(zip(deltas, los, his)):
        color = GAIN if d >= 0 else LOSS
        ax.plot([x[i], x[i]], [lo, hi], color=color, linewidth=1.4, alpha=0.6,
                zorder=2, solid_capstyle="butt")
        ax.plot(x[i], d, "o", markersize=8, color=color, markeredgecolor="white",
                markeredgewidth=1.2, zorder=3)
        ax.annotate(f"{d:+.1f} pp", xy=(x[i], d), xytext=(0, 12 if d >= 0 else -16),
                    textcoords="offset points", ha="center",
                    va="bottom" if d >= 0 else "top",
                    fontsize=9.5, color=color, fontweight="bold")

    # Edge-of-plot labels for the shaded regions.
    ax.text(-0.45, ymax * 0.92, "restoration helps",
            ha="left", va="top", fontsize=8, color=GAIN,
            style="italic")
    ax.text(-0.45, ymin + 0.5, "restoration hurts",
            ha="left", va="bottom", fontsize=8, color=LOSS,
            style="italic")

    ax.set_xticks(x)
    ax.set_xticklabels([f"{lr:g}" for lr in lrs])
    ax.set_xlabel("QLoRA learning rate")
    ax.set_ylabel(r"$\Delta$Accuracy vs. quantized baseline  (pp)")
    ax.yaxis.grid(True, linewidth=0.4, color="#DDDDDD")
    ax.set_axisbelow(True)
    ax.set_ylim(ymin, ymax)
    ax.set_xlim(-0.55, len(lrs) - 0.45)

    pretty_quant = {"awq_w4": "AWQ w4", "gptq_w4": "GPTQ w4", "bnb_nf4_w4": "BnB NF4"}.get(args.quant, args.quant)
    ax.text(1.0, 1.02, f"{args.model} · {pretty_quant} · {args.benchmark}",
            transform=ax.transAxes, ha="right", va="bottom",
            fontsize=8, color="#555")

    os.makedirs(os.path.dirname(args.output), exist_ok=True)
    fig.savefig(args.output)
    plt.close(fig)
    print(f"  Paper fig 8 (Llama LR sweep) saved: {args.output}")


if __name__ == "__main__":
    main()