Spaces:
Running on Zero
Running on Zero
Download models/tracker.py from Charlie839242/StreamTAP3D: direct link, hf CLI and curl.
- Browser
- Download file 41.3 kB
-
https://huggingface.co/spaces/Charlie839242/StreamTAP3D/resolve/main/models/tracker.py
- Command line
-
hf download hf://spaces/Charlie839242/StreamTAP3D/models/tracker.py
-
curl -L -o tracker.py https://huggingface.co/spaces/Charlie839242/StreamTAP3D/resolve/main/models/tracker.py
41.3 kB
| from typing import Any, Callable, Dict, List, Optional, Tuple | |
| from box import Box | |
| import torch | |
| import torch.nn as nn | |
| from einops import rearrange, repeat | |
| import logging | |
| from types import SimpleNamespace | |
| from utils.common_utils import batch_unproject, ensure_float32, apply_homo_transform, project_queries, graph_safe_inverse | |
| from .utils.cotracker_utils import posenc, get_1d_sincos_pos_embed_from_grid | |
| from .utils.layers import build_mlp | |
| from .corr_features import load_corr_processor | |
| from .motion import build_motion | |
| from .point_updaters import load_point_updater | |
| from functools import partial | |
| logger = logging.getLogger(__name__) | |
| # Depth <= 0 is an invalid pixel. KNN indexes the full image grid, so the point stays | |
| # in the grid and is moved far from the scene instead of sitting on the camera center. | |
| INVALID_DEPTH_XYZ = 1e6 | |
| def park_invalid_depth_points(pcds: torch.Tensor, depth: torch.Tensor) -> torch.Tensor: | |
| """pcds is (B, T, 3, H, W) and depth is (B, T, H, W). Pixels with depth <= 0 become a far constant.""" | |
| if pcds.ndim != 5 or pcds.shape[2] != 3 or depth.shape != pcds.shape[:2] + pcds.shape[-2:]: | |
| raise RuntimeError( | |
| f"cannot park invalid depth: pcds {tuple(pcds.shape)}, depth {tuple(depth.shape)}" | |
| ) | |
| return pcds.masked_fill((depth <= 0).unsqueeze(-3), INVALID_DEPTH_XYZ) | |
| def nanvar(tensor, dim=None, keepdim=False): | |
| tensor_mean = tensor.nanmean(dim=dim, keepdim=True) | |
| output = (tensor - tensor_mean).square().nanmean(dim=dim, keepdim=keepdim) | |
| return output | |
| def nanstd(tensor, dim=None, keepdim=False): | |
| output = nanvar(tensor, dim=dim, keepdim=keepdim) | |
| output = output.sqrt() | |
| return output | |
| SNAP_DEPTH_MIN = 0.1 | |
| def _invert_rigid(extrinsics: torch.Tensor) -> torch.Tensor: | |
| """Inverse of a rigid transform, as tensor ops a CUDA graph can capture. Identity stays identity.""" | |
| rotation = extrinsics[..., :3, :3] | |
| translation = extrinsics[..., :3, 3:] | |
| rotation_t = rotation.transpose(-1, -2) | |
| out = extrinsics.new_zeros(extrinsics.shape) | |
| out[..., :3, :3] = rotation_t | |
| out[..., :3, 3:] = -rotation_t.matmul(translation) | |
| out[..., 3, 3] = 1 | |
| return out | |
| def snap_world_to_rays( | |
| world: torch.Tensor, | |
| uv: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| depth_min: float = SNAP_DEPTH_MIN, | |
| rigid_inverse: bool = False, | |
| ) -> torch.Tensor: | |
| """Keep camera-frame depth and place the point on the ray through ``uv``. | |
| world: (B, T, N, 3). uv: (B, T, N, 2) pixels, x along width. | |
| intrinsics: (B, T, 3, 3). extrinsics: (B, T, 4, 4), world to camera. | |
| Points with camera Z <= depth_min keep ``world``. | |
| """ | |
| batch, time, tracks, _ = world.shape | |
| assert uv.shape == (batch, time, tracks, 2), f"uv shape {tuple(uv.shape)} does not match world {tuple(world.shape)}" | |
| assert intrinsics.shape[:2] == (batch, time) and extrinsics.shape[:2] == (batch, time) | |
| with torch.autocast(device_type=world.device.type, enabled=False): | |
| return _snap_world_to_rays( | |
| world.float(), uv.float(), intrinsics.float(), extrinsics.float(), depth_min, rigid_inverse, | |
| ) | |
| def _snap_world_to_rays(world, uv, intrinsics, extrinsics, depth_min, rigid_inverse=False): | |
| batch, time, tracks, _ = world.shape | |
| ext = extrinsics[:, :, None].expand(batch, time, tracks, 4, 4) | |
| camera = apply_homo_transform(world, ext) | |
| depth = camera[..., 2] | |
| focal_x = intrinsics[:, :, 0, 0][:, :, None] | |
| focal_y = intrinsics[:, :, 1, 1][:, :, None] | |
| center_x = intrinsics[:, :, 0, 2][:, :, None] | |
| center_y = intrinsics[:, :, 1, 2][:, :, None] | |
| snapped_x = (uv[..., 0] - center_x) * depth / focal_x | |
| snapped_y = (uv[..., 1] - center_y) * depth / focal_y | |
| snapped_camera = torch.stack([snapped_x, snapped_y, depth], dim=-1) | |
| inverse = _invert_rigid(extrinsics) if rigid_inverse else torch.linalg.inv(extrinsics) | |
| inverse_ext = inverse[:, :, None].expand(batch, time, tracks, 4, 4) | |
| snapped_world = apply_homo_transform(snapped_camera, inverse_ext) | |
| keep = depth > depth_min | |
| return torch.where(keep[..., None], snapped_world, world) | |
| class _CoTrackerStepper: | |
| """One frame of the 2D branch, one iteration at a time, on a side CUDA stream unless inline. | |
| The updater and correlation run in bf16. The full-step graph uses inline: bf16 on a stream created during | |
| capture does not replay to the eager result. | |
| """ | |
| def __init__(self, tracker: "Tracker", state: Dict[str, Any], frame_index: int, inline: bool = False): | |
| self.tracker = tracker | |
| self.state = state | |
| self.frame_index = frame_index | |
| self.stream = None if inline else tracker._cotracker_side_stream(state["pred_coords"].device) | |
| self.frame = None | |
| self.started = False | |
| self.event = None | |
| self.pixels = None | |
| def launch(self): | |
| def run(): | |
| if not self.started: | |
| self.frame = self.tracker.motion.begin_frame(self.state, self.frame_index) | |
| self.started = True | |
| self.pixels = self.tracker.motion.step_frame(self.frame) | |
| self.event = _run_cotracker(self.stream, self.state["pred_coords"].device.type, run) | |
| def wait_pixels(self) -> torch.Tensor: | |
| if self.event is not None: | |
| torch.cuda.current_stream().wait_event(self.event) | |
| return self.pixels | |
| def finish(self): | |
| def run(): | |
| self.tracker.motion.end_frame(self.frame) | |
| self.event = _run_cotracker(self.stream, self.state["pred_coords"].device.type, run) | |
| def _cotracker_autocast(device_type: str): | |
| """bf16 for the online updater and correlation. | |
| A capturing stream cannot keep the autocast weight cache: replay would reference casts freed after capture. | |
| """ | |
| # The side stream is created during capture, and is_current_stream_capturing() can miss it. | |
| # A cached weight cast recorded there is freed before replay and the tracks come back wrong. | |
| return torch.autocast( | |
| device_type=device_type, | |
| dtype=torch.bfloat16, | |
| enabled=True, | |
| cache_enabled=False, | |
| ) | |
| def _run_cotracker(stream, device_type: str, fn): | |
| """Queue ``fn`` on ``stream``. Returns an event the current stream can wait on, or None when inline.""" | |
| if stream is None: | |
| with torch.no_grad(): | |
| with _cotracker_autocast(device_type): | |
| fn() | |
| return None | |
| with torch.cuda.stream(stream): | |
| with torch.no_grad(): | |
| with _cotracker_autocast("cuda"): | |
| fn() | |
| event = torch.cuda.Event() | |
| event.record(stream) | |
| return event | |
| # end_frame replaces these. Predictions are written into the existing tensors. | |
| _COTRACKER_OWNED_KEYS = ("cache_vis", "cache_conf", "cache_corr", "cache_coords", "cache_valid") | |
| def _cotracker_owned(state: Any): | |
| """The cache and TTT tensors this step will read. end_frame assigns new ones.""" | |
| cot = state.cotracker_state | |
| caches = {key: cot[key] for key in _COTRACKER_OWNED_KEYS} | |
| return caches, cot.get("ttt_states") | |
| def _commit_cotracker_inplace(state: Any, caches: Dict[str, torch.Tensor], ttt): | |
| """Write end_frame's new tensors back into the ones this step read, and keep the state pointing at those.""" | |
| cot = state.cotracker_state | |
| for key, original in caches.items(): | |
| current = cot[key] | |
| if current is not original: | |
| original.copy_(current) | |
| cot[key] = original | |
| if ttt is not None and cot.get("ttt_states") is not ttt: | |
| for old_layer, new_layer in zip(ttt, cot["ttt_states"]): | |
| for name, old in old_layer.items(): | |
| old.copy_(new_layer[name]) | |
| cot["ttt_states"] = ttt | |
| class Tracker(nn.Module): | |
| """Online 3D point tracker in world coordinates, one frame per step, with isotropic normalization from frame 0.""" | |
| EPS = 1e-6 | |
| def __init__( | |
| self, | |
| image_size: Tuple[int, int], | |
| corr_feature: dict, | |
| point_updater: dict, | |
| corr_levels: int = 4, | |
| time_emb_len: int = 16, | |
| input_cache_size: int = 15, | |
| ttt_layers: Tuple[int, ...] = (0, 1, 2), | |
| ttt_type: str = "linear", | |
| ttt_head_dim: int = 32, | |
| ttt_base_lr: float = 0.1, | |
| feature_dim: int = 128, | |
| ): | |
| super().__init__() | |
| image_size = (int(image_size[0]), int(image_size[1])) | |
| self.image_size = image_size | |
| self.corr_levels = corr_levels | |
| self.feature_dim = int(feature_dim) | |
| # fnet and the pixel update live in this module. Their weights are part of the tracker checkpoint. | |
| self.motion = build_motion(image_size) | |
| self.motion.eval() | |
| self.corr_processor = load_corr_processor(corr_feature, feat_dim=self.feature_dim, corr_levels=corr_levels, image_size=image_size) | |
| self.ttt_layers = [int(i) for i in ttt_layers] | |
| self.point_updater = load_point_updater( | |
| point_updater, | |
| ttt_layers=self.ttt_layers, ttt_type=ttt_type, ttt_write_dim=point_updater["hidden_size"], | |
| ttt_head_dim=ttt_head_dim, ttt_base_lr=ttt_base_lr, | |
| ) | |
| self._pixel_normalizer_cache: Dict[Any, torch.Tensor] = {} | |
| assert input_cache_size > 0 and input_cache_size + 1 <= time_emb_len | |
| self.input_cache_size = input_cache_size | |
| # written once per frame for each track: posenc(coords), posenc(motion from the previous frame), [visibs, corr_embs], appearance | |
| pos_dim = posenc(torch.zeros(1, 3), min_deg=-2, max_deg=14).shape[-1] | |
| head_dim, _ = self._input_cache_dims() | |
| write_input_dim = 2 * pos_dim + head_dim + self.corr_processor.appearance_dim | |
| hidden_size = self.point_updater.hidden_size | |
| self.ttt_write_encoder = build_mlp(input_size=write_input_dim, output_size=hidden_size, hidden_size=hidden_size, n_layers=2) | |
| time_grid = torch.linspace(0, time_emb_len - 1, time_emb_len).reshape(1, time_emb_len, 1) | |
| self.register_buffer( | |
| "time_emb", get_1d_sincos_pos_embed_from_grid(self.point_updater.input_dim, time_grid[0]) | |
| ) | |
| logger.info(f"Image Feature Dim: {self.feature_dim}") | |
| def encode(self, rgb: torch.Tensor) -> torch.Tensor: | |
| """Finest feature map of this frame. rgb is (1, 3, H, W) in [0, 1], or already (1, 1, 3, H, W).""" | |
| video = (rgb.detach() * 255.0).float() | |
| if video.ndim == 4: | |
| video = video[None] | |
| with torch.autocast(device_type=rgb.device.type, enabled=False): | |
| return self.motion.encode_normalized(video).detach() | |
| def start(self, **kwargs): | |
| return self.online_start(**kwargs) | |
| def step(self, state, **kwargs): | |
| return self.online_step(state, **kwargs) | |
| def _snap_normalized( | |
| self, | |
| coords: torch.Tensor, | |
| uv: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| mean_coords: torch.Tensor, | |
| std_coords: torch.Tensor, | |
| ) -> torch.Tensor: | |
| """Snap normalized coords onto the rays of ``uv``, then return them in normalized space.""" | |
| uv = uv.detach().to(device=coords.device, dtype=torch.float32) | |
| coords_f = coords.float() | |
| intrinsics = intrinsics.to(device=coords.device, dtype=torch.float32) | |
| extrinsics = extrinsics.to(device=coords.device, dtype=torch.float32) | |
| world = coords_f * std_coords[:, None, None, :] + mean_coords[:, None, None, :] | |
| fused = snap_world_to_rays( | |
| world, uv, intrinsics, extrinsics, SNAP_DEPTH_MIN, | |
| rigid_inverse=getattr(self, "_graph_safe_camera", False), | |
| ) | |
| normalized = (fused - mean_coords[:, None, None, :]) / std_coords[:, None, None, :] | |
| return normalized.to(dtype=coords.dtype) | |
| def _get_pixel_normalizer(self, device: torch.device) -> torch.Tensor: | |
| # cached to avoid a blocking host-to-device copy in every iteration | |
| key = (tuple(self.image_size), device) | |
| if key not in self._pixel_normalizer_cache: | |
| self._pixel_normalizer_cache[key] = torch.tensor([self.image_size[1] - 1, self.image_size[0] - 1], device=device) | |
| return self._pixel_normalizer_cache[key] | |
| def _project( | |
| self, | |
| points: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| mean_coords: torch.Tensor, | |
| std_coords: torch.Tensor, | |
| ) -> torch.Tensor: | |
| ''' | |
| Project 3D points to 2D pixel coordinates | |
| One should not assume this transform is invertible. | |
| Args: | |
| points: (B, N, 4), (t, x, y, z) | |
| intrinsics: (B, T, 3, 3) | |
| extrinsics: (B, T, 4, 4) | |
| Returns: | |
| coords_2d: (B, N, 3), the last dimension is (x, y, d). Note that x corresponds to width. | |
| ''' | |
| B, N, _ = points.shape | |
| time_index = points[..., 0].long() # B, N | |
| coords = points[..., 1:] | |
| batch_index = torch.arange(B, device=points.device)[:, None].expand(-1, N) | |
| intrinsics = intrinsics[batch_index, time_index] # B, N, 3, 3 | |
| extrinsics = extrinsics[batch_index, time_index] # B, N, 4, 4 | |
| coords = (coords * std_coords[:, None, :]) + mean_coords[:, None, :] | |
| coords_local = apply_homo_transform(coords, extrinsics) | |
| coords_pixel = torch.einsum("bnij,bnj->bni", intrinsics, coords_local) | |
| coords_pixel = coords_pixel[..., :2] / torch.clamp(coords_pixel[..., 2:3], min=self.EPS) | |
| clamped_x = torch.clamp(coords_pixel[..., 0], min=-self.image_size[1] * 2, max=self.image_size[1] * 2) | |
| clamped_y = torch.clamp(coords_pixel[..., 1], min=-self.image_size[0] * 2, max=self.image_size[0] * 2) | |
| result = torch.cat([clamped_x[..., None], clamped_y[..., None], coords_local[..., 2:]], dim=-1) | |
| return result | |
| def _encode_frame_input( | |
| self, | |
| coords: torch.Tensor, | |
| visibs: torch.Tensor, | |
| corr_ctx: Box, | |
| projector: Callable[[torch.Tensor], torch.Tensor], | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| The parts of the updater input that depend on each frame alone, i.e. all but the relative motion. | |
| Returns head (B, T, N, 1 + corr_dim), [visibs, corr_embs], and tail (B, T, N, uv_dim), the uv posenc. | |
| """ | |
| B, T = coords.shape[:2] | |
| N = coords.shape[2] | |
| # Fetch correlation features | |
| corr_embs = self.corr_processor( | |
| ctx=corr_ctx, | |
| curr_coords=coords, | |
| ) | |
| head = torch.cat([visibs[..., None], corr_embs], dim=-1) | |
| coords_with_time = torch.cat([ | |
| repeat(torch.arange(T, device=coords.device, dtype=coords.dtype), "t -> b t n 1", b=B, n=N), | |
| coords | |
| ], dim=-1) | |
| pixel_coords = rearrange(projector(rearrange(coords_with_time, "b t n c -> b (t n) c")), "b (t n) c -> b t n c", t=T)[..., :2] | |
| normalized_pixel_coords = pixel_coords / self._get_pixel_normalizer(pixel_coords.device) | |
| tail = posenc(normalized_pixel_coords, min_deg=-2, max_deg=14) | |
| return head, tail | |
| def _input_cache_dims(self) -> Tuple[int, int]: | |
| """Widths of the head and tail returned by _encode_frame_input.""" | |
| rel_dim = posenc(torch.zeros(1, 6), min_deg=-2, max_deg=14).shape[-1] | |
| tail_dim = posenc(torch.zeros(1, 2), min_deg=-2, max_deg=14).shape[-1] | |
| return self.point_updater.input_dim - rel_dim - tail_dim, tail_dim | |
| def _forward_window_iter( | |
| self, | |
| coords: torch.Tensor, | |
| visibs: torch.Tensor, | |
| projector: Callable[[torch.Tensor], torch.Tensor], | |
| corr_ctx: Box, | |
| track_mask: torch.Tensor, | |
| input_cache: Dict[str, torch.Tensor], | |
| ttt_states: List[Dict[str, torch.Tensor]], | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| input_cache holds the encoded inputs of the K past frames of each track, the newest last: | |
| head (B, K, N, ·), tail (B, K, N, ·), coords (B, K, N, 3), valid (B, N, K), where the valid slots are a suffix. | |
| The updater runs on the K past frames followed by the single current frame, and only the output of the current frame is used. | |
| ttt_states holds the per-layer TTT states of the N tracks (B == 1), read by the point updater. | |
| """ | |
| T = coords.shape[1] | |
| head, tail = self._encode_frame_input(coords, visibs, corr_ctx, projector) | |
| assert T == 1 | |
| K = input_cache["valid"].shape[-1] | |
| # missing history repeats the earliest valid frame of the track, or the current frame for a new track | |
| first = K - input_cache["valid"].sum(dim=-1) # (B, N) | |
| index = torch.maximum(torch.arange(K + 1, device=coords.device)[None, None, :], first[..., None]) # (B, N, K + 1) | |
| def with_history(cached: torch.Tensor, current: torch.Tensor) -> torch.Tensor: | |
| frames = torch.cat([cached.to(current.dtype), current], dim=1) # (B, K + 1, N, C) | |
| return frames.gather(1, repeat(index, "b n t -> b t n c", c=frames.shape[-1])) | |
| head = with_history(input_cache["head"], head) | |
| tail = with_history(input_cache["tail"], tail) | |
| window_coords = with_history(input_cache["coords"], coords) | |
| T_in = window_coords.shape[1] | |
| rel_coords_forward = window_coords[:, :-1] - window_coords[:, 1:] | |
| rel_coords_backward = window_coords[:, 1:] - window_coords[:, :-1] | |
| rel_coords_forward = torch.nn.functional.pad( | |
| rel_coords_forward, (0, 0, 0, 0, 0, 1) | |
| ) | |
| rel_coords_backward = torch.nn.functional.pad( | |
| rel_coords_backward, (0, 0, 0, 0, 1, 0) | |
| ) | |
| rel_pos_emb_input = posenc( | |
| torch.cat([rel_coords_forward, rel_coords_backward], dim=-1), | |
| min_deg=-2, | |
| max_deg=14, | |
| ) | |
| updater_input = torch.cat([head, rel_pos_emb_input, tail], dim=-1) # (B, T_in, N, D) | |
| assert self.point_updater.input_dim == updater_input.shape[-1], "Input dimension of point_updater must match the last dimension of updater_input." \ | |
| f"{self.point_updater.input_dim} != {updater_input.shape[-1]}" | |
| # the current frame takes the last position of the embedding, as the newest frame of a full window would | |
| time_emb = self.time_emb[:, -T_in:] | |
| updater_input = updater_input + time_emb[:, :, None, :] | |
| out = self.point_updater(updater_input, mask=repeat(track_mask, "b n -> (b t) n", t=T_in), ttt_states=ttt_states) | |
| out = out[:, -1:] | |
| delta_coords = out[..., :3] | |
| delta_visibs = out[..., 3] | |
| visibs = visibs + delta_visibs | |
| coords = coords + delta_coords | |
| assert coords.dtype == torch.float32, "coords should be float32. we could use bfloat16 for delta, but not for coords" | |
| return coords, visibs | |
| def _forward_window( | |
| self, | |
| *, | |
| coords_init: torch.Tensor, | |
| visibs_init: torch.Tensor, | |
| num_iters: int, | |
| corr_ctx: Any, | |
| projector: Callable[[torch.Tensor], torch.Tensor], | |
| track_mask: torch.Tensor, | |
| memory_out: Dict[str, Any], | |
| input_cache: Dict[str, torch.Tensor], | |
| ttt_states: List[Dict[str, torch.Tensor]], | |
| snap_stepper: "_CoTrackerStepper", | |
| snap_intrinsics: torch.Tensor, | |
| snap_extrinsics: torch.Tensor, | |
| snap_mean: torch.Tensor, | |
| snap_std: torch.Tensor, | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| All the coordinates in this function are in the normalized space. Returns the final (coords, visibs). | |
| input_cache and ttt_states are read by every iteration. memory_out receives the final prediction | |
| re-encoded as the input of a cached frame ("frame_input": head, tail, coords) and the TTT states | |
| after writing the final prediction ("ttt_states"). | |
| """ | |
| B, T = coords_init.shape[:2] | |
| coords = coords_init.clone() | |
| visibs = visibs_init.clone() | |
| for it in range(num_iters): | |
| coords = coords.detach().clone() | |
| visibs = visibs.detach().clone() | |
| raw_coords, visibs = self._forward_window_iter( | |
| coords=coords, | |
| visibs=visibs, | |
| corr_ctx=corr_ctx, | |
| projector=projector, | |
| track_mask=track_mask, | |
| input_cache=input_cache, | |
| ttt_states=ttt_states, | |
| ) | |
| coords = self._snap_normalized( | |
| raw_coords, snap_stepper.wait_pixels(), snap_intrinsics, snap_extrinsics, snap_mean, snap_std, | |
| ) | |
| if it + 1 < num_iters: | |
| snap_stepper.launch() | |
| else: | |
| snap_stepper.finish() | |
| # the correlation is centered at the coords, so it is recomputed at the final prediction instead of reusing the last iteration's | |
| with torch.no_grad(): | |
| head, tail = self._encode_frame_input(coords.detach(), visibs.detach(), corr_ctx, projector) | |
| memory_out["frame_input"] = {"head": head, "tail": tail, "coords": coords.detach()} | |
| assert B == 1 and T == 1 | |
| final_coords = coords.detach() | |
| appearance = self.corr_processor.sample_appearance(corr_ctx, final_coords) | |
| write_input = torch.cat([ | |
| posenc(final_coords, min_deg=-2, max_deg=14), | |
| posenc(final_coords - coords_init.detach(), min_deg=-2, max_deg=14), | |
| head.to(appearance.dtype), | |
| appearance, | |
| ], dim=-1) | |
| write_token = self.ttt_write_encoder(write_input[0, 0]) # (N, C) | |
| memory_out["ttt_states"] = self.point_updater.ttt_write(write_token, ttt_states) | |
| return coords.detach().clone(), visibs.detach().clone() | |
| def _build_normalized_ctx( | |
| self, | |
| *, | |
| feats: torch.Tensor, | |
| depths: torch.Tensor, | |
| queries: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| shared_corr_ctx: Any, | |
| depth_roi: Optional[torch.Tensor] = None, | |
| norm_stats: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, | |
| ) -> Box: | |
| """ | |
| Normalize the scene isotropically with statistics of this frame, and prepare its correlation context in the normalized space. | |
| norm_stats, if given, the (mean_coords, std_coords) (B, 3) returned by an earlier call, used instead of computing them. | |
| """ | |
| B = feats.shape[0] | |
| with torch.autocast(device_type="cuda", enabled=False): | |
| # local -> normalized | |
| pcds = batch_unproject(depths, intrinsics, extrinsics) | |
| if norm_stats is not None: | |
| mean_coords = norm_stats[0].reshape(B, 1, 3, 1, 1) | |
| std_coords = norm_stats[1].reshape(B, 1, 3, 1, 1) | |
| else: | |
| _original_pcds = pcds.clone() | |
| _original_pcds[(depths == 0)[:, :, None, :, :].expand(-1, -1, 3, -1, -1)] = torch.nan | |
| if depth_roi is not None: | |
| assert B == 1 | |
| depth_roi = depth_roi.reshape(2) | |
| _original_pcds.masked_fill_(depths[:, :, None] > depth_roi[1], torch.nan) | |
| _original_pcds.masked_fill_(depths[:, :, None] < depth_roi[0], torch.nan) | |
| mean_coords = torch.nanmean(_original_pcds, dim=(1, 3, 4), keepdim=True) # (B, T, C, H, W) -> (B, 1, C, 1, 1) | |
| std_coords = nanstd(_original_pcds - mean_coords, dim=(1, 2, 3, 4), keepdim=True).expand(-1, -1, 3, -1, -1) # (B, T, C, H, W) -> (B, 1, 3, 1, 1) | |
| pcds = park_invalid_depth_points(pcds, depths) | |
| normalized_pcds = (pcds - mean_coords) / std_coords | |
| mean_coords = mean_coords.reshape(-1, 3) | |
| std_coords = std_coords.reshape(-1, 3) | |
| normalized_queries = queries.clone() | |
| normalized_queries[..., 1:] = (normalized_queries[..., 1:] - mean_coords[:, None, :]) / std_coords[:, None, :] | |
| projector = partial( | |
| self._project, | |
| intrinsics=intrinsics, | |
| extrinsics=extrinsics, | |
| mean_coords=mean_coords, | |
| std_coords=std_coords, | |
| ) | |
| corr_ctx = self.corr_processor.prepare_window( # type: ignore | |
| feats=feats, | |
| pcds=normalized_pcds, | |
| queries=normalized_queries, | |
| projector=projector, | |
| shared_ctx=shared_corr_ctx, | |
| ) | |
| return Box( | |
| mean_coords=mean_coords, | |
| std_coords=std_coords, | |
| intrinsics=intrinsics, | |
| extrinsics=extrinsics, | |
| projector=projector, | |
| corr_ctx=corr_ctx, | |
| ) | |
| def _wrapped_forward_window( | |
| self, | |
| *, | |
| norm_ctx: Box, | |
| num_iters: int, | |
| coords_init: torch.Tensor, | |
| visibs_init: torch.Tensor, | |
| track_mask: torch.Tensor, | |
| memory_out: Dict[str, Any], | |
| input_cache: Dict[str, torch.Tensor], | |
| ttt_states: List[Dict[str, torch.Tensor]], | |
| snap_stepper: "_CoTrackerStepper", | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| Same as _forward_window, but in the original coordinate space. | |
| norm_ctx is built by _build_normalized_ctx for the current frame. | |
| """ | |
| mean_coords, std_coords = norm_ctx.mean_coords, norm_ctx.std_coords | |
| with torch.autocast(device_type="cuda", enabled=False): | |
| coords_init = (coords_init - mean_coords[:, None, None, :]) / std_coords[:, None, None, :] | |
| corr_ctx = norm_ctx.corr_ctx.time_slice(start=0, end=1) | |
| coords, visibs = self._forward_window( | |
| coords_init=coords_init, | |
| visibs_init=visibs_init, | |
| num_iters=num_iters, | |
| corr_ctx=corr_ctx, | |
| projector=norm_ctx.projector, | |
| track_mask=track_mask, | |
| memory_out=memory_out, | |
| input_cache=input_cache, | |
| ttt_states=ttt_states, | |
| snap_stepper=snap_stepper, | |
| snap_intrinsics=norm_ctx.intrinsics, | |
| snap_extrinsics=norm_ctx.extrinsics, | |
| snap_mean=mean_coords, | |
| snap_std=std_coords, | |
| ) | |
| with torch.autocast(device_type="cuda", enabled=False): | |
| coords = (coords * std_coords[:, None, None, :]) + mean_coords[:, None, None, :] | |
| return coords, visibs | |
| def _cotracker_side_stream(self, device: torch.device): | |
| """A non-default stream for the 2D branch. CPU execution stays on the current stream.""" | |
| if device.type != "cuda": | |
| return None | |
| stream = getattr(self, "_cotracker_stream", None) | |
| if stream is None: | |
| stream = torch.cuda.Stream(device=device) | |
| self._cotracker_stream = stream | |
| return stream | |
| # correlation fields sampled at the query frame, kept from frame 0 | |
| _ONLINE_QUERY_FIELDS = ("query_feat_pyramid", "query_support_offset_pyramid", "query_support_feat_pyramid", "query_support_ti_pyramid") | |
| def _online_frame_ctx( | |
| self, | |
| state: Any, | |
| feats: torch.Tensor, | |
| depth: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| ) -> Box: | |
| """One frame for the online 3D branch. feats is the shared visual encoder map (1, 1, C, H, W). | |
| extrinsics is world-to-camera, (1, 1, 4, 4). | |
| """ | |
| feats = feats.detach().float() | |
| depths = depth[None, None].float() if depth.ndim == 2 else depth.float() | |
| intrinsics_b = intrinsics[None, None].float() if intrinsics.ndim == 2 else intrinsics.float() | |
| if state.shared_corr_ctx is None: | |
| # pointops zeros its buffers on the current stream and launches the kernel on the legacy null | |
| # stream. Those two are ordered on the PyTorch default stream, and not on a side stream. | |
| current = torch.cuda.current_stream(feats.device) | |
| default = torch.cuda.default_stream(feats.device) | |
| pcds = park_invalid_depth_points(batch_unproject(depths, intrinsics_b, extrinsics), depths) | |
| if current != default: | |
| default.wait_stream(current) | |
| with torch.cuda.stream(default): | |
| state.shared_corr_ctx = self.corr_processor.prepare_shared( | |
| pcds=pcds, feats=feats, queries=state.queries, | |
| ) | |
| current.wait_stream(default) | |
| else: | |
| state.shared_corr_ctx = self.corr_processor.prepare_shared( | |
| pcds=pcds, feats=feats, queries=state.queries, | |
| ) | |
| norm_ctx = self._build_normalized_ctx( | |
| feats=feats, | |
| depths=depths, | |
| queries=state.queries, | |
| intrinsics=intrinsics_b, | |
| extrinsics=extrinsics, | |
| shared_corr_ctx=state.shared_corr_ctx, | |
| depth_roi=state.depth_roi, | |
| norm_stats=state.norm_stats, | |
| ) | |
| if state.norm_stats is None: | |
| state.norm_stats = (norm_ctx.mean_coords, norm_ctx.std_coords) | |
| state.query_ctx = {name: getattr(norm_ctx.corr_ctx, name) for name in self._ONLINE_QUERY_FIELDS} | |
| else: | |
| for name, value in state.query_ctx.items(): | |
| setattr(norm_ctx.corr_ctx, name, value) | |
| return norm_ctx | |
| def _online_prepare_cotracker( | |
| self, | |
| state: Any, | |
| fnet: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| extrinsics: torch.Tensor, | |
| inline: bool = False, | |
| ): | |
| """Build the streaming CoTracker state on frame 0, or point it at this frame's pyramid. | |
| extrinsics is world-to-camera for the frame-0 query projection, (1, 1, 4, 4). | |
| """ | |
| pyramid = self.motion.make_pyramid(fnet) | |
| if state.cotracker_state is None: | |
| intrinsics_b = intrinsics[None, None].float() if intrinsics.ndim == 2 else intrinsics.float() | |
| pixels = project_queries(state.queries, intrinsics_b, extrinsics) | |
| cotracker_state = self.motion.build_state(pixels, pyramid) | |
| state.cotracker_state = cotracker_state | |
| else: | |
| state.cotracker_state["fmaps_pyramid"] = pyramid | |
| if not inline: | |
| # the 2D branch reads the pyramid on its own stream; the pyramid was just built on the current one | |
| ready = torch.cuda.Event() | |
| ready.record() | |
| side = self._cotracker_side_stream(fnet.device) | |
| if side is not None: | |
| side.wait_event(ready) | |
| return _CoTrackerStepper(self, state.cotracker_state, state.frame_index, inline=inline) | |
| def online_start( | |
| self, | |
| *, | |
| query_coords: torch.Tensor, | |
| num_iters: int, | |
| depth_roi: Optional[torch.Tensor] = None, | |
| ) -> Any: | |
| """ | |
| Frame-by-frame tracking. query_coords (N, 3) are points of frame 0 in world coordinates. | |
| Pass frames to online_step in order. Normalization, query features and support points come from frame 0. | |
| """ | |
| N = query_coords.shape[0] | |
| device = query_coords.device | |
| head_dim, tail_dim = self._input_cache_dims() | |
| return SimpleNamespace( | |
| num_iters=num_iters, | |
| depth_roi=depth_roi, | |
| queries=torch.cat([query_coords.new_zeros(1, N, 1), query_coords[None].float()], dim=-1), | |
| coords=query_coords[None, None].float().clone(), | |
| visibs=torch.zeros(1, 1, N, device=device, dtype=torch.float32), | |
| shared_corr_ctx=None, | |
| norm_stats=None, | |
| query_ctx=None, | |
| cotracker_state=None, | |
| frame_index=0, | |
| cache_head=torch.zeros(N, self.input_cache_size, head_dim, device=device, dtype=torch.float32), | |
| cache_tail=torch.zeros(N, self.input_cache_size, tail_dim, device=device, dtype=torch.float32), | |
| cache_coords=torch.zeros(N, self.input_cache_size, 3, device=device, dtype=torch.float32), | |
| cache_valid=torch.zeros(N, self.input_cache_size, device=device, dtype=torch.bool), | |
| ttt_states=self.point_updater.ttt_init_states(N), | |
| ) | |
| def _online_commit(self, state: Any, coords: torch.Tensor, visibs: torch.Tensor, memory_out: Dict[str, Any], inplace: bool): | |
| N = state.coords.shape[2] | |
| new_state = {"coords": coords, "visibs": visibs} | |
| frame_input = memory_out.pop("frame_input") | |
| for name, key in [("cache_head", "head"), ("cache_tail", "tail"), ("cache_coords", "coords")]: | |
| cache = getattr(state, name) | |
| new_state[name] = torch.cat([cache[:, 1:], frame_input[key][0, 0].float()[:, None]], dim=1) | |
| new_state["cache_valid"] = torch.cat([state.cache_valid[:, 1:], state.cache_valid.new_ones(N, 1)], dim=1) | |
| new_ttt = memory_out.pop("ttt_states") | |
| if inplace: | |
| for name, value in new_state.items(): | |
| getattr(state, name).copy_(value) | |
| for old_layer, new_layer in zip(state.ttt_states, new_ttt): | |
| for key, value in new_layer.items(): | |
| old_layer[key].copy_(value) | |
| else: | |
| for name, value in new_state.items(): | |
| setattr(state, name, value) | |
| state.ttt_states = new_ttt | |
| def online_step( | |
| self, | |
| state: Any, | |
| *, | |
| rgb: torch.Tensor, | |
| depth: torch.Tensor, | |
| intrinsics: torch.Tensor, | |
| c2w: torch.Tensor, | |
| fnet: torch.Tensor, | |
| inplace: bool = False, | |
| inline_cotracker: bool = False, | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| Track the next frame. rgb (1, 3, H, W) in [0, 1]; depth (H, W); intrinsics (3, 3); c2w (4, 4). | |
| fnet is this frame's shared visual encoder map (1, 1, C, H, W) or (1, C, H, W), already computed. | |
| inplace writes this frame into the existing state tensors. inline_cotracker runs the 2D branch on the | |
| current stream; OnlineStepGraph uses both. | |
| Returns world coordinates (N, 3) and visibility logits (N,). | |
| The prediction stays in world coordinates. World-to-camera is the rigid inverse of c2w, which a CUDA graph can capture. | |
| """ | |
| assert self.image_size == tuple(rgb.shape[-2:]) | |
| fnet = fnet.detach() | |
| if fnet.ndim == 4: | |
| fnet = fnet[None] | |
| input_cache = { | |
| "head": state.cache_head.transpose(0, 1)[None], | |
| "tail": state.cache_tail.transpose(0, 1)[None], | |
| "coords": state.cache_coords.transpose(0, 1)[None], | |
| "valid": state.cache_valid[None], | |
| } | |
| memory_out = {} | |
| extrinsics = _invert_rigid(c2w.float().view(1, 1, 4, 4)) | |
| stepper = self._online_prepare_cotracker(state, fnet, intrinsics, extrinsics, inline=inline_cotracker) | |
| # end_frame assigns new cache tensors; the graph must copy them back into the ones this step reads | |
| owned = _cotracker_owned(state) if inline_cotracker else None | |
| # the first 2D iteration overlaps unproject and the 3D pyramid; the window joins it at the snap | |
| stepper.launch() | |
| norm_ctx = self._online_frame_ctx(state, fnet, depth, intrinsics, extrinsics=extrinsics) | |
| coords, visibs = self._wrapped_forward_window( | |
| norm_ctx=norm_ctx, | |
| num_iters=state.num_iters, | |
| coords_init=state.coords, | |
| visibs_init=state.visibs, | |
| track_mask=torch.ones(1, state.coords.shape[2], device=state.coords.device, dtype=torch.bool), | |
| memory_out=memory_out, | |
| input_cache=input_cache, | |
| ttt_states=state.ttt_states, | |
| snap_stepper=stepper, | |
| ) | |
| self._online_commit(state, coords, visibs, memory_out, inplace) | |
| if owned is not None: | |
| _commit_cotracker_inplace(state, *owned) | |
| state.frame_index += 1 | |
| return coords[0, 0], visibs[0, 0] | |
| def _slot_get(container, key): | |
| return container[key] if isinstance(container, dict) else getattr(container, key) | |
| def _slot_set(container, key, value): | |
| if isinstance(container, dict): | |
| container[key] = value | |
| else: | |
| setattr(container, key, value) | |
| class OnlineStepGraph: | |
| """ | |
| Tracker.online_step of one tracking state, captured into a single CUDA graph. | |
| Build it on frame 2. Frame 0 has already run the pointops support search and the host syncs, and frame 1 has | |
| replaced every state tensor with a fresh contiguous one. CoTracker stays on the capture stream so its bf16 | |
| replay matches eager. The warmup and the capture both execute the step, and each result is discarded; the | |
| caller replays the frame it passed in. | |
| """ | |
| def __init__(self, model: Tracker, state: Any, example_inputs: Dict[str, torch.Tensor]): | |
| assert getattr(model.corr_processor, "knn_backend", None) == "torch", "the online CUDA graph requires knn_backend=torch" | |
| assert state.shared_corr_ctx is not None and state.norm_stats is not None, "run frame 0 eagerly first" | |
| assert state.cotracker_state is not None, "run frame 0 eagerly first" | |
| assert state.frame_index > 0, "capture after frame 0 so streaming CoTracker reads the previous prediction" | |
| self.model = model | |
| self.state = state | |
| self.static_inputs = {name: value.detach().clone() for name, value in example_inputs.items()} | |
| # capture is global, and frame 1 may still be finishing end_frame on the CoTracker side stream | |
| torch.cuda.synchronize() | |
| owned = self._owned_tensors() | |
| assert all(tensor.is_contiguous() for _, _, tensor in owned), "run frame 1 eagerly first" | |
| snapshot = [tensor.clone() for _, _, tensor in owned] | |
| frame_index = state.frame_index | |
| side = torch.cuda.Stream() | |
| side.wait_stream(torch.cuda.current_stream()) | |
| with torch.cuda.stream(side): | |
| self._step() | |
| torch.cuda.current_stream().wait_stream(side) | |
| self._restore(owned, snapshot, frame_index) | |
| torch.cuda.synchronize() | |
| self.graph = torch.cuda.CUDAGraph() | |
| autocast_on = torch.is_autocast_enabled() | |
| autocast_dtype = torch.get_autocast_gpu_dtype() if autocast_on else torch.bfloat16 | |
| with torch.autocast("cuda", enabled=autocast_on, dtype=autocast_dtype, cache_enabled=False): | |
| with torch.cuda.graph(self.graph): | |
| self.static_outputs = self._step() | |
| # capture executed the step; put the pre-step values back so the caller's replay is the one that counts | |
| self._restore(owned, snapshot, frame_index) | |
| state.frame_index = frame_index + 1 | |
| del snapshot | |
| def _owned_tensors(self): | |
| """State tensors the step reads and writes. Feature pyramids are rebuilt from the static fnet and are not here.""" | |
| state = self.state | |
| slots = [] | |
| for name in ("coords", "visibs", "cache_head", "cache_tail", "cache_coords", "cache_valid"): | |
| slots.append((state, name)) | |
| self._tracker_ttt = state.ttt_states | |
| for layer in self._tracker_ttt: | |
| for name in layer: | |
| slots.append((layer, name)) | |
| cot = state.cotracker_state | |
| for key in _COTRACKER_OWNED_KEYS + ("pred_coords", "pred_vis", "pred_conf"): | |
| slots.append((cot, key)) | |
| self._cot_ttt = cot.get("ttt_states") | |
| for layer in self._cot_ttt or []: | |
| for name in layer: | |
| slots.append((layer, name)) | |
| owned = [] | |
| for container, key in slots: | |
| tensor = _slot_get(container, key) | |
| if not tensor.is_contiguous(): | |
| tensor = tensor.contiguous() | |
| _slot_set(container, key, tensor) | |
| owned.append((container, key, tensor)) | |
| return owned | |
| def _restore(self, owned, snapshot, frame_index: int): | |
| self.state.ttt_states = self._tracker_ttt | |
| if self._cot_ttt is not None: | |
| self.state.cotracker_state["ttt_states"] = self._cot_ttt | |
| for (container, key, original), saved in zip(owned, snapshot): | |
| _slot_set(container, key, original) | |
| original.copy_(saved) | |
| self.state.frame_index = frame_index | |
| def _step(self) -> Tuple[torch.Tensor, torch.Tensor]: | |
| # linalg.inv cannot be captured. World-to-camera is the rigid inverse of c2w. | |
| # The 3x3 formula inverts the intrinsics. | |
| self.model._graph_safe_camera = True | |
| previous = graph_safe_inverse(True) | |
| try: | |
| # bf16 on a stream created during capture replays off the eager result. The capture stream matches. | |
| return self.model.step( | |
| self.state, **self.static_inputs, inplace=True, inline_cotracker=True, | |
| ) | |
| finally: | |
| self.model._graph_safe_camera = False | |
| graph_safe_inverse(previous) | |
| def __call__(self, **inputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """Same inputs and outputs as Tracker.online_step. Copies the inputs, then replays.""" | |
| for name, value in inputs.items(): | |
| self.static_inputs[name].copy_(value) | |
| self.graph.replay() | |
| return tuple(output.clone() for output in self.static_outputs) | |