# A causal CoTracker3: one new frame per step, with a FIFO of past updater inputs. import torch import torch.nn as nn import torch.nn.functional as F from .model_utils import sample_features4d from .online import CoTrackerThreeBase, posenc class CoTrackerThreeStream(CoTrackerThreeBase): """Frame-by-frame CoTracker3. Each step feeds the updater ``input_cache_size`` cached frames plus the current frame, and keeps only the last token. ``window_len`` is the length of ``time_emb`` for that span. The state holds only the current feature pyramid and the previous prediction. Every query is on frame 0. """ def __init__( self, input_cache_size=15, ttt_layers=(), ttt_type="linear", ttt_head_dim=32, ttt_base_lr=0.1, **args, ): super(CoTrackerThreeStream, self).__init__( ttt_layers=ttt_layers, ttt_type=ttt_type, ttt_head_dim=ttt_head_dim, ttt_base_lr=ttt_base_lr, **args, ) if input_cache_size < 0: raise ValueError("input_cache_size must be >= 0, got %s" % input_cache_size) if input_cache_size + 1 > self.window_len: raise ValueError( "input_cache_size + 1 (%d) must be <= window_len (%d)" % (input_cache_size + 1, self.window_len) ) self.input_cache_size = input_cache_size self._corr_dim = 256 * self.corr_levels probe = posenc(torch.zeros(1, 2), min_deg=0, max_deg=10) write_in = probe.shape[-1] * 2 + 2 + self._corr_dim + self.latent_dim * self.corr_levels hidden = self.updateformer.hidden_size self.ttt_write_encoder = nn.Sequential( nn.LayerNorm(write_in), nn.Linear(write_in, hidden), nn.GELU(), nn.Linear(hidden, hidden), ) def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): key = prefix + "time_emb" saved = state_dict.get(key) rows = self.time_emb.shape[1] if saved is not None and saved.shape[1] != rows and saved.shape[-1] == self.time_emb.shape[-1] and saved.shape[1] > rows: state_dict[key] = saved[:, -rows:].contiguous() super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) def encode_normalized(self, video): """Map a 0-255 video to the normalized feature pyramid's finest level, (B, T, C, H, W).""" assert video.shape[-2] % self.stride == 0 and video.shape[-1] % self.stride == 0 video = 2 * (video / 255.0) - 1.0 B, T, C, H, W = video.shape fmaps = self.fnet(video.reshape(B * T, C, H, W)) fmaps = fmaps.permute(0, 2, 3, 1) fmaps = fmaps / torch.sqrt( torch.maximum( torch.sum(torch.square(fmaps), dim=-1, keepdim=True), torch.tensor(1e-12, device=fmaps.device, dtype=fmaps.dtype), ) ) _, H4, W4, C4 = fmaps.shape return fmaps.permute(0, 3, 1, 2).reshape(B, T, C4, H4, W4) def make_pyramid(self, fmaps): pyramid = [fmaps] current = fmaps for _ in range(self.corr_levels - 1): B, T, C, H, W = current.shape pooled = F.avg_pool2d(current.reshape(B * T, C, H, W), 2, stride=2) current = pooled.reshape(B, T, C, pooled.shape[-2], pooled.shape[-1]) pyramid.append(current) return pyramid def _pixel_scale(self, device): """(width, height) in stride units. Built once; a host copy cannot be captured.""" cache = getattr(self, "_pixel_scale_cache", None) if cache is None: cache = {} self._pixel_scale_cache = cache scale = cache.get(device) if scale is None: scale = torch.tensor( [self.model_resolution[1], self.model_resolution[0]], device=device, dtype=torch.float32, ) / self.stride cache[device] = scale return scale def build_state(self, queries, fmaps_pyramid): """Track templates and the empty input cache. ``fmaps_pyramid`` is not copied.""" B = queries.shape[0] if B != 1: raise NotImplementedError("CoTrackerThreeStream currently supports batch size 1") T = fmaps_pyramid[0].shape[1] N = queries.shape[1] device = fmaps_pyramid[0].device queried_frames = queries[:, :, 0].long() queried_coords = queries[..., 1:3] / self.stride supports = [] for level, fmaps in enumerate(fmaps_pyramid): _, support = self.get_track_feat( fmaps, queried_frames, queried_coords / 2**level, support_radius=self.corr_radius, ) supports.append(support.unsqueeze(1)) K = self.input_cache_size state = { "fmaps_pyramid": fmaps_pyramid, "supports": supports, "queried_frames": queried_frames, "queried_coords": queried_coords, "N": N, "cache_vis": torch.zeros(N, K, 1, device=device), "cache_conf": torch.zeros(N, K, 1, device=device), "cache_corr": torch.zeros(N, K, self._corr_dim, device=device), "cache_coords": torch.zeros(N, K, 2, device=device), "cache_valid": torch.zeros(N, K, dtype=torch.bool, device=device), "pred_coords": torch.zeros(B, T, N, 2, device=device), "pred_vis": torch.zeros(B, T, N, device=device), "pred_conf": torch.zeros(B, T, N, device=device), } # Clone so later index_copy cannot write into the shared initial weights. state["ttt_states"] = [ {name: value.clone() for name, value in layer.items()} for layer in self.updateformer.ttt_init_states(N) ] return state def _corr_embs(self, fmaps_pyramid, support, coords): """Correlation embedding of one frame. ``coords`` is (B, 1, M, 2) in stride units.""" B, S, M, _ = coords.shape assert S == 1 radius = 2 * self.corr_radius + 1 corr_embs = [] for level in range(self.corr_levels): corr_feat = self.get_correlation_feat( fmaps_pyramid[level], coords.reshape(B * S, M, 2) / 2**level ) track_support = ( support[level] .reshape(B, 1, radius, radius, M, self.latent_dim) .squeeze(1) .permute(0, 3, 1, 2, 4) ) corr_volume = torch.einsum("btnhwc,bnijc->btnhwij", corr_feat, track_support) corr_emb = self.corr_mlp(corr_volume.reshape(B * S * M, radius * radius * radius * radius)) corr_embs.append(corr_emb) corr_embs = torch.cat(corr_embs, dim=-1).view(B, S, M, -1) if corr_embs.shape[-1] != self._corr_dim: raise RuntimeError( "correlation embedding is %d wide, expected %d" % (corr_embs.shape[-1], self._corr_dim) ) return corr_embs def _with_history(self, cached, current, valid): """Repeat the earliest valid cache slot, then append ``current``. Returns (1, K+1, M, C).""" M, K, channels = cached.shape first = K - valid.sum(dim=-1) positions = torch.arange(K + 1, device=cached.device) index = torch.maximum(positions[None, :], first[:, None]) frames = torch.cat([cached.to(dtype=current.dtype), current[:, None]], dim=1) gathered = frames.gather(1, index[:, :, None].expand(M, K + 1, channels)) return gathered.permute(1, 0, 2).unsqueeze(0) def _shift_cache(self, cache, index, new_value): """Drop the oldest slot of ``index`` and append ``new_value`` (M, C). Out of place.""" chosen = cache.index_select(0, index) updated = torch.cat([chosen[:, 1:], new_value[:, None]], dim=1) return cache.index_copy(0, index, updated) def begin_frame(self, state, frame_index): """Prepare one frame. The active set is the full track list.""" queried_frames = state["queried_frames"] B = 1 N = state["N"] device = state["pred_coords"].device index = torch.arange(N, device=device) M = index.shape[0] queried_coords = state["queried_coords"].index_select(1, index) coords = queried_coords.view(B, 1, M, 2) vis = torch.zeros(B, 1, M, 1, device=device, dtype=coords.dtype) conf = torch.zeros(B, 1, M, 1, device=device, dtype=coords.dtype) if frame_index > 0: use_prev = queried_frames[0].index_select(0, index) < frame_index # only the previous frame is stored, in slot 0 prev_coords = state["pred_coords"][:, 0].index_select(1, index) prev_vis = state["pred_vis"][:, 0].index_select(1, index) prev_conf = state["pred_conf"][:, 0].index_select(1, index) coords = torch.where(use_prev.view(1, 1, M, 1), prev_coords[:, None], coords) vis = torch.where(use_prev.view(1, 1, M, 1), prev_vis[:, None, :, None], vis) conf = torch.where(use_prev.view(1, 1, M, 1), prev_conf[:, None, :, None], conf) return { "state": state, "index": index, "B": B, "N": N, "M": M, "device": device, "coords": coords, "vis": vis, "conf": conf, "coords_init": coords.detach(), "ttt_reads": [ {name: tensor.index_select(0, index) for name, tensor in layer.items()} for layer in state["ttt_states"] ], "fmaps_t": [level[:, :1] for level in state["fmaps_pyramid"]], "support_t": [level.index_select(3, index) for level in state["supports"]], "cache_valid": state["cache_valid"].index_select(0, index), "cache_vis": state["cache_vis"].index_select(0, index), "cache_conf": state["cache_conf"].index_select(0, index), "cache_corr": state["cache_corr"].index_select(0, index), "cache_coords": state["cache_coords"].index_select(0, index), "scale": self._pixel_scale(device), } def step_frame(self, frame): """One updater iteration. Returns pixels (B, 1, N, 2) scattered back to every track.""" coords = frame["coords"] vis = frame["vis"] conf = frame["conf"] index = frame["index"] coords_det = coords.detach() corr = self._corr_embs(frame["fmaps_t"], frame["support_t"], coords_det) dtype = corr.dtype window_vis = self._with_history(frame["cache_vis"], vis[0, 0].to(dtype=dtype), frame["cache_valid"]) window_conf = self._with_history(frame["cache_conf"], conf[0, 0].to(dtype=dtype), frame["cache_valid"]) window_corr = self._with_history(frame["cache_corr"], corr[0, 0].to(dtype=dtype), frame["cache_valid"]) window_coords = self._with_history( frame["cache_coords"], coords_det[0, 0].to(dtype=torch.float32), frame["cache_valid"] ) rel_forward = window_coords[:, :-1] - window_coords[:, 1:] rel_backward = window_coords[:, 1:] - window_coords[:, :-1] rel_forward = F.pad(rel_forward, (0, 0, 0, 0, 0, 1)) rel_backward = F.pad(rel_backward, (0, 0, 0, 0, 1, 0)) rel_forward = rel_forward / frame["scale"] rel_backward = rel_backward / frame["scale"] rel = posenc(torch.cat([rel_forward, rel_backward], dim=-1), min_deg=0, max_deg=10) rel = rel.to(dtype=dtype) tokens = torch.cat([window_vis, window_conf, window_corr, rel], dim=-1) if tokens.shape[-1] != self.input_dim: raise RuntimeError( "updater input is %d wide, expected %d" % (tokens.shape[-1], self.input_dim) ) length = tokens.shape[1] tokens = tokens.permute(0, 2, 1, 3).reshape(frame["B"] * frame["M"], length, -1) tokens = tokens + self.time_emb[:, -length:].to(dtype=tokens.dtype) tokens = tokens.view(frame["B"], frame["M"], length, -1) delta = self.updateformer(tokens, ttt_states=frame["ttt_reads"]) delta = delta[:, :, -1:] delta_coords = delta[..., :2].permute(0, 2, 1, 3) delta_vis = delta[..., 2:3].permute(0, 2, 1, 3) delta_conf = delta[..., 3:].permute(0, 2, 1, 3) vis = vis + delta_vis.to(dtype=vis.dtype) conf = conf + delta_conf.to(dtype=conf.dtype) coords = coords_det + delta_coords.to(dtype=coords_det.dtype) frame["coords"] = coords frame["vis"] = vis frame["conf"] = conf return self._scatter_coords(coords * float(self.stride), index, frame["N"]) def end_frame(self, frame): """Write this frame's final coordinates into the input cache, predictions and TTT state.""" state = frame["state"] index = frame["index"] final_coords = frame["coords"].detach() final_vis = frame["vis"].detach() final_conf = frame["conf"].detach() with torch.no_grad(): final_corr = self._corr_embs(frame["fmaps_t"], frame["support_t"], final_coords).detach() state["cache_vis"] = self._shift_cache(state["cache_vis"], index, final_vis[0, 0].float()) state["cache_conf"] = self._shift_cache(state["cache_conf"], index, final_conf[0, 0].float()) state["cache_corr"] = self._shift_cache(state["cache_corr"], index, final_corr[0, 0].float()) state["cache_coords"] = self._shift_cache(state["cache_coords"], index, final_coords[0, 0].float()) ones = torch.ones(frame["M"], dtype=torch.bool, device=frame["device"]) state["cache_valid"] = self._shift_cache(state["cache_valid"], index, ones) # a single slot, the frame that the next step reads as its previous prediction state["pred_coords"][:, 0, index] = final_coords[:, 0] state["pred_vis"][:, 0, index] = final_vis[:, 0, :, 0] state["pred_conf"][:, 0, index] = final_conf[:, 0, :, 0] self._ttt_write( state, index, frame["ttt_reads"], frame["coords_init"], final_coords, final_vis, final_conf, final_corr, frame["fmaps_t"], frame["scale"], ) def _sample_appearance(self, fmaps_t, coords): """Bilinear sample of each pyramid level. ``coords`` is (B, 1, M, 2) in stride units.""" samples = [] for level, fmap in enumerate(fmaps_t): samples.append(sample_features4d(fmap[:, 0], coords[:, 0] / (2**level))) return torch.cat(samples, dim=-1).unsqueeze(1) def _ttt_write_token( self, coords_init, final_coords, final_vis, final_conf, final_corr, appearance, scale ): motion = (final_coords - coords_init) / scale parts = [ posenc(final_coords / scale, min_deg=0, max_deg=10), posenc(motion, min_deg=0, max_deg=10), final_vis, final_conf, final_corr, appearance, ] dtype = appearance.dtype write_input = torch.cat([part.to(dtype=dtype) for part in parts], dim=-1) expected = self.ttt_write_encoder[0].normalized_shape[0] if write_input.shape[-1] != expected: raise RuntimeError( "TTT write token is %d wide, expected %d" % (write_input.shape[-1], expected) ) return self.ttt_write_encoder(write_input[0, 0]) def _ttt_write( self, state, index, read_states, coords_init, final_coords, final_vis, final_conf, final_corr, fmaps_t, scale, ): appearance = self._sample_appearance(fmaps_t, final_coords) token = self._ttt_write_token( coords_init, final_coords, final_vis, final_conf, final_corr, appearance, scale ) written_active = self.updateformer.ttt_write(token, read_states) state["ttt_states"] = [ { name: layer[name].index_copy(0, index, new[name]) for name in layer } for layer, new in zip(state["ttt_states"], written_active) ] def _scatter_coords(self, coords, index, num_tracks): full = coords.new_zeros(coords.shape[0], 1, num_tracks, 2) return torch.index_copy(full, 2, index, coords)