File size: 28,700 Bytes
12b4729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate appendix LaTeX tables (full per-task results) from results.py."""
import os
from decimal import Decimal, ROUND_HALF_UP
from results import RESULTS, TASK_LABEL, TASK_GROUPS, PALOMA_LABEL, PALOMA_ORDER, tally, verdict, paloma_verdict

OUT = os.path.join(os.path.dirname(__file__), "..", "appendix_tables.tex")

TIER_NAME = {"HQ": "high-quality (HQ)", "MQ": "medium-quality (MQ)", "LQ": "low-quality (LQ)"}


def _ndec(x):
    """Number of decimals with which a value is stored (= reported in the result tables)."""
    t = repr(x)
    return len(t.split(".")[1]) if "." in t else 0


def hu(x, nd=2):
    """Half-up rounding (as in the result tables) of a computed statistic, signed."""
    q = Decimal(str(x)).quantize(Decimal(1).scaleb(-nd), rounding=ROUND_HALF_UP)
    return f"{q:+.{nd}f}"


def fmt_z(z):
    """z at the precision the result tables report it (1 decimal, 2 for most MQ values)."""
    if z is None:
        return "--"
    s = f"{z:+.{max(1, _ndec(z))}f}"
    if abs(z) >= 2:
        return r"\textbf{\boldmath " + s + "}"   # \boldmath: the math sign added by mathsign() is bold too
    return s


def fmt_d(d, nd=1):
    return f"{d:+.{nd}f}"


_SIGN = __import__("re").compile(r"(?<=[&\s{])([+-])(?=\d)")


def mathsign(row):
    """Typeset the sign of every signed number in a table row as a math +/- (not a hyphen)."""
    return _SIGN.sub(lambda m: "$" + m.group(1) + "$", row)


def downstream_table(tier):
    ds1, _ = RESULTS[(tier, "V1")]
    ds2, _ = RESULTS[(tier, "V2")]
    d1 = {r[0]: r for r in ds1}
    d2 = {r[0]: r for r in ds2}
    lines = []
    lines.append(r"\begin{table}[ht]")
    lines.append(r"\caption{Full downstream results on the " + TIER_NAME[tier] + r" tier: Raw (mean over three pre-training seeds) vs.\ V1 (surface repair) and V2 (surface + linguistic repair). $\sigma$ is the noise band $\sigma_{\mathrm{tot}}$ of \S\ref{sec:protocol} for that arm (its components $\sigma_{\mathrm{pretrain}}$, $\sigma_{\mathrm{eval}}$ and $\sigma_{\mathrm{binom}}$ are in the supplement's \texttt{data/results.py}); $z=\Delta/\sigma$; bold: $|z|\geq 2$. SQuAD~v2 values are reproduced as recorded by the evaluation script; their scale (above 100) is undecoded and its direction is not interpreted, so they are excluded from the percentage-point means and contribute no verdict.}")
    lines.append(r"\label{tab:full-" + tier.lower() + "}")
    lines.append(r"\begin{center}\small\setlength{\tabcolsep}{2.6pt}")
    lines.append(r"\begin{tabular}{l r rrrr rrrr}")
    lines.append(r"\toprule")
    lines.append(r" & & \multicolumn{4}{c}{V1 (surface)} & \multicolumn{4}{c}{V2 (surface + linguistic)} \\")
    lines.append(r"\cmidrule(lr){3-6}\cmidrule(lr){7-10}")
    lines.append(r"Task & Raw & $\sigma$ & mean & $\Delta$ (pp) & $z$ & $\sigma$ & mean & $\Delta$ (pp) & $z$ \\")
    lines.append(r"\midrule")
    for gname, tasks in TASK_GROUPS:
        lines.append(r"\multicolumn{10}{l}{\textit{" + gname + r"}} \\")
        for t in tasks:
            r1, r2 = d1[t], d2[t]
            raw = r1[1]
            nd = 2 if tier == "MQ" else 1
            lines.append(mathsign(
                f"{TASK_LABEL[t]} & {raw:.{nd}f} & {r1[5]:.3f} & {r1[6]:.{nd}f} & {fmt_d(r1[7], nd)} & {fmt_z(r1[9])} & "
                f"{r2[5]:.3f} & {r2[6]:.{nd}f} & {fmt_d(r2[7], nd)} & {fmt_z(r2[9])} \\\\"))
    t1, t2 = tally(tier, "V1"), tally(tier, "V2")
    lines.append(r"\midrule")
    lines.append(r"\multicolumn{2}{l}{Robust wins / losses ($|z|\geq 2$)} & \multicolumn{4}{c}{" + f"{t1['dW']} / {t1['dL']}" + r"} & \multicolumn{4}{c}{" + f"{t2['dW']} / {t2['dL']}" + r"} \\")
    mean1 = sum(Decimal(str(r[7])) for r in ds1 if r[0] != "squadv2") / 26
    mean2 = sum(Decimal(str(r[7])) for r in ds2 if r[0] != "squadv2") / 26
    lines.append(mathsign(r"\multicolumn{2}{l}{Mean $\Delta$ over 26 accuracy tasks (pp)} & \multicolumn{4}{c}{" + hu(mean1) + r"} & \multicolumn{4}{c}{" + hu(mean2) + r"} \\"))
    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}")
    lines.append(r"\end{center}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def paloma_table(tier):
    _, p1 = RESULTS[(tier, "V1")]
    _, p2 = RESULTS[(tier, "V2")]
    d1 = {r[0]: r for r in p1}
    d2 = {r[0]: r for r in p2}
    lines = []
    lines.append(r"\begin{table}[ht]")
    lines.append(r"\caption{Full Paloma bits-per-byte (BPB) results on the " + TIER_NAME[tier] + r" tier (lower is better). $\Delta$ is in BPB, $\Delta_{rel}$ in \%; $z=\Delta/\sigma_{\mathrm{tot}}$ with $\sigma_{\mathrm{tot}}=\sigma_{\mathrm{pretrain}}$ (no binomial fallback for continuous metrics). Bold: $|z|\geq 2$; negative $z$ is an improvement.}")
    lines.append(r"\label{tab:paloma-" + tier.lower() + "}")
    lines.append(r"\begin{center}\small\setlength{\tabcolsep}{4pt}")
    lines.append(r"\begin{tabular}{l r r rrr rrr}")
    lines.append(r"\toprule")
    lines.append(r" & & & \multicolumn{3}{c}{V1 (surface)} & \multicolumn{3}{c}{V2 (surface + linguistic)} \\")
    lines.append(r"\cmidrule(lr){4-6}\cmidrule(lr){7-9}")
    lines.append(r"Paloma corpus & Raw BPB & $\sigma_{\mathrm{tot}}$ & BPB & $\Delta_{rel}$ & $z$ & BPB & $\Delta_{rel}$ & $z$ \\")
    lines.append(r"\midrule")
    for c in PALOMA_ORDER:
        r1, r2 = d1[c], d2[c]
        lines.append(mathsign(
            f"{PALOMA_LABEL[c]} & {r1[1]:.4f} & {r1[4]:.4f} & {r1[5]:.4f} & {r1[7]:+.2f}\\% & {fmt_z(r1[8])} & "
            f"{r2[5]:.4f} & {r2[7]:+.2f}\\% & {fmt_z(r2[8])} \\\\"))
    t1, t2 = tally(tier, "V1"), tally(tier, "V2")
    lines.append(r"\midrule")
    lines.append(r"\multicolumn{3}{l}{Robust wins / losses ($|z|\geq 2$)} & \multicolumn{3}{c}{" + f"{t1['pW']} / {t1['pL']}" + r"} & \multicolumn{3}{c}{" + f"{t2['pW']} / {t2['pL']}" + r"} \\")
    m1 = sum(Decimal(str(r[7])) for r in p1) / len(p1)
    m2 = sum(Decimal(str(r[7])) for r in p2) / len(p2)
    lines.append(mathsign(r"\multicolumn{3}{l}{Mean $\Delta_{rel}$ over 11 corpora} & \multicolumn{3}{c}{" + hu(m1) + r"\%} & \multicolumn{3}{c}{" + hu(m2) + r"\%} \\"))
    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}")
    lines.append(r"\end{center}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


STRICT = 2 * (1 + 1 / 3) ** 0.5  # single-run repaired config: SE = sqrt(1+1/n) sigma_tot, n=3 seeds


def _counts(tier, cfg, thr, floor=False):
    ds, pal = RESULTS[(tier, cfg)]
    # SQuAD v2 never reaches |z| >= 2 in either direction, so it contributes no verdict.
    def zf(r):
        if floor and r[4] is not None and r[7] is not None and r[4] > 0 and r[5] is not None and r[4] > r[5]:
            return r[7] / r[4]          # sigma_tot floored at sigma_binom (multiple-choice tasks)
        return r[9]
    dW = sum(1 for r in ds if verdict(zf(r), thr) == "W")
    dL = sum(1 for r in ds if verdict(zf(r), thr) == "L")
    pW = sum(1 for r in pal if paloma_verdict(r[8], thr) == "W")
    pL = sum(1 for r in pal if paloma_verdict(r[8], thr) == "L")
    return dW, dL, pW, pL, dW + pW - dL - pL


def _zrep(z):
    """Print z at the precision it is reported in the result tables (1 or 2 decimals)."""
    return f"{z:+.{max(1, _ndec(z))}f}"


def _between(tier, cfg, lo=2.0, hi=STRICT):
    ds, pal = RESULTS[(tier, cfg)]
    out = []
    for r in ds:
        if r[0] != "squadv2" and r[9] is not None and lo <= abs(r[9]) < hi:
            out.append(f"{TASK_LABEL[r[0]]} ({'W' if r[9] > 0 else 'L'}, ${_zrep(r[9])}$)")
    for r in pal:
        if r[8] is not None and lo <= abs(r[8]) < hi:
            out.append(f"{PALOMA_LABEL[r[0]]} ({'W' if r[8] < 0 else 'L'}, ${_zrep(r[8])}$)")
    return ", ".join(out) if out else "none"


BONF = 3.2125 * (4 / 3) ** 0.5   # two-sided Bonferroni over 38 evaluations (3.2125), scaled like the single-run correction: 3.71
LADDER = [("2", 2.0), ("2.31", STRICT), ("3.71", BONF), ("5", 5.0)]


def strict_table():
    def net(n):
        return f"${n:+d}$" if n != 0 else "$0$"
    between = []
    for tier in ("HQ", "MQ", "LQ"):
        b = _between(tier, "V2")
        if b != "none":
            between.append(f"{tier}-V2: {b}")
    between_txt = "; ".join(between)
    lines = []
    lines.append(r"\begin{table}[ht]")
    lines.append(r"\caption{Sensitivity of the verdict tallies to the counting rule (\S\ref{sec:protocol}). Thresholds: $|z|\geq2$ (the protocol), $2\sqrt{1+1/3}\approx2.31$ (two standard errors when one treatment run is compared with a three-seed mean of equal variance), $3.71$ (two-sided Bonferroni over the 38 evaluations, 3.21, scaled by the same $\sqrt{4/3}$) and $5$ (above the two-degree-of-freedom $t$ cutoff 4.30 scaled the same way, 4.97); these are descriptive sensitivity cutoffs, not calibrated tests. Floor: $|z|\geq2$ with $\sigma_{\mathrm{tot}}$ floored at $\sigma_{\mathrm{binom}}$ for every multiple-choice task, which removes the near-degenerate denominators (e.g.\ SocialIQA on MQ-V1). DS: the 27 downstream tasks (SQuAD~v2 never reaches $|z|\geq2$); Pal.: the 11 Paloma corpora; W/L = wins/losses. V2 is net-positive and V1 is never net-positive on every tier under every rule. Verdicts with $2\leq|z|<2.31$ (all V2; no V1 or Paloma verdict lies there): " + between_txt + r".}")
    lines.append(r"\label{tab:strict}")
    lines.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{2.2pt}")
    lines.append(r"\begin{tabular}{@{}ll " + " ".join(["ccr"] * (len(LADDER) + 1)) + r"@{}}")
    lines.append(r"\toprule")
    head = " & ".join([r"\multicolumn{3}{c}{$|z|\geq " + lab + "$}" for lab, _ in LADDER]) + r" & \multicolumn{3}{c}{Floor}"
    lines.append(r" & & " + head + r" \\")
    cm = "".join([f"\\cmidrule(lr){{{3+3*i}-{5+3*i}}}" for i in range(len(LADDER) + 1)])
    lines.append(cm)
    lines.append(r"Tier & Repair & " + " & ".join([r"DS & Pal.\ & net"] * (len(LADDER) + 1)) + r" \\")
    lines.append(r"\midrule")
    for tier in ("HQ", "MQ", "LQ"):
        for cfg in ("V1", "V2"):
            cells = []
            for _, thr in LADDER:
                a = _counts(tier, cfg, thr)
                cells.append(f"{a[0]}/{a[1]} & {a[2]}/{a[3]} & {net(a[4])}")
            a = _counts(tier, cfg, 2.0, floor=True)
            cells.append(f"{a[0]}/{a[1]} & {a[2]}/{a[3]} & {net(a[4])}")
            lines.append(f"{tier if cfg == 'V1' else ''} & {cfg} & " + " & ".join(cells) + r" \\")
        if tier != "LQ":
            lines.append(r"\midrule")
    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}")
    lines.append(r"\end{center}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


# --------------------------------------------------------------------------
# Anatomy of the effect (main-text Table 3) and signal classification (App. G)
# --------------------------------------------------------------------------
# Random-choice baseline 1/k for multiple-choice tasks; None = open-ended or no simple baseline.
RANDOM_K = {"lambada_openai": None, "blimp": 2, "sciq": 4, "arc_easy": 4, "arc_challenge": 4, "pubmedqa": 3,
            "mmlu": 4, "hellaswag": 4, "piqa": 2, "commonsense_qa": 5, "social_iqa": 3, "copa": 2,
            "openbookqa": 4, "winogrande": 2, "logiqa": 4, "anli_r1": 3, "anli_r2": 3, "anli_r3": 3, "rte": 2,
            "cb": 3, "boolq": 2, "truthfulqa_mc2": None, "race": 4, "coqa": None, "triviaqa": None, "nq_open": None}
OPEN_SIGNAL = {"lambada_openai", "coqa"}   # open-ended tasks scored well above zero on every tier


def _tasks26():
    return [k for _, ts in TASK_GROUPS for k in ts if k != "squadv2"]


def signal_split():
    """Signal task: Raw score >= 10 pp above random choice (1/k) on every tier; open-ended LAMBADA and CoQA
    are included, TriviaQA/NQ-Open (<6% exact match) and TruthfulQA-MC2 (no simple random baseline) are not."""
    sig, near = [], []
    for k in _tasks26():
        raws = [{r[0]: r for r in RESULTS[(t, "V2")][0]}[k][1] for t in ("HQ", "MQ", "LQ")]
        if RANDOM_K[k] is None:
            (sig if k in OPEN_SIGNAL else near).append(k)
        else:
            (sig if min(r - 100.0 / RANDOM_K[k] for r in raws) >= 10 else near).append(k)
    return sig, near


def _anatomy(tier, cfg):
    d = {r[0]: r for r in RESULTS[(tier, cfg)][0]}
    p = {r[0]: r for r in RESULTS[(tier, cfg)][1]}
    ks = _tasks26()
    sig, _ = signal_split()
    tb = sum(1 for k in ks if d[k][7] > 0); tw = sum(1 for k in ks if d[k][7] < 0)
    pb = sum(1 for k in p if p[k][7] < 0); pw = sum(1 for k in p if p[k][7] > 0)
    gain = sum(d[k][7] for k in ks if d[k][7] > 0); loss = -sum(d[k][7] for k in ks if d[k][7] < 0)
    sb = sum(1 for k in sig if d[k][7] > 0); sw = sum(1 for k in sig if d[k][7] < 0)
    sW = sum(1 for k in sig if d[k][9] >= 2); sL = sum(1 for k in sig if d[k][9] <= -2)
    pg = -sum(p[k][7] for k in p if p[k][7] < 0); pl = sum(p[k][7] for k in p if p[k][7] > 0)
    v1lower = None
    if cfg == "V2":
        p1 = {r[0]: r for r in RESULTS[(tier, "V1")][1]}
        v1lower = sum(1 for k in p if p[k][5] < p1[k][5])
    return dict(better=tb + pb, worse=tw + pw, gain=gain, loss=loss, sb=sb, sw=sw, sW=sW, sL=sL, pg=pg, pl=pl, v1lower=v1lower)


def anatomy_table():
    sig, _ = signal_split()
    L = []
    L.append(r"\begin{table}[t]")
    L.append(r"\caption{Anatomy of the effect against Raw, counting every evaluation regardless of significance (ties omitted). Signal tasks: the " + str(len(sig)) + r" tasks whose Raw score is at least 10\pp{} above random choice on every tier (Table~\ref{tab:signal}); W/L: robust wins/losses. Gain/loss: summed positive and negative changes.}")
    L.append(r"\label{tab:anatomy}")
    L.append(r"\centering\footnotesize\setlength{\tabcolsep}{5pt}")
    L.append(r"\begin{tabular}{@{}ll c c cc c@{}}")
    L.append(r"\toprule")
    L.append(r" & & 37 evaluations & 26 tasks (pp) & \multicolumn{2}{c}{" + str(len(sig)) + r" signal tasks} & 11 Paloma (\% BPB) \\")
    L.append(r"\cmidrule(lr){3-3}\cmidrule(lr){4-4}\cmidrule(lr){5-6}\cmidrule(lr){7-7}")
    L.append(r"Tier & Repair & better / worse & gain / loss & better / worse & W / L & gain / loss \\")
    L.append(r"\midrule")
    for tier in ("HQ", "MQ", "LQ"):
        for cfg in ("V1", "V2"):
            a = _anatomy(tier, cfg)
            lab = "V1 surface" if cfg == "V1" else "V2 + linguistic"
            b = f"{a['better']}"
            if cfg == "V2":
                b = r"\textbf{" + b + "}"
            L.append(f"{tier if cfg == 'V1' else ''} & {lab} & {b} / {a['worse']} & {a['gain']:.1f} / {a['loss']:.1f} & "
                     f"{a['sb']} / {a['sw']} & {a['sW']} / {a['sL']} & {a['pg']:.1f} / {a['pl']:.1f} \\\\")
        if tier != "LQ":
            L.append(r"\midrule")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{table}")
    return "\n".join(L)


def signal_table():
    sig, near = signal_split()
    L = []
    L.append(r"\begin{table}[ht]")
    L.append(r"\caption{Classification of the 26 downstream tasks used in Table~\ref{tab:anatomy}. Random choice is $1/k$ for $k$ answer options; the Raw range is over the three tiers. A task has \emph{signal} at this scale if its Raw score is at least 10\pp{} above random choice on every tier; LAMBADA and CoQA are open-ended and far above zero; TriviaQA and NQ-Open are below 6\% exact match, and TruthfulQA-MC2 has no simple random baseline.}")
    L.append(r"\label{tab:signal}")
    L.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{4pt}")
    L.append(r"\begin{tabular}{@{}lccl@{}}")
    L.append(r"\toprule")
    L.append(r"Task & random choice (\%) & Raw range (\%) & class \\")
    L.append(r"\midrule")
    for k in _tasks26():
        raws = [{r[0]: r for r in RESULTS[(t, "V2")][0]}[k][1] for t in ("HQ", "MQ", "LQ")]
        rc = "--" if RANDOM_K[k] is None else f"{100.0 / RANDOM_K[k]:.1f}"
        cls = "signal" if k in sig else ("floor" if k in ("triviaqa", "nq_open") else "near chance")
        if k == "truthfulqa_mc2":
            cls = "no baseline"
        L.append(f"{TASK_LABEL[k]} & {rc} & {min(raws):.1f}--{max(raws):.1f} & {cls} \\\\")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{center}")
    L.append(r"\end{table}")
    return "\n".join(L)


# --------------------------------------------------------------------------
# In-depth analysis tables (main-text Table 2; App. analysis tables)
# --------------------------------------------------------------------------
FORMAT_GROUPS = [
    ("Passage-conditioned", ["lambada_openai", "sciq", "pubmedqa", "boolq", "race", "coqa", "logiqa"]),
    ("Premise--hypothesis", ["anli_r1", "anli_r2", "anli_r3", "rte", "cb"]),
    ("Short context", ["blimp", "hellaswag", "piqa", "commonsense_qa", "social_iqa", "copa", "winogrande"]),
    ("Closed-book knowledge", ["mmlu", "arc_easy", "arc_challenge", "openbookqa", "truthfulqa_mc2", "triviaqa", "nq_open"]),
]


def _grp(tier, cfg, ks):
    d = {r[0]: r for r in RESULTS[(tier, cfg)][0]}
    return dict(mean=sum(d[k][7] for k in ks) / len(ks), b=sum(1 for k in ks if d[k][7] > 0),
                w=sum(1 for k in ks if d[k][7] < 0), W=sum(1 for k in ks if d[k][9] >= 2),
                L=sum(1 for k in ks if d[k][9] <= -2))


def _robust(tier, cfg):
    ds, pal = RESULTS[(tier, cfg)]
    W = sum(1 for r in ds if r[9] >= 2) + sum(1 for r in pal if r[8] <= -2)
    L = sum(1 for r in ds if r[9] <= -2) + sum(1 for r in pal if r[8] >= 2)
    return W, L


def main_summary_table():
    L = []
    L.append(r"\captionof{table}{The full repair pipeline (V2) against Raw. Robust W/L: evaluations with $|z|\geq2$ in favour of / against repair (38 per tier); better/worse: all 37 scored evaluations regardless of significance (ties omitted); gain/loss: summed positive and negative changes; passage-conditioned tasks: the 7 tasks whose items include a multi-sentence passage (\S\ref{sec:analysis}). Surface-only repair (V1) and per-family Paloma means are in App.~\ref{app:full}.}")
    L.append(r"\label{tab:summary}")
    L.append(r"\centering\footnotesize\setlength{\tabcolsep}{4.2pt}")
    L.append(r"\begin{tabular}{@{}l cc c c c c@{}}")
    L.append(r"\toprule")
    L.append(r" & \multicolumn{2}{c}{Robust ($|z|\geq2$)} & All evaluations & 26 tasks (pp) & 11 Paloma (\%) & 7 passage tasks \\")
    L.append(r"\cmidrule(lr){2-3}\cmidrule(lr){4-4}\cmidrule(lr){5-5}\cmidrule(lr){6-6}\cmidrule(lr){7-7}")
    L.append(r"Tier & W / L & net & better / worse & gain / loss & gain / loss & better / worse, W / L \\")
    L.append(r"\midrule")
    tot = dict(W=0, L=0, b=0, w=0, g=0.0, l=0.0, pg=0.0, pl=0.0, gb=0, gw=0, gW=0, gL=0)
    for tier in ("HQ", "MQ", "LQ"):
        W, Lr = _robust(tier, "V2")
        a = _anatomy(tier, "V2")
        g = _grp(tier, "V2", FORMAT_GROUPS[0][1])
        L.append(f"{tier} & {W} / {Lr} & $+{W - Lr}$ & {a['better']} / {a['worse']} & {a['gain']:.1f} / {a['loss']:.1f} & "
                 f"{a['pg']:.1f} / {a['pl']:.1f} & {g['b']} / {g['w']}, {g['W']} / {g['L']} \\\\")
        tot['W'] += W; tot['L'] += Lr; tot['b'] += a['better']; tot['w'] += a['worse']
        tot['g'] += a['gain']; tot['l'] += a['loss']; tot['pg'] += a['pg']; tot['pl'] += a['pl']
        tot['gb'] += g['b']; tot['gw'] += g['w']; tot['gW'] += g['W']; tot['gL'] += g['L']
    L.append(r"\midrule")
    L.append(f"All & \\textbf{{{tot['W']} / {tot['L']}}} & $+{tot['W'] - tot['L']}$ & \\textbf{{{tot['b']} / {tot['w']}}} & {tot['g']:.1f} / {tot['l']:.1f} & "
             f"{tot['pg']:.1f} / {tot['pl']:.1f} & {tot['gb']} / {tot['gw']}, {tot['gW']} / {tot['gL']} \\\\")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    return "\n".join(L)


def format_group_table():
    L = []
    L.append(r"\begin{table}[ht]")
    L.append(r"\caption{Downstream changes of the full pipeline (V2) by task input format. Mean $\Delta$ in pp; better/worse over the tasks of the group; W/L: robust wins/losses. Groups are defined by a dataset property (whether an item contains a multi-sentence passage, a premise--hypothesis pair, a short context, or a closed-book question), not by the results; the MQ premise--hypothesis mean is carried by CB ($+23.8$\pp, not robust). Pooled: over the three tiers.}")
    L.append(r"\label{tab:formats}")
    L.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{4pt}")
    L.append(r"\begin{tabular}{@{}l c ccc ccc ccc c@{}}")
    L.append(r"\toprule")
    L.append(r" & & \multicolumn{3}{c}{HQ} & \multicolumn{3}{c}{MQ} & \multicolumn{3}{c}{LQ} & Pooled \\")
    L.append(r"\cmidrule(lr){3-5}\cmidrule(lr){6-8}\cmidrule(lr){9-11}\cmidrule(lr){12-12}")
    L.append(r"Group & $n$ & mean & b/w & W/L & mean & b/w & W/L & mean & b/w & W/L & better (of $3n$) \\")
    L.append(r"\midrule")
    for name, ks in FORMAT_GROUPS:
        cells = []
        pooled = 0
        for tier in ("HQ", "MQ", "LQ"):
            g = _grp(tier, "V2", ks)
            cells.append(f"${g['mean']:+.2f}$ & {g['b']}/{g['w']} & {g['W']}/{g['L']}")
            pooled += g['b']
        L.append(f"{name} & {len(ks)} & " + " & ".join(cells) + f" & {pooled} of {3 * len(ks)} \\\\")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{center}")
    L.append(r"\end{table}")
    return "\n".join(L)


def paloma_replication_table():
    from results import PALOMA_FAMILY
    L = []
    L.append(r"\begin{table}[ht]")
    L.append(r"\caption{Replication of the full pipeline's effect on each Paloma corpus across the three disjoint tiers (relative BPB change, \%; negative is better). Range: largest minus smallest of the three tier values.}")
    L.append(r"\label{tab:replication}")
    L.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{5pt}")
    L.append(r"\begin{tabular}{@{}llrrrrr@{}}")
    L.append(r"\toprule")
    L.append(r"Corpus & group & HQ & MQ & LQ & mean & range \\")
    L.append(r"\midrule")
    for c in PALOMA_ORDER:
        v = [{r[0]: r for r in RESULTS[(t, "V2")][1]}[c][7] for t in ("HQ", "MQ", "LQ")]
        L.append(mathsign(f"{PALOMA_LABEL[c]} & {PALOMA_FAMILY[c]} & {v[0]:+.2f} & {v[1]:+.2f} & {v[2]:+.2f} & "
                          f"{sum(v) / 3:+.2f} & {max(v) - min(v):.2f} \\\\"))
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{center}")
    L.append(r"\end{table}")
    return "\n".join(L)


def sensitivity_table():
    """Equal-weight task means of the full pipeline under exclusions, plus the two-way decomposition of the Paloma effects."""
    import numpy as np
    T = ("HQ", "MQ", "LQ")
    ds = {t: {r[0]: r for r in RESULTS[(t, "V2")][0]} for t in T}
    tasks = [k for k in ds["HQ"] if k != "squadv2"]
    rows = []
    for excl, name in (([], "All 26 tasks"), (["cb"], "Without CB"), (["cb", "lambada_openai"], "Without CB and LAMBADA")):
        ks = [k for k in tasks if k not in excl]
        per = [float(np.mean([ds[t][k][7] for k in ks])) for t in T]
        rows.append((name, per, float(np.mean(per))))
    M = np.array([[{r[0]: r for r in RESULTS[(t, "V2")][1]}[c][7] for c in PALOMA_ORDER] for t in T])
    g = M.mean(); tm = M.mean(axis=1, keepdims=True); cm = M.mean(axis=0, keepdims=True)
    sst = ((M - g) ** 2).sum(); ss_t = ((tm - g) ** 2).sum() * M.shape[1]; ss_c = ((cm - g) ** 2).sum() * M.shape[0]
    ss_r = ((M - tm - cm + g) ** 2).sum()
    L = []
    L.append(r"\begin{table}[ht]")
    L.append(r"\caption{Sensitivity of the full pipeline's downstream mean to the two most conspicuous gains (equal-weight mean change in pp over the tasks listed; SQuAD~v2 excluded throughout), and a two-way decomposition of the 33 Paloma effects (relative BPB changes) into between-corpus, between-tier and residual variation. Both are descriptive summaries of the recorded results.}")
    L.append(r"\label{tab:sensitivity}")
    L.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{6pt}")
    L.append(r"\begin{tabular}{@{}lrrrr@{}}")
    L.append(r"\toprule")
    L.append(r"Tasks included & HQ & MQ & LQ & pooled \\")
    L.append(r"\midrule")
    for name, per, pooled in rows:
        L.append(f"{name} & " + " & ".join(f"${v:+.2f}$" for v in per) + f" & ${pooled:+.2f}$ \\\\")
    L.append(r"\midrule")
    L.append(r"\multicolumn{5}{@{}l}{Paloma effects: variation between evaluation corpora " + f"{100 * ss_c / sst:.1f}" + r"\%, between input tiers " + f"{100 * ss_t / sst:.1f}" + r"\%, residual " + f"{100 * ss_r / sst:.1f}" + r"\%} \\")
    def _dec(Mx):
        gx = Mx.mean(); tmx = Mx.mean(axis=1, keepdims=True); cmx = Mx.mean(axis=0, keepdims=True)
        return 100 * ((cmx - gx) ** 2).sum() * Mx.shape[0] / ((Mx - gx) ** 2).sum()
    lab = {c: PALOMA_LABEL[c] for c in PALOMA_ORDER}
    pal = {t: {r[0]: r for r in RESULTS[(t, "V2")][1]} for t in T}
    c4 = [c for c in PALOMA_ORDER if lab[c] in ("C4-en", "C4-100-domains")]
    rest = [c for c in PALOMA_ORDER if c not in c4]
    M2 = np.array([[pal[t][c][7] for c in rest] + [np.mean([pal[t][c][7] for c in c4])] for t in T])
    drop = [c for c in PALOMA_ORDER if lab[c] in ("Falcon-RefinedWeb", "C4-en", "C4-100-domains")]
    M3 = np.array([[pal[t][c][7] for c in PALOMA_ORDER if c not in drop] for t in T])
    L.append(r"\multicolumn{5}{@{}l}{\quad between corpora, C4 evaluations merged: " + f"{_dec(M2):.1f}" + r"\%} \\")
    L.append(r"\multicolumn{5}{@{}l}{\quad between corpora, without Falcon-RefinedWeb and both C4: " + f"{_dec(M3):.1f}" + r"\%} \\")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{center}")
    L.append(r"\end{table}")
    return "\n".join(L)


def threshold_table():
    """Counts of full-pipeline task changes whose magnitude reaches a threshold, with and without CB and LAMBADA."""
    T = ("HQ", "MQ", "LQ")
    ds = {t: {r[0]: r for r in RESULTS[(t, "V2")][0]} for t in T}
    tasks = [k for k in ds["HQ"] if k != "squadv2"]
    L = []
    L.append(r"\begin{table}[ht]")
    L.append(r"\caption{Full-pipeline downstream changes against Raw whose magnitude reaches a threshold (improvements / declines over task--tier pairs; smaller changes omitted). Descriptive counts of the recorded changes, not significance tests.}")
    L.append(r"\label{tab:thresholds}")
    L.append(r"\begin{center}\footnotesize\setlength{\tabcolsep}{8pt}")
    L.append(r"\begin{tabular}{@{}lcc@{}}")
    L.append(r"\toprule")
    L.append(r"Threshold & All 26 tasks (78 pairs) & Without CB and LAMBADA (72 pairs) \\")
    L.append(r"\midrule")
    for th in (0.5, 1, 2):
        cells = []
        for excl in ([], ["cb", "lambada_openai"]):
            ks = [k for k in tasks if k not in excl]
            g = sum(1 for t in T for k in ks if ds[t][k][7] >= th)
            l = sum(1 for t in T for k in ks if ds[t][k][7] <= -th)
            cells.append(f"{g} / {l}")
        lab = f"$\\geq{th:g}$\\pp"
        L.append(f"{lab} & {cells[0]} & {cells[1]} \\\\")
    L.append(r"\bottomrule")
    L.append(r"\end{tabular}")
    L.append(r"\end{center}")
    L.append(r"\end{table}")
    return "\n".join(L)


if __name__ == "__main__":
    parts = ["% Auto-generated by data/make_tables.py -- do not edit by hand."]
    parts.append(strict_table())
    for tier in ("HQ", "MQ", "LQ"):
        parts.append(downstream_table(tier))
        parts.append(paloma_table(tier))
        parts.append(r"\clearpage")
    parts.append(signal_table())
    open(OUT, "w").write("\n\n".join(parts) + "\n")
    print("wrote", OUT)
    open(os.path.join(os.path.dirname(OUT), "table_anatomy.tex"), "w").write(
        "% Auto-generated by data/make_tables.py -- do not edit by hand.\n" + anatomy_table() + "\n")
    open(os.path.join(os.path.dirname(OUT), "table_summary.tex"), "w").write(
        "% Auto-generated by data/make_tables.py -- do not edit by hand.\n" + main_summary_table() + "\n")
    open(os.path.join(os.path.dirname(OUT), "appendix_analysis_tables.tex"), "w").write(
        "% Auto-generated by data/make_tables.py -- do not edit by hand.\n" + format_group_table() + "\n\n" + paloma_replication_table() + "\n\n" + sensitivity_table() + "\n\n" + threshold_table() + "\n")
    print("wrote table_anatomy.tex, table_summary.tex, appendix_analysis_tables.tex")
    # print the summary numbers used in the main text (half-up, as in the result tables)
    from results import PALOMA_FAMILY
    D = lambda v: Decimal(str(v))
    for tier in ("HQ", "MQ", "LQ"):
        for cfg in ("V1", "V2"):
            ds, pal = RESULTS[(tier, cfg)]
            m = sum(D(r[7]) for r in ds if r[0] != "squadv2") / 26
            pm = sum(D(r[7]) for r in pal) / 11
            fam = {}
            for r in pal:
                fam.setdefault(PALOMA_FAMILY[r[0]], []).append(D(r[7]))
            print(tier, cfg, "meanDS", hu(m), "| Paloma all", hu(pm),
                  " ".join(f"| {k} {hu(sum(v) / len(v))}" for k, v in fam.items()))