File size: 9,903 Bytes
f45837e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Render the rubric library + experiment metrics as one self-contained page.

    python3 make_browser.py --out browser.html

Everything inlined -- no server, no fetches: open the file. Regenerate after
any pipeline run; the page states which corpus and truth source produced each
number so a stale copy cannot masquerade as current.
"""

from __future__ import annotations

import argparse
import html
import json
import re
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent

CSS = """
body{font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;margin:0;background:#0f1115;color:#e6e6e6}
header{padding:24px 32px;background:#161a22;border-bottom:1px solid #2a2f3a}
h1{margin:0 0 6px;font-size:22px} .sub{color:#9aa4b2;font-size:13px}
main{max-width:1100px;margin:0 auto;padding:24px 32px}
h2{font-size:17px;border-bottom:1px solid #2a2f3a;padding-bottom:6px;margin-top:36px}
table{border-collapse:collapse;width:100%;font-size:13px;margin:12px 0}
th,td{border:1px solid #2a2f3a;padding:6px 10px;text-align:left}
th{background:#161a22} .good{color:#7ee08a} .bad{color:#ff7d7d} .warn{color:#ffd479}
.note{color:#9aa4b2;font-size:12px;margin:4px 0 16px}
details{border:1px solid #2a2f3a;border-radius:6px;margin:8px 0;background:#141822}
summary{cursor:pointer;padding:10px 14px;font-size:14px}
summary .cls{display:inline-block;min-width:170px;color:#8ab4ff}
summary .prov{float:right;color:#9aa4b2;font-size:12px}
.body{padding:0 18px 14px;font-size:13px;line-height:1.5}
.body pre{background:#0b0d12;border:1px solid #232838;border-radius:4px;padding:10px;overflow-x:auto;font-size:12px}
.body code{color:#ffd479}
.filter{margin:12px 0}
.filter button{background:#161a22;color:#e6e6e6;border:1px solid #2a2f3a;border-radius:4px;padding:4px 10px;margin-right:6px;cursor:pointer;font-size:12px}
.filter button.on{background:#2a3550;border-color:#8ab4ff}
"""

JS = """
function filt(cls,btn){
  document.querySelectorAll('.filter button').forEach(b=>b.classList.remove('on'));
  btn.classList.add('on');
  document.querySelectorAll('details.rubric').forEach(d=>{
    d.style.display=(cls==='all'||d.dataset.cls===cls)?'':'none';});
}
"""


def md_to_html(text: str) -> str:
    """Just enough markdown for these rubric files."""
    out, in_code = [], False
    for line in text.splitlines():
        if line.strip().startswith("```"):
            out.append("</pre>" if in_code else "<pre>")
            in_code = not in_code
            continue
        if in_code:
            out.append(html.escape(line))
            continue
        esc = html.escape(line)
        esc = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", esc)
        esc = re.sub(r"`([^`]+)`", r"<code>\1</code>", esc)
        if esc.startswith("### "):
            esc = f"<h3>{esc[4:]}</h3>"
        elif esc.strip().startswith("- "):
            esc = f"<div style='margin-left:1em'>&bull; {esc.strip()[2:]}</div>"
        elif re.match(r"^\s+\d+\.", esc):
            esc = f"<div style='margin-left:2em'>{esc.strip()}</div>"
        out.append(esc)
    return "\n".join(out)


def load_json(path: Path):
    try:
        return json.loads(path.read_text())
    except (OSError, json.JSONDecodeError):
        return None


def fmt(v, pct=False):
    if v is None:
        return "&mdash;"
    return f"{v:.1%}" if pct else f"{v:.3f}"


def metrics_section() -> str:
    pr = load_json(HERE / "data" / "pr_results.json")
    assist = load_json(HERE / "data" / "assist_results.json")
    cf = load_json(HERE / "data" / "counterfactual.json")
    truth_rep = load_json(HERE / "data" / "truth_report.json")
    parts = ["<h2>Experiment metrics</h2>"]

    if pr:
        parts.append(f"<div class=note>truth source: {html.escape(pr.get('truth_source','?'))} "
                     f"&middot; {pr.get('decisions','?')} blind decisions across "
                     f"{len(pr.get('eval_competitions',[]))} held-out competitions</div>")
        rows = ["<table><tr><th>family</th><th>precision</th><th>95% CI</th>"
                "<th>recall</th><th>95% CI</th><th>tp/fp/fn</th></tr>"]
        for fam in ("conceptual", "control_generic", "control_shuffled",
                    "control_conceptual"):
            m = (pr.get("by_family") or {}).get(fam)
            if not m:
                continue
            cls = "good" if fam == "conceptual" else "warn"
            rows.append(
                f"<tr><td class={cls}>{fam}</td>"
                f"<td>{fmt(m.get('precision'))}</td><td>{m.get('precision_ci95') or '&mdash;'}</td>"
                f"<td>{fmt(m.get('recall'))}</td><td>{m.get('recall_ci95') or '&mdash;'}</td>"
                f"<td>{m.get('tp')}/{m.get('fp')}/{m.get('fn')}</td></tr>")
        rows.append("</table>")
        parts.append("".join(rows))
        parts.append("<div class=note>Controls are the floor: vague criticism and "
                     "domain-swapped rubrics score zero precision; whatever the real "
                     "rubrics score above that is earned signal.</div>")
    if truth_rep:
        parts.append(f"<div class=note>ground-truth annotator agreement: "
                     f"{fmt(truth_rep.get('annotator_agreement_per_group'), pct=True)} per group of "
                     f"{truth_rep.get('annotation_batch','?')} (reference protocol reports 97%)</div>")

    if assist:
        p = assist.get("paired") or {}
        parts.append("<h2>Utility: does giving the rubrics to a coding agent help?</h2>")
        parts.append(
            f"<table><tr><th>paired states</th><th>guided better</th><th>revise better</th>"
            f"<th>ties</th><th>mean advantage</th><th>median advantage</th></tr>"
            f"<tr><td>{p.get('paired_states','&mdash;')}</td>"
            f"<td class=good>{p.get('guided_better','&mdash;')}</td>"
            f"<td class=bad>{p.get('revise_better','&mdash;')}</td>"
            f"<td>{p.get('ties','&mdash;')}</td>"
            f"<td>{fmt(p.get('mean_paired_advantage'), pct=True)}</td>"
            f"<td>{fmt(p.get('median_paired_advantage'), pct=True)}</td></tr></table>")
        parts.append("<div class=note>guided = revision with retrieved rubrics; revise = "
                     "same revision without them (the control). The rubrics' contribution "
                     "is the difference, paired on the same starting program.</div>")

    if cf:
        parts.append("<h2>Causal: does removing the flagged pattern improve the score?</h2>")
        parts.append(
            f"<table><tr><th>fires measured</th><th>improved</th><th>causal precision</th>"
            f"<th>mean improvement</th><th>outcomes</th></tr>"
            f"<tr><td>{cf.get('measured')}</td><td>{cf.get('helped')}</td>"
            f"<td>{fmt(cf.get('causal_precision'))}</td>"
            f"<td>{cf.get('mean_improvement')}</td>"
            f"<td>{html.escape(json.dumps(cf.get('outcomes', {})))}</td></tr></table>")
        parts.append("<div class=note>Patch out exactly what the rubric flagged, re-run, "
                     "re-grade against the official answers. Failed edits are excluded "
                     "from the denominator; they are facts about the editor.</div>")
    return "\n".join(parts)


def rubric_section() -> str:
    files = sorted((HERE / "out" / "conceptual").glob("*.md"))
    classes = sorted({f.name.split("__")[0].upper() for f in files})
    buttons = ["<div class=filter><button class=on onclick=\"filt('all',this)\">all "
               f"({len(files)})</button>"]
    for cls in classes:
        n = sum(1 for f in files if f.name.split("__")[0].upper() == cls)
        buttons.append(f"<button onclick=\"filt('{cls}',this)\">{cls} ({n})</button>")
    buttons.append("</div>")

    cards = []
    lib = {}
    for row in (load_json(HERE / "data" / "conceptual_applicable.jsonl") or []):
        pass  # jsonl, not json -- handled below
    try:
        for line in (HERE / "data" / "conceptual_applicable.jsonl").read_text().splitlines():
            if line.strip():
                r = json.loads(line)
                lib[r["id"]] = r
    except OSError:
        pass

    for f in files:
        cls = f.name.split("__")[0].upper()
        text = f.read_text()
        title = re.search(r"### P1 — (.+)", text)
        cand = lib.get(f.stem.rsplit("__", 1)[-1], {})
        prov = cand.get("provenance", "")
        eff = cand.get("measured_effect")
        prov_txt = prov + (f" &middot; effect {eff:+.4f}" if eff is not None else "")
        cards.append(
            f"<details class=rubric data-cls='{cls}'>"
            f"<summary><span class=cls>{cls} &middot; {html.escape(f.name.split('__')[1])}</span> "
            f"{html.escape(title.group(1) if title else f.name)}"
            f"<span class=prov>{prov_txt}</span></summary>"
            f"<div class=body>{md_to_html(text)}</div></details>")
    return ("<h2>Rubric library (conceptual / performance errors)</h2>"
            + "".join(buttons) + "\n" + "\n".join(cards))


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--out", default=str(HERE / "browser.html"))
    args = ap.parse_args()

    n = len(list((HERE / "out" / "conceptual").glob("*.md")))
    page = f"""<!doctype html><html><head><meta charset=utf-8>
<title>rubric_gen — conceptual rubric library</title><style>{CSS}</style>
<script>{JS}</script></head><body>
<header><h1>Conceptual rubric library &amp; experiment metrics</h1>
<div class=sub>{n} rubrics &middot; split rubric-gen-full75-v1 (15 train / 60 eval)
&middot; generated {time.strftime('%F %T UTC', time.gmtime())} &middot; regenerate with
<code>python3 make_browser.py</code></div></header>
<main>{metrics_section()}{rubric_section()}</main></body></html>"""
    Path(args.out).write_text(page)
    print(f"{n} rubrics + metrics -> {args.out}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())