seu-3dgs / code /campaign_batched.py
Lightcap's picture
Upload folder using huggingface_hub
121e1fb verified
Raw
History Blame Contribute Delete
5.29 kB
"""Batched parallel fault injection: render B independently-corrupted variants of
the scene in a single rasterizer call, so the device is saturated rather than
latency-bound. The batch buffer is allocated once; each step flips one bit in one
parameter of each batch element (vectorized, no Python loop), renders all B at
once, scores them against the clean image, then restores. Reports sustained
injection throughput and GPU utilisation.
"""
import argparse
import json
import os
import subprocess
import threading
import time
import numpy as np
import torch
from gsplat import rasterization
FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]
FIELD_ID = {f: i for i, f in enumerate(FIELDS)}
def util_sampler(stop, out):
while not stop.is_set():
try:
r = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,power.draw",
"--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=5)
u, p = r.stdout.strip().split("\n")[0].split(",")
out.append((float(u), float(p)))
except Exception:
pass
stop.wait(1.0)
def render_batch(wb, sh, vm, K, W, H):
colors = torch.cat([wb["sh0"], wb["shN"]], dim=2)
renders, alphas, _ = rasterization(
wb["means"], wb["quats"], torch.exp(wb["scales"]), torch.sigmoid(wb["opacities"]),
colors, vm, K, W, H, sh_degree=sh, packed=True, rasterize_mode="classic")
return (renders + (1.0 - alphas)).clamp(0, 1)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="/root/seu/results/chair/model.pt")
ap.add_argument("--out", default="/root/seu/results/batched")
ap.add_argument("--B", type=int, default=32)
ap.add_argument("--minutes", type=float, default=8.0)
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
os.makedirs(args.out, exist_ok=True)
dev = "cuda"
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, W, H = ck["sh_degree"], ck["W"], ck["H"]
N = params["means"].shape[0]
B = args.B
vmb = ck["test_viewmats"][:1].to(dev)[None].repeat(B, 1, 1, 1).contiguous()
Kb = ck["test_Ks"][:1].to(dev)[None].repeat(B, 1, 1, 1).contiguous()
comps = {f: params[f].reshape(N, -1).shape[1] for f in FIELDS}
# allocate the batch buffer once: B identical clean copies
wb = {k: params[k][None].repeat(B, *([1] * params[k].dim())).contiguous() for k in FIELDS}
clean = render_batch({k: params[k][None] for k in FIELDS}, sh, vmb[:1], Kb[:1], W, H)[0, 0]
rows_b = torch.arange(B, device=dev)
g = torch.Generator(device=dev); g.manual_seed(args.seed)
def step():
fi = int(torch.randint(0, 6, (1,), generator=g, device=dev).item())
field = FIELDS[fi]; Cf = comps[field]
fb = wb[field].reshape(B, N * Cf) # view of the batch buffer
iv = fb.view(torch.int32)
idx = torch.randint(0, N * Cf, (B,), generator=g, device=dev) # int64 index
bit = torch.randint(0, 32, (B,), generator=g, device=dev, dtype=torch.int32)
clean_int = iv[rows_b, idx].clone()
mask = (torch.ones(B, dtype=torch.int32, device=dev) << bit)
iv[rows_b, idx] = clean_int ^ mask # vectorized flip
img = render_batch(wb, sh, vmb, Kb, W, H) # [B,1,H,W,3]
d = (img[:, 0] - clean).abs()
fr = (d.amax(-1) > 1 / 255).float().mean(dim=(1, 2))
finite = torch.isfinite(img).all(dim=(1, 2, 3, 4))
iv[rows_b, idx] = clean_int # vectorized restore
bitc = torch.where(bit == 31, 0, torch.where(bit >= 23, 1, 2))
out = torch.stack([torch.full((B,), fi, device=dev), bit.float(), bitc.float(),
fr, ((~finite) | (fr > 0.01)).float()], dim=1)
return out.cpu().numpy()
for _ in range(3):
step()
torch.cuda.synchronize()
stop = threading.Event(); samples = []
th = threading.Thread(target=util_sampler, args=(stop, samples)); th.start()
t0 = time.time(); n_inj = 0; allrows = []
while time.time() - t0 < args.minutes * 60:
allrows.append(step()); n_inj += B
torch.cuda.synchronize(); dt = time.time() - t0
stop.set(); th.join()
util = np.array([s[0] for s in samples]) if samples else np.array([0.0])
powr = np.array([s[1] for s in samples]) if samples else np.array([0.0])
arr = np.concatenate(allrows, 0)
np.savez_compressed(os.path.join(args.out, "batched_rows.npz"), data=arr,
cols=np.array(["field_id", "bit", "bitclass", "fracchg", "cat"]))
res = {"N": int(N), "B": B, "W": W, "H": H, "minutes": args.minutes,
"injections": int(n_inj), "seconds": dt, "inj_per_s": n_inj / dt,
"batches_per_s": (n_inj / B) / dt, "gaussian_instances_per_render": int(B * N),
"mean_util": float(util.mean()), "p50_util": float(np.median(util)),
"max_util": float(util.max()), "mean_power_w": float(powr.mean())}
json.dump(res, open(os.path.join(args.out, "batched.json"), "w"), indent=2)
print("BATCHED_RESULT", json.dumps(res), flush=True)
if __name__ == "__main__":
main()