Download flow4rt/model/flow4rt.py from Shenhan/Flow4RT: direct link, hf CLI and curl.
- Browser
- Download file 5.31 kB
-
https://huggingface.co/spaces/Shenhan/Flow4RT/resolve/main/flow4rt/model/flow4rt.py
- Command line
-
hf download hf://spaces/Shenhan/Flow4RT/flow4rt/model/flow4rt.py
-
curl -L -o flow4rt.py https://huggingface.co/spaces/Shenhan/Flow4RT/resolve/main/flow4rt/model/flow4rt.py
5.31 kB
| from typing import Dict, Tuple | |
| import torch | |
| import torch.nn as nn | |
| from .dpt_head import DPTHead | |
| from .geometry import geotrf, solve_transfm | |
| from .geometry_blocks import GeometryBlocks | |
| from .motion_blocks import MotionBlocks | |
| class Flow4RT(nn.Module): | |
| """Flow4RT. | |
| Geometry blocks (a ViT-g) process all views jointly. At each of four read-out layers, motion | |
| blocks map the tokens of a source view toward its target view (viewpoint and time). A shared | |
| DPT head decodes the geometry branch into a local point map P with confidence C, and the | |
| motion branch into a displaced point map P_vt with rigidity W. The rigidity-weighted rigid | |
| alignment of P to P_vt gives the relative camera pose T, which separates scene flow into | |
| camera motion and object motion. | |
| """ | |
| PATCH_SIZE = 14 | |
| def __init__(self, motion_depth: int = 8): | |
| super().__init__() | |
| self.geometry_blocks = GeometryBlocks() | |
| self.motion_blocks = MotionBlocks(dim=1536, depth=motion_depth) | |
| self.head = DPTHead(dim_in=1536, output_dim=4) | |
| def from_pretrained(cls, path: str, device="cpu", **kwargs) -> "Flow4RT": | |
| """Loads weights from a `.safetensors` file or a training checkpoint (`.pth`).""" | |
| model = cls(**kwargs) | |
| if path.endswith(".safetensors"): | |
| from safetensors.torch import load_file | |
| state_dict = load_file(path) | |
| else: | |
| state_dict = torch.load(path, map_location="cpu", weights_only=False, mmap=True) | |
| state_dict = state_dict.get("model", state_dict) | |
| model.load_state_dict(state_dict, strict=True) | |
| return model.to(device).eval() | |
| def forward(self, views: Dict[str, torch.Tensor]) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]]: | |
| """ | |
| Args: | |
| views: dict with | |
| img: (B, V, 3, H, W) images in [-1, 1]; H and W multiples of 14. | |
| target_idx: (B, V) long, the target view of each view. | |
| Returns: | |
| (pred_src, pred_tgt), dicts of (B, V, ...) tensors. For view i with target j: | |
| pred_src: view i as the source, toward j; pred_tgt: view j as the source, toward i. | |
| Names follow the paper's notation (P, C, P_vt, W, T, P_v, P_t). | |
| pts3d P local point map: source viewpoint, source time | |
| conf C confidence of P | |
| pts3d_vt P_vt displaced point map: target viewpoint, target time | |
| rigidity W rigidity map, sums to 1 over the pixels of each view | |
| camera_pose T (B, V, 4, 4) relative pose (source -> target camera), solved | |
| from P, P_vt and W by weighted rigid alignment | |
| pts3d_v P_v target viewpoint, source time (T P) | |
| pts3d_t P_t source viewpoint, target time (T^-1 P_vt) | |
| """ | |
| images = views["img"] | |
| target_idx = views["target_idx"] | |
| B, V, _, H, W = images.shape | |
| x = (images + 1) / 2 # the geometry blocks take images in [0, 1] | |
| geometry_tokens, motion_tokens = [], [] | |
| for level, (patches, cls_token, time_token) in enumerate(self.geometry_blocks(x)): | |
| geometry_tokens.append(patches.flatten(0, 1)) # (B*V, P, C) | |
| tokens = torch.cat([cls_token.unsqueeze(2), time_token.unsqueeze(2), patches], dim=2) | |
| motion_tokens.append(self.motion_blocks(tokens, target_idx, level)) # (B*2V, P, C) | |
| with torch.autocast(device_type=images.device.type, dtype=torch.float32): | |
| pts3d, conf = self.head(geometry_tokens, (H, W)) # geometry branch, per view | |
| pts3d_vt, rigidity = self.head(motion_tokens, (H, W)) # motion branch, per (source, target) | |
| def with_target(t): # (B*V, ...) -> (B*2V, ...): views followed by their targets | |
| t = t.reshape(B, V, *t.shape[1:]) | |
| idx = target_idx.reshape(B, V, *([1] * (t.ndim - 2))).expand_as(t) | |
| return torch.cat([t, torch.gather(t, dim=1, index=idx)], dim=1).flatten(0, 1) | |
| out = { | |
| "pts3d": with_target(pts3d), | |
| "conf": with_target(1 + torch.exp(conf)), | |
| "pts3d_vt": pts3d_vt, | |
| "rigidity": rigidity.flatten(1).softmax(dim=1).view_as(rigidity), # sums to 1 over pixels | |
| } | |
| pred_src, pred_tgt = {}, {} | |
| for k, v in out.items(): | |
| pred_src[k], pred_tgt[k] = v.reshape(B, 2, V, *v.shape[1:]).unbind(dim=1) | |
| return self._postprocess(pred_src), self._postprocess(pred_tgt) | |
| def _postprocess(pred: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: | |
| pts = pred["pts3d"].detach() | |
| pts_vt = pred["pts3d_vt"] | |
| rigidity = pred["rigidity"] | |
| # relative camera pose: rigidity-weighted alignment of the two pointmaps of the same pixels | |
| trf_cam = solve_transfm(pts.flatten(-3, -2), pts_vt.flatten(-3, -2).detach(), rigidity.flatten(-2, -1)) | |
| pts_v = geotrf(trf_cam, pts) | |
| pts_t = geotrf(trf_cam.inverse(), pts_vt) | |
| pred["camera_pose"] = trf_cam # (B, V, 4, 4): source camera -> target camera | |
| pred["pts3d_v"] = pts_v | |
| pred["pts3d_t"] = pts_t | |
| return pred | |