File size: 5,641 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
133
134
135
136
137
138
"""Large-scale single-event-upset campaign over trained 3DGS models.

For every (scene, precision, field, bit) cell we draw S random fault sites
(a Gaussian and a component), flip the bit in the stored representation,
re-render K held-out views, and record perceptual degradation + a catastrophe
flag.  Results are written as compressed per-(scene,precision) shards plus a
running log so the run survives disconnects.
"""
import argparse
import glob
import json
import os
import time

import numpy as np
import torch
import lpips as lpips_mod

import faultlib as F
from common import ssim
import gsmodel

FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]
FIELD_ID = {f: i for i, f in enumerate(FIELDS)}
BITCLASS_ID = {"sign": 0, "exp": 1, "mantissa": 2}


def pick_views(tvm, tKs, K):
    n = tvm.shape[0]
    idx = np.linspace(0, n - 1, K).round().astype(int)
    return tvm[idx].cuda(), tKs[idx].cuda()


def run_model(model_path, out_dir, precisions, K, S, lpips_fn, seed, guard, log):
    ckpt = torch.load(model_path, map_location="cuda", weights_only=False)
    params = {k: v.cuda().float() for k, v in ckpt["params"].items()}
    sh_degree = ckpt["sh_degree"]
    W, H = ckpt["W"], ckpt["H"]
    scene = ckpt["scene"]
    N = params["means"].shape[0]
    tvm, tKs = pick_views(ckpt["test_viewmats"], ckpt["test_Ks"], K)
    bounds = F.compute_bounds(params)

    def log_print(*a):
        msg = " ".join(str(x) for x in a)
        print(msg, flush=True)
        with open(log, "a") as fh:
            fh.write(msg + "\n")

    log_print(f"[{scene}] N={N} WxH={W}x{H} K={K} S={S} guard={guard} views={tvm.shape[0]}")

    for prec in precisions:
        stored, work = F.quantize_params(params, prec)
        nbits = F.PREC[prec][2]
        # clean reference at this precision
        clean_img, clean_cat = F.render_views(work, tvm, tKs, W, H, sh_degree)
        assert not clean_cat, f"clean render catastrophe for {scene}/{prec}"

        # per-field flattened component counts
        comps = {f: work[f].reshape(N, -1).shape[1] for f in FIELDS}
        rows = []
        t0 = time.time()
        n_inj = 0
        rng = np.random.default_rng(seed + hash((scene, prec)) % (2 ** 31))
        for field in FIELDS:
            Cf = comps[field]
            wfield = work[field]
            sfield = stored[field]
            for bit in range(nbits):
                bc = BITCLASS_ID[F.bit_class(prec, bit)]
                for _ in range(S):
                    g = int(rng.integers(0, N))
                    c = int(rng.integers(0, Cf))
                    flat_idx = g * Cf + c
                    clean_val, corr_val = F.flip_one(sfield, wfield, flat_idx, bit, prec)
                    if guard:
                        gwork = F.apply_guard(work, bounds)
                        img, cat = F.render_views(gwork, tvm, tKs, W, H, sh_degree)
                    else:
                        img, cat = F.render_views(work, tvm, tKs, W, H, sh_degree)
                    m = F.metrics(img, clean_img, lpips_fn, ssim)
                    F.restore_one(wfield, flat_idx, clean_val)
                    rows.append((FIELD_ID[field], bit, bc, g, c,
                                 float(clean_val), float(corr_val),
                                 m["mse"], m["psnr"], m["ssim"], m["lpips"],
                                 m["maxerr"], m["fracchg"], int(cat)))
                    n_inj += 1
            dt = time.time() - t0
            log_print(f"  [{scene}/{prec}] field={field} done  "
                      f"n_inj={n_inj} elapsed={dt:.1f}s  rate={n_inj/dt:.1f}/s")

        arr = np.array(rows, dtype=np.float64)
        cols = ["field_id", "bit", "bitclass", "g", "c", "clean_val", "corr_val",
                "mse", "psnr", "ssim", "lpips", "maxerr", "fracchg", "cat"]
        tag = f"{scene}_{prec}" + ("_guard" if guard else "")
        np.savez_compressed(os.path.join(out_dir, f"shard_{tag}.npz"),
                            data=arr, cols=np.array(cols),
                            meta=np.array([scene, prec, str(N), str(K), str(S),
                                           str(sh_degree), str(W), str(H)]))
        log_print(f"  SAVED shard_{tag}.npz rows={len(rows)} "
                  f"total_time={time.time()-t0:.1f}s")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--results_dir", default="/root/seu/results")
    ap.add_argument("--scenes", default="chair,lego,ficus,hotdog")
    ap.add_argument("--out", default="/root/seu/results/campaign")
    ap.add_argument("--precisions", default="fp32,fp16,bf16")
    ap.add_argument("--K", type=int, default=4)
    ap.add_argument("--S", type=int, default=1500)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--guard", type=int, default=0)
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)
    log = os.path.join(args.out, "campaign.log")
    lpips_fn = lpips_mod.LPIPS(net="alex").cuda().eval()
    for p in lpips_fn.parameters():
        p.requires_grad_(False)

    precisions = args.precisions.split(",")
    scenes = args.scenes.split(",")
    t_all = time.time()
    for sc in scenes:
        mp = os.path.join(args.results_dir, sc, "model.pt")
        if not os.path.exists(mp):
            print("missing", mp, flush=True)
            continue
        run_model(mp, args.out, precisions, args.K, args.S, lpips_fn, args.seed,
                  args.guard, log)
    with open(log, "a") as fh:
        fh.write(f"CAMPAIGN_DONE total={time.time()-t_all:.1f}s\n")
    print(f"CAMPAIGN_DONE total={time.time()-t_all:.1f}s", flush=True)


if __name__ == "__main__":
    main()