nnInteractive 2.0.0__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.
Files changed (76) hide show
  1. nnInteractive/__init__.py +3 -0
  2. nnInteractive/inference/__init__.py +0 -0
  3. nnInteractive/inference/cvpr2025_challenge_baseline/__init__.py +0 -0
  4. nnInteractive/inference/cvpr2025_challenge_baseline/predict.py +173 -0
  5. nnInteractive/inference/inference_session.py +1400 -0
  6. nnInteractive/interaction/__init__.py +0 -0
  7. nnInteractive/interaction/point.py +166 -0
  8. nnInteractive/supervoxel/setup.py +4 -0
  9. nnInteractive/supervoxel/src/metadata.py +118 -0
  10. nnInteractive/supervoxel/src/reader.py +175 -0
  11. nnInteractive/supervoxel/src/run.py +136 -0
  12. nnInteractive/supervoxel/src/sam2/__init__.py +2 -0
  13. nnInteractive/supervoxel/src/sam2/sam2/__init__.py +11 -0
  14. nnInteractive/supervoxel/src/sam2/sam2/automatic_mask_generator.py +434 -0
  15. nnInteractive/supervoxel/src/sam2/sam2/benchmark.py +86 -0
  16. nnInteractive/supervoxel/src/sam2/sam2/build_sam.py +172 -0
  17. nnInteractive/supervoxel/src/sam2/sam2/modeling/__init__.py +5 -0
  18. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/__init__.py +5 -0
  19. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/hieradet.py +305 -0
  20. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/image_encoder.py +132 -0
  21. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/utils.py +89 -0
  22. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_attention.py +167 -0
  23. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_encoder.py +179 -0
  24. nnInteractive/supervoxel/src/sam2/sam2/modeling/position_encoding.py +217 -0
  25. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/__init__.py +5 -0
  26. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/mask_decoder.py +274 -0
  27. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/prompt_encoder.py +194 -0
  28. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/transformer.py +293 -0
  29. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_base.py +879 -0
  30. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_utils.py +315 -0
  31. nnInteractive/supervoxel/src/sam2/sam2/sam2_image_predictor.py +433 -0
  32. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor.py +1171 -0
  33. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor_legacy.py +1125 -0
  34. nnInteractive/supervoxel/src/sam2/sam2/utils/__init__.py +5 -0
  35. nnInteractive/supervoxel/src/sam2/sam2/utils/amg.py +332 -0
  36. nnInteractive/supervoxel/src/sam2/sam2/utils/misc.py +488 -0
  37. nnInteractive/supervoxel/src/sam2/sam2/utils/transforms.py +108 -0
  38. nnInteractive/supervoxel/src/sam2/setup.py +174 -0
  39. nnInteractive/supervoxel/src/sam2/training/__init__.py +5 -0
  40. nnInteractive/supervoxel/src/sam2/training/dataset/__init__.py +5 -0
  41. nnInteractive/supervoxel/src/sam2/training/dataset/sam2_datasets.py +176 -0
  42. nnInteractive/supervoxel/src/sam2/training/dataset/transforms.py +481 -0
  43. nnInteractive/supervoxel/src/sam2/training/dataset/utils.py +102 -0
  44. nnInteractive/supervoxel/src/sam2/training/dataset/vos_dataset.py +154 -0
  45. nnInteractive/supervoxel/src/sam2/training/dataset/vos_raw_dataset.py +290 -0
  46. nnInteractive/supervoxel/src/sam2/training/dataset/vos_sampler.py +103 -0
  47. nnInteractive/supervoxel/src/sam2/training/dataset/vos_segment_loader.py +289 -0
  48. nnInteractive/supervoxel/src/sam2/training/loss_fns.py +290 -0
  49. nnInteractive/supervoxel/src/sam2/training/model/__init__.py +5 -0
  50. nnInteractive/supervoxel/src/sam2/training/model/sam2.py +515 -0
  51. nnInteractive/supervoxel/src/sam2/training/optimizer.py +462 -0
  52. nnInteractive/supervoxel/src/sam2/training/scripts/sav_frame_extraction_submitit.py +157 -0
  53. nnInteractive/supervoxel/src/sam2/training/train.py +232 -0
  54. nnInteractive/supervoxel/src/sam2/training/trainer.py +1051 -0
  55. nnInteractive/supervoxel/src/sam2/training/utils/__init__.py +5 -0
  56. nnInteractive/supervoxel/src/sam2/training/utils/checkpoint_utils.py +328 -0
  57. nnInteractive/supervoxel/src/sam2/training/utils/data_utils.py +166 -0
  58. nnInteractive/supervoxel/src/sam2/training/utils/distributed.py +560 -0
  59. nnInteractive/supervoxel/src/sam2/training/utils/logger.py +236 -0
  60. nnInteractive/supervoxel/src/sam2/training/utils/train_utils.py +275 -0
  61. nnInteractive/supervoxel/src/supervoxel.py +198 -0
  62. nnInteractive/trainer/__init__.py +0 -0
  63. nnInteractive/trainer/nnInteractiveTrainer.py +24 -0
  64. nnInteractive/utils/__init__.py +0 -0
  65. nnInteractive/utils/bboxes.py +217 -0
  66. nnInteractive/utils/checkpoint_cleansing.py +9 -0
  67. nnInteractive/utils/crop.py +268 -0
  68. nnInteractive/utils/erosion_dilation.py +48 -0
  69. nnInteractive/utils/inference_helpers.py +45 -0
  70. nnInteractive/utils/os_shennanigans.py +16 -0
  71. nnInteractive/utils/rounding.py +13 -0
  72. nninteractive-2.0.0.dist-info/METADATA +511 -0
  73. nninteractive-2.0.0.dist-info/RECORD +76 -0
  74. nninteractive-2.0.0.dist-info/WHEEL +5 -0
  75. nninteractive-2.0.0.dist-info/licenses/LICENSE +201 -0
  76. nninteractive-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,5 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
