File size: 5,783 Bytes
121e1fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Real two-GPU distributed sort-first rendering with the node-local support guard.

Each of the two physical GPUs is a rendering node (rank) that renders one screen
half of the same model and contributes it to the composite over the real PCIe
interconnect (NCCL all-gather). We measure, on actual hardware rather than by
emulation: per-rank render time and load imbalance, the inter-GPU transfer time and
bandwidth for compositing, how many nodes a single scale-sign upset contaminates,
and how the node-local guard (applied independently on each GPU's replica before it
renders) contains that contamination. This validates the distributed claims against
a genuine multi-GPU interconnect.
"""
import argparse
import json
import os
import time

import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

import faultlib as F


def render_half(params, rank, world, vm, Kfull, W, H, sh):
    Wh = W // world
    K = Kfull.clone()
    K[0, 0, 2] = K[0, 0, 2] - rank * Wh   # shift principal point to this node's column band
    img, _ = F.render_views(params, vm, K, Wh, H, sh)
    return img[0].contiguous()            # [H, Wh, 3]


def worker(rank, world, args):
    os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
    os.environ.setdefault("MASTER_PORT", "29517")
    dist.init_process_group("nccl", rank=rank, world_size=world)
    torch.cuda.set_device(rank)
    dev = f"cuda:{rank}"
    ck = torch.load(args.model, map_location=dev, weights_only=False)
    params = {k: v.to(dev).float() for k, v in ck["params"].items()}
    sh, W0, H0 = ck["sh_degree"], ck["W"], ck["H"]
    vm = ck["test_viewmats"][:1].to(dev)
    K = ck["test_Ks"][:1].to(dev).clone()
    # render at a larger frame (supersample) so the inter-GPU transfer is bandwidth-
    # rather than latency-bound; scale the intrinsics accordingly
    W = H = args.render_W
    s = W / W0
    K[0, :2, :] = K[0, :2, :] * s
    Wh = W // world
    bounds = F.compute_bounds(params)
    stored, work = F.quantize_params(params, "fp32")
    N = params["means"].shape[0]

    # rank 0 finds a frame-spanning scale-sign upset and broadcasts the site
    site = torch.zeros(1, dtype=torch.long, device=dev)
    if rank == 0:
        cfull, _ = F.render_views(work, vm, K, W, H, sh)
        rng = np.random.default_rng(0); best = (-1.0, 0)
        for _ in range(80):
            gi = int(rng.integers(0, N)); flat = gi * 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] - cfull[0]).abs().amax(-1) > 1 / 255).float().mean().item()
            if fp > best[0]:
                best = (fp, flat)
        site[0] = best[1]
    dist.broadcast(site, src=0)
    flat = int(site[0].item())

    def render_gather(p, reps=25):
        render_half(p, rank, world, vm, K, W, H, sh)        # warmup (untimed)
        dist.barrier()
        rts, gts = [], []
        full = None
        for _ in range(reps):
            torch.cuda.synchronize(); t = time.time()
            half = render_half(p, rank, world, vm, K, W, H, sh)
            torch.cuda.synchronize(); rts.append(time.time() - t)
            halves = [torch.zeros_like(half) for _ in range(world)]
            torch.cuda.synchronize(); t2 = time.time()
            dist.all_gather(halves, half)                   # real inter-GPU transfer
            torch.cuda.synchronize(); gts.append(time.time() - t2)
            full = torch.cat(halves, dim=1)
        rt = float(np.median(rts)); gt = float(np.median(gts))
        rtimes = [torch.zeros(1, device=dev) for _ in range(world)]
        dist.all_gather(rtimes, torch.tensor([rt], device=dev))
        return full, [float(x.item()) for x in rtimes], gt, half.numel() * 4 * (world - 1)

    clean_full, ct, cg, _ = render_gather(work)
    cv, _ = F.flip_one(stored["scales"], work["scales"], flat, 31, "fp32")
    corr_full, xt, xg, xb = render_gather(work)
    gw = F.apply_guard(work, bounds)
    guard_full, gt, gg, _ = render_gather(gw)
    F.restore_one(work["scales"], flat, cv)

    if rank == 0:
        def nodes_changed(full):
            d = (full - clean_full).abs().amax(-1) > (1 / 255)
            return sum(int(bool(d[:, r * Wh:(r + 1) * Wh].any())) for r in range(world))
        res = {"world": world, "W": W, "H": H, "Wh": Wh, "N": int(N),
               "clean_rank_ms": [t * 1e3 for t in ct],
               "corrupt_rank_ms": [t * 1e3 for t in xt],
               "guard_rank_ms": [t * 1e3 for t in gt],
               "transfer_ms": xg * 1e3, "transfer_bytes": int(xb),
               "transfer_gbps": (xb / 1e9) / xg if xg > 0 else 0,
               "imbalance_corrupt": max(xt) / (sum(xt) / world),
               "imbalance_guard": max(gt) / (sum(gt) / world),
               "contam_corrupt_nodes": nodes_changed(corr_full),
               "contam_guard_nodes": nodes_changed(guard_full),
               "frame_ms_clean": max(ct) * 1e3 + cg * 1e3,
               "frame_ms_corrupt": max(xt) * 1e3 + xg * 1e3,
               "frame_ms_guard": max(gt) * 1e3 + gg * 1e3}
        json.dump(res, open(args.out, "w"), indent=2)
        print("MULTIGPU_RESULT", json.dumps(res), flush=True)
    dist.barrier(); dist.destroy_process_group()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", default="/root/seu/results/chair/model.pt")
    ap.add_argument("--out", default="/root/seu/results/multigpu.json")
    ap.add_argument("--world", type=int, default=2)
    ap.add_argument("--render_W", type=int, default=1600)
    args = ap.parse_args()
    mp.spawn(worker, args=(args.world, args), nprocs=args.world, join=True)


if __name__ == "__main__":
    main()