AGT / code /agt /recon /reconstruct.py
MRBSTUDIO's picture
Update the inference and evaluation code
2ad60ce verified
Raw History Blame Contribute Delete
22.8 kB
from __future__ import annotations
import argparse
from contextlib import contextmanager
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import sys
import time
import numpy as np
from . import interp as interp_vectorized
from .outputs import write_clip, write_depth_clip, write_meta, write_depth_meta
from .pose_rule import interpolate_poses
TARGET_SIZE = 518
GRID = (518, 294)
SKY_LABEL = 10
PRECISION = {'matmul': False, 'cudnn': True}
SKY_PRECISION = {'matmul': False, 'cudnn': False}
MOTION_HEAD = 'motion_head.pth'
MOTION_SEQ_LEN = 2
INTERVAL, VIEWS = 5, 1
DY_THRESHOLD, DY_MIN_PIXELS = 0.95, 500
OBSERVABILITY_FILE = 'observability.npz'
def rendered_positions(input_positions) -> list:
return list(range(input_positions[0], input_positions[-1] + 1))
def plain_gate(t, t0, alpha, gamma0=1, gamma1=0.1):
import torch
sigma = torch.log(torch.tensor(gamma1)).to(gamma0.device) / ((gamma0)**2 + 1e-6)
conf = torch.exp(sigma*(t0-t)**2)
alpha_ = alpha * conf
return alpha_.float()
def previous_context(context_positions, positions) -> list:
ctx = list(context_positions)
out = []
for p in positions:
before = [i for i, c in enumerate(ctx) if c <= p]
if not before:
raise ValueError(f'Position {p} precedes the first input frame {ctx[0]} (extrapolation is not rendered)')
out.append(before[-1])
return out
def target_cameras(ext_ctx, k_ctx, t_ctx, context_positions, t_targets, positions):
ext_ctx = np.asarray(ext_ctx, np.float64)
k_ctx = np.asarray(k_ctx, np.float64)
t_ctx = np.asarray(t_ctx, np.float64)
t_targets = np.asarray(t_targets, np.float64)
ctx = list(context_positions)
if ext_ctx.shape != (len(ctx), 4, 4) or k_ctx.shape != (len(ctx), 3, 3) or len(t_targets) != len(positions):
raise ValueError('Inconsistent camera / time shapes')
c2w = interpolate_poses(t_ctx, np.linalg.inv(ext_ctx), t_targets)
ext = np.linalg.inv(c2w)
ks = np.empty((len(positions), 3, 3))
for j, p in enumerate(positions):
if p in ctx:
i = ctx.index(p)
ext[j], ks[j] = ext_ctx[i], k_ctx[i]
continue
a = previous_context(ctx, [p])[0]
if a + 1 >= len(ctx):
raise ValueError(f'Position {p} lies after the last input frame (extrapolation is not rendered)')
alpha = (t_targets[j] - t_ctx[a]) / (t_ctx[a + 1] - t_ctx[a])
ks[j] = (1 - alpha) * k_ctx[a] + alpha * k_ctx[a + 1]
return ext, ks
def clip_seed(clip_id: str) -> int:
return int.from_bytes(hashlib.sha256(clip_id.encode('utf-8')).digest()[:4], 'little')
def interp_frame_index(context_positions, positions) -> list:
if list(context_positions) != [i * INTERVAL for i in range(len(context_positions))]:
raise ValueError(f'inputs {list(context_positions)} are not every {INTERVAL}th sample from 0')
last = (len(context_positions) - 1) * INTERVAL
if any(not 0 <= p <= last for p in positions):
raise ValueError(f'positions outside 0..{last} (extrapolation is not rendered)')
return list(positions)
def move_dynamic(interp_all, motion_model, ext, k, xyz, gs, dy, conf, mask, images, depth, seed: int) -> dict:
np.random.seed(seed)
(ext_i, k_i, point_map, gs_map, dy_map, gs_conf, bg_mask, _, _, _, _) = interp_all(
ext, k, xyz, gs, dy, conf, mask, images, None, depth[0].unsqueeze(0), motion_model, INTERVAL, VIEWS)
return {'extrinsics': ext_i, 'intrinsics': k_i, 'point_map': point_map, 'gs_map': gs_map, 'dy_map': dy_map,
'gs_conf': gs_conf, 'bg_mask': bg_mask}
@contextmanager
def precision(matmul: bool, cudnn: bool):
import torch
old = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32
torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = matmul, cudnn
try:
yield
finally:
torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = old
class _Probe:
def __init__(self, module):
self.calls, self.fits = [], []
inference, dbscan, probe = module.inference, module.DBSCAN, self
def recorded_inference(**kwargs):
start, device = time.perf_counter(), str(kwargs['video'].device)
try:
out = inference(**kwargs)
except Exception as error:
probe.calls.append({'device': device, 'ok': False, 'seconds': time.perf_counter() - start,
'error': f'{type(error).__name__}: {error}'[:300]})
raise
probe.calls.append({'device': device, 'ok': True, 'queries': int(kwargs['query_point'].shape[0]),
'seconds': time.perf_counter() - start})
return out
class RecordedDBSCAN(dbscan):
def fit(self, X, y=None, sample_weight=None):
fitted = super().fit(X, y=y, sample_weight=sample_weight)
probe.fits.append({'points': int(len(fitted.labels_)),
'clusters': len(set(fitted.labels_.tolist()) - {-1})})
return fitted
module.inference, module.DBSCAN = recorded_inference, RecordedDBSCAN
def reset(self):
self.calls, self.fits = [], []
def counting_filter_dense_points(points, radius=0.2, min_neighbors=10, min_total=50):
from scipy.spatial import cKDTree
if len(points) < min_total:
return np.empty((0, 3))
valid_mask = np.isfinite(points).all(axis=1)
points = points[valid_mask]
if len(points) < min_total:
return np.empty((0, 3))
tree = cKDTree(points)
counts = tree.query_ball_point(points, r=radius, return_length=True)
mask = np.asarray(counts) > min_neighbors
filtered = points[mask]
if len(filtered) < min_total:
return np.empty((0, 3))
return filtered
def load_motion_head(dggt_root, ckpt) -> dict:
import importlib
import importlib.util
copy, ckpt = Path(dggt_root).resolve(), Path(ckpt)
if str(copy) not in sys.path:
sys.path.insert(0, str(copy))
importlib.import_module('third_party').__path__ = [str(copy / 'third_party')]
inference_utils = importlib.import_module('third_party.TAPIP3D.utils.inference_utils')
spec = importlib.util.spec_from_file_location('dggt_interplation', copy / 'utils' / 'interplation.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
model = inference_utils.load_model(str(ckpt))
model.to('cuda')
model.seq_len = MOTION_SEQ_LEN
module.filter_dense_points = counting_filter_dense_points
return {'interp_all': interp_vectorized.bind(module), 'model': model, 'probe': _Probe(module)}
def motion_sources(motion_head, ext, k, xyz, gs, dy, conf, mask, images, depth, seed, context_positions):
import torch
probe = motion_head['probe']
probe.reset()
dy_pixels = int((dy.sigmoid() > DY_THRESHOLD)[0, 0].count_nonzero())
diag = {'seed': seed, 'dynamic_pixels_input0': dy_pixels, 'moves_objects': dy_pixels > DY_MIN_PIXELS}
start = time.perf_counter()
try:
src = move_dynamic(motion_head['interp_all'], motion_head['model'], ext, k, xyz, gs, dy, conf, mask, images,
depth, seed)
except UnboundLocalError as error:
if not (diag['moves_objects'] and probe.fits and probe.fits[0]['clusters'] == 0 and not probe.calls):
raise
src, diag['fallback'] = None, f'repeat: interp_all {type(error).__name__} ({error}) with no cluster on input 0'
if torch.cuda.is_available():
torch.cuda.synchronize()
diag.update({'interp_all_seconds': time.perf_counter() - start, 'dbscan_clusters': [f['clusters'] for f in probe.fits],
'objects': probe.fits[0]['clusters'] if probe.fits else 0, 'motion_head_calls': probe.calls})
return src, diag
def render(model, images, sky, times, validity, target_times, target_positions, context_positions,
motion_head=None, seed=None, v_z_tol=None, attention_mask=None):
import torch
from gsplat.rendering import rasterization
from dggt.utils.geometry import unproject_depth_map_to_point_map
from dggt.utils.gs import concat_list, get_split_gs
from dggt.utils.pose_enc import pose_encoding_to_extri_intri
from ..model.runtime import predict, render_visibility
pred, online_v = predict(model, images, ~validity, **({'attention_mask': attention_mask} if attention_mask is not None else {}),
**({'z_tol': v_z_tol} if v_z_tol is not None else {}))
h, w = images.shape[-2:]
ext, k = pose_encoding_to_extri_intri(pred['pose_enc'], (h, w)); ext = ext[0]; k = k[0]
xyz = torch.from_numpy(unproject_depth_map_to_point_map(pred['depth'][0], ext, k)[None]).to(images.device).float()
ext = torch.cat([ext, ext.new_tensor([0, 0, 0, 1])[None, None].expand(len(ext), 1, 4)], 1)
dy = pred['dynamic_conf'].squeeze(-1); gs = pred['gs_map']; conf = pred['gs_conf']
mask = (sky == 0)[None]
static = torch.ones_like(mask)
points = xyz[static].reshape(-1, 3); rgb, opacity, scales, quats = get_split_gs(gs, static)
opacity = opacity * (1 - dy[static].sigmoid()); gamma = conf[static]
frame = torch.nonzero(static, as_tuple=False)[:, 1]; t = times[frame]
ext_np, k_np = target_cameras(ext.double().cpu().numpy(), k.double().cpu().numpy(), times.double().cpu().numpy(),
context_positions, target_times.double().cpu().numpy(), target_positions)
ext_t = torch.as_tensor(ext_np, dtype=ext.dtype, device=ext.device)
k_t = torch.as_tensor(k_np, dtype=k.dtype, device=k.device)
dynamic_from = previous_context(context_positions, target_positions)
src, motion_diag = None, None
if motion_head is not None:
frame_of = interp_frame_index(context_positions, target_positions)
src, motion_diag = motion_sources(motion_head, ext, k, xyz, gs, dy, conf, mask, images, pred['depth'], seed,
context_positions)
renders, alphas, depths = [], [], []
for j in range(len(target_positions)):
if src is None:
i = dynamic_from[j]
bm = mask[:, i]; dr, do, ds, dq = get_split_gs(gs[:, i], bm)
do = do * dy[:, i][bm].sigmoid()
dynamic_points = xyz[:, i][bm].reshape(-1, 3)
else:
f = frame_of[j]
bm = src['bg_mask'][:, f]; dr, do, ds, dq = get_split_gs(src['gs_map'][:, f], bm)
do = do * src['dy_map'][:, f][bm].sigmoid()
dynamic_points = src['point_map'][:, f][bm].reshape(-1, 3)
static_opacity = plain_gate(t, target_times[j], opacity, gamma0=gamma)
pts, c, o, s, q = concat_list([points, rgb, static_opacity, scales, quats], [dynamic_points, dr, do, ds, dq])
r, a, _ = rasterization(means=pts, quats=q, scales=s, opacities=o, colors=c, viewmats=ext_t[j:j + 1],
Ks=k_t[j:j + 1], width=w, height=h)
renders.append(r); alphas.append(a)
ed, _, _ = rasterization(means=pts, quats=q, scales=s, opacities=o, colors=c, viewmats=ext_t[j:j + 1],
Ks=k_t[j:j + 1], width=w, height=h, render_mode='ED')
depths.append(ed[..., 0])
alpha = torch.cat(alphas); foreground = torch.cat(renders)
background = model.sky_model.forward_with_new_pose(images, ext, k, ext_t, k_t)
out = alpha * foreground + (1 - alpha) * background
depth = torch.cat(depths)
ctx = list(context_positions)
unobserved = torch.zeros(depth.shape, dtype=torch.bool, device=depth.device)
held_out = [j for j, p in enumerate(target_positions) if p not in ctx]
for j, p in enumerate(target_positions):
if p in ctx:
unobserved[j] = ~online_v[0, ctx.index(p)]
if held_out:
observed = render_visibility(pred['depth'][..., 0], k[None], ext[None], depth[held_out][None], k_t[held_out][None],
ext_t[held_out][None], ~validity,
z_tol=model._options['v_z_tol'] if v_z_tol is None else v_z_tol)
unobserved[held_out] = ~observed[0]
diag = {'sources': int(mask.sum()), 'alpha_mean': float(alpha.mean())}
if motion_diag is not None:
diag['motion_head'] = motion_diag
auxiliary = {'depth': depth, 'alpha': alpha[..., 0], 'gate_v': online_v[0].to(torch.uint8), 'unobserved': unobserved}
return out, diag, auxiliary
def _clips(inputs: Path, shard: str | None, limit: int | None):
clips = json.loads((inputs / 'manifest.json').read_text())['clips']
if shard:
i, n = (int(x) for x in shard.split('/'))
clips = clips[i::n]
return clips[:limit] if limit else clips
def open_masks(args):
from ..masks.io import DatasetMasks, MaskDir, MaskImages
if args.masks == 'dataset':
if not args.data_root:
raise SystemExit('--masks dataset needs --data-root')
return DatasetMasks(args.data_root, args.mask_dilate)
if not args.mask_dir:
raise SystemExit(f'--masks {args.masks} needs --mask-dir')
return (MaskDir if args.masks == 'dir' else MaskImages)(args.mask_dir, args.mask_dilate)
def run_render(args) -> None:
import importlib.metadata as md
from concurrent.futures import ThreadPoolExecutor
import torch
from PIL import Image
from ..model.build import DGGT_ROOT, add_dggt_to_path, build_model, load_config
from .preprocess import PilResize
from .sky import load_segformer, slide_inference
add_dggt_to_path()
pil_resize = PilResize(TARGET_SIZE)
torch.manual_seed(20260929); np.random.seed(20260929)
torch.backends.cudnn.benchmark = False
inputs, out = Path(args.inputs), Path(args.out)
out.mkdir(parents=True, exist_ok=True)
config = load_config(args.config)
v_z_tol = config['visibility_depth_tolerance']
masks = open_masks(args)
seg = load_segformer(args.segformer)
model = build_model(config, args.checkpoint, args.checkpoint_dir)
motion_head = None
if args.input_frames is None or rendered_positions(args.input_frames) != args.input_frames:
ckpt = args.motion_head or Path(args.checkpoint_dir or 'checkpoints') / MOTION_HEAD
motion_head = load_motion_head(DGGT_ROOT, ckpt)
versions = {}
for name in ('torch', 'torchvision', 'gsplat', 'numpy', 'scipy', 'pillow', 'transformers'):
try:
versions[name] = md.version(name)
except md.PackageNotFoundError:
versions[name] = None
tag = args.shard.replace('/', 'of') if args.shard else 'all'
record = {'command': ' '.join(sys.argv), 'started_utc': datetime.now(timezone.utc).isoformat(),
'python': sys.version.split()[0], 'packages': versions, 'gpu': torch.cuda.get_device_name(0),
'config': config, 'masks': args.masks, 'mask_dilate': args.mask_dilate,
'input_frames': args.input_frames, 'v_z_tol': v_z_tol}
(out / f'render.{tag}.json').write_text(json.dumps(record, indent=1) + '\n')
log = (out / f'runtime.{tag}.jsonl').open('a')
writer = ThreadPoolExecutor(max_workers=2)
pending = []
for clip_id in _clips(inputs, args.shard, args.limit):
done = [out / clip_id / n for n in ('frames.npz', 'depth.npz', OBSERVABILITY_FILE)]
if all(p.is_file() for p in done):
continue
try:
clip = json.loads((inputs / clip_id / 'clip.json').read_text())
ctx = list(args.input_frames or clip['context_positions'])
targets = rendered_positions(ctx)
held_out = targets != ctx
occluder_mask, attention_np = masks.load(clip)
validity_np = ~occluder_mask
torch.cuda.synchronize(); start = time.perf_counter()
frames, skies = [], []
for p in ctx:
with Image.open(inputs / clip_id / clip['frame_files'][p]) as image:
image = image.convert('RGB')
rgb_t = pil_resize(np.asarray(image)[None])[0]
if tuple(rgb_t.shape) != (3, GRID[1], GRID[0]):
raise ValueError(f'PilResize gave {tuple(rgb_t.shape)}')
frames.append(rgb_t)
source = np.asarray(image).copy()
with precision(**SKY_PRECISION), torch.inference_mode():
labels = slide_inference(seg, source[..., ::-1].copy(), 'cuda', torch.float32)
sky = np.asarray(Image.fromarray((labels == SKY_LABEL).astype(np.uint8) * 255)
.resize(GRID, Image.Resampling.BICUBIC)).astype(np.float32) / 255
skies.append(sky)
images = torch.stack(frames)[None].cuda()
sky = torch.from_numpy(np.stack(skies)).cuda()
validity = torch.from_numpy(validity_np)[None, None].expand(1, len(ctx), -1, -1).contiguous().cuda()
t_norm = torch.tensor(clip['t_norm'], dtype=torch.float64, device='cuda')
t_norm = (t_norm - t_norm[ctx[0]]) / (t_norm[ctx[-1]] - t_norm[ctx[0]])
attention_mask = torch.from_numpy(attention_np)[None, None].expand(1, len(ctx), -1, -1).to(images.device)
with precision(**PRECISION), torch.no_grad():
rgb, diag, aux = render(model, images, sky, t_norm[ctx], validity, t_norm[targets], targets, ctx,
motion_head=motion_head if held_out else None,
seed=clip_seed(clip_id) if held_out else None,
v_z_tol=v_z_tol, attention_mask=attention_mask)
rgb = rgb.clamp(0, 1).float()
torch.cuda.synchronize(); seconds = time.perf_counter() - start
rgb = rgb.cpu().numpy().astype(np.float32)
if rgb.shape != (len(targets), GRID[1], GRID[0], 3) or not np.isfinite(rgb).all():
raise ValueError(f'render {rgb.shape}, finite={np.isfinite(rgb).all()}')
depth_np = aux['depth'].float().cpu().numpy(); alpha_np = aux['alpha'].float().cpu().numpy()
write_depth_clip(out, clip_id, depth_np, alpha_np, targets)
clip_out = out / clip_id
clip_out.mkdir(parents=True, exist_ok=True)
np.savez_compressed(clip_out / OBSERVABILITY_FILE, unobserved=aux['unobserved'].cpu().numpy().astype(np.uint8),
positions=np.asarray(targets), input_positions=np.asarray(ctx))
pending.append((clip_id, writer.submit(write_clip, out, clip_id, rgb, targets)))
log.write(json.dumps({'clip_id': clip_id, 'seconds': seconds,
'peak_vram_gb': torch.cuda.max_memory_allocated() / 1e9,
'valid_fraction': float(validity_np.mean()), **diag}) + '\n')
except Exception as error:
log.write(json.dumps({'clip_id': clip_id, 'error': f'{type(error).__name__}: {error}'}) + '\n')
log.flush()
while len(pending) > 4:
cid, fut = pending.pop(0)
try:
fut.result()
except Exception as error:
log.write(json.dumps({'clip_id': cid, 'error': f'write {type(error).__name__}: {error}'}) + '\n')
for cid, fut in pending:
try:
fut.result()
except Exception as error:
log.write(json.dumps({'clip_id': cid, 'error': f'write {type(error).__name__}: {error}'}) + '\n')
writer.shutdown()
log.close()
if not args.shard:
run_finalize(args)
def run_finalize(args) -> None:
inputs, out = Path(args.inputs), Path(args.out)
manifest = json.loads((inputs / 'manifest.json').read_text())
missing = [c for c in manifest['clips'] if not (out / c / 'frames.npz').is_file()]
if missing:
raise SystemExit(f'{len(missing)} clips without renders, e.g. {missing[:3]}; see runtime.*.jsonl')
first = json.loads(next(iter(sorted(out.glob('render.*.json')))).read_text())
clip = json.loads((inputs / manifest['clips'][0] / 'clip.json').read_text())
positions = rendered_positions(first['input_frames'] or clip['context_positions'])
write_meta(out, manifest['clips'], positions, {'method': 'agt', 'config': first['config']})
write_depth_meta(out, manifest['clips'], positions, {'method': 'agt'})
print(json.dumps({'out': str(out), 'clips': len(manifest['clips'])}))
def main(argv=None) -> None:
p = argparse.ArgumentParser(prog='agt.recon.reconstruct')
p.add_argument('step', choices=('render', 'finalize'))
p.add_argument('--inputs', required=True, help='clip export directory (manifest.json + <clip>/clip.json + frames)')
p.add_argument('--out', required=True, help='output directory')
p.add_argument('--config', default=None, help='model config (default configs/model.json)')
p.add_argument('--checkpoint', help='reconstruction checkpoint (default <checkpoint-dir>/agt_reconstruction.safetensors)')
p.add_argument('--checkpoint-dir', default='checkpoints', help='directory with the released and third-party weights')
p.add_argument('--segformer', default='nvidia/segformer-b5-finetuned-cityscapes-1024-1024',
help='SegFormer-B5 Cityscapes: Hugging Face id or local directory')
p.add_argument('--motion-head', help=f'motion head checkpoint (default <checkpoint-dir>/{MOTION_HEAD})')
p.add_argument('--masks', choices=('dataset', 'dir', 'images'), default='dataset',
help='dataset: predicted masks of the AmodalDrive data root; dir: per-clip npz from tools/make_masks.py; '
'images: <mask-dir>/<clip_id>.png (255 = occluder)')
p.add_argument('--data-root', help='AmodalDrive data root (--masks dataset)')
p.add_argument('--mask-dir')
p.add_argument('--mask-dilate', type=int, default=0, help='mask dilation radius in pixels on the 294x518 grid')
p.add_argument('--input-frames', type=int, nargs='+',
help='positions of the input frames in the clip (default: context_positions of clip.json); the frames '
'from the first to the last input are rendered, and the motion head moves the dynamic Gaussians '
'to the frames between the inputs')
p.add_argument('--shard', help='i/n: every n-th clip from i (run finalize after all shards)')
p.add_argument('--limit', type=int, help='render only the first n clips')
args = p.parse_args(argv)
if args.config is None:
from ..model.build import DEFAULT_CONFIG
args.config = DEFAULT_CONFIG
if args.step == 'render':
run_render(args)
else:
run_finalize(args)
if __name__ == '__main__':
main()