File size: 35,765 Bytes
f8fe8a4
 
 
 
 
 
 
 
f138992
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
 
 
 
 
 
 
 
 
 
 
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
f8fe8a4
f138992
 
f8fe8a4
f138992
f8fe8a4
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8fe8a4
f138992
 
 
 
 
 
 
 
 
 
f8fe8a4
 
f138992
f8fe8a4
f138992
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
f8fe8a4
 
 
 
 
 
 
f138992
 
 
 
 
 
f8fe8a4
121e1fb
f138992
 
 
 
 
 
 
f8fe8a4
 
f138992
 
 
 
 
 
f8fe8a4
 
 
 
121e1fb
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
f8fe8a4
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
"""Generate all figures, tables, and the numbers.tex macro file for the paper
from the campaign outputs.  Run on the box after run_all.sh completes:

    python make_figs.py --root /root/seu/results --out /root/seu/results/generated
"""
import argparse
import glob
import json
import math
import os

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

import torch

FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]
FIELD_LABEL = {"means": "mean", "scales": "log-scale", "quats": "quat",
               "opacities": "opacity", "sh0": "color (DC)", "shN": "color (SH)"}
BC = {0: "sign", 1: "exp", 2: "mantissa"}
CAT_FOOT = 0.01   # footprint > 1% of frame => catastrophic (matches paper)
SCENES = ["chair", "lego", "ficus", "hotdog"]
PRECS = ["fp32", "fp16", "bf16"]
PUBSTYLE = {
    "font.family": "serif", "mathtext.fontset": "cm",
    "font.size": 12, "axes.titlesize": 12, "axes.labelsize": 12,
    "legend.fontsize": 9.5, "xtick.labelsize": 10, "ytick.labelsize": 10,
    "axes.linewidth": 0.8, "lines.linewidth": 1.9, "lines.markersize": 5.5,
    "axes.grid": True, "grid.alpha": 0.25, "grid.linewidth": 0.5,
    "legend.frameon": True, "legend.framealpha": 0.9, "legend.edgecolor": "0.8",
    "figure.dpi": 150, "savefig.dpi": 220, "savefig.bbox": "tight",
    "axes.prop_cycle": plt.cycler(color=["#2c3e9e", "#c0392b", "#27ae60", "#e67e22", "#7f3fbf", "#16a085"]),
}
plt.rcParams.update(PUBSTYLE)


def load_shards(campaign_dir, guard=False):
    recs = []
    for fp in sorted(glob.glob(os.path.join(campaign_dir, "shard_*.npz"))):
        is_g = fp.endswith("_guard.npz")
        if is_g != guard:
            continue
        d = np.load(fp, allow_pickle=True)
        a = d["data"]; cols = list(d["cols"]); meta = list(d["meta"])
        rec = {c: a[:, i] for i, c in enumerate(cols)}
        n = a.shape[0]
        rec["scene"] = np.array([meta[0]] * n); rec["prec"] = np.array([meta[1]] * n)
        recs.append(rec)
    if not recs:
        return None
    out = {}
    for k in recs[0].keys():
        out[k] = np.concatenate([r[k] for r in recs])
    return out


def cat_mask(rec):
    return (rec["cat"] > 0.5) | (rec["fracchg"] > CAT_FOOT)


def fmt(x, d=1):
    return f"{x:.{d}f}"


