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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

# pyre-unsafe

from dataclasses import dataclass
from enum import Enum
from typing import Iterator, List, Optional, Tuple

import torch
from pytorch3d.implicitron.tools.config import registry, ReplaceableBase
from torch.utils.data import (
    BatchSampler,
    ConcatDataset,
    DataLoader,
    RandomSampler,
    Sampler,
)

from .dataset_base import DatasetBase
from .dataset_map_provider import DatasetMap
from .frame_data import FrameData
from .scene_batch_sampler import SceneBatchSampler
from .utils import is_known_frame_scalar


@dataclass
class DataLoaderMap:
    """
    A collection of data loaders for Implicitron.

    Members:

        train: a data loader for training
        val: a data loader for validating during training
        test: a data loader for final evaluation
    """

    train: Optional[DataLoader[FrameData]]
    val: Optional[DataLoader[FrameData]]
    test: Optional[DataLoader[FrameData]]

    def __getitem__(self, split: str) -> Optional[DataLoader[FrameData]]:
        """
        Get one of the data loaders by key (name of data split)
        """
        if split not in ["train", "val", "test"]:
            raise ValueError(f"{split} was not a valid split name (train/val/test)")
        return getattr(self, split)


class DataLoaderMapProviderBase(ReplaceableBase):
    """
    Provider of a collection of data loaders for a given collection of datasets.
    """

    def get_data_loader_map(self, datasets: DatasetMap) -> DataLoaderMap:
        """
        Returns a collection of data loaders for a given collection of datasets.
        """
        raise NotImplementedError()


@registry.register
class SimpleDataLoaderMapProvider(DataLoaderMapProviderBase):
    """
    Trivial implementation of DataLoaderMapProviderBase.

    If a dataset returns batches from get_eval_batches(), then
    they will be what the corresponding dataloader returns,
    independently of any of the fields on this class.

    Otherwise, returns shuffled batches.
    """

    batch_size: int = 1
    num_workers: int = 0
    dataset_length_train: int = 0
    dataset_length_val: int = 0
    dataset_length_test: int = 0

    def get_data_loader_map(self, datasets: DatasetMap) -> DataLoaderMap:
        """
        Returns a collection of data loaders for a given collection of datasets.
        """
        return DataLoaderMap(
            train=self._make_data_loader(
                datasets.train,
                self.dataset_length_train,
            ),
            val=self._make_data_loader(
                datasets.val,
                self.dataset_length_val,
            ),
            test=self._make_data_loader(
                datasets.test,
                self.dataset_length_test,
            ),
        )

    def _make_data_loader(
        self,
        dataset: Optional[DatasetBase],
        num_batches: int,
    ) -> Optional[DataLoader[FrameData]]:
        """
        Returns the dataloader for a dataset.

        Args:
            dataset: the dataset
            num_batches: possible ceiling on number of batches per epoch
        """
        if dataset is None:
            return None

        data_loader_kwargs = {
            "num_workers": self.num_workers,
            "collate_fn": dataset.frame_data_type.collate,
        }

        eval_batches = dataset.get_eval_batches()
        if eval_batches is not None:
            return DataLoader(
                dataset,
                batch_sampler=eval_batches,
                **data_loader_kwargs,
            )

        if num_batches > 0:
            num_samples = self.batch_size * num_batches
        else:
            num_samples = None

        # sample with replacement only if a custom number of samples is specified
        sampler = RandomSampler(
            dataset,
            replacement=num_samples is not None,
            num_samples=num_samples,
        )

        batch_sampler = BatchSampler(sampler, self.batch_size, drop_last=True)
        return DataLoader(
            dataset,
            batch_sampler=batch_sampler,
            **data_loader_kwargs,
        )


