File size: 16,824 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Generate the paper's LaTeX tables from results/ and a values manifest.

Every printed number is recorded in figures/table_values.json so that
experiments/check_numbers.py can verify it traces to a results file.
"""
from __future__ import annotations

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
RESULTS = ROOT / "results"
TABLES = ROOT / "paper" / "tables"
VALUES = ROOT / "figures" / "table_values.json"

PRETTY = {
    "clsa": "CLSA",
    "language_first": "Language-first",
    "dense_probe": "Dense probe",
    "sae_probe": "Probe-only SAE",
    "sae_probe_only": "Probe-only SAE",
    "behaviour_only": "Behaviour only",
    "consequence_rules": "Consequence rules",
    "uncertainty_only": "Uncertainty only",
    "abort_only": "Abort always",
    "external_verifier": "External verifier",
    "external_ttc": "External TTC",
    "clsa_no_dynamics": "CLSA, no dynamics",
    "clsa_no_evidence": "CLSA, no evidence",
    "clsa_naive_acquire": "CLSA, naive acquire",
    "clsa_no_admission": "CLSA, no admission split",
}


def load(name: str) -> dict | None:
    p = RESULTS / f"{name}.json"
    if not p.exists():
        return None
    try:
        return json.loads(p.read_text())["results"]
    except Exception:
        return None


def tex(s: str) -> str:
    """Escape text for LaTeX so policy names with underscores do not break maths mode."""
    for a, b in (("\\", "\\textbackslash{}"), ("_", "\\_"), ("%", "\\%"), ("&", "\\&"), ("#", "\\#")):
        s = s.replace(a, b)
    return s


def fmt(v, nd=3) -> str:
    if v is None:
        return "--"
    if isinstance(v, float):
        if v != v:  # nan
            return "--"
        return f"{v:.{nd}f}"
    return str(v)


def pending(what: str, label: str, caption: str) -> str:
    return (
        "\\begin{table}[h]\n\\centering\n"
        f"\\caption{{{caption}}}\n\\label{{{label}}}\n"
        f"\\pending{{{what}}}\n\\end{{table}}\n"
    )


def write_table(name: str, body: str) -> None:
    TABLES.mkdir(parents=True, exist_ok=True)
    (TABLES / f"{name}.tex").write_text(body, encoding="utf-8")
    print(f"wrote paper/tables/{name}.tex")


def t1_main(values: dict) -> None:
    r = load("e1_main")
    if not r:
        write_table("t1_main", pending("E1 not run", "tab:main", "Main comparison."))
        return
    order = [
        "clsa",
        "language_first",
        "dense_probe",
        "sae_probe",
        "behaviour_only",
        "consequence_rules",
        "uncertainty_only",
        "external_verifier",
        "clsa_no_dynamics",
        "clsa_no_evidence",
        "abort_only",
    ]
    keys = [k for k in order if k in r["per_policy"]]
    keys += [k for k in r["per_policy"] if k not in keys]
    rows = []
    vals = {}
    for k in keys:
        p = r["per_policy"][k]["point"]
        rows.append(
            f"{tex(PRETTY.get(k, k))} & {fmt(p.get('harm_rate'))} & {fmt(p.get('irreversible_rate'))} & "
            f"{fmt(p.get('success_rate'))} & {fmt(p.get('correct_rate'))} & "
            f"{fmt(p.get('abstain_rate'))} & {fmt(p.get('tokens_per_decision'), 0)} \\\\"
        )
        vals[k] = {m: p.get(m) for m in ("harm_rate", "irreversible_rate", "success_rate", "correct_rate", "abstain_rate", "tokens_per_decision")}
    values["t1_main"] = vals
    comparisons = []
    for base, c in (r.get("paired_vs_clsa") or {}).items():
        h = c.get("harm_rate", {})
        comparisons.append(
            f"{tex(PRETTY.get(base, base))} & {fmt(h.get('diff'))} & "
            f"[{fmt(h.get('lo'))}, {fmt(h.get('hi'))}] \\\\"
        )
        values[f"t1_paired_{base}"] = {"diff": h.get("diff"), "lo": h.get("lo"), "hi": h.get("hi")}
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}lrrrrrr@{}}\n\\toprule\n"
        "Policy & Harm & Irrev. & Success & Correct & Abstain & Tokens \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        f"\\caption{{E1: decision-level comparison on {r.get('n_states')} held-out states "
        f"({', '.join(r.get('splits', []))}), backbone \\texttt{{{r.get('backbone','')}}}. "
        "Harm and irreversibility are state-verified by fork replay; tokens are charged per decision.}\n"
        "\\label{tab:main}\n\\end{table}\n"
    )
    write_table("t1_main", body)
    if comparisons:
        body2 = (
            "\\begin{table}[h]\n\\centering\n\\small\n"
            "\\begin{tabular}{@{}lrr@{}}\n\\toprule\n"
            "Baseline & $\\Delta$ harm (CLSA $-$ baseline) & 95\\% CI \\\\\n\\midrule\n"
            + "\n".join(comparisons)
            + "\n\\bottomrule\n\\end{tabular}\n"
            "\\caption{Paired differences against CLSA, bootstrapped over episodes "
            "(2{,}000 resamples). Negative is better for CLSA.}\n"
            "\\label{tab:paired}\n\\end{table}\n"
        )
        write_table("t1_paired", body2)


def t2_world_model(values: dict) -> None:
    r = load("e2_world_model")
    if not r or not r.get("horizons"):
        write_table("t2_world_model", pending("E2 not run", "tab:world", "World-model quality."))
        return
    rows = []
    vals = {}
    for h, d in sorted(r["horizons"].items()):
        mse = d.get("mse", {})
        rows.append(
            f"{h} & {d.get('n')} & {fmt(mse.get('text'), 4)} & {fmt(mse.get('belief'), 4)} & "
            f"{fmt(mse.get('evidence'), 4)} & {fmt(mse.get('image'), 4)} & "
            f"{fmt(mse.get('tool_state'), 4)} \\\\"
        )
        vals[h] = {"n": d.get("n"), **{f"mse_{k}": v for k, v in mse.items()}}
    values["t2_world_model"] = vals
    values["t2_scores"] = {
        "cf_consistency": r.get("cf_consistency"),
        "cf_brier": r.get("cf_brier"),
        "hallucinated_world_rate": r.get("hallucinated_world_rate"),
        "predicted_harm_mean": r.get("predicted_harm_mean"),
        "observed_harm_rate": r.get("observed_harm_rate"),
    }
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}rrrrrrr@{}}\n\\toprule\n"
        "Horizon & $n$ & Text & Belief & Evidence & Image & Tool \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        "\\caption{E2: one-step and multi-step latent prediction error (MSE) by modality block, "
        f"on {r.get('n_transitions')} held-out transitions. "
        f"Counterfactual consistency {fmt(r.get('cf_consistency'))}, Brier {fmt(r.get('cf_brier'))}; "
        f"predicted harm {fmt(r.get('predicted_harm_mean'))} against observed "
        f"{fmt(r.get('observed_harm_rate'))}.}}\n"
        "\\label{tab:world}\n\\end{table}\n"
    )
    write_table("t2_world_model", body)


def t3_budget(values: dict) -> None:
    r = load("e3_budget")
    if not r:
        write_table("t3_budget", pending("E3 not run", "tab:budget", "Budget frontier."))
        return
    rows, vals = [], {}
    for mult, d in sorted(r["points"].items(), key=lambda kv: float(kv[0])):
        c, lf = d["clsa"], d["language_first"]
        rows.append(
            f"{fmt(d.get('budget'), 0)} & {fmt(c.get('harm_rate'))} & {fmt(c.get('success_rate'))} & "
            f"{fmt(c.get('tokens'), 0)} & {fmt(lf.get('harm_rate'))} & {fmt(lf.get('success_rate'))} \\\\"
        )
        vals[mult] = {"budget": d.get("budget"), "clsa_harm": c.get("harm_rate"), "clsa_success": c.get("success_rate"), "lf_harm": lf.get("harm_rate"), "lf_success": lf.get("success_rate")}
    values["t3_budget"] = vals
    marginal = r.get("marginal") or []
    values["t3_marginal"] = {str(p.get("rollouts_per_candidate")): p.get("decision_change_rate") for p in marginal}
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}rrrrrr@{}}\n\\toprule\n"
        "Budget (tokens) & CLSA harm & CLSA success & CLSA tokens & Lang.-first harm & Lang.-first success \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        "\\caption{E3: the frontier as the budget is scaled, with simulation and verification charged.}\n"
        "\\label{tab:budget}\n\\end{table}\n"
    )
    write_table("t3_budget", body)


def t4_calibration(values: dict) -> None:
    r = load("e4_calibration")
    if not r:
        write_table("t4_calibration", pending("E4 not run", "tab:calib", "Calibration."))
        return
    sel = r.get("selective", {})
    feas = r.get("feasibility", {})
    rows = [
        f"ECE & {fmt(r.get('ece'))} \\\\",
        f"Brier & {fmt(r.get('brier'))} \\\\",
        f"Selective risk (accepted) & {fmt(sel.get('selective_risk'))} \\\\",
        f"Coverage & {fmt(sel.get('coverage'))} \\\\",
        f"Clopper--Pearson upper & {fmt(sel.get('upper'))} \\\\",
        f"Realised $-$ promised $\\alpha$ & {fmt(r.get('realised_minus_promised'))} \\\\",
        f"Base risk & {fmt(feas.get('base_risk'))} \\\\",
        f"Required abstention & {fmt(feas.get('required_abstention'))} \\\\",
        f"Observed abstention & {fmt(feas.get('observed_abstention'))} \\\\",
    ]
    values["t4_calibration"] = {
        "ece": r.get("ece"),
        "brier": r.get("brier"),
        "selective_risk": sel.get("selective_risk"),
        "coverage": sel.get("coverage"),
        "upper": sel.get("upper"),
        "realised_minus_promised": r.get("realised_minus_promised"),
        "required_abstention": feas.get("required_abstention"),
    }
    alpha_rows = []
    for a, d in sorted((r.get("by_alpha") or {}).items(), key=lambda kv: float(kv[0])):
        alpha_rows.append(
            f"{a} & {fmt(d.get('threshold'))} & {fmt(d.get('selective_risk'))} & {fmt(d.get('coverage'))} \\\\"
        )
        values[f"t4_alpha_{a}"] = {"threshold": d.get("threshold"), "risk": d.get("selective_risk")}
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}lr@{}}\n\\toprule\nQuantity & Value \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        "\\caption{E4: calibration and selective risk under the feasibility test.}\n"
        "\\label{tab:calib}\n\\end{table}\n"
    )
    write_table("t4_calibration", body)
    if alpha_rows:
        write_table(
            "t4_alpha",
            "\\begin{table}[h]\n\\centering\n\\small\n"
            "\\begin{tabular}{@{}rrrr@{}}\n\\toprule\n$\\alpha$ & Threshold & Selective risk & Coverage \\\\\n\\midrule\n"
            + "\n".join(alpha_rows)
            + "\n\\bottomrule\n\\end{tabular}\n"
            "\\caption{E4: the gate at three target miscoverage levels.}\n\\label{tab:alpha}\n\\end{table}\n",
        )


def t5_tiers(values: dict) -> None:
    t1 = load("tier1_overhead")
    t3 = load("tier3_quickstart")
    rows = []
    if t1:
        rows.append(
            f"1 & {fmt(t1.get('monitor_ms_per_decision'), 4)} & {fmt(100 * float(t1.get('overhead_fraction', 0)), 3)}\\% & "
            f"{'met' if t1.get('target_met') else 'not met'} \\\\"
        )
        values["t5_tier1"] = {
            "monitor_ms": t1.get("monitor_ms_per_decision"),
            "overhead_fraction": t1.get("overhead_fraction"),
            "target_met": t1.get("target_met"),
        }
    if t3 and t3.get("by_policy"):
        for name, d in t3["by_policy"].items():
            values[f"t5_tier3_{name}"] = d
    if not rows:
        write_table("t5_tiers", pending("tier measurements not run", "tab:tiers", "Tier overhead."))
        return
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}rrrr@{}}\n\\toprule\nTier & Monitor (ms/decision) & Added latency & Target \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        "\\caption{Tier 1 measured overhead against the 0.1\\% target. The target is reported as met "
        "or not met from the measurement, not restated as achieved.}\n"
        "\\label{tab:tiers}\n\\end{table}\n"
    )
    write_table("t5_tiers", body)


def t6_efficiency(values: dict) -> None:
    r = load("e9_efficiency")
    if not r:
        write_table("t6_efficiency", pending("E9 not run", "tab:eff", "Efficiency."))
        return
    rows, vals = [], {}
    for name, d in r.get("per_policy", {}).items():
        rows.append(
            f"{tex(PRETTY.get(name, name))} & {fmt(d.get('tokens_per_decision'), 0)} & "
            f"{fmt(d.get('latency_ms_per_decision'), 3)} & {fmt(d.get('peak_memory_mb'), 1)} & "
            f"{fmt(d.get('harm_rate'))} \\\\"
        )
        vals[name] = {k: d.get(k) for k in ("tokens_per_decision", "latency_ms_per_decision", "peak_memory_mb", "harm_rate")}
    values["t6_efficiency"] = vals
    dist = r.get("distillation") or {}
    values["t6_distillation"] = dist
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}lrrrr@{}}\n\\toprule\n"
        "Policy & Tokens & Latency (ms) & Peak memory (MB) & Harm \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        "\\caption{E9: charged cost, latency and Python-allocated peak memory per decision "
        f"(a lower bound on RSS). Distilled student: {dist.get('student_params')} parameters against "
        f"{dist.get('teacher_params')} for the teacher, harm agreement {fmt(dist.get('p_harm_agreement'))}.}}\n"
        "\\label{tab:eff}\n\\end{table}\n"
    )
    write_table("t6_efficiency", body)


def t7_cross_backbone(values: dict) -> None:
    r = load("e6_transfer")
    cb = (r or {}).get("cross_backbone") or {}
    if cb.get("status") != "ok":
        write_table(
            "t7_cross_backbone",
            pending("cross-backbone run not available", "tab:cross", "Cross-backbone replication."),
        )
        return
    adm1, adm2 = cb.get("admission_primary") or {}, cb.get("admission_secondary") or {}
    tr = cb.get("threshold_transfer") or {}
    rc = cb.get("recalibrated") or {}
    dl = cb.get("decision_level") or {}
    clsa2, lf2 = dl.get("clsa") or {}, dl.get("language_first") or {}
    paired = dl.get("paired_harm") or {}
    rows = [
        f"Shared states & {cb.get('n_shared_states')} & -- \\\\",
        f"Probe-score correlation & {fmt(cb.get('score_correlation'))} & -- \\\\",
        f"Flip rate, shared features & {fmt(adm1.get('flip_rate_shared'))} & {fmt(adm2.get('flip_rate_shared'))} \\\\",
        f"Flip rate, probe-only & {fmt(adm1.get('flip_rate_probe_only'))} & {fmt(adm2.get('flip_rate_probe_only'))} \\\\",
        f"Admitted shared features & {adm1.get('n_shared')} & {adm2.get('n_shared')} \\\\",
        "\\midrule",
        f"Transferred threshold & {fmt(tr.get('threshold_from_primary'))} & {fmt(rc.get('threshold'))} \\\\",
        f"Coverage & {fmt(tr.get('coverage'))} & {fmt(rc.get('coverage'))} \\\\",
        f"Selective risk & {fmt(tr.get('selective_risk'))} & {fmt(rc.get('selective_risk'))} \\\\",
        f"Upper bound & {fmt(tr.get('upper'))} & {fmt(rc.get('upper'))} \\\\",
        "\\midrule",
        f"Harm rate, CLSA & {fmt(clsa2.get('harm_rate'))} & {fmt(lf2.get('harm_rate'))} \\\\",
        f"Success rate & {fmt(clsa2.get('success_rate'))} & {fmt(lf2.get('success_rate'))} \\\\",
        f"Tokens per decision & {fmt(clsa2.get('tokens_per_decision'), 0)} & {fmt(lf2.get('tokens_per_decision'), 0)} \\\\",
    ]
    values["t7_cross_backbone"] = {
        "score_correlation": cb.get("score_correlation"),
        "transfer_coverage": tr.get("coverage"),
        "transfer_risk": tr.get("selective_risk"),
        "recal_coverage": rc.get("coverage"),
        "recal_risk": rc.get("selective_risk"),
        "recal_threshold": rc.get("threshold"),
        "secondary_clsa_harm": clsa2.get("harm_rate"),
        "secondary_lf_harm": lf2.get("harm_rate"),
        "secondary_paired_diff": paired.get("diff"),
    }
    body = (
        "\\begin{table}[h]\n\\centering\n\\small\n"
        "\\begin{tabular}{@{}lrr@{}}\n\\toprule\n"
        "Quantity & Primary (Qwen2.5-0.5B) & Secondary (SmolLM2-360M) \\\\\n\\midrule\n"
        + "\n".join(rows)
        + "\n\\bottomrule\n\\end{tabular}\n"
        f"\\caption{{E6 cross-backbone block, on {cb.get('n_secondary_eval_states')} secondary "
        "held-out rows. The lower block compares the transferred primary threshold with one "
        "refitted on the secondary calibration split.}\n"
        "\\label{tab:cross}\n\\end{table}\n"
    )
    write_table("t7_cross_backbone", body)


def main() -> None:
    values: dict = {}
    t1_main(values)
    t2_world_model(values)
    t3_budget(values)
    t4_calibration(values)
    t5_tiers(values)
    t6_efficiency(values)
    t7_cross_backbone(values)
    VALUES.write_text(json.dumps(values, indent=2), encoding="utf-8")
    print(f"wrote {VALUES}")


if __name__ == "__main__":
    main()