AGT / code /agt /refine /scene.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
6.32 kB
from __future__ import annotations
import math
import numpy as np
from ..recon.reconstruct import previous_context
from .capture import FROZEN
SOURCE = 0
O_CLAMP = 1e-6
def logit(p):
return math.log(p / (1 - p))
def dynamic_entries(bg, u_src):
bg = np.asarray(bg, bool)
rank = np.cumsum(bg.ravel()) - 1
sel = (np.asarray(u_src, bool) & bg).ravel()
flat = np.flatnonzero(sel)
return rank[flat], flat
def o_raw_estimate(op0_static, op0_dyn, dyn_flat, static_mult):
o = np.asarray(op0_static, np.float64) / np.maximum(np.asarray(static_mult, np.float64), 1e-30)
o[dyn_flat] = np.asarray(op0_static, np.float64)[dyn_flat] + np.asarray(op0_dyn, np.float64)
return o
class FrameScene:
def __init__(self, cap, device, den=None, height=294, width=518):
import torch
self.calls = [{k: c[k].to(device) for k in FROZEN} for c in cap['rgb_calls']]
self.background = cap['background'].to(device)
self.height, self.width, self.device = height, width, device
self.context, self.positions = list(cap['context_positions']), list(cap['positions'])
prev = previous_context(self.context, self.positions)
gate_v = cap['gate_v'].numpy()
hw = height * width
n_static = len(self.context) * hw
self.hw = hw
self.idx = torch.arange(hw, device=device)
is_u = gate_v[SOURCE].ravel() == 0
self.is_u = torch.from_numpy(is_u).to(device)
dy0 = cap['dy4_used'][SOURCE].numpy().ravel()
static_mult = 1 / (1 + np.exp(dy0))
self.touched_idx, self.param, self.A, self.n_dyn = [], [], [], []
dyn0 = None
for j in range(len(self.calls)):
if prev[j] == SOURCE:
rank, flat = dynamic_entries(cap['bg16'][j].numpy(), np.ones((height, width), bool))
n_dyn = self.calls[j]['means'].shape[0] - n_static
if len(rank) and rank.max() >= n_dyn:
raise ValueError(f'call {j}: dynamic rank {rank.max()} >= {n_dyn}')
dyn_mult = 1 / (1 + np.exp(-cap['dy16'][j].numpy().ravel()[flat]))
else:
rank, flat, dyn_mult = np.zeros(0, np.int64), np.zeros(0, np.int64), np.zeros(0, np.float32)
touched = torch.from_numpy(np.concatenate([np.arange(hw), n_static + rank])).long().to(device)
param = torch.from_numpy(np.concatenate([np.arange(hw), flat])).long().to(device)
mult_u = torch.from_numpy(np.concatenate([static_mult, dyn_mult]).astype(np.float32)).to(device)
A = torch.where(self.is_u[param], mult_u, self.calls[j]['opacities'][touched])
self.touched_idx.append(touched); self.param.append(param); self.A.append(A); self.n_dyn.append(int(len(rank)))
if j == 0:
dyn0 = (flat, self.calls[0]['opacities'][n_static + torch.from_numpy(rank).to(device)].cpu().numpy())
op0 = self.calls[0]['opacities'][:hw].cpu().numpy()
o_est = np.clip(o_raw_estimate(op0, dyn0[1], dyn0[0], static_mult), O_CLAMP, 1 - O_CLAMP)
self.theta0 = torch.from_numpy(np.log(o_est / (1 - o_est)).astype(np.float32)).to(device)
if den is None:
den = torch.where(self.is_u, torch.ones_like(self.theta0), self.theta0.sigmoid())
self.den = den.to(device)
def touched(self, j):
return self.touched_idx[j]
def head_colors(self):
return self.calls[0]['colors'][self.idx].clone()
def merged(self, j, colors=None, theta=None):
call = self.calls[j]
if colors is None and theta is None:
return call['colors'], call['opacities']
r = theta.sigmoid() / self.den
p, t = self.param[j], self.touched_idx[j]
return call['colors'].index_copy(0, t, colors[p]), call['opacities'].index_copy(0, t, r[p] * self.A[j])
def zero_theta(self):
import torch
return torch.where(self.is_u, torch.full_like(self.theta0, -math.inf), self.theta0)
def rasterize(self, j, colors, opacities):
from gsplat.rendering import rasterization
call = self.calls[j]
r, a, _ = rasterization(means=call['means'], quats=call['quats'], scales=call['scales'], opacities=opacities, colors=colors,
viewmats=call['viewmats'], Ks=call['Ks'], width=self.width, height=self.height)
return r[0], a[0]
def render(self, j, colors=None, theta=None):
fg, alpha = self.rasterize(j, *self.merged(j, colors, theta))
return alpha * fg + (1 - alpha) * self.background[j], fg, alpha
def frozen_check(scene, calls, colors, theta):
import torch
out = dict(stored_max_abs={}, merged_other_colors_max_abs=0., merged_other_opacities_max_abs=0.)
for j, cap in enumerate(calls):
for k in FROZEN:
d = float((scene.calls[j][k].cpu() - cap[k]).abs().max())
out['stored_max_abs'][k] = max(out['stored_max_abs'].get(k, 0.), d)
c, o = scene.merged(j, colors, theta)
keep = torch.ones(cap['means'].shape[0], dtype=torch.bool); keep[scene.touched(j).cpu()] = False
if keep.any():
out['merged_other_colors_max_abs'] = max(out['merged_other_colors_max_abs'], float((c.cpu()[keep] - cap['colors'][keep]).abs().max()))
out['merged_other_opacities_max_abs'] = max(out['merged_other_opacities_max_abs'], float((o.cpu()[keep] - cap['opacities'][keep]).abs().max()))
out['ok'] = all(v == 0 for v in out['stored_max_abs'].values()) and out['merged_other_colors_max_abs'] == 0 and out['merged_other_opacities_max_abs'] == 0
return out
def zero_step(scene, cap):
import torch
colors0, theta0 = scene.head_colors(), scene.zero_theta()
merged_c, merged_o, rgb = 0., 0., 0.
with torch.no_grad():
for j in range(len(scene.calls)):
c, o = scene.merged(j, colors0, theta0)
merged_c = max(merged_c, float((c - scene.calls[j]['colors']).abs().max()))
merged_o = max(merged_o, float((o - scene.calls[j]['opacities']).abs().max()))
out, _, _ = scene.render(j, colors0, theta0)
rgb = max(rgb, float((out.clamp(0, 1).float().cpu() - cap['rgb_final'][j]).abs().max()))
return dict(merged_colors_max_abs=merged_c, merged_opacities_max_abs=merged_o, rgb_max_abs=rgb)