File size: 10,525 Bytes
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""E9: distributed (sort-first) tile-rendering experiment.

A sort-first parallel rasterizer partitions the screen into node regions; each
node renders the primitives whose projected footprint overlaps its region.  Two
quantities follow directly from the real projected geometry that gsplat exposes
(per-primitive projected centre and radius): the communication amplification (how
many nodes each primitive must be sent to) and, under a single-bit upset, the
contamination (how many node regions a corrupted primitive reaches).  We measure
both as a function of the node count and with/without the support guard, and we
validate the predicted contaminated regions against an actual per-region render.
"""
import argparse
import json
import math
import os
import time

import numpy as np
import torch

import faultlib as F
import gsmodel


def grid_for(T):
    """near-square (rows, cols) with rows*cols == T."""
    r = int(round(math.sqrt(T)))
    while T % r:
        r -= 1
    return r, T // r


def nodes_overlapped(cx, cy, rx, ry, W, H, rows, cols):
    """number of (rows x cols) screen-node regions a centre+radius box overlaps."""
    x0 = np.clip(np.floor((cx - rx) / W * cols), 0, cols - 1)
    x1 = np.clip(np.floor((cx + rx) / W * cols), 0, cols - 1)
    y0 = np.clip(np.floor((cy - ry) / H * rows), 0, rows - 1)
    y1 = np.clip(np.floor((cy + ry) / H * rows), 0, rows - 1)
    return (x1 - x0 + 1) * (y1 - y0 + 1)


def visible_geometry(params, vm, K, W, H, sh):
    _, _, info = gsmodel.render(params, vm, K, W, H, sh)
    gid = info["gaussian_ids"].detach().cpu().numpy()
    radii = info["radii"].detach().float().cpu().numpy()  # [nnz,2]
    m2d = info["means2d"].detach().cpu().numpy()           # [nnz,2]
    return gid, radii, m2d


def run(model_path, out, Ts, S, seed, 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"]
    bounds = F.compute_bounds(params)
    vm = ck["test_viewmats"][:1].cuda()
    K = ck["test_Ks"][:1].cuda()
    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")

    gid, radii, m2d = visible_geometry(params, vm, K, W, H, sh)
    rx = radii[:, 0]; ry = radii[:, 1]
    cx = m2d[:, 0]; cy = m2d[:, 1]
    vis = gid  # global ids of visible primitives
    lg(f"[{scene}] visible primitives={len(vis)} WxH={W}x{H}")

    # sample scale-sign upsets among visible primitives
    sample = rng.choice(len(vis), size=min(S, len(vis)), replace=False)
    stored, work = F.quantize_params(params, "fp32")
    results = {}
    for T in Ts:
        rows, cols = grid_for(T)
        # communication amplification on the clean model
        clean_nodes = nodes_overlapped(cx, cy, rx, ry, W, H, rows, cols)
        comm_clean = float(clean_nodes.mean())

        cont_ng, cont_g, comm_amp = [], [], []
        for s in sample:
            g = int(vis[s]); comp = 0
            flat = g * 3 + comp
            cval, _ = F.flip_one(stored["scales"], work["scales"], flat, 31, "fp32")
            # corrupted geometry: re-render, read this primitive's projected radius
            gid2, radii2, m2d2 = visible_geometry(work, vm, K, W, H, sh)
            loc = np.where(gid2 == g)[0]
            if len(loc):
                i = loc[0]
                n_ng = nodes_overlapped(m2d2[i, 0], m2d2[i, 1], radii2[i, 0], radii2[i, 1], W, H, rows, cols)
            else:
                n_ng = T  # off-screen-huge: treat as global
            # guarded
            gw = F.apply_guard(work, bounds)
            gid3, radii3, m2d3 = visible_geometry(gw, vm, K, W, H, sh)
            loc3 = np.where(gid3 == g)[0]
            if len(loc3):
                j = loc3[0]
                n_g = nodes_overlapped(m2d3[j, 0], m2d3[j, 1], radii3[j, 0], radii3[j, 1], W, H, rows, cols)
            else:
                n_g = 1
            F.restore_one(work["scales"], flat, cval)
            cont_ng.append(float(n_ng)); cont_g.append(float(n_g))
            comm_amp.append(float(n_ng))  # extra transmissions for the corrupted primitive
        cont_ng = np.array(cont_ng); cont_g = np.array(cont_g)
        results[T] = {
            "rows": rows, "cols": cols, "comm_clean": comm_clean,
            "contam_mean_noguard": float(cont_ng.mean()),
            "contam_p99_noguard": float(np.percentile(cont_ng, 99)),
            "contam_frac_noguard": float((cont_ng / T).mean()),
            "contam_mean_guard": float(cont_g.mean()),
            "contam_p99_guard": float(np.percentile(cont_g, 99)),
            "contam_frac_guard": float((cont_g / T).mean()),
        }
        lg(f"  T={T:3d} ({rows}x{cols}) comm_clean={comm_clean:.2f} "
           f"contam(no guard) mean={cont_ng.mean():.1f}/{T} p99={np.percentile(cont_ng,99):.0f} | "
           f"contam(guard) mean={cont_g.mean():.2f}")

    # rendering-based validation: predicted contaminated regions vs actually changed regions
    val = validate_render(work, stored, bounds, vm, K, W, H, sh, vis, sample[:20], rng)
    rt = rank_timing(work, stored, bounds, vm, K, W, H, sh, vis, sample, T=16)
    lg(f"  rank timing T=16: barrier(max rank) clean={rt['clean']['max_ms']:.2f}ms "
       f"corrupt={rt['corrupt']['max_ms']:.2f}ms guard={rt['guard']['max_ms']:.2f}ms; "
       f"imbalance corrupt={rt['corrupt']['imbalance']:.2f} guard={rt['guard']['imbalance']:.2f}")
    out_obj = {"scene": scene, "Ts": {str(k): v for k, v in results.items()},
               "validation": val, "rank_timing": rt}
    json.dump(out_obj, open(os.path.join(out, f"distributed_{scene}.json"), "w"), indent=2)
    lg(f"  validation pred-vs-render IoU={val['mean_iou']:.3f} over {val['n']} cases")


def regions_of_bbox(cx, cy, rx, ry, W, H, rows, cols):
    x0 = int(np.clip(np.floor((cx - rx) / W * cols), 0, cols - 1))
    x1 = int(np.clip(np.floor((cx + rx) / W * cols), 0, cols - 1))
    y0 = int(np.clip(np.floor((cy - ry) / H * rows), 0, rows - 1))
    y1 = int(np.clip(np.floor((cy + ry) / H * rows), 0, rows - 1))
    return {(r, c) for r in range(y0, y1 + 1) for c in range(x0, x1 + 1)}


def validate_render(work, stored, bounds, vm, K, W, H, sh, vis, sample, rng, T=16):
    """Compare the node regions predicted contaminated (from the corrupted
    primitive's projected radius) against the regions whose pixels actually
    change when the scene is rendered.  Reports mean intersection-over-union."""
    rows, cols = grid_for(T)
    clean, _ = F.render_views(work, vm, K, W, H, sh)
    clean = clean[0]
    th, tw = H // rows, W // cols
    ious, n = [], 0
    for s in sample:
        g = int(vis[s]); flat = g * 3
        cval, _ = F.flip_one(stored["scales"], work["scales"], flat, 31, "fp32")
        corr, _ = F.render_views(work, vm, K, W, H, sh)
        gid2, radii2, m2d2 = visible_geometry(work, vm, K, W, H, sh)
        F.restore_one(work["scales"], flat, cval)
        diff = (corr[0] - clean).abs().amax(-1) > (1 / 255)
        actual = set()
        for ri in range(rows):
            for ci in range(cols):
                if bool(diff[ri * th:(ri + 1) * th, ci * tw:(ci + 1) * tw].any()):
                    actual.add((ri, ci))
        loc = np.where(gid2 == g)[0]
        if len(loc):
            i = loc[0]
            pred = regions_of_bbox(m2d2[i, 0], m2d2[i, 1], radii2[i, 0], radii2[i, 1], W, H, rows, cols)
        else:
            pred = {(r, c) for r in range(rows) for c in range(cols)}
        if actual or pred:
            inter = len(actual & pred); union = len(actual | pred)
            ious.append(inter / max(union, 1))
        n += 1
    return {"mean_iou": float(np.mean(ious)) if ious else 0.0, "n": n, "T": T}


def rank_timing(work, stored, bounds, vm, K, W, H, sh, vis, sample, T=16):
    """Per-rank (per-tile) render time under sort-first partitioning, for a clean
    scene, an unguarded scale-sign explosion, and the guarded version.  The slowest
    rank sets the barrier-synchronized frame time; the sum is total compute."""
    import time
    rows, cols = grid_for(T)
    th, tw = H // rows, W // cols

    def render_tile(params, ri, ci):
        Kt = K.clone()
        Kt[0, 0, 2] -= ci * tw
        Kt[0, 1, 2] -= ri * th
        torch.cuda.synchronize(); t = time.time()
        for _ in range(3):
            gsmodel.render(params, vm, Kt, tw, th, sh)
        torch.cuda.synchronize()
        return (time.time() - t) / 3 * 1e3  # ms

    def all_ranks(params):
        ts = [render_tile(params, ri, ci) for ri in range(rows) for ci in range(cols)]
        ts = np.array(ts)
        return {"max_ms": float(ts.max()), "mean_ms": float(ts.mean()),
                "sum_ms": float(ts.sum()), "imbalance": float(ts.max() / ts.mean())}
    # pick a large-footprint scale-sign primitive
    best = (-1, int(vis[sample[0]]))
    clean, _ = F.render_views(work, vm, K, W, H, sh)
    for s in sample[:40]:
        g = int(vis[s]); flat = g * 3
        cv, _ = F.flip_one(stored["scales"], work["scales"], flat, 31, "fp32")
        img, _ = F.render_views(work, vm, K, W, H, sh)
        F.restore_one(work["scales"], flat, cv)
        fp = ((img[0] - clean[0]).abs().amax(-1) > 1 / 255).float().mean().item()
        if fp > best[0]:
            best = (fp, g)
    g = best[1]; flat = g * 3
    clean_t = all_ranks(work)
    cv, _ = F.flip_one(stored["scales"], work["scales"], flat, 31, "fp32")
    corr_t = all_ranks(work)
    guard_t = all_ranks(F.apply_guard(work, bounds))
    F.restore_one(work["scales"], flat, cv)
    return {"T": T, "clean": clean_t, "corrupt": corr_t, "guard": guard_t}


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/distributed")
    ap.add_argument("--Ts", default="4,8,16,32,64")
    ap.add_argument("--S", type=int, default=300)
    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, "distributed.log")
    Ts = [int(x) for x in args.Ts.split(",")]
    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, Ts, args.S, args.seed, log)
    print("DISTRIBUTED_DONE", flush=True)


if __name__ == "__main__":
    main()