class DoublePoolBatchSampler(Sampler[List[int]]):
    """
    Batch sampler for making random batches of a single frame
    from one list and a number of known frames from another list.
    """

    def __init__(
        self,
        first_indices: List[int],
        rest_indices: List[int],
        batch_size: int,
        replacement: bool,
        num_batches: Optional[int] = None,
    ) -> None:
        """
        Args:
            first_indices: indexes of dataset items to use as the first element
                        of each batch.
            rest_indices: indexes of dataset items to use as the subsequent
                        elements of each batch. Not used if batch_size==1.
            batch_size: The common size of any batch.
            replacement: Whether the sampling of first items is with replacement.
            num_batches: The number of batches in an epoch. If 0 or None,
                        one epoch is the length of `first_indices`.
        """
        self.first_indices = first_indices
        self.rest_indices = rest_indices
        self.batch_size = batch_size
        self.replacement = replacement
        self.num_batches = None if num_batches == 0 else num_batches

        if batch_size - 1 > len(rest_indices):
            raise ValueError(
                f"Cannot make up ({batch_size})-batches from {len(self.rest_indices)}"
            )

        # copied from RandomSampler
        seed = int(torch.empty((), dtype=torch.int64).random_().item())
        self.generator = torch.Generator()
        self.generator.manual_seed(seed)

    def __len__(self) -> int:
        if self.num_batches is not None:
            return self.num_batches
        return len(self.first_indices)

    def __iter__(self) -> Iterator[List[int]]:
        num_batches = self.num_batches
        if self.replacement:
            i_first = torch.randint(
                len(self.first_indices),
                size=(len(self),),
                generator=self.generator,
            )
        elif num_batches is not None:
            n_copies = 1 + (num_batches - 1) // len(self.first_indices)
            raw_indices = [
                torch.randperm(len(self.first_indices), generator=self.generator)
                for _ in range(n_copies)
            ]
            i_first = torch.cat(raw_indices)[:num_batches]
        else:
            i_first = torch.randperm(len(self.first_indices), generator=self.generator)
        first_indices = [self.first_indices[i] for i in i_first]

        if self.batch_size == 1:
            for first_index in first_indices:
                yield [first_index]
            return

        for first_index in first_indices:
            # Consider using this class in a program which sets the seed. This use
            # of randperm means that rerunning with a higher batch_size
            # results in batches whose first elements as the first run.
            i_rest = torch.randperm(
                len(self.rest_indices),
                generator=self.generator,
            )[: self.batch_size - 1]
            yield [first_index] + [self.rest_indices[i] for i in i_rest]


class BatchConditioningType(Enum):
    """
    Ways to add conditioning frames for the val and test batches.

    SAME: Use the corresponding dataset for all elements of val batches
        without regard to frame type.
    TRAIN: Use the corresponding dataset for the first element of each
        batch, and the training dataset for the extra conditioning
            elements. No regard to frame type.
    KNOWN: Use frames from the corresponding dataset but separate them
        according to their frame_type. Each batch will contain one UNSEEN
        frame followed by many KNOWN frames.
    """

    SAME = "same"
    TRAIN = "train"
    KNOWN = "known"


