Spaces:
Running on Zero

4danything / anything4d /model /decoder4d.py
multimodalart's picture
multimodalart HF Staff
4DAnything demo
72f8c75 verified
Raw History Blame Contribute Delete
10.6 kB
"""4D decoder: packed SLat of a clip -> canonical Gaussians G* and one node deformation field per frame.
Deformation stream: the SLat Gaussian decoder runs on one copy of the canonical latent per frame; in its last
`n_cross` blocks copy t reads frame t (and every other copy) through cross-frame adapters, and a node head
predicts per-node transforms canonical -> t. Canonical stream: a second decoder on the canonical latent reads every
frame and predicts G* plus a per-node [weight, log-radius, opacity]. Nodes are 1000 FPS voxel centres;
Gaussians are carried by PAD3R-style hybrid (LBS/DQS) skinning.
"""
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
NODE_CH = 15
def _quat_mul(a, b):
aw, ax, ay, az = a.unbind(-1); bw, bx, by, bz = b.unbind(-1)
return torch.stack([aw*bw - ax*bx - ay*by - az*bz,
aw*bx + ax*bw + ay*bz - az*by,
aw*by - ax*bz + ay*bw + az*bx,
aw*bz + ax*by - ay*bx + az*bw], -1)
def _quat_to_mat(q):
"""Quaternion residual around identity -> rotation matrix."""
q = q + q.new_tensor([1.0, 0.0, 0.0, 0.0])
q = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-8)
w, x, y, z = q.unbind(-1)
return torch.stack([
1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y),
2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x),
2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)], -1).reshape(*q.shape[:-1], 3, 3)
def strain_to_matrix(s6):
"""I + symmetric(diag=s[:3], off=s[3:])."""
m = torch.zeros(*s6.shape[:-1], 9, dtype=s6.dtype, device=s6.device)
m[..., [0, 4, 8]] = 1.0
m[..., [0, 4, 8]] = m[..., [0, 4, 8]] + s6[..., :3]
m[..., [1, 2, 5]] = m[..., [1, 2, 5]] + s6[..., 3:]
m[..., [3, 6, 7]] = m[..., [3, 6, 7]] + s6[..., 3:]
return m.reshape(*s6.shape[:-1], 3, 3)
def dqs_blend(q, t, w):
"""Dual-quaternion linear blending. q (N,k,4) unit, t (N,k,3), w (N,k)."""
qd = 0.5 * _quat_mul(torch.cat([torch.zeros_like(t[..., :1]), t], -1), q)
qr = (q * w[..., None]).sum(-2)
qd = (qd * w[..., None]).sum(-2)
n = qr.norm(dim=-1, keepdim=True).clamp_min(1e-8)
qr, qd = qr / n, qd / n
qd = qd - qr * (qr * qd).sum(-1, keepdim=True)
R = _quat_to_mat(qr - qr.new_tensor([1.0, 0.0, 0.0, 0.0]))
tt = 2.0 * _quat_mul(qd, torch.cat([qr[..., :1], -qr[..., 1:]], -1))[..., 1:]
return R, tt
def fps(x, n, seed=0):
"""Farthest-point sample n indices."""
if len(x) <= n:
return torch.arange(len(x), device=x.device)
idx = [int(torch.randint(len(x), (1,), device="cpu", generator=torch.Generator(device="cpu").manual_seed(seed)))]
d = (x - x[idx[0]]).norm(dim=-1)
for _ in range(n - 1):
j = int(d.argmax()); idx.append(j)
d = torch.minimum(d, (x - x[j]).norm(dim=-1))
return torch.tensor(idx, device=x.device, dtype=torch.long)
def _knn(pts, p, kk, chunk=8192):
"""kk nearest nodes p (M,3) of each point (N,3): (distances, indices)."""
if pts.is_cuda:
from pytorch3d.ops import knn_points
d2, idx, _ = knn_points(pts[None].float(), p[None].float(), K=kk, return_sorted=True)
return d2[0].clamp_min(0).sqrt().to(pts.dtype), idx[0]
chunk = max(128, min(chunk, (1 << 27) // max(len(p), 1)))
NB, DD = [], []
for i in range(0, len(pts), chunk):
dd, nb = torch.topk(torch.cdist(pts[i:i + chunk], p, compute_mode="donot_use_mm_for_euclid_dist"), kk, dim=1, largest=False)
NB.append(nb); DD.append(dd)
return torch.cat(DD), torch.cat(NB)
def _sdpa(q, k, v, am):
if any(t.storage_offset() + sum((n - 1) * s for n, s in zip(t.shape, t.stride())) >= 2**31 for t in (k, v)):
k, v = k.contiguous(), v.contiguous()
try:
from torch.nn.attention import SDPBackend, sdpa_kernel
with sdpa_kernel([SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH]):
return F.scaled_dot_product_attention(q, k, v, attn_mask=am)
except Exception:
return F.scaled_dot_product_attention(q, k, v, attn_mask=am)
class CrossFrameAdapter(nn.Module):
"""Query rows attend to key rows; the output is added to the query rows."""
def __init__(self, channels: int, num_heads: int):
super().__init__()
self.num_heads = num_heads
self.norm_q = nn.LayerNorm(channels); self.norm_kv = nn.LayerNorm(channels)
self.to_q = nn.Linear(channels, channels); self.to_kv = nn.Linear(channels, channels * 2)
self.to_out = nn.Linear(channels, channels)
def forward(self, fa, ft):
"""fa (Na, C) query feats, ft (Nt, C) key feats -> (Na, C) update."""
H = self.num_heads; C = fa.shape[-1]
q = self.to_q(self.norm_q(fa)).reshape(1, -1, H, C // H).transpose(1, 2)
k, v = self.to_kv(self.norm_kv(ft)).reshape(1, -1, 2, H, C // H).unbind(2)
o = _sdpa(q, k.transpose(1, 2), v.transpose(1, 2), None)
return self.to_out(o.transpose(1, 2).reshape(-1, C))
class NodeField:
"""Node field canonical -> frame t. p (M,3) node rest positions, hn (M,NODE_CH) = [t3 | quat4 | strain6 | logw1 |
opacity1], kernel (M,2) learned [weight, log-radius] of each node. Raw [0,1] voxel frame throughout."""
SIGMA_BASE = 0.03
def __init__(self, p, hn, kernel, conn=8):
self.p, self.hn, self.kernel, self.conn = p, hn, kernel, conn
self.t = hn[:, 0:3]
self.q = hn[:, 3:7] + hn.new_tensor([1.0, 0.0, 0.0, 0.0])
self.q = self.q / self.q.norm(dim=-1, keepdim=True).clamp_min(1e-8)
self.R = _quat_to_mat(hn[:, 3:7])
self.S = strain_to_matrix(hn[:, 7:13])
self.op = torch.sigmoid(hn[:, 14:15])
def weights(self, x):
"""Skinning nodes + softmax(weight - d^2 / 2 sigma^2) weights of points x (N,3)."""
kk = max(1, min(self.conn, len(self.p)))
_, nb = _knn(x, self.p, kk)
d2 = ((x[:, None, :] - self.p[nb]) ** 2).sum(-1)
sig = self.SIGMA_BASE * F.softplus(self.kernel[nb, 1] + 1.0)
return nb, torch.softmax(self.kernel[nb, 0] - d2 / (2 * sig ** 2), 1)
def forward(self, x):
"""Canonical points (N,3) -> frame t, and the blended rotation quaternion (hybrid LBS/DQS skinning)."""
nb, w = self.weights(x)
p, t, R, S = self.p[nb], self.t[nb], self.R[nb], self.S[nb]
x_lbs = torch.einsum("nkab,nkb->nka", R, torch.einsum("nkab,nkb->nka", S, x[:, None, :] - p)) + p + t
x_lbs = (x_lbs * w[..., None]).sum(1)
rot = (self.q[nb] * w[..., None]).sum(1)
rot = rot / rot.norm(dim=-1, keepdim=True).clamp_min(1e-8)
Rd, td = dqs_blend(self.q[nb], p + t - torch.einsum("nkab,nkb->nka", R, p), w)
x_dqs = torch.einsum("nab,nb->na", Rd, x) + td
m = (w * self.op[nb].squeeze(-1)).sum(1, keepdim=True)
return m * x_lbs + (1.0 - m) * x_dqs, rot
class Decoder4D(nn.Module):
def __init__(self, base, n_cross: int = 6, n_nodes: int = 1000, node_conn: int = 8, delta_scale: float = 1.0,
resolution: int = 64):
super().__init__()
self.base = base; self.base.dtype = torch.float32
self.canonical = copy.deepcopy(base); self.canonical.dtype = torch.float32
self.resolution, self.n_nodes, self.node_conn, self.delta_scale = resolution, int(n_nodes), int(node_conn), float(delta_scale)
nb = len(base.blocks); self.cross_from = max(0, nb - n_cross)
C = base.out_layer.in_features
heads = getattr(base.blocks[0].attn, "num_heads", 12)
mk = lambda: nn.ModuleList([CrossFrameAdapter(C, heads) for _ in range(nb - self.cross_from)])
self.xattn, self.xattn_c, self.xattn_g = mk(), mk(), mk()
self.node_head = nn.Linear(C, NODE_CH)
self.prop_head = nn.Linear(C, 3)
@staticmethod
def _embed(dec, x):
h = dec.input_layer(x)
if getattr(dec, "pe_mode", None) == "ape":
h = h + dec.pos_embedder(x.coords[:, 1:])
return h.type(torch.float32)
def forward(self, x_canonical, x_frames):
"""x_canonical: the canonical frame's SLat, x_frames: all F frames packed. Returns (G*, [NodeField] * F)."""
F_ = x_frames.shape[0]
ca, fa = x_canonical.coords, x_canonical.feats.float()
coords = torch.cat([torch.cat([torch.full_like(ca[:, :1], f), ca[:, 1:]], 1) for f in range(F_)], 0)
ha = self._embed(self.base, type(x_canonical)(feats=fa.repeat(F_, 1), coords=coords))
hd = self._embed(self.base, x_frames)
hg = self._embed(self.canonical, type(x_canonical)(feats=fa, coords=ca))
for i, blk in enumerate(self.base.blocks):
ha = blk(ha); hd = blk(hd); hg = self.canonical.blocks[i](hg)
if i >= self.cross_from:
j = i - self.cross_from
upd = torch.cat([self.xattn[j](ha.feats[ha.layout[f]], hd.feats[hd.layout[f]]) for f in range(F_)], 0)
ha = ha.replace(ha.feats + upd)
ha = ha.replace(ha.feats + self.xattn_c[j](ha.feats, torch.cat([ha.feats, hg.feats], 0)))
hg = hg.replace(hg.feats + self.xattn_g[j](hg.feats, hd.feats))
gs = self.canonical.to_representation(self.canonical.out_layer(hg.replace(F.layer_norm(hg.feats, hg.feats.shape[-1:]))))[0]
head = self.node_head(F.layer_norm(ha.feats, ha.feats.shape[-1:]).float())
props = self.prop_head(F.layer_norm(hg.feats, hg.feats.shape[-1:]).float())
centres = (ca[:, 1:].float() + 0.5) / self.resolution
idx = fps(centres, self.n_nodes); pk = props[idx]
fields = []
for f in range(F_):
h = head[ha.layout[f]][idx]
hn = torch.cat([h[:, :NODE_CH - 2], pk[:, 0:1], pk[:, 2:3]], 1) * self.delta_scale
fields.append(NodeField(centres[idx], hn, pk[:, 0:2], conn=self.node_conn))
return gs, fields
def gaussians_at_frame(self, gs, field):
"""G* carried to the field's frame: positions and rotations."""
xt, rot = field.forward(gs._xyz)
g = copy.copy(gs)
g._xyz = xt
q = gs._rotation + gs.rots_bias[None, :]
q = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-8)
g._rotation = _quat_mul(rot, q) - gs.rots_bias[None, :]
return g
def build_decoder(base, args=None):
"""Decoder4D for a checkpoint's architecture args (n_joint, nodes, conn, delta_scale)."""
a = dict(args or {})
return Decoder4D(base, n_cross=int(a.get("n_joint", 6)), n_nodes=int(a.get("nodes", 1000)),
node_conn=int(a.get("conn", 8)), delta_scale=float(a.get("delta_scale", 1.0)))