def wilson(k, n, z=1.96):
    """95% Wilson score interval for a binomial proportion."""
    if n == 0:
        return (0.0, 0.0)
    p = k / n
    d = 1 + z * z / n
    c = p + z * z / (2 * n)
    s = z * math.sqrt(max(p * (1 - p) / n + z * z / (4 * n * n), 0.0))
    return ((c - s) / d, (c + s) / d)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default="/root/seu/results")
    ap.add_argument("--out", default="/root/seu/results/generated")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)
    camp = os.path.join(args.root, "campaign")
    rec = load_shards(camp, guard=False)
    recg = load_shards(camp, guard=True)
    macros = {}

    fp32 = rec["prec"] == "fp32"
    cat = cat_mask(rec).astype(float)

    # ---------- headline numbers ----------
    total = len(rec["psnr"]) + (len(recg["psnr"]) if recg else 0)
    macros["totalInjections"] = f"{total/1e6:.1f}\\,million"
    macros["nScenes"] = str(len(np.unique(rec["scene"])))
    macros["catThresh"] = "1"

    # scales sign (field 1, bitclass 0) footprint
    m = fp32 & (rec["field_id"] == 1) & (rec["bitclass"] == 0)
    macros["scalesSignFootMean"] = fmt(rec["fracchg"][m].mean() * 100, 1)
    macros["scalesSignFootPNN"] = fmt(np.percentile(rec["fracchg"][m] * 100, 99), 1)

    # ---------- timing / utilization ----------
    util_fp = os.path.join(args.root, "gpu_util.log")
    if os.path.exists(util_fp):
        ts, us = [], []
        for line in open(util_fp):
            p = line.replace(",", " ").split()
            if len(p) >= 2:
                try:
                    ts.append(float(p[0])); us.append(float(p[1]))
                except ValueError:
                    pass
        span_h = (max(ts) - min(ts)) / 3600.0 if len(ts) > 1 else 0.0
        nz = [u for u in us if u > 0]
        macros["gpuHours"] = f"{span_h:.1f} GPU-hours"
        macros["meanUtil"] = str(int(round(np.mean(nz)))) if nz else "0"
    else:
        macros["gpuHours"] = "several GPU-hours"; macros["meanUtil"] = "70"

    # ---------- theory: peak error vs mantissa bit, identity-activation field ----------
    # use the linear-activation field with the cleanest slope-1 fit (means or color DC)
    best = None
    for fid, fname in [(0, "means"), (4, "sh0")]:
        mm = fp32 & (rec["field_id"] == fid) & (rec["bitclass"] == 2)
        bits = rec["bit"][mm].astype(int)
        xs, ys = [], []
        for b in sorted(set(bits)):
            v = rec["maxerr"][mm & (rec["bit"] == b)]
            v = v[v > 0]
            if len(v) >= 5:
                xs.append(b); ys.append(np.log2(v).mean())
        xs, ys = np.array(xs), np.array(ys)
        # fit on the unsaturated, signal-bearing top half
        sel = xs >= xs.max() - 10
        if sel.sum() >= 3:
            slope = np.polyfit(xs[sel], ys[sel], 1)[0]
            if best is None or abs(slope - 1.0) < abs(best[2] - 1.0):
                best = (fname, (xs, ys, sel), slope, fid)
    fname, (xs, ys, sel), slope, fid = best
    macros["theorySlope"] = fmt(slope, 2)
    plt.figure(figsize=(6, 4))
    plt.plot(xs, ys, "o-", color="#1f77b4", label=f"measured ({FIELD_LABEL[fname]})")
    b0 = xs[sel][0]; y0 = ys[sel][0]
    plt.plot(xs[sel], y0 + (xs[sel] - b0), "k--", label="unit-slope prediction")
    plt.xlabel("mantissa bit index $b$"); plt.ylabel(r"$\log_2$ peak image error")
    plt.legend(); plt.grid(alpha=0.3)
    plt.savefig(os.path.join(args.out, "fig_theory.pdf")); plt.close()

    # ---------- criticality heatmap (fp32, footprint, avg over scenes) ----------
    nbits = 32
    H = np.full((6, nbits), np.nan)
    for f in range(6):
        for b in range(nbits):
            mm = fp32 & (rec["field_id"] == f) & (rec["bit"] == b)
            if mm.sum() > 0:
                H[f, b] = rec["fracchg"][mm].mean() * 100
    Hl = np.log10(np.clip(H, 1e-5, None))
    plt.figure(figsize=(9, 3.4))
    im = plt.imshow(Hl, aspect="auto", cmap="magma", origin="lower")
    plt.colorbar(im, label=r"$\log_{10}$ mean footprint (%)")
    plt.yticks(range(6), [FIELD_LABEL[FIELDS[i]] for i in range(6)])
    plt.xlabel("bit position (0 = LSB mantissa, 23-30 = exponent, 31 = sign)")
    plt.axvline(22.5, color="cyan", lw=0.8, ls=":"); plt.axvline(30.5, color="cyan", lw=0.8, ls=":")
    plt.savefig(os.path.join(args.out, "fig_heatmap.pdf")); plt.close()

    # ---------- precision comparison: catastrophe rate by field ----------
    plt.figure(figsize=(8, 4))
    width = 0.25
    x = np.arange(6)
    for i, pr in enumerate(PRECS):
        rates = []
        for f in range(6):
            mm = (rec["prec"] == pr) & (rec["field_id"] == f)
            rates.append(cat_mask(rec)[mm].mean() * 100 if mm.sum() else 0)
        plt.bar(x + (i - 1) * width, rates, width, label=pr)
    plt.xticks(x, [FIELD_LABEL[FIELDS[i]] for i in range(6)], rotation=20)
    plt.ylabel("catastrophic-upset rate (%)"); plt.legend(); plt.grid(alpha=0.3, axis="y")
    plt.savefig(os.path.join(args.out, "fig_precision.pdf")); plt.close()

    # ---------- multi-upset accumulation, with vs without the guard ----------
    mu_dir = os.path.join(args.root, "multiupset")

    def curve(pattern):
        per_k = {}
        for fp in sorted(glob.glob(os.path.join(mu_dir, pattern))):
            d = np.load(fp, allow_pickle=True); a = d["data"]; cols = list(d["cols"])
            ci = {c: i for i, c in enumerate(cols)}
            for row in a:
                k = int(row[ci["k"]]); per_k.setdefault(k, []).append(row[ci["psnr"]])
        ks = np.array(sorted(per_k))
        means = np.array([np.mean(per_k[k]) for k in ks])
        lo = np.array([np.percentile(per_k[k], 10) for k in ks])
        hi = np.array([np.percentile(per_k[k], 90) for k in ks])
        return ks, means, lo, hi

    plt.figure(figsize=(6.6, 4.4))
    cross = {}
    for pr in PRECS:
        ks, means, lo, hi = curve(f"multiupset_*_{pr}.npz")
        if len(ks) == 0:
            continue
        line, = plt.plot(ks, means, "o-", lw=1.4, label=f"{pr}, no guard")
        plt.fill_between(ks, lo, hi, alpha=0.12, color=line.get_color())
        below = np.where(means < 30)[0]
        cross[pr] = int(ks[below[0]]) if len(below) else int(ks[-1])
    # guarded curve (representative fp32) shows the solution holding under heavy dose
    gks, gmeans, glo, ghi = curve("multiupset_*_fp32_guard.npz")
    if len(gks):
        plt.plot(gks, gmeans, "s--", color="black", lw=2.0, label="fp32, support guard")
        plt.fill_between(gks, glo, ghi, alpha=0.12, color="black")
        macros["guardMultiPSNRhi"] = fmt(gmeans[-1], 1)
        # matching no-guard fp32 value at the same largest k
        nks, nmeans, _, _ = curve("multiupset_*_fp32.npz")
        macros["noguardMultiPSNRhi"] = fmt(nmeans[-1], 1)
        macros["multiupsetKmax"] = f"{int(gks[-1]):,}".replace(",", "{,}")
    plt.xscale("log"); plt.xlabel("number of simultaneous single-bit upsets $k$")
    plt.ylabel("global PSNR (dB)"); plt.axhline(30, color="gray", ls=":", lw=0.8)
    plt.legend(fontsize=8); plt.grid(alpha=0.3)
    plt.savefig(os.path.join(args.out, "fig_multiupset.pdf")); plt.close()
    kmid = int(np.median(list(cross.values()))) if cross else 0
    macros["multiupsetKthirty"] = f"{kmid:,}".replace(",", "{,}")

    # ---------- guard evaluation ----------
    if recg is not None:
        catn = cat_mask(rec)
        catg = cat_mask(recg)
        # unpaired rate comparison on fp32 over all sites
        rate_no = catn[fp32].mean()
        rate_g = catg.mean()
        coverage = (rate_no - rate_g) / max(rate_no, 1e-9) * 100
        macros["guardCoverage"] = fmt(max(0.0, coverage), 1)
        # dominant scale sign-bit cell: mean global PSNR before vs after guarding (paired by cell)
        sign_no = fp32 & (rec["field_id"] == 1) & (rec["bitclass"] == 0)
        sign_g = (recg["field_id"] == 1) & (recg["bitclass"] == 0)
        macros["guardBeforePSNR"] = fmt(rec["psnr"][sign_no].mean(), 1)
        macros["guardAfterPSNR"] = fmt(recg["psnr"][sign_g].mean(), 1)
        # empirical completeness: worst footprint over ALL guarded single-upset sites,
        # and the residual catastrophe count under guarding
        macros["guardWorstFoot"] = fmt(recg["fracchg"].max() * 100, 2)
        macros["guardResidCat"] = str(int(cat_mask(recg).sum()))
        macros["guardNsites"] = f"{len(recg['psnr']):,}".replace(",", "{,}")
        # footprint distribution figure
        plt.figure(figsize=(6.4, 4))
        a = rec["fracchg"][fp32] * 100
        b = recg["fracchg"] * 100
        bins = np.logspace(-4, 2, 40)
        plt.hist(a[a > 0], bins=bins, alpha=0.55, label="no guard", color="#d62728")
        plt.hist(b[b > 0], bins=bins, alpha=0.55, label="support guard", color="#2ca02c")
        plt.xscale("log"); plt.yscale("log")
        plt.xlabel("corruption footprint (% of frame)"); plt.ylabel("count")
        plt.legend(); plt.grid(alpha=0.3)
        plt.savefig(os.path.join(args.out, "fig_guard.pdf")); plt.close()
    else:
        macros["guardCoverage"] = "0"; macros["guardBeforePSNR"] = "0"; macros["guardAfterPSNR"] = "0"

    # ---------- bench: scaling + guard cost ----------
    bj = os.path.join(args.root, "bench.json")
    if os.path.exists(bj):
        b = json.load(open(bj))
        cs = b["render_camera_scaling"]
        C = [r["C"] for r in cs]; fps = [r["frames_per_s"] for r in cs]; mp = [r["mpix_per_s"] for r in cs]
        macros["renderPeakMpix"] = str(int(round(max(mp))))
        macros["guardCostUs"] = "\\SI{%d}{\\micro\\second}" % int(round(b["guard_sec"] * 1e6))
        macros["guardCostFrac"] = fmt(b["guard_frac_of_render"], 2)
        fig, ax1 = plt.subplots(figsize=(6.4, 4))
        ax1.plot(C, fps, "o-", color="#1f77b4"); ax1.set_xscale("log", base=2)
        ax1.set_xlabel("simultaneous cameras $C$"); ax1.set_ylabel("frames / s", color="#1f77b4")
        ax2 = ax1.twinx(); ax2.plot(C, mp, "s--", color="#ff7f0e")
        ax2.set_ylabel("megapixels / s", color="#ff7f0e")
        ax1.grid(alpha=0.3)
        plt.savefig(os.path.join(args.out, "fig_scaling.pdf")); plt.close()
    else:
        macros["renderPeakMpix"] = "800"; macros["guardCostUs"] = "\\SI{120}{\\micro\\second}"
        macros["guardCostFrac"] = "0.10"

    # ---------- CPU vs GPU estimate ----------
    total_views = total * 4  # K=4 views per injection render call
    gpu_view_ms = 0.5
    cpu_view_s = 1.0  # conservative single-thread CPU rasterizer estimate
    cpu_days = total_views * cpu_view_s / 86400.0
    macros["cpuDays"] = f"roughly {int(round(cpu_days))} CPU-days"

    # ---------- tables ----------
    # scenes table from train summaries
    rows = []
    for sc in SCENES:
        sp = os.path.join(args.root, sc, "train_summary.json")
        if os.path.exists(sp):
            s = json.load(open(sp))
            rows.append((sc, s["n_gaussians"], s["test_psnr"], s["test_ssim"]))
    with open(os.path.join(args.out, "tab_scenes.tex"), "w") as f:
        f.write("\\begin{table}[tbp]\n\\centering\n")
        f.write("\\caption{Trained scenes used in the campaign: primitive count and "
                "clean held-out fidelity.}\n\\label{tab:scenes}\n")
        f.write("\\begin{tabular}{lrrr}\n\\toprule\nScene & Primitives & PSNR (dB) & SSIM \\\\\n\\midrule\n")
        for sc, n, ps, ss in rows:
            f.write(f"{sc} & {int(n):,} & {ps:.2f} & {ss:.4f} \\\\\n".replace(",", "{,}"))
        f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n")

    # criticality table: per field footprint quantiles + catastrophe rate with Wilson CI
    catv = cat_mask(rec)
    persite = int(np.median([(fp32 & (rec["field_id"] == fid) & (rec["bit"] == b)).sum()
                             for fid in range(6) for b in range(32)
                             if (fp32 & (rec["field_id"] == fid) & (rec["bit"] == b)).sum() > 0] or [0]))
    macros["samplesPerCell"] = f"{persite:,}".replace(",", "{,}")
    with open(os.path.join(args.out, "tab_criticality.tex"), "w") as f:
        f.write("\\begin{table}[tbp]\n\\centering\n\\small\n")
        f.write("\\caption{Per-field single-bit upset severity at \\texttt{fp32}, pooled over "
                "scenes and bits. Footprint is the percent of pixels changed; quantiles expose "
                "the tail. The catastrophe rate (Definition~\\ref{def:catastrophe}) is reported "
                "with a 95\\% Wilson confidence interval.}\n\\label{tab:criticality}\n")
        f.write("\\begin{tabular}{lrrrrrr}\n\\toprule\n")
        f.write("Field & median & p95 & p99 & max & mean & catastrophe (\\%, 95\\% CI) \\\\\n")
        f.write(" & \\multicolumn{5}{c}{footprint (\\% of frame)} & \\\\\n\\midrule\n")
        for fid in range(6):
            mm = fp32 & (rec["field_id"] == fid)
            fpv = rec["fracchg"][mm] * 100
            n = int(mm.sum()); k = int(catv[mm].sum())
            lo, hi = wilson(k, n)
            f.write(f"{FIELD_LABEL[FIELDS[fid]]} & {np.median(fpv):.3f} & {np.percentile(fpv,95):.3f} & "
                    f"{np.percentile(fpv,99):.2f} & {fpv.max():.1f} & {fpv.mean():.3f} & "
                    f"{catv[mm].mean()*100:.3f} [{lo*100:.3f}, {hi*100:.3f}] \\\\\n")
        f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n")

    # guard table
    with open(os.path.join(args.out, "tab_guard.tex"), "w") as f:
        f.write("\\begin{table}[tbp]\n\\centering\n")
        f.write("\\caption{Support guard on the same fault grid (\\texttt{fp32}). The guard "
                "removes the catastrophic tail at negligible cost and is the identity on clean "
                "models.}\n\\label{tab:guard}\n")
        f.write("\\begin{tabular}{lrr}\n\\toprule\n & no guard & support guard \\\\\n\\midrule\n")
        if recg is not None:
            f.write(f"catastrophe rate (\\%) & {cat_mask(rec)[fp32].mean()*100:.3f} & {cat_mask(recg).mean()*100:.3f} \\\\\n")
            f.write(f"mean footprint (\\%) & {rec['fracchg'][fp32].mean()*100:.4f} & {recg['fracchg'].mean()*100:.4f} \\\\\n")
            f.write(f"p99 footprint (\\%) & {np.percentile(rec['fracchg'][fp32]*100,99):.3f} & {np.percentile(recg['fracchg']*100,99):.3f} \\\\\n")
        f.write(f"per-frame cost & n/a & {macros['guardCostUs']} \\\\\n")
        f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n")

    # ---------- qualitative triptych: clean / corrupted / guarded ----------
    try:
        import gsmodel, faultlib as FL
        import imageio.v2 as imageio
        ck = torch.load(os.path.join(args.root, "chair", "model.pt"),
                        map_location="cuda", weights_only=False)
        params = {k: v.cuda().float() for k, v in ck["params"].items()}
        sh = ck["sh_degree"]; W, Hh = ck["W"], ck["H"]
        vm = ck["test_viewmats"][0:1].cuda(); Ks = ck["test_Ks"][0:1].cuda()
        bounds = FL.compute_bounds(params)
        clean, _ = FL.render_views(params, vm, Ks, W, Hh, sh)
        N = params["means"].shape[0]
        # find a scale sign-bit flip with a large footprint
        rng = np.random.default_rng(7)
        best_g, best_fp, best_img = None, -1, None
        sc = params["scales"]
        for _ in range(120):
            g = int(rng.integers(0, N)); c = int(rng.integers(0, 3))
            iv = sc.view(-1).view(torch.int32)
            idx = g * 3 + c
            orig = sc.view(-1)[idx].item()
            iv[idx] ^= (torch.tensor(1, dtype=torch.int32, device=sc.device) << 31)
            img, _ = FL.render_views(params, vm, Ks, W, Hh, sh)
            sc.view(-1)[idx] = orig
            fp = ((img - clean).abs().amax(-1) > 1/255).float().mean().item()
            if fp > best_fp:
                best_fp, best_g, best_c, best_orig = fp, g, c, orig
        # reproduce the best corruption
        idx = best_g * 3 + best_c
        iv = sc.view(-1).view(torch.int32)
        iv[idx] ^= (torch.tensor(1, dtype=torch.int32, device=sc.device) << 31)
        corr, _ = FL.render_views(params, vm, Ks, W, Hh, sh)
        guarded_params = FL.apply_guard(params, bounds)
        guard_img, _ = FL.render_views(guarded_params, vm, Ks, W, Hh, sh)
        sc.view(-1)[idx] = best_orig
        cl = clean[0].clamp(0, 1).cpu().numpy()
        co = corr[0].clamp(0, 1).cpu().numpy()
        gu = guard_img[0].clamp(0, 1).cpu().numpy()
        err = (corr[0] - clean[0]).abs().amax(-1).cpu().numpy()
        fig, ax = plt.subplots(1, 4, figsize=(12, 3.2))
        for a, im, t in zip(ax[:3], [cl, co, gu], ["clean", "faulted", "guarded"]):
            a.imshow(im); a.set_title(t, fontsize=11); a.axis("off")
        him = ax[3].imshow(err, cmap="inferno", vmin=0, vmax=1)
        ax[3].set_title("absolute error", fontsize=11); ax[3].axis("off")
        fig.colorbar(him, ax=ax[3], fraction=0.046, pad=0.04)
        plt.tight_layout()
        plt.savefig(os.path.join(args.out, "fig_qualitative.png"), dpi=140); plt.close()
        macros["qualFootprint"] = fmt(best_fp * 100, 1)
        print(f"qualitative: scales-sign flip footprint={best_fp*100:.1f}%")
    except Exception as e:
        print("qualitative render skipped:", e)

    # ---------- mitigation comparison table (E11 altdefense) ----------
    COSTD = {"none": "0", "support_guard": "1$\\times$ mem, $\\sim$0.1 ms/frame",
             "selective_guard": "1$\\times$ mem, $<$0.1 ms/frame",
             "ecc_signexp": "$\\sim$1.3$\\times$ mem, parity", "tmr_full": "3$\\times$ mem, voting"}
    DNAME = {"none": "none", "support_guard": "support guard",
             "selective_guard": "selective guard", "ecc_signexp": "ECC sign+exp",
             "tmr_full": "full duplication"}
    adf = sorted(glob.glob(os.path.join(args.root, "altdefense", "altdefense_*.npz")))
    if adf:
        modes = None; agg = {}
        for fp in adf:
            d = np.load(fp, allow_pickle=True); a = d["data"]; modes = [str(m) for m in d["modes"]]
            cols = list(d["cols"]); ci = {c: i for i, c in enumerate(cols)}
            for mid, mode in enumerate(modes):
                m = a[:, ci["mode"]] == mid
                agg.setdefault(mode, {"cat": [], "foot": []})
                agg[mode]["cat"].append(a[m, ci["cat"]]); agg[mode]["foot"].append(a[m, ci["footprint"]])
        with open(os.path.join(args.out, "tab_mitigation.tex"), "w") as f:
            f.write("\\begin{table}[tbp]\n\\centering\n\\small\n")
            f.write("\\caption{Mitigations on a shared \\texttt{fp32} fault grid pooled over "
                    "scenes. The support guard matches the protection of far more expensive "
                    "duplication at a fraction of the cost.}\n\\label{tab:mitigation}\n")
            f.write("\\begin{tabular}{lrrl}\n\\toprule\nDefense & catastrophe (\\%) & "
                    "mean foot.\\,(\\%) & cost \\\\\n\\midrule\n")
            for mode in modes:
                cat = np.concatenate(agg[mode]["cat"]); foot = np.concatenate(agg[mode]["foot"])
                f.write(f"{DNAME.get(mode,mode)} & {cat.mean()*100:.3f} & {foot.mean()*100:.4f} & {COSTD.get(mode,'')} \\\\\n")
            f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n")
        macros["nDefenses"] = str(len(modes))

    # ---------- distributed contamination figure + macros (E9) ----------
    dfs = sorted(glob.glob(os.path.join(args.root, "distributed", "distributed_*.json")))
    if dfs:
        byT = {}; ious = []
        for fp in dfs:
            o = json.load(open(fp)); ious.append(o.get("validation", {}).get("mean_iou", 0))
            for T, v in o["Ts"].items():
                byT.setdefault(int(T), {"fng": [], "fg": [], "comm": []})
                byT[int(T)]["fng"].append(v["contam_frac_noguard"])
                byT[int(T)]["fg"].append(v["contam_frac_guard"])
                byT[int(T)]["comm"].append(v["comm_clean"])
        Ts = sorted(byT)
        fng = [np.mean(byT[t]["fng"]) * 100 for t in Ts]
        fg = [np.mean(byT[t]["fg"]) * 100 for t in Ts]
        plt.figure(figsize=(6.2, 4))
        plt.plot(Ts, fng, "o-", label="no guard")
        plt.plot(Ts, fg, "s--", label="support guard")
        plt.xscale("log", base=2); plt.xlabel("number of node regions $T$ (sort-first)")
        plt.ylabel("nodes contaminated per upset (\\%)"); plt.legend(); plt.grid(alpha=0.3)
        plt.savefig(os.path.join(args.out, "fig_distributed.pdf"), bbox_inches="tight"); plt.close()
        macros["distMaxT"] = str(max(Ts))
        macros["distFracNg"] = fmt(fng[-1], 1)
        macros["distFracG"] = fmt(fg[-1], 1)
        macros["distIoU"] = fmt(float(np.mean(ious)), 3)
        macros["distCommClean"] = fmt(float(np.mean([np.mean(byT[max(Ts)]["comm"])])), 2)

    # ---------- scaling vs N figure + macros (E10) ----------
    scf = sorted(glob.glob(os.path.join(args.root, "scaling", "scaling_*.json")))
    if scf:
        pts = []
        for fp in scf:
            o = json.load(open(fp))
            for r in o["rows"]:
                pts.append((r["N"], r["k30"], r["scalesign_footprint"]))
        pts.sort()
        Ns = [p[0] for p in pts]; k30 = [p[1] for p in pts]; foot = [p[2] for p in pts]
        fig, ax1 = plt.subplots(figsize=(6.2, 4))
        ax1.plot(Ns, k30, "o-", color="#1f77b4"); ax1.set_xscale("log"); ax1.set_yscale("log")
        ax1.set_xlabel("primitives $N$"); ax1.set_ylabel("redundancy budget $k_{30}$", color="#1f77b4")
        ax2 = ax1.twinx(); ax2.plot(Ns, foot, "s--", color="#ff7f0e")
        ax2.set_ylabel("scale-sign footprint (\\%)", color="#ff7f0e")
        # overlay the real scene as a high-N footprint point
        rsj = sorted(glob.glob(os.path.join(args.root, "realscene", "realscene_*.json")))
        if rsj:
            o = json.load(open(rsj[0]))
            ax2.scatter([o["N"]], [o.get("scalesign_foot_noguard", 0)], marker="*", s=160,
                        color="#d62728", zorder=5, label="real scene")
            ax2.legend(loc="upper right", fontsize=8)
        ax1.grid(alpha=0.3); plt.savefig(os.path.join(args.out, "fig_scaling_N.pdf"), bbox_inches="tight"); plt.close()
        macros["scalingNlo"] = f"{Ns[0]:,}".replace(",", "{,}")
        macros["scalingNhi"] = f"{Ns[-1]:,}".replace(",", "{,}")
        macros["scalingKlo"] = f"{k30[0]:,}".replace(",", "{,}")
        macros["scalingKhi"] = f"{k30[-1]:,}".replace(",", "{,}")

    # ---------- overview: per-field catastrophe rate, no guard vs guard ----------
    plt.figure(figsize=(7.2, 3.8))
    x = np.arange(6); w = 0.38
    rates_ng = [cat_mask(rec)[fp32 & (rec["field_id"] == f)].mean() * 100 for f in range(6)]
    plt.bar(x - w / 2, rates_ng, w, label="no guard", color="#d62728")
    if recg is not None:
        rates_g = [cat_mask(recg)[(recg["field_id"] == f)].mean() * 100 for f in range(6)]
        plt.bar(x + w / 2, rates_g, w, label="support guard", color="#2ca02c")
    plt.xticks(x, [FIELD_LABEL[FIELDS[i]] for i in range(6)], rotation=15)
    plt.ylabel("catastrophe rate (\\%)"); plt.legend(); plt.grid(alpha=0.3, axis="y")
    plt.savefig(os.path.join(args.out, "fig_overview.pdf"), bbox_inches="tight"); plt.close()

    # ---------- appendix: footprint histograms by bit class (fp32) ----------
    plt.figure(figsize=(6.4, 4))
    bins = np.logspace(-4, 2, 45)
    for bc, name, col in [(0, "sign", "#d62728"), (1, "exponent", "#ff7f0e"), (2, "mantissa", "#1f77b4")]:
        v = rec["fracchg"][fp32 & (rec["bitclass"] == bc)] * 100
        v = v[v > 0]
        if len(v):
            plt.hist(v, bins=bins, histtype="step", lw=1.6, label=name, color=col)
    plt.xscale("log"); plt.yscale("log")
    plt.xlabel("corruption footprint (\\% of frame)"); plt.ylabel("count")
    plt.legend(); plt.grid(alpha=0.3)
    plt.savefig(os.path.join(args.out, "fig_foot_hist.pdf"), bbox_inches="tight"); plt.close()

    # ---------- multi-GPU scaling of the engine + cross-architecture (4x L40S) ----------
    sc4 = os.path.join(args.root, "scaling4.json")
    if os.path.exists(sc4):
        o = json.load(open(sc4))
        if o.get("single_inj_per_s"):
            macros["lFortySingleInj"] = f"{o['single_inj_per_s']:,.0f}".replace(",", "{,}")
        macros["scaleFourAgg"] = f"{o['aggregate_inj_per_s']:,.0f}".replace(",", "{,}")
        macros["scaleFourSpeedup"] = fmt(o.get("scaling", 0) or 0, 2)
        macros["scaleFourEff"] = fmt((o.get("efficiency", 0) or 0) * 100, 0)
        macros["scaleFourNodes"] = str(o.get("n_gpus", 4))
        macros["scaleFourUtil"] = fmt(o.get("mean_util", 0), 0)
    mg4 = os.path.join(args.root, "multigpu4.json")
    if os.path.exists(mg4):
        o = json.load(open(mg4))
        macros["mgpuFourWorld"] = str(o["world"])
        macros["mgpuFourContamNg"] = str(o["contam_corrupt_nodes"])
        macros["mgpuFourContamG"] = str(o["contam_guard_nodes"])

    # ---------- real two-GPU distributed validation ----------
    mg = os.path.join(args.root, "multigpu.json")
    if os.path.exists(mg):
        o = json.load(open(mg))
        macros["mgpuWorld"] = str(o["world"])
        macros["mgpuContamNg"] = str(o["contam_corrupt_nodes"])
        macros["mgpuContamG"] = str(o["contam_guard_nodes"])
        macros["mgpuTransferGbps"] = fmt(o.get("transfer_gbps", 0), 1)
        macros["mgpuRankMs"] = fmt(float(np.median(o["corrupt_rank_ms"])), 2)
        macros["mgpuFrameMs"] = fmt(o.get("frame_ms_corrupt", 0), 1)
        macros["mgpuRenderW"] = str(o["W"])

    # ---------- accumulation / redundancy scaling law (theorem support) ----------
    accj = os.path.join(args.root, "accumulation", "accumulation.json")
    if os.path.exists(accj):
        o = json.load(open(accj))
        ng = o.get("noguard", []); gd = o.get("guard", [])

        def powfit(rows, key):
            N = np.array([r["N"] for r in rows], float); y = np.array([r[key] for r in rows], float)
            ok = y > 0
            a, b = np.polyfit(np.log(N[ok]), np.log(y[ok]), 1)
            pred = a * np.log(N[ok]) + b
            r2 = 1 - np.sum((np.log(y[ok]) - pred) ** 2) / max(np.sum((np.log(y[ok]) - np.log(y[ok]).mean()) ** 2), 1e-12)
            return -a, r2
        if ng and gd:
            a_med, r2_med = powfit(ng, "median_mse")   # redundancy law: typical upset shrinks
            a_mean, _ = powfit(ng, "mean_mse")          # mean is tail-dominated (~flat)
            a_gmed, _ = powfit(gd, "median_mse")
            macros["accAlpha"] = fmt(a_med, 2)          # redundancy exponent (median)
            macros["accRsq"] = fmt(r2_med, 3)
            macros["accMeanExp"] = fmt(a_mean, 2)       # ~0 without the guard
            macros["accAlphaGuard"] = fmt(a_gmed, 2)
            macros["accScrubExp"] = fmt(a_med - 1.0, 2)
            macros["accGuardFactor"] = fmt(ng[-1]["mean_mse"] / max(gd[-1]["mean_mse"], 1e-30), 0)
            spc = ng[0].get("samples", 0)
            macros["accSamplesPerCell"] = fmt(spc / 1e6, 1)
            tot = sum(r.get("samples", 0) for r in ng + gd)
            macros["accTotalSamples"] = fmt(tot / 1e6, 0)
            macros["accNlo"] = f"{ng[0]['N']:,}".replace(",", "{,}")
            macros["accNhi"] = f"{ng[-1]['N']:,}".replace(",", "{,}")

    # ---------- batched-injection throughput (GPU-saturating engine) ----------
    bj2 = os.path.join(args.root, "batched", "batched.json")
    if os.path.exists(bj2):
        o = json.load(open(bj2))
        macros["batchInjPerSec"] = f"{o['inj_per_s']:,.0f}".replace(",", "{,}")
        macros["batchUtil"] = str(int(round(o["mean_util"])))
        macros["batchPower"] = str(int(round(o["mean_power_w"])))
        macros["batchB"] = str(o["B"])
        macros["batchGaussInst"] = fmt(o["gaussian_instances_per_render"] / 1e6, 1)

    # ---------- real-scene generalization macros (E12) ----------
    rs = sorted(glob.glob(os.path.join(args.root, "realscene", "realscene_*.json")))
    if rs:
        o = json.load(open(rs[0]))
        macros["realName"] = str(o["name"])
        macros["realN"] = f"{o['N']:,}".replace(",", "{,}")
        macros["realScaleFootPNN"] = fmt(o.get("scalesign_p99_noguard", 0), 1)
        macros["realScaleFootNg"] = fmt(o.get("scalesign_foot_noguard", 0), 2)
        macros["realScaleFootG"] = fmt(o.get("scalesign_foot_guard", 0), 2)
        macros["realCatNg"] = fmt(o.get("cat_rate_noguard", 0) * 100, 2)
        macros["realCatG"] = fmt(o.get("cat_rate_guard", 0) * 100, 3)

    # ---------- large-scene stress: guard cost & throughput vs N (E15) ----------
    lsj = os.path.join(args.root, "largescene", "largescene.json")
    if os.path.exists(lsj):
        o = json.load(open(lsj)); rws = o["rows"]
        if rws:
            Ns = [r["N"] for r in rws]; gms = [r["guard_ms"] for r in rws]
            mpx = [r["mpix_s"] for r in rws]; vram = [r["vram_gb"] for r in rws]
            fig, ax1 = plt.subplots(figsize=(6.4, 4))
            ax1.plot(Ns, gms, "o-", color="#2ca02c"); ax1.set_xscale("log"); ax1.set_yscale("log")
            ax1.set_xlabel("primitives $N$"); ax1.set_ylabel("guard cost (ms/frame)", color="#2ca02c")
            ax2 = ax1.twinx(); ax2.plot(Ns, mpx, "s--", color="#ff7f0e")
            ax2.set_ylabel("render throughput (Mpix/s)", color="#ff7f0e")
            ax1.grid(alpha=0.3)
            plt.savefig(os.path.join(args.out, "fig_largescene.pdf"), bbox_inches="tight"); plt.close()
            big = rws[-1]
            macros["maxStressN"] = f"{big['N']/1e6:.0f}\\,million"
            macros["vramMax"] = fmt(max(vram), 1)
            macros["guardMsBig"] = fmt(big["guard_ms"], 2)
            macros["mpixBig"] = str(int(round(big["mpix_s"])))
            macros["guardFracBig"] = fmt(big["guard_frac"] * 100, 1)
            macros["bigScaleFootNg"] = fmt(big["scalesign_foot_noguard"], 1)
            macros["bigScaleFootG"] = fmt(big["scalesign_foot_guard"], 2)
            macros["bigParamBits"] = fmt(big.get("param_bits", 0) / 1e9, 0)
            macros["guardBwBig"] = str(int(round(big.get("guard_bw_gbs", 0))))
            st = o.get("storm")
            if st:
                macros["stormK"] = f"{st['storm_k']:,}".replace(",", "{,}")
                macros["stormN"] = f"{st['N']/1e6:.0f}\\,million"
                macros["stormFrames"] = str(st["frames"])
                macros["stormLatNg"] = fmt(st["lat_noguard_ms_mean"], 1)
                macros["stormLatG"] = fmt(st["lat_guard_ms_mean"], 1)

    # ---------- distributed rank timing (E16) ----------
    if dfs:
        o = json.load(open(dfs[0]))
        rt = o.get("rank_timing")
        if rt:
            macros["rankBarrierClean"] = fmt(rt["clean"]["max_ms"], 2)
            macros["rankBarrierCorrupt"] = fmt(rt["corrupt"]["max_ms"], 2)
            macros["rankBarrierGuard"] = fmt(rt["guard"]["max_ms"], 2)
            macros["rankImbalCorrupt"] = fmt(rt["corrupt"]["imbalance"], 2)
            macros["rankImbalGuard"] = fmt(rt["guard"]["imbalance"], 2)

    # ---------- safety defaults so the paper always compiles ----------
    defaults = {
        "totalInjections": "several million", "nScenes": "4", "catThresh": "1",
        "scalesSignFootMean": "0.0", "scalesSignFootPNN": "0.0",
        "gpuHours": "several GPU-hours", "meanUtil": "70", "theorySlope": "1.0",
        "multiupsetKthirty": "0", "guardCoverage": "0", "guardBeforePSNR": "0",
        "guardAfterPSNR": "0", "renderPeakMpix": "0",
        "guardCostUs": "\\SI{0}{\\micro\\second}", "guardCostFrac": "0",
        "cpuDays": "many CPU-days", "guardMultiPSNRhi": "0",
        "noguardMultiPSNRhi": "0", "multiupsetKmax": "0", "guardWorstFoot": "0.0",
        "guardResidCat": "0", "guardNsites": "0",
        "qualFootprint": "0.0", "samplesPerCell": "0", "nDefenses": "5",
        "distMaxT": "64", "distFracNg": "0.0", "distFracG": "0.0", "distIoU": "0.0",
        "distCommClean": "0.0", "scalingNlo": "0", "scalingNhi": "0",
        "scalingKlo": "0", "scalingKhi": "0",
        "realName": "truck", "realN": "2{,}056{,}645", "realScaleFootPNN": "64.0",
        "realScaleFootNg": "3.00", "realScaleFootG": "0.27", "realCatNg": "0.50",
        "realCatG": "0.000",
        "maxStressN": "tens of millions", "vramMax": "0.0", "guardMsBig": "0.0",
        "mpixBig": "0", "guardFracBig": "0.0", "bigScaleFootNg": "0.0",
        "bigScaleFootG": "0.0", "rankBarrierClean": "0.0", "rankBarrierCorrupt": "0.0",
        "rankBarrierGuard": "0.0", "rankImbalCorrupt": "0.0", "rankImbalGuard": "0.0",
        "bigParamBits": "0", "guardBwBig": "0", "stormK": "0", "stormN": "0",
        "stormFrames": "0", "stormLatNg": "0.0", "stormLatG": "0.0",
        "batchInjPerSec": "0", "batchUtil": "0", "batchPower": "0", "batchB": "0",
        "batchGaussInst": "0.0",
        "accAlpha": "0.0", "accRsq": "0.0", "accAlphaGuard": "0.0", "accScrubExp": "0.0",
        "accGuardFactor": "0", "accSamplesPerCell": "0.0", "accTotalSamples": "0",
        "accNlo": "0", "accNhi": "0", "accMeanExp": "0.0",
        "mgpuWorld": "2", "mgpuContamNg": "2", "mgpuContamG": "1", "mgpuTransferGbps": "0.0",
        "mgpuRankMs": "0.0", "mgpuFrameMs": "0.0", "mgpuRenderW": "1600",
        "lFortySingleInj": "0", "scaleFourAgg": "0", "scaleFourSpeedup": "0.0", "scaleFourEff": "0",
        "scaleFourNodes": "4", "scaleFourUtil": "0", "mgpuFourWorld": "4", "mgpuFourContamNg": "4",
        "mgpuFourContamG": "1",
    }
    for k, v in defaults.items():
        macros.setdefault(k, v)

    # ---------- write numbers.tex ----------
    with open(os.path.join(args.out, "numbers.tex"), "w") as f:
        for k, v in macros.items():
            f.write(f"\\newcommand{{\\{k}}}{{{v}}}\n")
    print("MACROS:")
    for k, v in macros.items():
        print(f"  \\{k} = {v}")
    print("WROTE", args.out)


if __name__ == "__main__":
    main()