File size: 5,815 Bytes
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
f8fe8a4
 
 
 
 
 
 
 
 
 
 
f138992
 
 
 
 
 
 
 
f8fe8a4
 
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
"""Single-event-upset (single-bit) fault injection for 3D Gaussian Splatting.

A fault site is (field, gaussian, component, bit).  The bit is flipped in the
*stored* representation of the parameter (the value as it sits in VRAM), at the
requested numeric precision (fp32 / fp16 / bf16), then the model is re-rendered.

IEEE-754 bit layout (bit 0 = LSB):
    fp32 : [31]=sign, [30:23]=exponent(8), [22:0]=mantissa(23)
    fp16 : [15]=sign, [14:10]=exponent(5), [9:0]=mantissa(10)
    bf16 : [15]=sign, [14:7]=exponent(8),  [6:0]=mantissa(7)
"""
from typing import Dict, List, Tuple

import torch

import gsmodel

# precision -> (float dtype, int dtype, n_bits, exp_lo, exp_hi)  exponent bits in [exp_lo, exp_hi]
PREC = {
    "fp32": (torch.float32, torch.int32, 32, 23, 30),
    "fp16": (torch.float16, torch.int16, 16, 10, 14),
    "bf16": (torch.bfloat16, torch.int16, 16, 7, 14),
}

# fields that gsplat renders, with the per-Gaussian component count after flattening
FIELD_COMPONENTS = {  # filled per-model because shN depends on sh_degree
    "means": 3, "scales": 3, "quats": 4, "opacities": 1, "sh0": 3,
}


def bit_class(prec: str, bit: int) -> str:
    """Return 'sign' | 'exp' | 'mantissa' for a bit position at a precision."""
    _, _, nbits, elo, ehi = PREC[prec]
    if bit == nbits - 1:
        return "sign"
    if elo <= bit <= ehi:
        return "exp"
    return "mantissa"


def quantize_params(params: Dict[str, torch.Tensor], prec: str) -> Tuple[Dict, Dict]:
    """Return (stored, work_fp32): `stored` holds each field at the target precision
    (the VRAM image); `work_fp32` is its fp32 view used for rendering."""
    fdt = PREC[prec][0]
    stored = {k: v.detach().to(fdt).contiguous() for k, v in params.items()}
    work = {k: v.to(torch.float32).contiguous() for k, v in stored.items()}
    return stored, work


def flip_one(stored_field: torch.Tensor, work_field: torch.Tensor, flat_idx: int,
             bit: int, prec: str):
    """Flip `bit` of element `flat_idx` (in the flattened field) of the stored
    field; write the resulting fp32 value into work_field.  Returns
    (clean_fp32_value, corrupted_fp32_value) so the caller can restore."""
    fdt, idt, _, _, _ = PREC[prec]
    iv = stored_field.view(-1).view(idt)              # int view of stored (read-only)
    mask = torch.tensor(1, dtype=idt, device=iv.device) << bit
    corr_int = (iv[flat_idx] ^ mask).reshape(1)        # corrupted bit pattern
    corr_fp32 = corr_int.view(fdt).to(torch.float32).reshape(())  # reinterpret -> fp32
    wv = work_field.view(-1)
    clean_fp32 = wv[flat_idx].clone()
    wv[flat_idx] = corr_fp32
    return clean_fp32, wv[flat_idx].clone()


def restore_one(work_field: torch.Tensor, flat_idx: int, clean_fp32: torch.Tensor):
    work_field.view(-1)[flat_idx] = clean_fp32


def render_views(work: Dict[str, torch.Tensor], viewmats, Ks, W, H, sh_degree):
    """Render and composite over white.  Returns (img[K,H,W,3] sanitized & clamped,
    catastrophe_bool)."""
    try:
        renders, alphas, _ = gsmodel.render(work, viewmats, Ks, W, H, sh_degree,
                                             bg_white=True, packed=True)
        out = renders
        finite = torch.isfinite(out).all().item()
        img = torch.nan_to_num(out, nan=1.0, posinf=1.0, neginf=0.0).clamp(0.0, 1.0)
        return img, (not finite)
    except Exception:
        K = viewmats.shape[0]
        return torch.ones(K, H, W, 3, device=viewmats.device), True


def metrics(pred: torch.Tensor, clean: torch.Tensor, lpips_fn, ssim_fn) -> Dict[str, float]:
    """pred, clean : [K,H,W,3] in [0,1].  Returns averaged metrics."""
    mse = torch.mean((pred - clean) ** 2).item()
    psnr = -10.0 * torch.log10(torch.tensor(max(mse, 1e-12))).item()
    p = pred.permute(0, 3, 1, 2)
    c = clean.permute(0, 3, 1, 2)
    ss = ssim_fn(p, c).item()
    with torch.no_grad():
        lp = lpips_fn(p * 2 - 1, c * 2 - 1).mean().item()
    maxerr = (pred - clean).abs().max().item()
    fracchg = ((pred - clean).abs().amax(dim=-1) > (1.0 / 255.0)).float().mean().item()
    return {"mse": mse, "psnr": psnr, "ssim": ss, "lpips": lp,
            "maxerr": maxerr, "fracchg": fracchg}


# ---------------- parallel range-guard (SDC detector/corrector) ----------------

# Fields the guard clamps. The higher-order spherical-harmonic coefficients
# (shN, 45 of the 59 per-primitive components) are inert under single-bit upsets:
# they modulate view-dependent colour within a primitive's existing footprint and
# cannot expand its spatial extent. Guarding them is therefore unnecessary and is
# the bulk of the cost, so the deployed guard skips them.
GUARD_FIELDS = ["means", "scales", "quats", "opacities", "sh0"]


def compute_bounds(params: Dict[str, torch.Tensor]) -> Dict[str, Tuple[torch.Tensor, torch.Tensor]]:
    """Per-field, per-component [min,max] box of the trained model (its support)."""
    bounds = {}
    for k, v in params.items():
        flat = v.reshape(v.shape[0], -1)  # [N, C]
        lo = flat.min(dim=0).values
        hi = flat.max(dim=0).values
        bounds[k] = (lo.contiguous(), hi.contiguous())
    return bounds


def apply_guard(work: Dict[str, torch.Tensor], bounds, fields=None) -> Dict[str, torch.Tensor]:
    """Clamp each guarded field to the trained support box and replace non-finite
    values, leaving the inert SH-rest field untouched. Embarrassingly parallel,
    O(N) per field. Unguarded fields are returned by reference (no copy)."""
    fields = GUARD_FIELDS if fields is None else fields
    out = dict(work)
    for k in fields:
        v = work[k]
        lo, hi = bounds[k]
        flat = v.reshape(v.shape[0], -1)
        flat = torch.clamp(torch.nan_to_num(flat, nan=0.0, posinf=0.0, neginf=0.0), lo, hi)
        out[k] = flat.reshape(v.shape)
    return out