from __future__ import annotations import argparse import json import shutil from pathlib import Path import numpy as np from ..completion.handoff import load_handoff from ..model.mask_attention import mask_context FROZEN = ('means', 'quats', 'scales', 'opacities', 'colors', 'viewmats', 'Ks') def splice(first, new, mask): import torch return torch.where(mask, new, first) def capture(a): import torch import gsplat.rendering as GR from ..model import runtime from ..recon import reconstruct as R argv = json.loads(Path(a.render_json).read_text())['command'].split()[1:] if '--shard' in argv: i = argv.index('--shard'); del argv[i:i + 2] out_dir = Path(a.out) rerender = out_dir / 'rerender' argv[argv.index('--out') + 1] = str(rerender) inputs = Path(argv[argv.index('--inputs') + 1]) clips = a.clips or json.loads((inputs / 'manifest.json').read_text())['clips'] clips = [c for c in clips if not (out_dir / f'{c}.pt').is_file()] current = {} def walk(inputs, shard, limit): for c in clips: current['cid'] = c yield c state = {} orig_motion, orig_render = R.motion_sources, R.render def moved(motion_head, ext, k, xyz, gs, dy, conf, mask, images, depth, seed, ctx): rep = state.get('rep_images') src, diag = orig_motion(motion_head, ext, k, xyz, gs, dy, conf, mask, images if rep is None else rep, depth, seed, ctx) if src is None: prev = R.previous_context(ctx, state['positions']) state['dy16'], state['bg16'] = dy[0, prev].float().cpu(), mask[0, prev].cpu() else: state['dy16'], state['bg16'] = src['dy_map'][0].float().cpu(), src['bg_mask'][0].cpu() state['motion_fallback'] = src is None return src, diag def wrapped(model, images, sky, times, validity, target_times, target_positions, context_positions, **kw): cid = current['cid'] cap = dict(clip_id=cid, rgb_calls=[], context_positions=list(context_positions), positions=list(target_positions), repaired=a.repaired is not None) state.clear() state['positions'] = list(target_positions) rep_mask = None if a.repaired: rep_np, rep_mask, _ = load_handoff(Path(a.repaired) / f'{cid}.npz', context_positions) rep_t = torch.from_numpy(rep_np).permute(0, 3, 1, 2)[None].to(images.device, images.dtype) m = torch.from_numpy(rep_mask)[None, :, None].to(images.device) state['rep_images'] = torch.where(m, rep_t, images) orig_pred, orig_ras = runtime.predict, GR.rasterization orig_sky = model.sky_model.forward_with_new_pose def pred_w(model_, images_, occluder_mask, **q): pred, visible = orig_pred(model_, images_, occluder_mask, **q) if rep_mask is not None: dy_first = pred['dynamic_conf'] rep = state['rep_images'] attention = q.get('attention_mask') with mask_context(model_, occluder_mask if attention is None else attention, rep): pr = model_(rep) m = torch.from_numpy(rep_mask).to(dy_first.device)[None, ..., None] pred = dict(pred) pred['dynamic_conf'] = splice(dy_first, pr['dynamic_conf'].to(dy_first.dtype), m) del pr cap['dy4_used'] = pred['dynamic_conf'][0, ..., 0].float().cpu() return pred, visible def ras(**q): res = orig_ras(**q) if q.get('render_mode', 'RGB') != 'ED': cap['rgb_calls'].append({n: q[n].cpu() for n in FROZEN}) return res def sky_w(*p, **q): b = orig_sky(*p, **q) cap['background'] = b.cpu() return b runtime.predict, GR.rasterization = pred_w, ras model.sky_model.forward_with_new_pose = sky_w try: r = orig_render(model, images, sky, times, validity, target_times, target_positions, context_positions, **kw) finally: runtime.predict, GR.rasterization = orig_pred, orig_ras model.sky_model.forward_with_new_pose = orig_sky if kw.get('motion_head') is None: mask = (sky == 0)[None] prev = R.previous_context(context_positions, target_positions) state['dy16'], state['bg16'] = cap['dy4_used'][prev].float(), mask[0, prev].cpu() state['motion_fallback'] = True n_static = len(context_positions) * images.shape[-2] * images.shape[-1] for j in range(len(target_positions)): n_dyn = cap['rgb_calls'][j]['opacities'].shape[0] - n_static if n_dyn != int(state['bg16'][j].sum()): raise ValueError(f'{cid} p{j}: dynamic layer size {n_dyn} != source mask {int(state["bg16"][j].sum())}') cap.update(gate_v=r[2]['gate_v'].cpu(), unobserved=r[2]['unobserved'].cpu(), rgb_final=r[0].clamp(0, 1).float().cpu(), dy16=state['dy16'], bg16=state['bg16'], motion_fallback=state['motion_fallback']) line = dict(captured=cid, calls=len(cap['rgb_calls']), motion_fallback=state['motion_fallback']) if a.pass1: with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h: saved = h['rgb'].astype(np.float32) line['max_abs_vs_pass1'] = float(np.abs(cap['rgb_final'].numpy() - saved).max()) out_dir.mkdir(parents=True, exist_ok=True) tmp = out_dir / f'.{cid}.pt' torch.save(cap, tmp) tmp.replace(out_dir / f'{cid}.pt') print(json.dumps(line), flush=True) return r if not clips: return R._clips, R.render, R.motion_sources = walk, wrapped, moved R.run_finalize = lambda args: None shutil.rmtree(rerender, ignore_errors=True) R.main(argv) missing = [c for c in clips if not (out_dir / f'{c}.pt').is_file()] for log in sorted(rerender.glob('runtime.*.jsonl')): for row in log.read_text().splitlines(): if '"error"' in row: print(row, flush=True) shutil.rmtree(rerender, ignore_errors=True) if missing: raise SystemExit(f'{len(missing)} clips not captured, e.g. {missing[:3]}') def main(argv=None): p = argparse.ArgumentParser(prog='agt.refine.capture') p.add_argument('--render-json', required=True, help='first-pass render..json (its recorded command is re-run)') p.add_argument('--out', required=True) p.add_argument('--repaired', default=None, help='hand-off directory /.npz of repaired input frames') p.add_argument('--pass1', default=None, help='first-pass output directory (prints the difference to its renders)') p.add_argument('--clips', nargs='+', help='clip ids (default: every clip of the export)') capture(p.parse_args(argv)) if __name__ == '__main__': main()