@@ -0,0 +1,328 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import contextlib
8
+ import fnmatch
9
+ import logging
10
+ from typing import (
11
+ Any,
12
+ Callable,
13
+ Dict,
14
+ List,
15
+ Mapping,
16
+ Optional,
17
+ Sequence,
18
+ Set,
19
+ Tuple,
20
+ Union,
21
+ )
22
+
23
+ import numpy as np
24
+ import torch
25
+ import torch.nn as nn
26
+ from iopath.common.file_io import g_pathmgr
27
+ from torch.jit._script import RecursiveScriptModule
28
+
29
+
30
+ def unix_pattern_to_parameter_names(
31
+ constraints: List[str], all_parameter_names: Sequence[str]
32
+ ) -> Union[None, Set[str]]:
33
+ """
34
+ Go through the list of parameter names and select those that match
35
+ any of the provided constraints
36
+ """
37
+ parameter_names = []
38
+ for param_name in constraints:
39
+ matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
40
+ assert len(matching_parameters) > 0, f"param_names {param_name} don't match any param in the given names."
41
+ parameter_names.append(matching_parameters)
42
+ return set.union(*parameter_names)
43
+
44
+
45
+ def filter_params_matching_unix_pattern(
46
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
47
+ ) -> Dict[str, torch.Tensor]:
48
+ """
49
+ Remove from the state dictionary the parameters matching the provided unix patterns
50
+
51
+ Args:
52
+ patterns: the list of unix patterns to exclude
53
+ state_dict: the dictionary to filter
54
+
55
+ Returns:
56
+ A new state dictionary
57
+ """
58
+ if len(patterns) == 0:
59
+ return {}
60
+
61
+ all_keys = list(state_dict.keys())
62
+ included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
63
+ return {k: state_dict[k] for k in included_keys}
64
+
65
+
66
+ def exclude_params_matching_unix_pattern(
67
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
68
+ ) -> Dict[str, torch.Tensor]:
69
+ """
70
+ Remove from the state dictionary the parameters matching the provided unix patterns
71
+
72
+ Args:
73
+ patterns: the list of unix patterns to exclude
74
+ state_dict: the dictionary to filter
75
+
76
+ Returns:
77
+ A new state dictionary
78
+ """
79
+ if len(patterns) == 0:
80
+ return state_dict
81
+
82
+ all_keys = list(state_dict.keys())
83
+ excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
84
+ return {k: v for k, v in state_dict.items() if k not in excluded_keys}
85
+
86
+
87
+ def _get_state_dict_summary(state_dict: Dict[str, torch.Tensor]):
88
+ keys = []
89
+ trace = []
90
+ for k, v in state_dict.items():
91
+ keys.append(k)
92
+ trace.append(v.sum().item())
93
+ trace = np.array(trace)[np.argsort(keys)]
94
+ return trace
95
+
96
+
97
+ def assert_skipped_parameters_are_frozen(model: nn.Module, patterns: List[str]):
98
+ """
99
+ Verifies that all the parameters matching the provided patterns
100
+ are frozen - this acts as a safeguard when ignoring parameter
101
+ when saving checkpoints - if the parameters are in fact trainable
102
+ """
103
+ if not patterns:
104
+ return
105
+
106
+ frozen_state_dict = filter_params_matching_unix_pattern(patterns=patterns, state_dict=model.state_dict())
107
+ non_frozen_keys = {n for n, p in model.named_parameters() if n in frozen_state_dict and p.requires_grad}
108
+ if non_frozen_keys:
109
+ raise ValueError(f"Parameters excluded with `skip_saving_parameters` should be frozen: {non_frozen_keys}")
110
+
111
+
112
+ @contextlib.contextmanager
113
+ def with_check_parameter_frozen(model: nn.Module, patterns: List[str], disabled: bool = True):
114
+ """
115
+ Context manager that inspects a model surrounding a piece of code
116
+ and verifies if the model has been updated by this piece of code
117
+
118
+ The function will raise an exception if the model has been updated
119
+ on at least one of the parameter that matches one of the pattern
120
+
121
+ Args:
122
+ model: the model that might have been updated
123
+ patterns: for the parameters we want to observe
124
+ allowed:
125
+ """
126
+ if not patterns or disabled:
127
+ yield
128
+ return
129
+
130
+ frozen_state_dict = filter_params_matching_unix_pattern(patterns=patterns, state_dict=model.state_dict())
131
+ summary_before = _get_state_dict_summary(frozen_state_dict)
132
+
133
+ yield
134
+
135
+ frozen_state_dict = filter_params_matching_unix_pattern(patterns=patterns, state_dict=model.state_dict())
136
+ summary_after = _get_state_dict_summary(frozen_state_dict)
137
+
138
+ if not np.allclose(summary_before, summary_after, atol=1e-6):
139
+ raise ValueError(
140
+ f"""
141
+ The `model_weight_initializer` has initialized parameters frozen with `skip_saving_parameters`.
142
+ You can resolve this error by either initializing those parameters from within the model definition
143
+ or using the flag `trainer.checkpoint.initialize_after_preemption` to True.
144
+ """
145
+ )
146
+
147
+
148
+ class CkptExcludeKernel:
149
+ """
150
+ Removes the keys from the given model state_dict that match the key_pattern.
151
+
152
+ Args:
153
+ key_pattern: Patterns used to select the keys in the state_dict
154
+ that are eligible for this kernel.
155
+ """
156
+
157
+ def __init__(self, key_pattern: List[str]):
158
+ self.key_pattern = key_pattern
159
+
160
+ def __call__(self, state_dict: Dict):
161
+ """
162
+ Args:
163
+ state_dict: A dictionary representing the given checkpoint's state dict.
164
+ """
165
+ if len(self.key_pattern) == 0:
166
+ return state_dict
167
+ exclude_keys = unix_pattern_to_parameter_names(self.key_pattern, state_dict.keys())
168
+ return {k: v for k, v in state_dict.items() if k not in exclude_keys}
169
+
170
+
171
+ def load_checkpoint(
172
+ path_list: List[str],
173
+ pick_recursive_keys: Optional[List[str]] = None,
174
+ map_location: str = "cpu",
175
+ ) -> Any:
176
+ """
177
+ Loads a checkpoint from the specified path.
178
+
179
+ Args:
180
+ path_list: A list of paths which contain the checkpoint. Each element
181
+ is tried (in order) until a file that exists is found. That file is then
182
+ used to read the checkpoint.
183
+ pick_recursive_keys: Picks sub dicts from the loaded checkpoint if not None.
184
+ For pick_recursive_keys = ["a", "b"], will return checkpoint_dict["a"]["b"]
185
+ map_location (str): a function, torch.device, string or a dict specifying how to
186
+ remap storage locations
187
+
188
+ Returns: Model with the matchin pre-trained weights loaded.
189
+ """
190
+ path_exists = False
191
+ for path in path_list:
192
+ if g_pathmgr.exists(path):
193
+ path_exists = True
194
+ break
195
+
196
+ if not path_exists:
197
+ raise ValueError(f"No path exists in {path_list}")
198
+
199
+ with g_pathmgr.open(path, "rb") as f:
200
+ checkpoint = torch.load(f, map_location=map_location)
201
+
202
+ logging.info(f"Loaded checkpoint from {path}")
203
+ if pick_recursive_keys is not None:
204
+ for key in pick_recursive_keys:
205
+ checkpoint = checkpoint[key]
206
+ return checkpoint
207
+
208
+
209
+ def get_state_dict(checkpoint, ckpt_state_dict_keys):
210
+ if isinstance(checkpoint, RecursiveScriptModule):
211
+ # This is a torchscript JIT model
212
+ return checkpoint.state_dict()
213
+ pre_train_dict = checkpoint
214
+ for i, key in enumerate(ckpt_state_dict_keys):
215
+ if (isinstance(pre_train_dict, Mapping) and key not in pre_train_dict) or (
216
+ isinstance(pre_train_dict, Sequence) and key >= len(pre_train_dict)
217
+ ):
218
+ key_str = '["' + '"]["'.join(list(map(ckpt_state_dict_keys[:i], str))) + '"]'
219
+ raise KeyError(f"'{key}' not found in checkpoint{key_str} " f"with keys: {pre_train_dict.keys()}")
220
+ pre_train_dict = pre_train_dict[key]
221
+ return pre_train_dict
222
+
223
+
224
+ def load_checkpoint_and_apply_kernels(
225
+ checkpoint_path: str,
226
+ checkpoint_kernels: List[Callable] = None,
227
+ ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
228
+ map_location: str = "cpu",
229
+ ) -> nn.Module:
230
+ """
231
+ Performs checkpoint loading with a variety of pre-processing kernel applied in
232
+ sequence.
233
+
234
+ Args:
235
+ checkpoint_path (str): Path to the checkpoint.
236
+ checkpoint_kernels List(Callable): A list of checkpoint processing kernels
237
+ to apply in the specified order. Supported kernels include `CkptIncludeKernel`,
238
+ `CkptExcludeKernel`, etc. These kernels are applied in the
239
+ given order.
240
+ ckpt_state_dict_keys (str): Keys containing the model state dict.
241
+ map_location (str): a function, torch.device, string or a dict specifying how to
242
+ remap storage locations
243
+
244
+ Returns: Model with the matchin pre-trained weights loaded.
245
+ """
246
+ assert g_pathmgr.exists(checkpoint_path), "Checkpoint '{}' not found".format(checkpoint_path)
247
+
248
+ # Load the checkpoint on CPU to avoid GPU mem spike.
249
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
250
+ checkpoint = torch.load(f, map_location=map_location)
251
+
252
+ pre_train_dict = get_state_dict(checkpoint, ckpt_state_dict_keys)
253
+
254
+ # Not logging into info etc since it's a huge log
255
+ logging.debug(
256
+ "Loaded Checkpoint State Dict pre-kernel application: %s" % str(", ".join(list(pre_train_dict.keys())))
257
+ )
258
+ # Apply kernels
259
+ if checkpoint_kernels is not None:
260
+ for f in checkpoint_kernels:
261
+ pre_train_dict = f(state_dict=pre_train_dict)
262
+
263
+ logging.debug(
264
+ "Loaded Checkpoint State Dict Post-kernel application %s" % str(", ".join(list(pre_train_dict.keys())))
265
+ )
266
+
267
+ return pre_train_dict
268
+
269
+
270
+ def check_load_state_dict_errors(
271
+ missing_keys,
272
+ unexpected_keys,
273
+ strict: bool,
274
+ ignore_missing_keys: List[str] = None,
275
+ ignore_unexpected_keys: List[str] = None,
276
+ ):
277
+ if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
278
+ ignored_keys = unix_pattern_to_parameter_names(ignore_missing_keys, missing_keys)
279
+ missing_keys = [key for key in missing_keys if key not in ignored_keys]
280
+
281
+ if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
282
+ ignored_unexpected_keys = unix_pattern_to_parameter_names(ignore_unexpected_keys, unexpected_keys)
283
+ unexpected_keys = [key for key in unexpected_keys if key not in ignored_unexpected_keys]
284
+
285
+ err = "State key mismatch."
286
+ if unexpected_keys:
287
+ err += f" Unexpected keys: {unexpected_keys}."
288
+ if missing_keys:
289
+ err += f" Missing keys: {missing_keys}."
290
+
291
+ if unexpected_keys or missing_keys:
292
+ logging.warning(err)
293
+ if unexpected_keys or strict:
294
+ raise KeyError(err)
295
+
296
+
297
+ def load_state_dict_into_model(
298
+ state_dict: Dict,
299
+ model: nn.Module,
300
+ strict: bool = True,
301
+ ignore_missing_keys: List[str] = None,
302
+ ignore_unexpected_keys: List[str] = None,
303
+ checkpoint_kernels: List[Callable] = None,
304
+ ):
305
+ """
306
+ Loads a state dict into the given model.
307
+
308
+ Args:
309
+ state_dict: A dictionary containing the model's
310
+ state dict, or a subset if strict is False
311
+ model: Model to load the checkpoint weights into
312
+ strict: raise if the state_dict has missing state keys
313
+ ignore_missing_keys: unix pattern of keys to ignore
314
+ """
315
+ # Apply kernels
316
+ if checkpoint_kernels is not None:
317
+ for f in checkpoint_kernels:
318
+ state_dict = f(state_dict=state_dict)
319
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
320
+
321
+ check_load_state_dict_errors(
322
+ missing_keys,
323
+ unexpected_keys,
324
+ strict=strict,
325
+ ignore_missing_keys=ignore_missing_keys,
326
+ ignore_unexpected_keys=ignore_unexpected_keys,
327
+ )
328
+ return model
@@ -0,0 +1,166 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Misc functions, including distributed helpers.
9
+
10
+ Mostly copy-paste from torchvision references.
11
+ """
12
+
13
+ from dataclasses import dataclass
14
+ from typing import List, Optional, Tuple, Union
15
+
16
+ import torch
17
+
18
+ from PIL import Image as PILImage
19
+ from tensordict import tensorclass
20
+
21
+
22
+ @tensorclass
23
+ class BatchedVideoMetaData:
24
+ """
25
+ This class represents metadata about a batch of videos.
26
+ Attributes:
27
+ unique_objects_identifier: A tensor of shape Bx3 containing unique identifiers for each object in the batch. Index consists of (video_id, obj_id, frame_id)
28
+ frame_orig_size: A tensor of shape Bx2 containing the original size of each frame in the batch.
29
+ """
30
+
31
+ unique_objects_identifier: torch.LongTensor
32
+ frame_orig_size: torch.LongTensor
33
+
34
+
35
+ @tensorclass
36
+ class BatchedVideoDatapoint:
37
+ """
38
+ This class represents a batch of videos with associated annotations and metadata.
39
+ Attributes:
40
+ img_batch: A [TxBxCxHxW] tensor containing the image data for each frame in the batch, where T is the number of frames per video, and B is the number of videos in the batch.
41
+ obj_to_frame_idx: A [TxOx2] tensor containing the image_batch index which the object belongs to. O is the number of objects in the batch.
42
+ masks: A [TxOxHxW] tensor containing binary masks for each object in the batch.
43
+ metadata: An instance of BatchedVideoMetaData containing metadata about the batch.
44
+ dict_key: A string key used to identify the batch.
45
+ """
46
+
47
+ img_batch: torch.FloatTensor
48
+ obj_to_frame_idx: torch.IntTensor
49
+ masks: torch.BoolTensor
50
+ metadata: BatchedVideoMetaData
51
+
52
+ dict_key: str
53
+
54
+ def pin_memory(self, device=None):
55
+ return self.apply(torch.Tensor.pin_memory, device=device)
56
+
57
+ @property
58
+ def num_frames(self) -> int:
59
+ """
60
+ Returns the number of frames per video.
61
+ """
62
+ return self.batch_size[0]
63
+
64
+ @property
65
+ def num_videos(self) -> int:
66
+ """
67
+ Returns the number of videos in the batch.
68
+ """
69
+ return self.img_batch.shape[1]
70
+
71
+ @property
72
+ def flat_obj_to_img_idx(self) -> torch.IntTensor:
73
+ """
74
+ Returns a flattened tensor containing the object to img index.
75
+ The flat index can be used to access a flattened img_batch of shape [(T*B)xCxHxW]
76
+ """
77
+ frame_idx, video_idx = self.obj_to_frame_idx.unbind(dim=-1)
78
+ flat_idx = video_idx * self.num_frames + frame_idx
79
+ return flat_idx
80
+
81
+ @property
82
+ def flat_img_batch(self) -> torch.FloatTensor:
83
+ """
84
+ Returns a flattened img_batch_tensor of shape [(B*T)xCxHxW]
85
+ """
86
+
87
+ return self.img_batch.transpose(0, 1).flatten(0, 1)
88
+
89
+
90
+ @dataclass
91
+ class Object:
92
+ # Id of the object in the media
93
+ object_id: int
94
+ # Index of the frame in the media (0 if single image)
95
+ frame_index: int
96
+ segment: Union[torch.Tensor, dict] # RLE dict or binary mask
97
+
98
+
99
+ @dataclass
100
+ class Frame:
101
+ data: Union[torch.Tensor, PILImage.Image]
102
+ objects: List[Object]
103
+
104
+
105
+ @dataclass
106
+ class VideoDatapoint:
107
+ """Refers to an image/video and all its annotations"""
108
+
109
+ frames: List[Frame]
110
+ video_id: int
111
+ size: Tuple[int, int]
112
+
113
+
114
+ def collate_fn(
115
+ batch: List[VideoDatapoint],
116
+ dict_key,
117
+ ) -> BatchedVideoDatapoint:
118
+ """
119
+ Args:
120
+ batch: A list of VideoDatapoint instances.
121
+ dict_key (str): A string key used to identify the batch.
122
+ """
123
+ img_batch = []
124
+ for video in batch:
125
+ img_batch += [torch.stack([frame.data for frame in video.frames], dim=0)]
126
+
127
+ img_batch = torch.stack(img_batch, dim=0).permute((1, 0, 2, 3, 4))
128
+ T = img_batch.shape[0]
129
+ # Prepare data structures for sequential processing. Per-frame processing but batched across videos.
130
+ step_t_objects_identifier = [[] for _ in range(T)]
131
+ step_t_frame_orig_size = [[] for _ in range(T)]
132
+
133
+ step_t_masks = [[] for _ in range(T)]
134
+ step_t_obj_to_frame_idx = [[] for _ in range(T)] # List to store frame indices for each time step
135
+
136
+ for video_idx, video in enumerate(batch):
137
+ orig_video_id = video.video_id
138
+ orig_frame_size = video.size
139
+ for t, frame in enumerate(video.frames):
140
+ objects = frame.objects
141
+ for obj in objects:
142
+ orig_obj_id = obj.object_id
143
+ orig_frame_idx = obj.frame_index
144
+ step_t_obj_to_frame_idx[t].append(torch.tensor([t, video_idx], dtype=torch.int))
145
+ step_t_masks[t].append(obj.segment.to(torch.bool))
146
+ step_t_objects_identifier[t].append(torch.tensor([orig_video_id, orig_obj_id, orig_frame_idx]))
147
+ step_t_frame_orig_size[t].append(torch.tensor(orig_frame_size))
148
+
149
+ obj_to_frame_idx = torch.stack(
150
+ [torch.stack(obj_to_frame_idx, dim=0) for obj_to_frame_idx in step_t_obj_to_frame_idx],
151
+ dim=0,
152
+ )
153
+ masks = torch.stack([torch.stack(masks, dim=0) for masks in step_t_masks], dim=0)
154
+ objects_identifier = torch.stack([torch.stack(id, dim=0) for id in step_t_objects_identifier], dim=0)
155
+ frame_orig_size = torch.stack([torch.stack(id, dim=0) for id in step_t_frame_orig_size], dim=0)
156
+ return BatchedVideoDatapoint(
157
+ img_batch=img_batch,
158
+ obj_to_frame_idx=obj_to_frame_idx,
159
+ masks=masks,
160
+ metadata=BatchedVideoMetaData(
161
+ unique_objects_identifier=objects_identifier,
162
+ frame_orig_size=frame_orig_size,
163
+ ),
164
+ dict_key=dict_key,
165
+ batch_size=[T],
166
+ )