diffvid 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1077 @@
1
+ # Copyright 2024 DeepMind Technologies Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """TAPIR models definition."""
17
+
18
+ import functools
19
+ from typing import Any, List, Mapping, NamedTuple, Optional, Sequence, Tuple, Union, Dict
20
+
21
+ import torch
22
+ from torch import nn
23
+ import torch.nn.functional as F
24
+ import numpy as np
25
+ from einops import rearrange
26
+
27
+ from . import nets, utils
28
+ from .cmdtop import CMDTop
29
+
30
+
31
+ def posenc(x, min_deg, max_deg, legacy_posenc_order=False):
32
+ """Cat x with a positional encoding of x with scales 2^[min_deg, max_deg-1].
33
+
34
+ Instead of computing [sin(x), cos(x)], we use the trig identity
35
+ cos(x) = sin(x + pi/2) and do one vectorized call to sin([x, x+pi/2]).
36
+
37
+ Args:
38
+ x: torch.Tensor, variables to be encoded. Note that x should be in [-pi, pi].
39
+ min_deg: int, the minimum (inclusive) degree of the encoding.
40
+ max_deg: int, the maximum (exclusive) degree of the encoding.
41
+ legacy_posenc_order: bool, keep the same ordering as the original tf code.
42
+
43
+ Returns:
44
+ encoded: torch.Tensor, encoded variables.
45
+ """
46
+ if min_deg == max_deg:
47
+ return x
48
+ scales = torch.tensor([2**i for i in range(min_deg, max_deg)], dtype=x.dtype, device=x.device)
49
+ if legacy_posenc_order:
50
+ xb = x[..., None, :] * scales[:, None]
51
+ four_feat = torch.reshape(
52
+ torch.sin(torch.stack([xb, xb + 0.5 * np.pi], dim=-2)),
53
+ list(x.shape[:-1]) + [-1]
54
+ )
55
+ else:
56
+ xb = torch.reshape((x[..., None, :] * scales[:, None]), list(x.shape[:-1]) + [-1])
57
+ four_feat = torch.sin(torch.cat([xb, xb + 0.5 * np.pi], dim=-1))
58
+ return torch.cat([x] + [four_feat], dim=-1)
59
+
60
+
61
+ def get_relative_positions(seq_len, reverse=False, device='cuda'):
62
+ x = torch.arange(seq_len, device=device)[None, :]
63
+ y = torch.arange(seq_len, device=device)[:, None]
64
+ return torch.tril(x - y) if not reverse else torch.triu(y - x)
65
+
66
+
67
+ def get_alibi_slope(num_heads, device='cuda'):
68
+ x = (24) ** (1 / num_heads)
69
+ return torch.tensor([1 / x ** (i + 1) for i in range(num_heads)], device=device, dtype=torch.float32).view(-1, 1, 1)
70
+
71
+
72
+ class MultiHeadAttention(nn.Module):
73
+ """Multi-headed attention (MHA) module."""
74
+
75
+ def __init__(self, num_heads, key_size, w_init_scale=None, w_init=None, with_bias=True, b_init=None, value_size=None, model_size=None):
76
+ super(MultiHeadAttention, self).__init__()
77
+ self.num_heads = num_heads
78
+ self.key_size = key_size
79
+ self.value_size = value_size or key_size
80
+ self.model_size = model_size or key_size * num_heads
81
+
82
+ self.with_bias = with_bias
83
+
84
+ self.query_proj = nn.Linear(num_heads * key_size, num_heads * key_size, bias=with_bias)
85
+ self.key_proj = nn.Linear(num_heads * key_size, num_heads * key_size, bias=with_bias)
86
+ self.value_proj = nn.Linear(num_heads * self.value_size, num_heads * self.value_size, bias=with_bias)
87
+ self.final_proj = nn.Linear(num_heads * self.value_size, self.model_size, bias=with_bias)
88
+
89
+ def forward(self, query, key, value, mask=None):
90
+ batch_size, sequence_length, _ = query.size()
91
+
92
+ query_heads = self._linear_projection(query, self.key_size, self.query_proj) # [T', H, Q=K]
93
+ key_heads = self._linear_projection(key, self.key_size, self.key_proj) # [T, H, K]
94
+ value_heads = self._linear_projection(value, self.value_size, self.value_proj) # [T, H, V]
95
+
96
+ device = query.device
97
+ bias_forward = get_alibi_slope(self.num_heads // 2, device=device) * get_relative_positions(sequence_length, device=device)
98
+ bias_forward = bias_forward + torch.triu(torch.full_like(bias_forward, -1e9), diagonal=1)
99
+ bias_backward = get_alibi_slope(self.num_heads // 2, device=device) * get_relative_positions(sequence_length, reverse=True, device=device)
100
+ bias_backward = bias_backward + torch.tril(torch.full_like(bias_backward, -1e9), diagonal=-1)
101
+ attn_bias = torch.cat([bias_forward, bias_backward], dim=0)
102
+
103
+ attn = F.scaled_dot_product_attention(query_heads, key_heads, value_heads, attn_mask=attn_bias, scale=1 / np.sqrt(self.key_size))
104
+ attn = attn.permute(0, 2, 1, 3).reshape(batch_size, sequence_length, -1)
105
+
106
+ return self.final_proj(attn) # [T', D']
107
+
108
+ def _linear_projection(self, x, head_size, proj_layer):
109
+ y = proj_layer(x)
110
+ batch_size, sequence_length, _= x.shape
111
+ return y.reshape((batch_size, sequence_length, self.num_heads, head_size)).permute(0, 2, 1, 3)
112
+
113
+
114
+ class Transformer(nn.Module):
115
+ """A transformer stack."""
116
+
117
+ def __init__(self, num_heads, num_layers, attn_size, dropout_rate, widening_factor=4):
118
+ super(Transformer, self).__init__()
119
+ self.num_heads = num_heads
120
+ self.num_layers = num_layers
121
+ self.attn_size = attn_size
122
+ self.dropout_rate = dropout_rate
123
+ self.widening_factor = widening_factor
124
+
125
+ self.layers = nn.ModuleList([
126
+ nn.ModuleDict({
127
+ 'attn': MultiHeadAttention(num_heads, attn_size, model_size=attn_size * num_heads),
128
+ 'dense': nn.Sequential(
129
+ nn.Linear(attn_size * num_heads, widening_factor * attn_size * num_heads),
130
+ nn.GELU(),
131
+ nn.Linear(widening_factor * attn_size * num_heads, attn_size * num_heads)
132
+ ),
133
+ 'layer_norm1': nn.LayerNorm(attn_size * num_heads),
134
+ 'layer_norm2': nn.LayerNorm(attn_size * num_heads)
135
+ })
136
+ for _ in range(num_layers)
137
+ ])
138
+
139
+ self.ln_out = nn.LayerNorm(attn_size * num_heads)
140
+
141
+ def forward(self, embeddings, mask=None):
142
+ h = embeddings
143
+ for layer in self.layers:
144
+ h_norm = layer['layer_norm1'](h)
145
+ h_attn = layer['attn'](h_norm, h_norm, h_norm, mask=mask)
146
+ h_attn = F.dropout(h_attn, p=self.dropout_rate, training=self.training)
147
+ h = h + h_attn
148
+
149
+ h_norm = layer['layer_norm2'](h)
150
+ h_dense = layer['dense'](h_norm)
151
+ h_dense = F.dropout(h_dense, p=self.dropout_rate, training=self.training)
152
+ h = h + h_dense
153
+
154
+ return self.ln_out(h)
155
+
156
+
157
+ class PIPSTransformer(nn.Module):
158
+ def __init__(self, input_channels, output_channels, dim=512, num_heads=8, num_layers=1):
159
+ super(PIPSTransformer, self).__init__()
160
+ self.dim = dim
161
+
162
+ self.transformer = Transformer(
163
+ num_heads=num_heads,
164
+ num_layers=num_layers,
165
+ attn_size=dim // num_heads,
166
+ dropout_rate=0.,
167
+ widening_factor=4,
168
+ )
169
+ self.input_proj = nn.Linear(input_channels, dim)
170
+ self.output_proj = nn.Linear(dim, output_channels)
171
+
172
+ def forward(self, x):
173
+ x = self.input_proj(x)
174
+ x = self.transformer(x, mask=None)
175
+ return self.output_proj(x)
176
+
177
+
178
+ class FeatureGrids(NamedTuple):
179
+ """Feature grids for a video, used to compute trajectories.
180
+
181
+ These are per-frame outputs of the encoding resnet.
182
+
183
+ Attributes:
184
+ lowres: Low-resolution features, one for each resolution; 256 channels.
185
+ hires: High-resolution features, one for each resolution; 64 channels.
186
+ resolutions: Resolutions used for trajectory computation. There will be one
187
+ entry for the initialization, and then an entry for each PIPs refinement
188
+ resolution.
189
+ """
190
+
191
+ lowres: Sequence[torch.Tensor]
192
+ hires: Sequence[torch.Tensor]
193
+ highest: Sequence[torch.Tensor]
194
+ resolutions: Sequence[Tuple[int, int]]
195
+
196
+
197
+ class QueryFeatures(NamedTuple):
198
+ """Query features used to compute trajectories.
199
+
200
+ These are sampled from the query frames and are a full descriptor of the
201
+ tracked points. They can be acquired from a query image and then reused in a
202
+ separate video.
203
+
204
+ Attributes:
205
+ lowres: Low-resolution features, one for each resolution; each has shape
206
+ [batch, num_query_points, 256]
207
+ hires: High-resolution features, one for each resolution; each has shape
208
+ [batch, num_query_points, 64]
209
+ resolutions: Resolutions used for trajectory computation. There will be one
210
+ entry for the initialization, and then an entry for each PIPs refinement
211
+ resolution.
212
+ """
213
+
214
+ lowres: Sequence[torch.Tensor]
215
+ hires: Sequence[torch.Tensor]
216
+ highest: Sequence[torch.Tensor]
217
+ lowres_supp: Sequence[torch.Tensor]
218
+ hires_supp: Sequence[torch.Tensor]
219
+ highest_supp: Sequence[torch.Tensor]
220
+ resolutions: Sequence[Tuple[int, int]]
221
+
222
+
223
+ class LocoTrack(nn.Module):
224
+ """TAPIR model."""
225
+
226
+ def __init__(
227
+ self,
228
+ bilinear_interp_with_depthwise_conv: bool = False,
229
+ num_pips_iter: int = 4,
230
+ pyramid_level: int = 0,
231
+ mixer_hidden_dim: int = 512,
232
+ num_mixer_blocks: int = 12,
233
+ mixer_kernel_shape: int = 3,
234
+ patch_size: int = 7,
235
+ softmax_temperature: float = 20.0,
236
+ parallelize_query_extraction: bool = False,
237
+ initial_resolution: Tuple[int, int] = (256, 256),
238
+ blocks_per_group: Sequence[int] = (2, 2, 2, 2),
239
+ feature_extractor_chunk_size: int = 256,
240
+ extra_convs: bool = False,
241
+ use_casual_conv: bool = False,
242
+ model_size: str = 'base',
243
+ ):
244
+ super().__init__()
245
+
246
+ if model_size == 'small':
247
+ model_params = {
248
+ 'dim': 256,
249
+ 'num_heads': 4,
250
+ 'num_layers': 3,
251
+ }
252
+ cmdtop_params = {
253
+ 'in_channel': 49,
254
+ 'out_channels': (64, 128),
255
+ 'kernel_shapes': (5, 2),
256
+ 'strides': (4, 2),
257
+ }
258
+ elif model_size == 'base':
259
+ model_params = {
260
+ 'dim': 384,
261
+ 'num_heads': 6,
262
+ 'num_layers': 3,
263
+ }
264
+ cmdtop_params = {
265
+ 'in_channel': 49,
266
+ 'out_channels': (64, 128, 128),
267
+ 'kernel_shapes': (3, 3, 2),
268
+ 'strides': (2, 2, 2),
269
+ }
270
+ else:
271
+ raise ValueError(f"Unknown model size '{model_size}'")
272
+
273
+ self.highres_dim = 128
274
+ self.lowres_dim = 256
275
+ self.bilinear_interp_with_depthwise_conv = (
276
+ bilinear_interp_with_depthwise_conv
277
+ )
278
+ self.parallelize_query_extraction = parallelize_query_extraction
279
+
280
+ self.num_pips_iter = num_pips_iter
281
+ self.pyramid_level = pyramid_level
282
+ self.patch_size = patch_size
283
+ self.softmax_temperature = softmax_temperature
284
+ self.initial_resolution = tuple(initial_resolution)
285
+ self.feature_extractor_chunk_size = feature_extractor_chunk_size
286
+ self.num_mixer_blocks = num_mixer_blocks
287
+ self.use_casual_conv = use_casual_conv
288
+
289
+ highres_dim = 128
290
+ lowres_dim = 256
291
+ strides = (1, 2, 2, 1)
292
+ blocks_per_group = (2, 2, 2, 2)
293
+ channels_per_group = (64, highres_dim, 256, lowres_dim)
294
+ use_projection = (True, True, True, True)
295
+
296
+ self.resnet_torch = nets.ResNet(
297
+ blocks_per_group=blocks_per_group,
298
+ channels_per_group=channels_per_group,
299
+ use_projection=use_projection,
300
+ strides=strides,
301
+ )
302
+
303
+ self.torch_pips_mixer = PIPSTransformer(
304
+ input_channels=854,
305
+ output_channels=4 + self.highres_dim + self.lowres_dim,
306
+ **model_params
307
+ )
308
+
309
+ self.cmdtop = nn.ModuleList([
310
+ CMDTop(
311
+ **cmdtop_params
312
+ ) for _ in range(3)
313
+ ])
314
+
315
+ self.cost_conv = utils.Conv2dSamePadding(2, 1, 3, 1)
316
+ self.occ_linear = nn.Linear(6, 2)
317
+
318
+ if extra_convs:
319
+ self.extra_convs = nets.ExtraConvs()
320
+ else:
321
+ self.extra_convs = None
322
+
323
+ def forward(
324
+ self,
325
+ video: torch.Tensor,
326
+ query_points: torch.Tensor,
327
+ feature_grids: Optional[FeatureGrids] = None,
328
+ is_training: bool = False,
329
+ query_chunk_size: Optional[int] = 64,
330
+ get_query_feats: bool = False,
331
+ refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
332
+ ) -> Mapping[str, torch.Tensor]:
333
+ """Runs a forward pass of the model.
334
+
335
+ Args:
336
+ video: A 5-D tensor representing a batch of sequences of images.
337
+ query_points: The query points for which we compute tracks.
338
+ is_training: Whether we are training.
339
+ query_chunk_size: When computing cost volumes, break the queries into
340
+ chunks of this size to save memory.
341
+ get_query_feats: Return query features for other losses like contrastive.
342
+ Not supported in the current version.
343
+ refinement_resolutions: A list of (height, width) tuples. Refinement will
344
+ be repeated at each specified resolution, in order to achieve high
345
+ accuracy on resolutions higher than what TAPIR was trained on. If None,
346
+ reasonable refinement resolutions will be inferred from the input video
347
+ size.
348
+
349
+ Returns:
350
+ A dict of outputs, including:
351
+ occlusion: Occlusion logits, of shape [batch, num_queries, num_frames]
352
+ where higher indicates more likely to be occluded.
353
+ tracks: predicted point locations, of shape
354
+ [batch, num_queries, num_frames, 2], where each point is [x, y]
355
+ in raster coordinates
356
+ expected_dist: uncertainty estimate logits, of shape
357
+ [batch, num_queries, num_frames], where higher indicates more likely
358
+ to be far from the correct answer.
359
+ """
360
+ if get_query_feats:
361
+ raise ValueError('Get query feats not supported in TAPIR.')
362
+
363
+ if feature_grids is None:
364
+ feature_grids = self.get_feature_grids(
365
+ video,
366
+ is_training,
367
+ refinement_resolutions,
368
+ )
369
+
370
+ query_features = self.get_query_features(
371
+ video,
372
+ is_training,
373
+ query_points,
374
+ feature_grids,
375
+ refinement_resolutions,
376
+ )
377
+
378
+ trajectories = self.estimate_trajectories(
379
+ video.shape[-3:-1],
380
+ is_training,
381
+ feature_grids,
382
+ query_features,
383
+ query_points,
384
+ query_chunk_size,
385
+ )
386
+
387
+ p = self.num_pips_iter
388
+ out = dict(
389
+ occlusion=torch.mean(
390
+ torch.stack(trajectories['occlusion'][p::p]), dim=0
391
+ ),
392
+ tracks=torch.mean(torch.stack(trajectories['tracks'][p::p]), dim=0),
393
+ expected_dist=torch.mean(
394
+ torch.stack(trajectories['expected_dist'][p::p]), dim=0
395
+ ),
396
+ unrefined_occlusion=trajectories['occlusion'][:-1],
397
+ unrefined_tracks=trajectories['tracks'][:-1],
398
+ unrefined_expected_dist=trajectories['expected_dist'][:-1],
399
+ )
400
+
401
+ return out
402
+
403
+ def get_query_features(
404
+ self,
405
+ video: torch.Tensor,
406
+ is_training: bool,
407
+ query_points: torch.Tensor,
408
+ feature_grids: Optional[FeatureGrids] = None,
409
+ refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
410
+ ) -> QueryFeatures:
411
+ """Computes query features, which can be used for estimate_trajectories.
412
+
413
+ Args:
414
+ video: A 5-D tensor representing a batch of sequences of images.
415
+ is_training: Whether we are training.
416
+ query_points: The query points for which we compute tracks.
417
+ feature_grids: If passed, we'll use these feature grids rather than
418
+ computing new ones.
419
+ refinement_resolutions: A list of (height, width) tuples. Refinement will
420
+ be repeated at each specified resolution, in order to achieve high
421
+ accuracy on resolutions higher than what TAPIR was trained on. If None,
422
+ reasonable refinement resolutions will be inferred from the input video
423
+ size.
424
+
425
+ Returns:
426
+ A QueryFeatures object which contains the required features for every
427
+ required resolution.
428
+ """
429
+
430
+ if feature_grids is None:
431
+ feature_grids = self.get_feature_grids(
432
+ video,
433
+ is_training=is_training,
434
+ refinement_resolutions=refinement_resolutions,
435
+ )
436
+
437
+ feature_grid = feature_grids.lowres
438
+ hires_feats = feature_grids.hires
439
+ highest_feats = feature_grids.highest
440
+ resize_im_shape = feature_grids.resolutions
441
+
442
+ shape = video.shape
443
+ # shape is [batch_size, time, height, width, channels]; conversion needs
444
+ # [time, width, height]
445
+ curr_resolution = (-1, -1)
446
+ query_feats = []
447
+ hires_query_feats = []
448
+ highest_query_feats = []
449
+ query_supp = []
450
+ hires_query_supp = []
451
+ highest_query_supp = []
452
+ for i, resolution in enumerate(resize_im_shape):
453
+ if utils.is_same_res(curr_resolution, resolution):
454
+ query_feats.append(query_feats[-1])
455
+ hires_query_feats.append(hires_query_feats[-1])
456
+ highest_query_feats.append(highest_query_feats[-1])
457
+ query_supp.append(query_supp[-1])
458
+ hires_query_supp.append(hires_query_supp[-1])
459
+ highest_query_supp.append(highest_query_supp[-1])
460
+ continue
461
+ position_in_grid = utils.convert_grid_coordinates(
462
+ query_points,
463
+ shape[1:4],
464
+ feature_grid[i].shape[1:4],
465
+ coordinate_format='tyx',
466
+ )
467
+ position_in_grid_hires = utils.convert_grid_coordinates(
468
+ query_points,
469
+ shape[1:4],
470
+ hires_feats[i].shape[1:4],
471
+ coordinate_format='tyx',
472
+ )
473
+ position_in_grid_highest = utils.convert_grid_coordinates(
474
+ query_points,
475
+ shape[1:4],
476
+ highest_feats[i].shape[1:4],
477
+ coordinate_format='tyx',
478
+ )
479
+
480
+ support_size = 7
481
+ ctxx, ctxy = torch.meshgrid(
482
+ torch.arange(-(support_size // 2), support_size // 2 + 1),
483
+ torch.arange(-(support_size // 2), support_size // 2 + 1),
484
+ indexing='xy',
485
+ )
486
+ ctx = torch.stack([torch.zeros_like(ctxy), ctxy, ctxx], axis=-1)
487
+ ctx = torch.reshape(ctx, [-1, 3]).to(video.device) # s*s 3
488
+
489
+ position_support = position_in_grid[..., None, :] + ctx[None, None, ...] # b n s*s 3
490
+ position_support = rearrange(position_support, 'b n s c -> b (n s) c')
491
+ interp_supp = utils.map_coordinates_3d(
492
+ feature_grid[i], position_support
493
+ )
494
+ interp_supp = rearrange(interp_supp, 'b (n h w) c -> b n h w c', h=support_size, w=support_size)
495
+
496
+ position_support_hires = position_in_grid_hires[..., None, :] + ctx[None, None, ...]
497
+ position_support_hires = rearrange(position_support_hires, 'b n s c -> b (n s) c')
498
+ hires_interp_supp = utils.map_coordinates_3d(
499
+ hires_feats[i], position_support_hires
500
+ )
501
+ hires_interp_supp = rearrange(hires_interp_supp, 'b (n h w) c -> b n h w c', h=support_size, w=support_size)
502
+
503
+ position_support_highest = position_in_grid_highest[..., None, :] + ctx[None, None, ...]
504
+ position_support_highest = rearrange(position_support_highest, 'b n s c -> b (n s) c')
505
+ highest_interp_supp = utils.map_coordinates_3d(
506
+ highest_feats[i], position_support_highest
507
+ )
508
+ highest_interp_supp = rearrange(highest_interp_supp, 'b (n h w) c -> b n h w c', h=support_size, w=support_size)
509
+
510
+ interp_features = interp_supp[..., support_size // 2, support_size // 2, :]
511
+ hires_interp = hires_interp_supp[..., support_size // 2, support_size // 2, :]
512
+ highest_interp = highest_interp_supp[..., support_size // 2, support_size // 2, :]
513
+
514
+ hires_query_feats.append(hires_interp)
515
+ query_feats.append(interp_features)
516
+ highest_query_feats.append(highest_interp)
517
+ query_supp.append(interp_supp)
518
+ hires_query_supp.append(hires_interp_supp)
519
+ highest_query_supp.append(highest_interp_supp)
520
+
521
+ return QueryFeatures(
522
+ tuple(query_feats), tuple(hires_query_feats), tuple(highest_query_feats),
523
+ tuple(query_supp), tuple(hires_query_supp), tuple(highest_query_supp), tuple(resize_im_shape),
524
+ )
525
+
526
+ def get_feature_grids(
527
+ self,
528
+ video: torch.Tensor,
529
+ is_training: Optional[bool] = False,
530
+ refinement_resolutions: Optional[List[Tuple[int, int]]] = None,
531
+ ) -> FeatureGrids:
532
+ """Computes feature grids.
533
+
534
+ Args:
535
+ video: A 5-D tensor representing a batch of sequences of images.
536
+ is_training: Whether we are training.
537
+ refinement_resolutions: A list of (height, width) tuples. Refinement will
538
+ be repeated at each specified resolution, to achieve high accuracy on
539
+ resolutions higher than what TAPIR was trained on. If None, reasonable
540
+ refinement resolutions will be inferred from the input video size.
541
+
542
+ Returns:
543
+ A FeatureGrids object containing the required features for every
544
+ required resolution. Note that there will be one more feature grid
545
+ than there are refinement_resolutions, because there is always a
546
+ feature grid computed for TAP-Net initialization.
547
+ """
548
+ del is_training
549
+ if refinement_resolutions is None:
550
+ refinement_resolutions = utils.generate_default_resolutions(
551
+ video.shape[2:4], self.initial_resolution
552
+ )
553
+
554
+ all_required_resolutions = []
555
+ all_required_resolutions.extend(refinement_resolutions)
556
+
557
+ feature_grid = []
558
+ hires_feats = []
559
+ highest_feats = []
560
+ resize_im_shape = []
561
+ curr_resolution = (-1, -1)
562
+
563
+ latent = None
564
+ hires = None
565
+ video_resize = None
566
+ for resolution in all_required_resolutions:
567
+ if resolution[0] % 8 != 0 or resolution[1] % 8 != 0:
568
+ raise ValueError('Image resolution must be a multiple of 8.')
569
+
570
+ if not utils.is_same_res(curr_resolution, resolution):
571
+ if utils.is_same_res(curr_resolution, video.shape[-3:-1]):
572
+ video_resize = video
573
+ else:
574
+ video_resize = utils.bilinear(video, resolution)
575
+
576
+ curr_resolution = resolution
577
+ n, f, h, w, c = video_resize.shape
578
+ video_resize = video_resize.view(n*f, h, w, c).permute(0, 3, 1, 2)
579
+
580
+ if self.feature_extractor_chunk_size > 0:
581
+ latent_list = []
582
+ hires_list = []
583
+ highest_list = []
584
+ chunk_size = self.feature_extractor_chunk_size
585
+ for start_idx in range(0, video_resize.shape[0], chunk_size):
586
+ video_chunk = video_resize[start_idx:start_idx + chunk_size]
587
+ resnet_out = self.resnet_torch(video_chunk)
588
+
589
+ u3 = resnet_out['resnet_unit_3'].permute(0, 2, 3, 1)
590
+ latent_list.append(u3)
591
+ u1 = resnet_out['resnet_unit_1'].permute(0, 2, 3, 1)
592
+ hires_list.append(u1)
593
+ u0 = resnet_out['resnet_unit_0'].permute(0, 2, 3, 1)
594
+ highest_list.append(u0)
595
+
596
+ latent = torch.cat(latent_list, dim=0)
597
+ hires = torch.cat(hires_list, dim=0)
598
+ highest = torch.cat(highest_list, dim=0)
599
+
600
+ else:
601
+ resnet_out = self.resnet_torch(video_resize)
602
+ latent = resnet_out['resnet_unit_3'].permute(0, 2, 3, 1)
603
+ hires = resnet_out['resnet_unit_1'].permute(0, 2, 3, 1)
604
+ highest = resnet_out['resnet_unit_0'].permute(0, 2, 3, 1)
605
+
606
+ if self.extra_convs:
607
+ latent = self.extra_convs(latent)
608
+
609
+ latent = latent / torch.sqrt(
610
+ torch.maximum(
611
+ torch.sum(torch.square(latent), axis=-1, keepdims=True),
612
+ torch.tensor(1e-12, device=latent.device),
613
+ )
614
+ )
615
+ hires = hires / torch.sqrt(
616
+ torch.maximum(
617
+ torch.sum(torch.square(hires), axis=-1, keepdims=True),
618
+ torch.tensor(1e-12, device=hires.device),
619
+ )
620
+ )
621
+ highest = highest / torch.sqrt(
622
+ torch.maximum(
623
+ torch.sum(torch.square(highest), axis=-1, keepdims=True),
624
+ torch.tensor(1e-12, device=highest.device),
625
+ )
626
+ )
627
+
628
+ latent = latent.view(n, f, *latent.shape[1:])
629
+ hires = hires.view(n, f, *hires.shape[1:])
630
+ highest = highest.view(n, f, *highest.shape[1:])
631
+
632
+ feature_grid.append(latent)
633
+ hires_feats.append(hires)
634
+ highest_feats.append(highest)
635
+ resize_im_shape.append(video_resize.shape[2:4])
636
+
637
+ return FeatureGrids(
638
+ tuple(feature_grid), tuple(hires_feats), tuple(highest_feats), tuple(resize_im_shape)
639
+ )
640
+
641
+ def estimate_trajectories(
642
+ self,
643
+ video_size: Tuple[int, int],
644
+ is_training: bool,
645
+ feature_grids: FeatureGrids,
646
+ query_features: QueryFeatures,
647
+ query_points_in_video: Optional[torch.Tensor],
648
+ query_chunk_size: Optional[int] = None,
649
+ causal_context: Optional[Dict[str, torch.Tensor]] = None,
650
+ get_causal_context: bool = False,
651
+ ) -> Mapping[str, Any]:
652
+ """Estimates trajectories given features for a video and query features.
653
+
654
+ Args:
655
+ video_size: A 2-tuple containing the original [height, width] of the
656
+ video. Predictions will be scaled with respect to this resolution.
657
+ is_training: Whether we are training.
658
+ feature_grids: a FeatureGrids object computed for the given video.
659
+ query_features: a QueryFeatures object computed for the query points.
660
+ query_points_in_video: If provided, assume that the query points come from
661
+ the same video as feature_grids, and therefore constrain the resulting
662
+ trajectories to (approximately) pass through them.
663
+ query_chunk_size: When computing cost volumes, break the queries into
664
+ chunks of this size to save memory.
665
+ causal_context: If provided, a dict of causal context to use for
666
+ refinement.
667
+ get_causal_context: If True, return causal context in the output.
668
+
669
+ Returns:
670
+ A dict of outputs, including:
671
+ occlusion: Occlusion logits, of shape [batch, num_queries, num_frames]
672
+ where higher indicates more likely to be occluded.
673
+ tracks: predicted point locations, of shape
674
+ [batch, num_queries, num_frames, 2], where each point is [x, y]
675
+ in raster coordinates
676
+ expected_dist: uncertainty estimate logits, of shape
677
+ [batch, num_queries, num_frames], where higher indicates more likely
678
+ to be far from the correct answer.
679
+ """
680
+ del is_training
681
+
682
+ def train2orig(x):
683
+ return utils.convert_grid_coordinates(
684
+ x,
685
+ self.initial_resolution[::-1],
686
+ video_size[::-1],
687
+ coordinate_format='xy',
688
+ )
689
+
690
+ occ_iters = []
691
+ pts_iters = []
692
+ expd_iters = []
693
+ new_causal_context = []
694
+ num_iters = self.num_pips_iter
695
+ for _ in range(num_iters + 1):
696
+ occ_iters.append([])
697
+ pts_iters.append([])
698
+ expd_iters.append([])
699
+ new_causal_context.append([])
700
+ del new_causal_context[-1]
701
+
702
+ infer = functools.partial(
703
+ self.tracks_from_cost_volume,
704
+ im_shp=feature_grids.lowres[0].shape[0:2]
705
+ + self.initial_resolution
706
+ + (3,),
707
+ )
708
+
709
+ num_queries = query_features.lowres[0].shape[1]
710
+
711
+ for ch in range(0, num_queries, query_chunk_size):
712
+ chunk = query_features.lowres[0][:, ch:ch + query_chunk_size]
713
+ chunk_hires = query_features.hires[0][:, ch:ch + query_chunk_size]
714
+
715
+ if query_points_in_video is not None:
716
+ infer_query_points = query_points_in_video[
717
+ :, ch : ch + query_chunk_size
718
+ ]
719
+ num_frames = feature_grids.lowres[0].shape[1]
720
+ infer_query_points = utils.convert_grid_coordinates(
721
+ infer_query_points,
722
+ (num_frames,) + video_size,
723
+ (num_frames,) + self.initial_resolution,
724
+ coordinate_format='tyx',
725
+ )
726
+ else:
727
+ infer_query_points = None
728
+
729
+ points, occlusion, expected_dist, cost_volume = infer(
730
+ chunk,
731
+ chunk_hires,
732
+ feature_grids.lowres[0],
733
+ feature_grids.hires[0],
734
+ infer_query_points,
735
+ )
736
+ pts_iters[0].append(train2orig(points))
737
+ occ_iters[0].append(occlusion)
738
+ expd_iters[0].append(expected_dist)
739
+
740
+ mixer_feats = None
741
+ for i in range(num_iters):
742
+ feature_level = -1
743
+ queries = [
744
+ query_features.hires[feature_level][:, ch:ch + query_chunk_size],
745
+ query_features.lowres[feature_level][:, ch:ch + query_chunk_size],
746
+ query_features.highest[feature_level][:, ch:ch + query_chunk_size],
747
+ ]
748
+ supports = [
749
+ query_features.hires_supp[feature_level][:, ch:ch + query_chunk_size],
750
+ query_features.lowres_supp[feature_level][:, ch:ch + query_chunk_size],
751
+ query_features.highest_supp[feature_level][:, ch:ch + query_chunk_size],
752
+ ]
753
+ for _ in range(self.pyramid_level):
754
+ queries.append(queries[-1])
755
+ pyramid = [
756
+ feature_grids.hires[feature_level],
757
+ feature_grids.lowres[feature_level],
758
+ feature_grids.highest[feature_level],
759
+ ]
760
+ for _ in range(self.pyramid_level):
761
+ pyramid.append(
762
+ F.avg_pool3d(
763
+ pyramid[-1],
764
+ kernel_size=(2, 2, 1),
765
+ stride=(2, 2, 1),
766
+ padding=0,
767
+ )
768
+ )
769
+
770
+ refined = self.refine_pips(
771
+ queries,
772
+ supports,
773
+ None,
774
+ pyramid,
775
+ points.detach(),
776
+ occlusion.detach(),
777
+ expected_dist.detach(),
778
+ orig_hw=self.initial_resolution,
779
+ last_iter=mixer_feats,
780
+ mixer_iter=i,
781
+ resize_hw=feature_grids.resolutions[feature_level],
782
+ get_causal_context=get_causal_context,
783
+ cost_volume=cost_volume
784
+ )
785
+ points, occlusion, expected_dist, mixer_feats, new_causal = refined
786
+ pts_iters[i + 1].append(train2orig(points))
787
+ occ_iters[i + 1].append(occlusion)
788
+ expd_iters[i + 1].append(expected_dist)
789
+ new_causal_context[i].append(new_causal)
790
+
791
+ if (i + 1) % self.num_pips_iter == 0:
792
+ mixer_feats = None
793
+ expected_dist = expd_iters[0][-1]
794
+ occlusion = occ_iters[0][-1]
795
+
796
+ occlusion = []
797
+ points = []
798
+ expd = []
799
+ for i, _ in enumerate(occ_iters):
800
+ occlusion.append(torch.cat(occ_iters[i], dim=1))
801
+ points.append(torch.cat(pts_iters[i], dim=1))
802
+ expd.append(torch.cat(expd_iters[i], dim=1))
803
+
804
+ out = dict(
805
+ occlusion=occlusion,
806
+ tracks=points,
807
+ expected_dist=expd,
808
+ )
809
+ return out
810
+
811
+ def refine_pips(
812
+ self,
813
+ target_feature,
814
+ support_feature,
815
+ frame_features,
816
+ pyramid,
817
+ pos_guess,
818
+ occ_guess,
819
+ expd_guess,
820
+ orig_hw,
821
+ last_iter=None,
822
+ mixer_iter=0.0,
823
+ resize_hw=None,
824
+ causal_context=None,
825
+ get_causal_context=False,
826
+ cost_volume=None,
827
+ ):
828
+ del frame_features
829
+ del mixer_iter
830
+ orig_h, orig_w = orig_hw
831
+ resized_h, resized_w = resize_hw
832
+ corrs_pyr = []
833
+ assert len(target_feature) == len(pyramid)
834
+ for pyridx, (query, supp, grid) in enumerate(zip(target_feature, support_feature, pyramid)):
835
+ # note: interp needs [y,x]
836
+ coords = utils.convert_grid_coordinates(
837
+ pos_guess, (orig_w, orig_h), grid.shape[-2:-4:-1]
838
+ )
839
+ coords = torch.flip(coords, dims=(-1,))
840
+
841
+ support_size = 7
842
+ ctxx, ctxy = torch.meshgrid(
843
+ torch.arange(-(support_size // 2), support_size // 2 + 1),
844
+ torch.arange(-(support_size // 2), support_size // 2 + 1),
845
+ indexing='xy',
846
+ )
847
+ ctx = torch.stack([ctxy, ctxx], dim=-1)
848
+ ctx = ctx.reshape(-1, 2).to(coords.device)
849
+ coords2 = coords.unsqueeze(3) + ctx.unsqueeze(0).unsqueeze(0).unsqueeze(0)
850
+ neighborhood = utils.map_coordinates_2d(grid, coords2)
851
+
852
+ neighborhood = rearrange(neighborhood, 'b n t (h w) c -> b n t h w c', h=support_size, w=support_size)
853
+ patches_input = torch.einsum('bnthwc,bnijc->bnthwij', neighborhood, supp)
854
+ patches_input = rearrange(patches_input, 'b n t h w i j -> (b n t) h w i j')
855
+ patches_emb = self.cmdtop[pyridx](patches_input)
856
+ patches = rearrange(patches_emb, '(b n t) c -> b n t c', b=neighborhood.shape[0], n=neighborhood.shape[1])
857
+
858
+ corrs_pyr.append(patches)
859
+ corrs_pyr = torch.concatenate(corrs_pyr, dim=-1)
860
+
861
+ corrs_chunked = corrs_pyr
862
+ pos_guess_input = pos_guess
863
+ occ_guess_input = occ_guess[..., None]
864
+ expd_guess_input = expd_guess[..., None]
865
+
866
+ # mlp_input is batch, num_points, num_chunks, frames_per_chunk, channels
867
+ if last_iter is None:
868
+ both_feature = torch.cat([target_feature[0], target_feature[1]], axis=-1)
869
+ mlp_input_features = torch.tile(
870
+ both_feature.unsqueeze(2), (1, 1, corrs_chunked.shape[-2], 1)
871
+ )
872
+ else:
873
+ mlp_input_features = last_iter
874
+
875
+ mlp_input_list = [
876
+ occ_guess_input,
877
+ expd_guess_input,
878
+ corrs_chunked
879
+ ]
880
+
881
+ rel_pos_forward = F.pad(pos_guess_input[..., :-1, :] - pos_guess_input[..., 1:, :], (0, 0, 0, 1))
882
+ rel_pos_backward = F.pad(pos_guess_input[..., 1:, :] - pos_guess_input[..., :-1, :], (0, 0, 1, 0))
883
+ scale = torch.tensor([resized_w / orig_w, resized_h / orig_h]) / torch.tensor([orig_w, orig_h])
884
+ scale = scale.to(pos_guess_input.device)
885
+ rel_pos_forward = rel_pos_forward * scale
886
+ rel_pos_backward = rel_pos_backward * scale
887
+ rel_pos_emb_input = posenc(torch.cat([rel_pos_forward, rel_pos_backward], axis=-1), min_deg=0, max_deg=10) # batch, num_points, num_frames, 84
888
+ mlp_input_list.append(rel_pos_emb_input)
889
+ mlp_input = torch.cat(mlp_input_list, axis=-1)
890
+
891
+ x = rearrange(mlp_input, 'b n f c -> (b n) f c')
892
+ res = self.torch_pips_mixer(x)
893
+
894
+ res = rearrange(res, '(b n) f c -> b n f c', b=mlp_input.shape[0])
895
+
896
+ pos_update = utils.convert_grid_coordinates(
897
+ res[..., :2],
898
+ (resized_w, resized_h),
899
+ (orig_w, orig_h),
900
+ )
901
+ return (
902
+ pos_update + pos_guess,
903
+ res[..., 2] + occ_guess,
904
+ res[..., 3] + expd_guess,
905
+ res[..., 4:] + (mlp_input_features if last_iter is None else last_iter),
906
+ None,
907
+ )
908
+
909
+ def tracks_from_cost_volume(
910
+ self,
911
+ interp_feature: torch.Tensor,
912
+ interp_feature_hires: torch.Tensor,
913
+ feature_grid: torch.Tensor,
914
+ feature_grid_hires: torch.Tensor,
915
+ query_points: Optional[torch.Tensor],
916
+ im_shp=None,
917
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
918
+ """Converts features into tracks by computing a cost volume.
919
+
920
+ The computed cost volume will have shape
921
+ [batch, num_queries, time, height, width], which can be very
922
+ memory intensive.
923
+
924
+ Args:
925
+ interp_feature: A tensor of features for each query point, of shape
926
+ [batch, num_queries, channels, heads].
927
+ feature_grid: A tensor of features for the video, of shape [batch, time,
928
+ height, width, channels, heads].
929
+ query_points: When computing tracks, we assume these points are given as
930
+ ground truth and we reproduce them exactly. This is a set of points of
931
+ shape [batch, num_points, 3], where each entry is [t, y, x] in frame/
932
+ raster coordinates.
933
+ im_shp: The shape of the original image, i.e., [batch, num_frames, time,
934
+ height, width, 3].
935
+
936
+ Returns:
937
+ A 2-tuple of the inferred points (of shape
938
+ [batch, num_points, num_frames, 2] where each point is [x, y]) and
939
+ inferred occlusion (of shape [batch, num_points, num_frames], where
940
+ each is a logit where higher means occluded)
941
+ """
942
+
943
+ cost_volume = torch.einsum(
944
+ 'bnc,bthwc->tbnhw',
945
+ interp_feature,
946
+ feature_grid,
947
+ )
948
+ cost_volume_hires = torch.einsum(
949
+ 'bnc,bthwc->tbnhw',
950
+ interp_feature_hires,
951
+ feature_grid_hires,
952
+ )
953
+
954
+ shape = cost_volume.shape
955
+ batch_size, num_points = cost_volume.shape[1:3]
956
+
957
+ interp_cost = rearrange(cost_volume, 't b n h w -> (t b n) () h w')
958
+ interp_cost = F.interpolate(interp_cost, cost_volume_hires.shape[3:], mode='bilinear', align_corners=False)
959
+ interp_cost = rearrange(interp_cost, '(t b n) () h w -> t b n h w', b=batch_size, n=num_points)
960
+ cost_volume_stack = torch.stack(
961
+ [
962
+ interp_cost,
963
+ cost_volume_hires,
964
+ ], dim=-1
965
+ )
966
+ pos = rearrange(cost_volume_stack, 't b n h w c -> (t b n) c h w')
967
+ pos = self.cost_conv(pos)
968
+ pos = rearrange(pos, '(t b n) () h w -> b n t h w', b=batch_size, n=num_points)
969
+
970
+ pos_sm = pos.reshape(pos.size(0), pos.size(1), pos.size(2), -1)
971
+ softmaxed = F.softmax(pos_sm * self.softmax_temperature, dim=-1)
972
+ pos = softmaxed.view_as(pos)
973
+
974
+ points = utils.heatmaps_to_points(pos, im_shp, query_points=query_points)
975
+
976
+ occlusion = torch.cat(
977
+ [
978
+ torch.mean(cost_volume_stack, dim=(-2, -3)),
979
+ torch.amax(cost_volume_stack, dim=(-2, -3)),
980
+ torch.amin(cost_volume_stack, dim=(-2, -3)),
981
+ ], dim=-1
982
+ )
983
+ occlusion = self.occ_linear(occlusion)
984
+ expected_dist = rearrange(occlusion[..., 1:2], 't b n () -> b n t', t=shape[0])
985
+ occlusion = rearrange(occlusion[..., 0:1], 't b n () -> b n t', t=shape[0])
986
+
987
+ return points, occlusion, expected_dist, rearrange(cost_volume, 't b n h w -> b n t h w')
988
+
989
+ def construct_initial_causal_state(self, num_points, num_resolutions=1):
990
+ """Construct initial causal state."""
991
+ value_shapes = {}
992
+ for i in range(self.num_mixer_blocks):
993
+ value_shapes[f'block_{i}_causal_1'] = (1, num_points, 2, 512)
994
+ value_shapes[f'block_{i}_causal_2'] = (1, num_points, 2, 2048)
995
+ fake_ret = {
996
+ k: torch.zeros(v, dtype=torch.float32) for k, v in value_shapes.items()
997
+ }
998
+ return [fake_ret] * num_resolutions * 4
999
+
1000
+ def inference(
1001
+ self,
1002
+ video : Union[np.ndarray, torch.Tensor],
1003
+ query_points : torch.Tensor,
1004
+ query_chunk_size : int = 64,
1005
+ resolution : Tuple[int, int] = (256, 256),
1006
+ query_format : str = 'tyx',
1007
+ ) -> dict:
1008
+ """
1009
+ Run inference on LocoTrack model.
1010
+ Args:
1011
+ model: LocoTrack model
1012
+ video: np.ndarray or torch.Tensor, shape [batch, time, height, width, 3], normalized to [-1, 1]
1013
+ if np.ndarray, it will be converted to torch.Tensor
1014
+ if dtype is uint8, it will be converted to float32 and normalized to [-1, 1]
1015
+ query_points: torch.Tensor, shape [batch, num_points, 3]
1016
+ query_chunk_size: int, default 64
1017
+ resolution: Tuple[int, int], default (256, 256)
1018
+ query_format: str, default 'tyx', query points format
1019
+ Returns:
1020
+ dict with keys: 'tracks', 'occlusion'
1021
+ """
1022
+ assert video.shape[-1] == 3, f'video shape should be [batch, time, height, width, 3], got {video.shape}'
1023
+ device = next(self.parameters()).device
1024
+
1025
+ # query_format is not tyx, then convert query_points to tyx
1026
+ query_shuffle_ind = [query_format.index(c) for c in 'tyx']
1027
+ query_points = query_points[..., query_shuffle_ind].to(device)
1028
+
1029
+ if isinstance(video, np.ndarray):
1030
+ video = torch.from_numpy(video).to(device)
1031
+
1032
+ if video.dtype == torch.uint8:
1033
+ video = video.float() / 255.0 * 2 - 1
1034
+
1035
+ B, _, H, W, _ = video.shape
1036
+ if (H, W) != resolution:
1037
+ video = rearrange(video, 'b t h w c -> (b t) c h w')
1038
+ video = F.interpolate(video, resolution, mode='bilinear', align_corners=False)
1039
+ video = rearrange(video, '(b t) c h w -> b t h w c', b=B)
1040
+
1041
+ query_points = query_points.clone()
1042
+ query_points[..., 1] = query_points[..., 1] / H * resolution[0]
1043
+ query_points[..., 2] = query_points[..., 2] / W * resolution[1]
1044
+
1045
+ out = self.forward(video, query_points, query_chunk_size=query_chunk_size)
1046
+ tracks, occlusion, expected_dist = out['tracks'], out['occlusion'], out['expected_dist']
1047
+
1048
+ tracks = tracks * torch.tensor([W / resolution[1], H / resolution[0]], device=tracks.device)
1049
+
1050
+ pred_occ = torch.sigmoid(occlusion)
1051
+ pred_occ = 1 - (1 - pred_occ) * (1 - torch.sigmoid(expected_dist))
1052
+ pred_occ = pred_occ > 0.5 # threshold
1053
+
1054
+ return {
1055
+ 'tracks': tracks,
1056
+ 'occlusion': pred_occ,
1057
+ }
1058
+
1059
+
1060
+ CHECKPOINT_LINK = {
1061
+ 'small': 'https://huggingface.co/datasets/hamacojr/LocoTrack-pytorch-weights/resolve/main/locotrack_small.ckpt',
1062
+ 'base': 'https://huggingface.co/datasets/hamacojr/LocoTrack-pytorch-weights/resolve/main/locotrack_base.ckpt',
1063
+ }
1064
+
1065
+ def load_model(ckpt_path=None, model_size='base'):
1066
+ if ckpt_path is None:
1067
+ ckpt_link = CHECKPOINT_LINK[model_size]
1068
+ state_dict = torch.hub.load_state_dict_from_url(ckpt_link, map_location='cpu')['state_dict']
1069
+ else:
1070
+ state_dict = torch.load(ckpt_path)['state_dict']
1071
+ state_dict = {k.replace('model.', ''): v for k, v in state_dict.items()}
1072
+
1073
+ model = LocoTrack(model_size=model_size)
1074
+ model.load_state_dict(state_dict)
1075
+ model.eval()
1076
+
1077
+ return model