File size: 5,067 Bytes
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
"""Aggregate SEU campaign shards into per-cell statistics and sanity tables.

Catastrophe is defined as a non-finite render OR PSNR < 10 dB w.r.t. the clean
render at the same precision.
"""
import argparse
import glob
import json
import os

import numpy as np

FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]
BC = {0: "sign", 1: "exp", 2: "mantissa"}
CAT_PSNR = 10.0


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


def catastrophe(rec):
    return (rec["cat"] > 0.5) | (rec["psnr"] < CAT_PSNR)


def aggregate(rec):
    """Per (scene,prec,field,bit) aggregate rows."""
    cat = catastrophe(rec).astype(float)
    out = []
    scenes = np.unique(rec["scene"])
    precs = np.unique(rec["prec"])
    for sc in scenes:
        for pr in precs:
            base = (rec["scene"] == sc) & (rec["prec"] == pr)
            if base.sum() == 0:
                continue
            for fid in range(6):
                for bit in sorted(set(rec["bit"][base].astype(int))):
                    m = base & (rec["field_id"] == fid) & (rec["bit"] == bit)
                    if m.sum() == 0:
                        continue
                    ps = rec["psnr"][m]
                    out.append({
                        "scene": str(sc), "prec": str(pr), "field": FIELDS[fid],
                        "bit": int(bit), "bitclass": BC[int(rec["bitclass"][m][0])],
                        "n": int(m.sum()),
                        "mean_psnr": float(ps.mean()), "median_psnr": float(np.median(ps)),
                        "mean_ssim": float(rec["ssim"][m].mean()),
                        "mean_lpips": float(rec["lpips"][m].mean()),
                        "median_lpips": float(np.median(rec["lpips"][m])),
                        "cat_rate": float(cat[m].mean()),
                        "mean_mse": float(rec["mse"][m].mean()),
                        "mean_fracchg": float(rec["fracchg"][m].mean()),
                    })
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--campaign", default="/root/seu/results/campaign")
    ap.add_argument("--out", default="/root/seu/results/agg")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)

    rec = load_shards(args.campaign, guard=False)
    if rec is None:
        print("no shards found")
        return
    agg = aggregate(rec)
    with open(os.path.join(args.out, "aggregate.json"), "w") as f:
        json.dump(agg, f, indent=1)

    # sanity print: field x bitclass summary, fp32 only, averaged across scenes
    print(f"total rows: {len(rec['psnr'])}")
    print("\n=== fp32: local-impact metrics by field x bitclass (all scenes) ===")
    print("  maxerr = peak pixel error (L-inf); footprint = frac pixels changed >1/255")
    cat = catastrophe(rec).astype(float)
    fp32 = rec["prec"] == "fp32"
    hdr = (f"{'field':10s} {'class':9s} {'n':>6s} {'meanMaxErr':>10s} {'medMaxErr':>10s} "
           f"{'footprint%':>10s} {'p99foot%':>9s} {'meanLPIPS':>9s} {'catRate':>8s}")
    print(hdr)
    for fid in range(6):
        for bc in [0, 1, 2]:
            m = fp32 & (rec["field_id"] == fid) & (rec["bitclass"] == bc)
            if m.sum() == 0:
                continue
            fp = rec["fracchg"][m] * 100
            print(f"{FIELDS[fid]:10s} {BC[bc]:9s} {int(m.sum()):6d} "
                  f"{rec['maxerr'][m].mean():10.4f} {np.median(rec['maxerr'][m]):10.4f} "
                  f"{fp.mean():10.4f} {np.percentile(fp,99):9.4f} "
                  f"{rec['lpips'][m].mean():9.4f} {cat[m].mean():8.3f}")

    # mantissa bit-position scaling using LOCAL peak error (expect ~2^b -> log2 slope ~1/bit)
    print("\n=== fp32 scales mantissa: mean log2(maxerr) vs bit (expect ~+1/bit until saturation) ===")
    m0 = fp32 & (rec["field_id"] == 1) & (rec["bitclass"] == 2)
    bits = rec["bit"][m0].astype(int)
    for b in sorted(set(bits)):
        mm = m0 & (rec["bit"] == b)
        me = rec["maxerr"][mm]
        me = me[me > 0]
        if len(me) == 0:
            print(f"  bit {b:2d}: (all zero)")
            continue
        print(f"  bit {b:2d}: mean_log2(maxerr) {np.log2(me).mean():7.3f}  "
              f"meanMaxErr {rec['maxerr'][mm].mean():.5f}  footprint% {rec['fracchg'][mm].mean()*100:.4f}  n={mm.sum()}")
    print("\nSAVED", os.path.join(args.out, "aggregate.json"))


if __name__ == "__main__":
    main()