from __future__ import annotations import argparse import json import time from pathlib import Path import numpy as np from ..completion.handoff import load_handoff, write_handoff from .losses import frame_loss, make_lpips from .scene import SOURCE, FrameScene, frozen_check, logit, zero_step CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'refinement.json' def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + '.tmp') tmp.write_text(json.dumps(value, indent=1) + '\n') tmp.replace(path) def optimize(scene, targets, masks, supervised, cfg, lpips_fn, theta_init, color_init): import torch theta = theta_init.clone().requires_grad_(True) colors = color_init.clone().requires_grad_(True) opt = torch.optim.Adam([dict(params=[theta], lr=cfg['lr_opacity']), dict(params=[colors], lr=cfg['lr_color'])], eps=cfg['eps']) sup = set(supervised) n = len(scene.calls) losses = [] for step in range(cfg['steps']): opt.zero_grad(set_to_none=True) total = 0. for j in range(n): out, _, _ = scene.render(j, colors, theta) loss, _ = frame_loss(out, targets[j], masks[j], j in sup, lpips_fn, cfg['w_lpips']) (loss / n).backward() total += float(loss.detach()) / n opt.step() losses.append(total) return colors.detach(), theta.detach(), losses def load_cfg(path): return json.loads(Path(path).read_text())['optimizer'] def run_clip(cid, a, cfg, lpips_fn, device): import torch work = Path(a.work) cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False) target0, hmask, _ = load_handoff(Path(a.handoff) / f'{cid}.npz', [SOURCE]) target0, hmask = target0[0], hmask[0] unobserved = cap['unobserved'].numpy().astype(bool) if not np.array_equal(unobserved[SOURCE], hmask): raise ValueError(f'{cid}: hand-off mask != unobserved region of the first input frame') scene = FrameScene(cap, device) context = scene.context is_u = scene.is_u captured_u = max(float(c['opacities'][scene.touched(j).cpu()][is_u[scene.param[j]].cpu()].max()) if is_u[scene.param[j]].any() else 0. for j, c in enumerate(cap['rgb_calls'])) z = zero_step(scene, cap) diag = dict(clip_id=cid, n_open=scene.hw, n_U=int(is_u.sum()), unobserved_pixels=[int(u.sum()) for u in unobserved], motion_fallback=cap['motion_fallback'], captured_U_opacity_max=captured_u, zero_step=z) if z['rgb_max_abs'] != 0 or z['merged_colors_max_abs'] != 0 or z['merged_opacities_max_abs'] != 0 or captured_u != 0: write_json(work / 'diag' / f'{cid}.json', diag) raise RuntimeError(f'{cid}: zero-step check failed {z}, captured U opacity {captured_u}') targets = cap['rgb_final'].numpy().copy(); targets[SOURCE] = target0 targets = torch.from_numpy(targets).to(device) masks = torch.from_numpy(unobserved).to(device) tgt = torch.from_numpy(target0).to(device).reshape(-1, 3) color_init = torch.where(is_u[:, None], tgt, scene.head_colors()) theta_init = torch.where(is_u, torch.full_like(scene.theta0, logit(cfg['opacity_init'])), scene.theta0) start = time.perf_counter() colors, theta, losses = optimize(scene, targets, masks, [SOURCE], cfg, lpips_fn, theta_init, color_init) seconds = time.perf_counter() - start fz = frozen_check(scene, cap['rgb_calls'], colors, theta) if not fz['ok']: raise RuntimeError(f'{cid}: frozen check failed {fz}') inputs = [scene.positions.index(c) for c in context] with torch.no_grad(): views = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in inputs] write_handoff(work / 'views' / f'{cid}.npz', np.stack(views), unobserved[inputs], context, dict(clip_id=cid, content='renders of the input frames after scene optimization')) (work / 'params').mkdir(parents=True, exist_ok=True) torch.save(dict(colors=colors.cpu(), theta=theta.cpu(), den=scene.den.cpu(), is_u=is_u.cpu()), work / 'params' / f'{cid}.pt') diag.update(seconds=seconds, frozen=fz, loss_first=losses[0], loss_last=losses[-1]) write_json(work / 'diag' / f'{cid}.json', diag) print(json.dumps(dict(clip=cid, seconds=round(seconds, 1), loss_first=losses[0], loss_last=losses[-1], n_U=diag['n_U'])), flush=True) def transplant_render(cap, pr, device, indices): import torch scene = FrameScene(cap, device, den=pr['den']) if not torch.equal(scene.is_u.cpu(), pr['is_u']): raise ValueError('unobserved Gaussians of the first input frame differ between the refined capture and this capture') colors, theta = pr['colors'].to(device), pr['theta'].to(device) with torch.no_grad(): frames = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in indices] return np.stack(frames), scene, colors, theta def transplant_depth(scene, colors, theta, indices): import torch from gsplat.rendering import rasterization depths, alphas = [], [] with torch.no_grad(): for j in indices: c, o = scene.merged(j, colors, theta) call = scene.calls[j] kw = dict(means=call['means'], quats=call['quats'], scales=call['scales'], opacities=o, colors=c, viewmats=call['viewmats'], Ks=call['Ks'], width=scene.width, height=scene.height) _, a, _ = rasterization(**kw) ed, _, _ = rasterization(**kw, render_mode='ED') depths.append(ed[0, ..., 0].float().cpu().numpy()); alphas.append(a[0, ..., 0].float().cpu().numpy()) return np.stack(depths), np.stack(alphas) def final_clip(cid, a, device): import torch from ..recon.outputs import write_clip, write_depth_clip work = Path(a.work) pr = torch.load(work / 'params' / f'{cid}.pt', map_location='cpu', weights_only=False) cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False) positions = list(cap['positions']) frames, scene, colors, theta = transplant_render(cap, pr, device, range(len(positions))) depth, alpha = transplant_depth(scene, colors, theta, range(len(positions))) fz = frozen_check(scene, cap['rgb_calls'], colors, theta) if not fz['ok']: raise RuntimeError(f'{cid}: frozen check (final) failed {fz}') line = dict(final=cid, motion_fallback=cap['motion_fallback']) if a.check_capture: cap0 = torch.load(Path(a.check_capture) / f'{cid}.pt', map_location='cpu', weights_only=False) views, _, _, _ = transplant_render(cap0, pr, device, [cap0['positions'].index(c) for c in cap0['context_positions']]) with np.load(work / 'views' / f'{cid}.npz', allow_pickle=False) as h: ref = h['rgb'] line['transplant_bitwise'] = bool(views.tobytes() == ref.astype(np.float32).tobytes()) if not line['transplant_bitwise']: raise RuntimeError(f'{cid}: transplant check failed, max abs {float(np.abs(views - ref).max())}') write_depth_clip(a.out, cid, depth, alpha, positions=positions) write_clip(a.out, cid, frames, positions=positions) print(json.dumps(line), flush=True) return positions def _clips(a): return a.clips or sorted(p.stem for p in Path(a.capture).glob('*.pt') if not p.name.startswith('.')) def main(argv=None): p = argparse.ArgumentParser(prog='agt.refine.refine') sub = p.add_subparsers(dest='cmd', required=True) s = sub.add_parser('run', help='scene optimization on the first capture; writes the input-frame renders') s.add_argument('--capture', required=True, help='capture of the first pass') s.add_argument('--handoff', required=True, help='output of the generative completion (agt.completion.flux_fill)') s.add_argument('--work', required=True, help='refinement directory (views/, params/, diag/)') s.add_argument('--config', default=str(CONFIG)) s.add_argument('--clips', nargs='+') s = sub.add_parser('final', help='apply the optimized Gaussians to the second capture and render colour and depth') s.add_argument('--capture', required=True, help='capture with --repaired /views') s.add_argument('--work', required=True) s.add_argument('--out', required=True, help='final render directory') s.add_argument('--check-capture', default=None, help='first capture: the transplant must reproduce the views') s.add_argument('--clips', nargs='+') a = p.parse_args(argv) if a.cmd == 'run': cfg = load_cfg(a.config) device = 'cuda' lpips_fn = make_lpips(device) for cid in _clips(a): run_clip(cid, a, cfg, lpips_fn, device) else: from ..recon.outputs import write_depth_meta, write_meta positions = None for cid in _clips(a): positions = final_clip(cid, a, 'cuda') done = sorted(d.name for d in Path(a.out).iterdir() if (d / 'frames.npz').is_file()) write_meta(a.out, done, positions, {'method': 'agt'}) write_depth_meta(a.out, done, positions, {'method': 'agt'}) if __name__ == '__main__': main()