@registry.register
class SequenceDataLoaderMapProvider(DataLoaderMapProviderBase):
    """
    Default implementation of DataLoaderMapProviderBase.

    If a dataset returns batches from get_eval_batches(), then
    they will be what the corresponding dataloader returns,
    independently of any of the fields on this class.

    If conditioning is not required, then the batch size should
    be set as 1, and most of the fields do not matter.

    If conditioning is required, each batch will contain one main
    frame first to predict and the, rest of the elements are for
    conditioning.

    If images_per_seq_options is left empty, the conditioning
    frames are picked according to the conditioning type given.
    This does not have regard to the order of frames in a
    scene, or which frames belong to what scene.

    If images_per_seq_options is given, then the conditioning types
    must be SAME and the remaining fields are used.

    Members:
        batch_size: The size of the batch of the data loader.
        num_workers: Number of data-loading threads in each data loader.
        dataset_length_train: The number of batches in a training epoch. Or 0 to mean
            an epoch is the length of the training set.
        dataset_length_val: The number of batches in a validation epoch. Or 0 to mean
            an epoch is the length of the validation set.
        dataset_length_test: The number of batches in a testing epoch. Or 0 to mean
            an epoch is the length of the test set.
        train_conditioning_type: Whether the train data loader should use
            only known frames for conditioning.
            Only used if batch_size>1 and train dataset is
            present and does not return eval_batches.
        val_conditioning_type: Whether the val data loader should use
            training frames or known frames for conditioning.
            Only used if batch_size>1 and val dataset is
            present and does not return eval_batches.
        test_conditioning_type: Whether the test data loader should use
            training frames or known frames for conditioning.
            Only used if batch_size>1 and test dataset is
            present and does not return eval_batches.
        images_per_seq_options: Possible numbers of frames sampled per sequence in a batch.
            If a conditioning_type is KNOWN or TRAIN, then this must be left at its initial
            value. Empty (the default) means that we are not careful about which frames
            come from which scene.
        sample_consecutive_frames: if True, will sample a contiguous interval of frames
            in the sequence. It first sorts the frames by timestimps when available,
            otherwise by frame numbers, finds the connected segments within the sequence
            of sufficient length, then samples a random pivot element among them and
            ideally uses it as a middle of the temporal window, shifting the borders
            where necessary. This strategy mitigates the bias against shorter segments
            and their boundaries.
        consecutive_frames_max_gap: if a number > 0, then used to define the maximum
            difference in frame_number of neighbouring frames when forming connected
            segments; if both this and consecutive_frames_max_gap_seconds are 0s,
            the whole sequence is considered a segment regardless of frame numbers.
        consecutive_frames_max_gap_seconds: if a number > 0.0, then used to define the
            maximum difference in frame_timestamp of neighbouring frames when forming
            connected segments; if both this and consecutive_frames_max_gap are 0s,
            the whole sequence is considered a segment regardless of frame timestamps.
    """

    batch_size: int = 1
    num_workers: int = 0
    dataset_length_train: int = 0
    dataset_length_val: int = 0
    dataset_length_test: int = 0
    train_conditioning_type: BatchConditioningType = BatchConditioningType.SAME
    val_conditioning_type: BatchConditioningType = BatchConditioningType.SAME
    test_conditioning_type: BatchConditioningType = BatchConditioningType.KNOWN
    images_per_seq_options: Tuple[int, ...] = ()
    sample_consecutive_frames: bool = False
    consecutive_frames_max_gap: int = 0
    consecutive_frames_max_gap_seconds: float = 0.1

    def get_data_loader_map(self, datasets: DatasetMap) -> DataLoaderMap:
        """
        Returns a collection of data loaders for a given collection of datasets.
        """
        return DataLoaderMap(
            train=self._make_data_loader(
                datasets.train,
                self.dataset_length_train,
                datasets.train,
                self.train_conditioning_type,
            ),
            val=self._make_data_loader(
                datasets.val,
                self.dataset_length_val,
                datasets.train,
                self.val_conditioning_type,
            ),
            test=self._make_data_loader(
                datasets.test,
                self.dataset_length_test,
                datasets.train,
                self.test_conditioning_type,
            ),
        )

    def _make_data_loader(
        self,
        dataset: Optional[DatasetBase],
        num_batches: int,
        train_dataset: Optional[DatasetBase],
        conditioning_type: BatchConditioningType,
    ) -> Optional[DataLoader[FrameData]]:
        """
        Returns the dataloader for a dataset.

        Args:
            dataset: the dataset
            num_batches: possible ceiling on number of batches per epoch
            train_dataset: the training dataset, used if conditioning_type==TRAIN
            conditioning_type: source for padding of batches
        """
        if dataset is None:
            return None

        data_loader_kwargs = {
            "num_workers": self.num_workers,
            "collate_fn": dataset.frame_data_type.collate,
        }

        eval_batches = dataset.get_eval_batches()
        if eval_batches is not None:
            return DataLoader(
                dataset,
                batch_sampler=eval_batches,
                **data_loader_kwargs,
            )

        scenes_matter = len(self.images_per_seq_options) > 0
        if scenes_matter and conditioning_type != BatchConditioningType.SAME:
            raise ValueError(
                f"{conditioning_type} cannot be used with images_per_seq "
                + str(self.images_per_seq_options)
            )

        if self.batch_size == 1 or (
            not scenes_matter and conditioning_type == BatchConditioningType.SAME
        ):
            return self._simple_loader(dataset, num_batches, data_loader_kwargs)

        if scenes_matter:
            assert conditioning_type == BatchConditioningType.SAME
            batch_sampler = SceneBatchSampler(
                dataset,
                self.batch_size,
                num_batches=len(dataset) if num_batches <= 0 else num_batches,
                images_per_seq_options=self.images_per_seq_options,
                sample_consecutive_frames=self.sample_consecutive_frames,
                consecutive_frames_max_gap=self.consecutive_frames_max_gap,
                consecutive_frames_max_gap_seconds=self.consecutive_frames_max_gap_seconds,
            )
            return DataLoader(
                dataset,
                batch_sampler=batch_sampler,
                **data_loader_kwargs,
            )

        if conditioning_type == BatchConditioningType.TRAIN:
            return self._train_loader(
                dataset, train_dataset, num_batches, data_loader_kwargs
            )

        assert conditioning_type == BatchConditioningType.KNOWN
        return self._known_loader(dataset, num_batches, data_loader_kwargs)

    def _simple_loader(
        self,
        dataset: DatasetBase,
        num_batches: int,
        data_loader_kwargs: dict,
    ) -> DataLoader[FrameData]:
        """
        Return a simple loader for frames in the dataset.

        This is equivalent to
            Dataloader(dataset, batch_size=self.batch_size, **data_loader_kwargs)
        except that num_batches is fixed.

        Args:
            dataset: the dataset
            num_batches: possible ceiling on number of batches per epoch
            data_loader_kwargs: common args for dataloader
        """
        if num_batches > 0:
            num_samples = self.batch_size * num_batches
            replacement = True
        else:
            num_samples = None
            replacement = False
        sampler = RandomSampler(
            dataset, replacement=replacement, num_samples=num_samples
        )
        batch_sampler = BatchSampler(sampler, self.batch_size, drop_last=True)
        return DataLoader(
            dataset,
            batch_sampler=batch_sampler,
            **data_loader_kwargs,
        )

    def _train_loader(
        self,
        dataset: DatasetBase,
        train_dataset: Optional[DatasetBase],
        num_batches: int,
        data_loader_kwargs: dict,
    ) -> DataLoader[FrameData]:
        """
        Return the loader for TRAIN conditioning.

        Args:
            dataset: the dataset
            train_dataset: the training dataset
            num_batches: possible ceiling on number of batches per epoch
            data_loader_kwargs: common args for dataloader
        """
        if train_dataset is None:
            raise ValueError("No training data for conditioning.")
        length = len(dataset)
        first_indices = list(range(length))
        rest_indices = list(range(length, length + len(train_dataset)))
        sampler = DoublePoolBatchSampler(
            first_indices=first_indices,
            rest_indices=rest_indices,
            batch_size=self.batch_size,
            replacement=True,
            num_batches=num_batches,
        )
        return DataLoader(
            ConcatDataset([dataset, train_dataset]),
            batch_sampler=sampler,
            **data_loader_kwargs,
        )

    def _known_loader(
        self,
        dataset: DatasetBase,
        num_batches: int,
        data_loader_kwargs: dict,
    ) -> DataLoader[FrameData]:
        """
        Return the loader for KNOWN conditioning.

        Args:
            dataset: the dataset
            num_batches: possible ceiling on number of batches per epoch
            data_loader_kwargs: common args for dataloader
        """
        first_indices, rest_indices = [], []
        for idx in range(len(dataset)):
            frame_type = dataset[idx].frame_type
            assert isinstance(frame_type, str)
            if is_known_frame_scalar(frame_type):
                rest_indices.append(idx)
            else:
                first_indices.append(idx)
        sampler = DoublePoolBatchSampler(
            first_indices=first_indices,
            rest_indices=rest_indices,
            batch_size=self.batch_size,
            replacement=True,
            num_batches=num_batches,
        )
        return DataLoader(
            dataset,
            batch_sampler=sampler,
            **data_loader_kwargs,
        )