seu-3dgs / code /altdefense.py
Lightcap's picture
Upload folder using huggingface_hub
f138992 verified
Raw
History Blame Contribute Delete
4.99 kB
"""E11: alternative-defense comparison.
On a shared single-bit fault grid (fp32) we evaluate several mitigations and
report catastrophe rate, footprint, and a qualitative cost so that the support
guard can be placed in the design space rather than presented in isolation:
none no protection (baseline)
support_guard clamp every field to its trained coordinate box
selective_guard clamp only the scale and opacity fields
ecc_signexp parity/ECC that corrects sign and exponent bit flips
tmr_full full duplication: every upset corrected
Correction is applied to the stored parameters before rendering; footprint and
catastrophe are measured against the clean render.
"""
import argparse
import json
import os
import numpy as np
import torch
import faultlib as F
import gsmodel
FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]
COST = {
"none": "0",
"support_guard": "1x mem, ~0.1 ms/frame clamp",
"selective_guard": "1x mem, <0.1 ms/frame clamp",
"ecc_signexp": "~1.3x mem (parity on 9/32 bits), detect+correct",
"tmr_full": "3x mem, voting every access",
}
def guard_fields(work, bounds, fields):
out = {k: v for k, v in work.items()}
for k in fields:
lo, hi = bounds[k]
flat = work[k].reshape(work[k].shape[0], -1)
flat = torch.nan_to_num(flat, nan=0.0, posinf=0.0, neginf=0.0)
flat = torch.maximum(torch.minimum(flat, hi), lo)
out[k] = flat.reshape(work[k].shape).contiguous()
return out
def defended(mode, work, work_clean, bounds, field, bit, prec="fp32"):
bc = F.bit_class(prec, bit)
if mode == "none":
return work
if mode == "support_guard":
return F.apply_guard(work, bounds)
if mode == "selective_guard":
return guard_fields(work, bounds, ["scales", "opacities"])
if mode == "ecc_signexp":
return work_clean if bc != "mantissa" else work
if mode == "tmr_full":
return work_clean
return work
def run(model_path, out, modes, S, seed, lpips_fn, ssim_fn, log):
ck = torch.load(model_path, map_location="cuda", weights_only=False)
params = {k: v.cuda().float() for k, v in ck["params"].items()}
sh, W, H = ck["sh_degree"], ck["W"], ck["H"]
scene = ck["scene"]
N = params["means"].shape[0]
tvm = ck["test_viewmats"][:4].cuda(); tKs = ck["test_Ks"][:4].cuda()
bounds = F.compute_bounds(params)
stored, work = F.quantize_params(params, "fp32")
work_clean = {k: v.clone() for k, v in work.items()}
clean_img, _ = F.render_views(work, tvm, tKs, W, H, sh)
rng = np.random.default_rng(seed)
def lg(*a):
m = " ".join(str(x) for x in a); print(m, flush=True); open(log, "a").write(m + "\n")
rows = [] # (mode_id, field_id, bit, footprint, cat)
modemap = {m: i for i, m in enumerate(modes)}
comps = {f: work[f].reshape(N, -1).shape[1] for f in FIELDS}
for fi, field in enumerate(FIELDS):
Cf = comps[field]
for _ in range(S):
g = int(rng.integers(0, N)); c = int(rng.integers(0, Cf)); bit = int(rng.integers(0, 32))
flat = g * Cf + c
cv, _ = F.flip_one(stored[field], work[field], flat, bit, "fp32")
for mode in modes:
rp = defended(mode, work, work_clean, bounds, field, bit)
img, cat = F.render_views(rp, tvm, tKs, W, H, sh)
foot = ((img - clean_img).abs().amax(-1) > 1 / 255).float().mean().item()
rows.append((modemap[mode], fi, bit, foot, int(cat or foot > 0.01)))
F.restore_one(work[field], flat, cv)
lg(f"[{scene}] field={field} done ({len(rows)} rows)")
arr = np.array(rows, float)
np.savez_compressed(os.path.join(out, f"altdefense_{scene}.npz"),
data=arr, modes=np.array(modes),
cols=np.array(["mode", "field", "bit", "footprint", "cat"]))
# quick summary
for mode in modes:
m = arr[:, 0] == modemap[mode]
lg(f" {mode:16s} cat_rate={arr[m,4].mean()*100:6.3f}% mean_foot={arr[m,3].mean()*100:.4f}% cost={COST[mode]}")
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/altdefense")
ap.add_argument("--S", type=int, default=400)
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
os.makedirs(args.out, exist_ok=True)
log = os.path.join(args.out, "altdefense.log")
modes = ["none", "support_guard", "selective_guard", "ecc_signexp", "tmr_full"]
for sc in args.scenes.split(","):
mp = os.path.join(args.results_dir, sc, "model.pt")
if os.path.exists(mp):
run(mp, args.out, modes, args.S, args.seed, None, None, log)
print("ALTDEFENSE_DONE", flush=True)
if __name__ == "__main__":
main()