clip_sampler.py 6.11 KB
Newer Older
1
import math
2
3
from typing import Optional, List, Iterator, Sized, Union, cast

4
5
import torch
import torch.distributed as dist
6
from torch.utils.data import Sampler
Rahul Somani's avatar
Rahul Somani committed
7
from torchvision.datasets.video_utils import VideoClips
8
9
10
11
12
13


class DistributedSampler(Sampler):
    """
    Extension of DistributedSampler, as discussed in
    https://github.com/pytorch/pytorch/issues/23430
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

    Example:
        dataset: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        num_replicas: 4
        shuffle: False

    when group_size = 1
            RANK    |  shard_dataset
            =========================
            rank_0  |  [0, 4, 8, 12]
            rank_1  |  [1, 5, 9, 13]
            rank_2  |  [2, 6, 10, 0]
            rank_3  |  [3, 7, 11, 1]

    when group_size = 2

            RANK    |  shard_dataset
            =========================
            rank_0  |  [0, 1, 8, 9]
            rank_1  |  [2, 3, 10, 11]
            rank_2  |  [4, 5, 12, 13]
            rank_3  |  [6, 7, 0, 1]

37
38
    """

39
    def __init__(
40
41
42
43
44
45
        self,
        dataset: Sized,
        num_replicas: Optional[int] = None,
        rank: Optional[int] = None,
        shuffle: bool = False,
        group_size: int = 1,
46
    ) -> None:
47
48
49
50
51
52
53
54
        if num_replicas is None:
            if not dist.is_available():
                raise RuntimeError("Requires distributed package to be available")
            num_replicas = dist.get_world_size()
        if rank is None:
            if not dist.is_available():
                raise RuntimeError("Requires distributed package to be available")
            rank = dist.get_rank()
55
56
        assert (
            len(dataset) % group_size == 0
57
        ), "dataset length must be a multiplier of group size dataset length: %d, group size: %d" % (
58
59
            len(dataset),
            group_size,
60
        )
61
        self.dataset = dataset
62
        self.group_size = group_size
63
64
65
        self.num_replicas = num_replicas
        self.rank = rank
        self.epoch = 0
66
        dataset_group_length = len(dataset) // group_size
67
        self.num_group_samples = int(math.ceil(dataset_group_length * 1.0 / self.num_replicas))
68
        self.num_samples = self.num_group_samples * group_size
69
70
71
        self.total_size = self.num_samples * self.num_replicas
        self.shuffle = shuffle

72
    def __iter__(self) -> Iterator[int]:
73
74
75
        # deterministically shuffle based on epoch
        g = torch.Generator()
        g.manual_seed(self.epoch)
76
        indices: Union[torch.Tensor, List[int]]
77
78
79
80
81
82
        if self.shuffle:
            indices = torch.randperm(len(self.dataset), generator=g).tolist()
        else:
            indices = list(range(len(self.dataset)))

        # add extra samples to make it evenly divisible
83
        indices += indices[: (self.total_size - len(indices))]
84
85
        assert len(indices) == self.total_size

86
        total_group_size = self.total_size // self.group_size
87
        indices = torch.reshape(torch.LongTensor(indices), (total_group_size, self.group_size))
88

89
        # subsample
90
        indices = indices[self.rank : total_group_size : self.num_replicas, :]
91
        indices = torch.reshape(indices, (-1,)).tolist()
92
93
94
95
96
97
98
99
        assert len(indices) == self.num_samples

        if isinstance(self.dataset, Sampler):
            orig_indices = list(iter(self.dataset))
            indices = [orig_indices[i] for i in indices]

        return iter(indices)

100
    def __len__(self) -> int:
101
102
        return self.num_samples

103
    def set_epoch(self, epoch: int) -> None:
104
105
106
        self.epoch = epoch


Rahul Somani's avatar
Rahul Somani committed
107
class UniformClipSampler(Sampler):
108
    """
109
110
111
112
    Sample `num_video_clips_per_video` clips for each video, equally spaced.
    When number of unique clips in the video is fewer than num_video_clips_per_video,
    repeat the clips until `num_video_clips_per_video` clips are collected

113
    Args:
114
        video_clips (VideoClips): video clips to sample from
115
        num_clips_per_video (int): number of clips to be sampled per video
116
    """
117

118
    def __init__(self, video_clips: VideoClips, num_clips_per_video: int) -> None:
Rahul Somani's avatar
Rahul Somani committed
119
        if not isinstance(video_clips, VideoClips):
120
            raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}")
121
        self.video_clips = video_clips
122
        self.num_clips_per_video = num_clips_per_video
123

124
    def __iter__(self) -> Iterator[int]:
125
126
        idxs = []
        s = 0
127
        # select num_clips_per_video for each video, uniformly spaced
128
129
        for c in self.video_clips.clips:
            length = len(c)
130
131
132
133
            if length == 0:
                # corner case where video decoding fails
                continue

134
            sampled = torch.linspace(s, s + length - 1, steps=self.num_clips_per_video).floor().to(torch.int64)
135
136
            s += length
            idxs.append(sampled)
137
        return iter(cast(List[int], torch.cat(idxs).tolist()))
138

139
    def __len__(self) -> int:
140
        return sum(self.num_clips_per_video for c in self.video_clips.clips if len(c) > 0)
141
142


Rahul Somani's avatar
Rahul Somani committed
143
class RandomClipSampler(Sampler):
144
145
146
    """
    Samples at most `max_video_clips_per_video` clips for each video randomly

147
    Args:
148
149
150
        video_clips (VideoClips): video clips to sample from
        max_clips_per_video (int): maximum number of clips to be sampled per video
    """
151

152
    def __init__(self, video_clips: VideoClips, max_clips_per_video: int) -> None:
Rahul Somani's avatar
Rahul Somani committed
153
        if not isinstance(video_clips, VideoClips):
154
            raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}")
155
156
157
        self.video_clips = video_clips
        self.max_clips_per_video = max_clips_per_video

158
    def __iter__(self) -> Iterator[int]:
159
160
161
162
163
164
165
166
167
        idxs = []
        s = 0
        # select at most max_clips_per_video for each video, randomly
        for c in self.video_clips.clips:
            length = len(c)
            size = min(length, self.max_clips_per_video)
            sampled = torch.randperm(length)[:size] + s
            s += length
            idxs.append(sampled)
168
        idxs_ = torch.cat(idxs)
169
        # shuffle all clips randomly
170
171
        perm = torch.randperm(len(idxs_))
        return iter(idxs_[perm].tolist())
172

173
    def __len__(self) -> int:
174
        return sum(min(len(c), self.max_clips_per_video) for c in self.video_clips.clips)