kaiw7 commited on
Commit
73d6593
·
verified ·
1 Parent(s): db4e154

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +11 -0
  2. eval_gt/gt_audio_test/LBXYlTnm0Fw_000054.wav +3 -0
  3. eval_gt/gt_audio_test/LC79lWBAlR4_000410.wav +3 -0
  4. example_demo_videos/_jB-IM_77lI_000000_silent.mp4 +3 -0
  5. example_demo_videos/demo1.mp4 +3 -0
  6. example_demo_videos/demo1_rep.mp4 +3 -0
  7. example_demo_videos/demo2.mp4 +3 -0
  8. example_demo_videos/demo2_rep.mp4 +3 -0
  9. example_demo_videos/demo3.mp4 +3 -0
  10. example_demo_videos/demo5.mp4 +3 -0
  11. example_demo_videos/demo6.mp4 +3 -0
  12. example_demo_videos/demo7.mp4 +3 -0
  13. reward_models/ib_sync_rewards/args.py +36 -0
  14. reward_models/ib_sync_rewards/data/video_dataset.py +428 -0
  15. reward_models/ib_sync_rewards/imagebind/data.py +383 -0
  16. reward_models/ib_sync_rewards/imagebind/models/__init__.py +0 -0
  17. reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/deployment/common/__init__.py +1 -0
  18. reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/deployment/mobile_cpu/transmuter/__init__.py +10 -0
  19. reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/efficient_blocks/__init__.py +1 -0
  20. reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/efficient_blocks/no_op_convert_block.py +26 -0
  21. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/__init__.py +18 -0
  22. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/clip_sampling.py +410 -0
  23. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/dataset_manifest_utils.py +314 -0
  24. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/decoder.py +8 -0
  25. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/ego4d/__init__.py +3 -0
  26. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video.py +75 -0
  27. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_decord.py +199 -0
  28. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_pyav.py +364 -0
  29. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_torchvision.py +276 -0
  30. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen/epic_kitchen_dataset.py +205 -0
  31. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen/utils.py +195 -0
  32. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen_forecasting.py +295 -0
  33. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/frame_video.py +258 -0
  34. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/hmdb51.py +231 -0
  35. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/json_dataset.py +254 -0
  36. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/labeled_video_dataset.py +304 -0
  37. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/labeled_video_paths.py +141 -0
  38. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/ucf101.py +70 -0
  39. reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/video.py +100 -0
  40. reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/accelerator/mobile_cpu/conv_helper.py +556 -0
  41. reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/accelerator/mobile_cpu/convolutions.py +629 -0
  42. reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/fusion.py +149 -0
  43. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/accelerator/__init__.py +1 -0
  44. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/accelerator/mobile_cpu/__init__.py +1 -0
  45. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/csn.py +191 -0
  46. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/__init__.py +14 -0
  47. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/csn.py +58 -0
  48. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/efficient_x3d_mobile_cpu.py +83 -0
  49. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/r2plus1d.py +54 -0
  50. reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/resnet.py +160 -0
.gitattributes ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ example_demo_videos/demo7.mp4 filter=lfs diff=lfs merge=lfs -text
2
+ example_demo_videos/demo3.mp4 filter=lfs diff=lfs merge=lfs -text
3
+ example_demo_videos/demo1_rep.mp4 filter=lfs diff=lfs merge=lfs -text
4
+ example_demo_videos/demo2_rep.mp4 filter=lfs diff=lfs merge=lfs -text
5
+ example_demo_videos/_jB-IM_77lI_000000_silent.mp4 filter=lfs diff=lfs merge=lfs -text
6
+ example_demo_videos/demo2.mp4 filter=lfs diff=lfs merge=lfs -text
7
+ example_demo_videos/demo5.mp4 filter=lfs diff=lfs merge=lfs -text
8
+ example_demo_videos/demo6.mp4 filter=lfs diff=lfs merge=lfs -text
9
+ example_demo_videos/demo1.mp4 filter=lfs diff=lfs merge=lfs -text
10
+ eval_gt/gt_audio_test/LC79lWBAlR4_000410.wav filter=lfs diff=lfs merge=lfs -text
11
+ eval_gt/gt_audio_test/LBXYlTnm0Fw_000054.wav filter=lfs diff=lfs merge=lfs -text
eval_gt/gt_audio_test/LBXYlTnm0Fw_000054.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4e0c7d6805314b4814dca2a08be9e64350897ed15bcfb8ecc5f18494023f13b
3
+ size 1767606
eval_gt/gt_audio_test/LC79lWBAlR4_000410.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e1f395c03b0fb69d2ebe62c93e833e0674fa7b1e619f7b20923f1df2eced9bd
3
+ size 1771130
example_demo_videos/_jB-IM_77lI_000000_silent.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd72bc28378147d9f3d0674acaf2ec06a80d3cf4b7a56a1dc19bea830334caa1
3
+ size 1253591
example_demo_videos/demo1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ed1fbaf07d800b0a3c51d9662a9a72a89f7b414e5aaaac840bfb4402341143d
3
+ size 825708
example_demo_videos/demo1_rep.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:baf9ede4eba39f72dff1a4f389c4a8d8d6842e818925dfb54640837a95d97159
3
+ size 1650644
example_demo_videos/demo2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8eb22e79c47021574d1f302c9a29c6dcdff7795043a83e1c514bed375af190c
3
+ size 764857
example_demo_videos/demo2_rep.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:347d2922ebec6dd3bb3445c65d18f51c38fd6b841de92a897a589caf2f0babd2
3
+ size 1529000
example_demo_videos/demo3.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:599e563ed57339c95658a70fbbaf9601f4b1792800ed733bdf027dd922eb5615
3
+ size 624675
example_demo_videos/demo5.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:481d36bebaf00c2aaf5dccb5b71491badb09f9e96e60f226952fbdb6261af34c
3
+ size 484500
example_demo_videos/demo6.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df99ad12aa47276584d0875b2af28068b59f76257127b53b7b3b5a434a86bb5f
3
+ size 821440
example_demo_videos/demo7.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5662d82ae7b64677d3fd92205adfd1b40ec136ef14f2c36674d96cf171fc98b4
3
+ size 821786
reward_models/ib_sync_rewards/args.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser
2
+ from pathlib import Path
3
+
4
+
5
+ def get_eval_parser() -> ArgumentParser:
6
+ parser = ArgumentParser()
7
+
8
+ # maximum length; does not pad if under (except internally in like PaSST)
9
+ parser.add_argument('--audio_length', type=float)
10
+ parser.add_argument('--num_workers', type=int, default=32)
11
+
12
+ # only bs=1 supports variable audio length
13
+ parser.add_argument('--gt_batch_size', type=int, default=1)
14
+ # typically your generations would have the same length; so larger batch sizes can be used
15
+ parser.add_argument('--pred_batch_size', type=int, default=64)
16
+
17
+ parser.add_argument('--gt_audio', type=Path)
18
+ parser.add_argument('--gt_cache', type=Path)
19
+ parser.add_argument('--pred_audio', type=Path)
20
+ parser.add_argument('--pred_cache', type=Path)
21
+ parser.add_argument('--json_path', type=Path) # todo newly added
22
+ parser.add_argument('--output_dir', type=Path) # todo newly added
23
+
24
+ parser.add_argument('--recompute_gt_cache', action='store_true')
25
+ parser.add_argument('--recompute_pred_cache', action='store_true')
26
+
27
+ # only single sample is supported
28
+ # parser.add_argument('--num_samples', type=int, default=1)
29
+ parser.add_argument('--unpaired', action='store_true')
30
+
31
+ parser.add_argument('--skip_video_related',
32
+ action='store_true',
33
+ help='skips ImageBind and SynchFormer computation')
34
+ parser.add_argument('--skip_clap', action='store_true', help='skips CLAP computation')
35
+
36
+ return parser
reward_models/ib_sync_rewards/data/video_dataset.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ from torch.utils.data.dataloader import default_collate
6
+ from torch.utils.data.dataset import Dataset
7
+ from torchvision.transforms import v2
8
+ from torio.io import StreamingMediaDecoder
9
+
10
+ from ib_sync_rewards.data.ib_data import SpatialCrop
11
+
12
+ # todo
13
+ from typing import List
14
+ import torchaudio
15
+ from ib_sync_rewards.imagebind.pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
16
+
17
+
18
+ log = logging.getLogger()
19
+
20
+ # https://github.com/facebookresearch/ImageBind/blob/main/imagebind/data.py
21
+ # https://pytorchvideo.readthedocs.io/en/latest/_modules/pytorchvideo/transforms/functional.html
22
+ _IMAGEBIND_SIZE = 224
23
+ _IMAGEBIND_FPS = 0.5
24
+
25
+ _SYNC_SIZE = 224
26
+ _SYNC_FPS = 25.0
27
+
28
+
29
+ def error_avoidance_collate(batch):
30
+ batch = list(filter(lambda x: x is not None, batch))
31
+ return default_collate(batch)
32
+
33
+ # todo
34
+ # from ImageBind
35
+ def get_clip_timepoints(clip_sampler, duration):
36
+ # Read out all clips in this video
37
+ all_clips_timepoints = []
38
+ is_last_clip = False
39
+ end = 0.0
40
+ while not is_last_clip:
41
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
42
+ all_clips_timepoints.append((start, end))
43
+ return all_clips_timepoints
44
+
45
+
46
+ # from ImageBind
47
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
48
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
49
+ waveform -= waveform.mean()
50
+ fbank = torchaudio.compliance.kaldi.fbank(
51
+ waveform,
52
+ htk_compat=True,
53
+ sample_frequency=sample_rate,
54
+ use_energy=False,
55
+ window_type="hanning",
56
+ num_mel_bins=num_mel_bins,
57
+ dither=0.0,
58
+ frame_length=25,
59
+ frame_shift=10,
60
+ )
61
+ # Convert to [mel_bins, num_frames] shape
62
+ fbank = fbank.transpose(0, 1)
63
+ # Pad to target_length
64
+ n_frames = fbank.size(1)
65
+ p = target_length - n_frames
66
+ # if p is too large (say >20%), flash a warning
67
+ if abs(p) / n_frames > 0.2:
68
+ logging.warning(
69
+ "Large gap between audio n_frames(%d) and "
70
+ "target_length (%d). Is the audio_target_length "
71
+ "setting correct?",
72
+ n_frames,
73
+ target_length,
74
+ )
75
+ # cut and pad
76
+ if p > 0:
77
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
78
+ elif p < 0:
79
+ fbank = fbank[:, 0:target_length]
80
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
81
+ # channel image
82
+ fbank = fbank.unsqueeze(0)
83
+ return fbank
84
+
85
+
86
+ # from synchformer
87
+ def pad_or_truncate(audio: torch.Tensor,
88
+ max_spec_t: int,
89
+ pad_mode: str = 'constant',
90
+ pad_value: float = 0.0):
91
+ difference = max_spec_t - audio.shape[-1] # safe for batched input
92
+ # pad or truncate, depending on difference
93
+ if difference > 0:
94
+ # pad the last dim (time) -> (..., n_mels, 0+time+difference) # safe for batched input
95
+ pad_dims = (0, difference)
96
+ audio = torch.nn.functional.pad(audio, pad_dims, pad_mode, pad_value)
97
+ elif difference < 0:
98
+ log.warning(f'Truncating spec ({audio.shape}) to max_spec_t ({max_spec_t}).')
99
+ audio = audio[..., :max_spec_t] # safe for batched input
100
+ return audio
101
+
102
+
103
+ def pad_short_audio(audio, min_samples=32000):
104
+ if (audio.size(-1) < min_samples):
105
+ audio = torch.nn.functional.pad(audio, (0, min_samples - audio.size(-1)),
106
+ mode='constant',
107
+ value=0.0)
108
+ return audio
109
+
110
+
111
+
112
+ # todo integrate imagebind and syncformer
113
+ # todo extracting audio+video+text
114
+ class VideoDataset(Dataset):
115
+
116
+ def __init__(
117
+ self,
118
+ video_paths: list[Path],
119
+ audio_paths: list[Path],
120
+ *,
121
+ duration_sec: float = 8.0,
122
+ video_id_caption={}
123
+ ):
124
+ self.video_paths = video_paths # todo for video
125
+ self.audio_paths = audio_paths #[f'{f[:-4]}.flac' for f in video_paths] # todo for audio
126
+ self.video_id_caption = video_id_caption # todo May 9
127
+
128
+ self.duration_sec = duration_sec
129
+
130
+ self.ib_expected_length = int(_IMAGEBIND_FPS * self.duration_sec)
131
+ self.sync_expected_length = int(_SYNC_FPS * self.duration_sec)
132
+
133
+ self.ib_transform = v2.Compose([
134
+ v2.Resize(_IMAGEBIND_SIZE, interpolation=v2.InterpolationMode.BICUBIC),
135
+ v2.ToImage(),
136
+ v2.ToDtype(torch.float32, scale=True),
137
+ v2.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
138
+ std=[0.26862954, 0.26130258, 0.27577711]),
139
+ ])
140
+
141
+ self.sync_transform = v2.Compose([
142
+ v2.Resize(_SYNC_SIZE, interpolation=v2.InterpolationMode.BICUBIC),
143
+ v2.CenterCrop(_SYNC_SIZE),
144
+ v2.ToImage(),
145
+ v2.ToDtype(torch.float32, scale=True),
146
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
147
+ ])
148
+
149
+ self.crop = SpatialCrop(_IMAGEBIND_SIZE, 3)
150
+
151
+ self.resampler = {} # todo for synchformer
152
+ self.sync_mel_spectrogram = torchaudio.transforms.MelSpectrogram(
153
+ sample_rate=16000,
154
+ win_length=400,
155
+ hop_length=160,
156
+ n_fft=1024,
157
+ n_mels=128,
158
+ )
159
+
160
+ # todo for imagebind audio
161
+ def load_and_transform_audio_data_for_ib(
162
+ self,
163
+ audio_path,
164
+ num_mel_bins=128,
165
+ target_length=204,
166
+ sample_rate=16000,
167
+ clip_duration=2,
168
+ clips_per_video=3,
169
+ mean=-4.268,
170
+ std=9.138,
171
+ ):
172
+
173
+ audio_outputs = []
174
+ clip_sampler = ConstantClipsPerVideoSampler(clip_duration=clip_duration,
175
+ clips_per_video=clips_per_video)
176
+
177
+ waveform, sr = torchaudio.load(audio_path)
178
+ if sample_rate != sr:
179
+ waveform = torchaudio.functional.resample(waveform, orig_freq=sr, new_freq=sample_rate)
180
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, waveform.size(1) / sample_rate)
181
+ all_clips = []
182
+ for clip_timepoints in all_clips_timepoints:
183
+ waveform_clip = waveform[
184
+ :,
185
+ int(clip_timepoints[0] * sample_rate):int(clip_timepoints[1] * sample_rate),
186
+ ]
187
+ waveform_melspec = waveform2melspec(waveform_clip, sample_rate, num_mel_bins,
188
+ target_length)
189
+ all_clips.append(waveform_melspec)
190
+
191
+ normalize = v2.Normalize(mean=[mean], std=[std])
192
+ all_clips = [normalize(ac) for ac in all_clips]
193
+
194
+ all_clips = torch.stack(all_clips, dim=0)
195
+ audio_outputs.append(all_clips)
196
+
197
+ return torch.stack(audio_outputs, dim=0)
198
+
199
+ # todo for synchformer audio
200
+ def load_and_transform_audio_data_for_sync(self, audio_path):
201
+ waveform, sr = torchaudio.load(audio_path)
202
+ waveform = waveform.mean(dim=0)
203
+
204
+ if sr != 16000:
205
+ if sr not in self.resampler:
206
+ self.resampler[sr] = torchaudio.transforms.Resample(sr, 16000)
207
+ waveform = self.resampler[sr](waveform)
208
+
209
+ waveform = waveform[:int(self.duration_sec * 16000)]
210
+ if waveform.shape[0] != int(self.duration_sec * 16000):
211
+ raise ValueError(f'Audio {audio_path} is too short')
212
+
213
+ waveform = waveform.squeeze()
214
+
215
+ return waveform
216
+
217
+ def sample(self, idx: int) -> dict[str, torch.Tensor]:
218
+ video_path = self.video_paths[idx] # todo for video path
219
+ audio_path = self.audio_paths[idx] # todo for audio path
220
+ caption = self.video_id_caption[video_path.stem] # todo May 9
221
+
222
+ # todo for video extraction
223
+ reader = StreamingMediaDecoder(video_path)
224
+ reader.add_basic_video_stream(
225
+ frames_per_chunk=int(_IMAGEBIND_FPS * self.duration_sec),
226
+ frame_rate=_IMAGEBIND_FPS,
227
+ format='rgb24',
228
+ )
229
+ reader.add_basic_video_stream(
230
+ frames_per_chunk=int(_SYNC_FPS * self.duration_sec),
231
+ frame_rate=_SYNC_FPS,
232
+ format='rgb24',
233
+ )
234
+
235
+ reader.fill_buffer()
236
+ data_chunk = reader.pop_chunks()
237
+
238
+ ib_chunk = data_chunk[0]
239
+ sync_chunk = data_chunk[1]
240
+ if ib_chunk is None:
241
+ raise RuntimeError(f'IB video returned None {video_path}')
242
+ if ib_chunk.shape[0] < self.ib_expected_length:
243
+ raise RuntimeError(
244
+ f'IB video too short {video_path}, expected {self.ib_expected_length}, got {ib_chunk.shape[0]}'
245
+ )
246
+
247
+ if sync_chunk is None:
248
+ raise RuntimeError(f'Sync video returned None {video_path}')
249
+ if sync_chunk.shape[0] < self.sync_expected_length:
250
+ raise RuntimeError(
251
+ f'Sync video too short {video_path}, expected {self.sync_expected_length}, got {sync_chunk.shape[0]}'
252
+ )
253
+
254
+ # truncate the video
255
+ ib_chunk = ib_chunk[:self.ib_expected_length]
256
+ if ib_chunk.shape[0] != self.ib_expected_length:
257
+ raise RuntimeError(f'IB video wrong length {video_path}, '
258
+ f'expected {self.ib_expected_length}, '
259
+ f'got {ib_chunk.shape[0]}')
260
+ ib_chunk = self.ib_transform(ib_chunk)
261
+
262
+ sync_chunk = sync_chunk[:self.sync_expected_length]
263
+ if sync_chunk.shape[0] != self.sync_expected_length:
264
+ raise RuntimeError(f'Sync video wrong length {video_path}, '
265
+ f'expected {self.sync_expected_length}, '
266
+ f'got {sync_chunk.shape[0]}')
267
+ sync_chunk = self.sync_transform(sync_chunk)
268
+
269
+ ib_chunk = self.crop([ib_chunk])
270
+ ib_chunk = torch.stack(ib_chunk)
271
+
272
+ # todo for audio extraction
273
+ ib_audio = self.load_and_transform_audio_data_for_ib(audio_path)
274
+ sync_audio = self.load_and_transform_audio_data_for_sync(audio_path)
275
+
276
+ data = {
277
+ 'name': video_path.stem,
278
+ 'label': caption, # todo May 9
279
+ 'ib_video': ib_chunk,
280
+ 'sync_video': sync_chunk,
281
+ 'ib_audio': ib_audio,
282
+ 'sync_audio': sync_audio,
283
+ }
284
+
285
+ return data
286
+
287
+ def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
288
+
289
+ try:
290
+ return self.sample(idx)
291
+ except Exception as e:
292
+ log.error(f'Error loading video {self.video_paths[idx]}: {e}')
293
+ return None
294
+
295
+ def __len__(self):
296
+ return len(self.video_paths)
297
+
298
+
299
+
300
+ class AudioDataset(Dataset):
301
+
302
+ def __init__(
303
+ self,
304
+ video_paths: list[Path],
305
+ audio_paths: list[Path],
306
+ *,
307
+ duration_sec: float = 8.0,
308
+ video_id_caption={}
309
+ ):
310
+ self.video_paths = video_paths # todo for video
311
+ self.audio_paths = audio_paths #[f'{f[:-4]}.flac' for f in video_paths] # todo for audio
312
+ self.video_id_caption = video_id_caption # todo May 9
313
+
314
+ self.duration_sec = duration_sec
315
+
316
+ self.ib_expected_length = int(_IMAGEBIND_FPS * self.duration_sec)
317
+ self.sync_expected_length = int(_SYNC_FPS * self.duration_sec)
318
+
319
+ self.ib_transform = v2.Compose([
320
+ v2.Resize(_IMAGEBIND_SIZE, interpolation=v2.InterpolationMode.BICUBIC),
321
+ v2.ToImage(),
322
+ v2.ToDtype(torch.float32, scale=True),
323
+ v2.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
324
+ std=[0.26862954, 0.26130258, 0.27577711]),
325
+ ])
326
+
327
+ self.sync_transform = v2.Compose([
328
+ v2.Resize(_SYNC_SIZE, interpolation=v2.InterpolationMode.BICUBIC),
329
+ v2.CenterCrop(_SYNC_SIZE),
330
+ v2.ToImage(),
331
+ v2.ToDtype(torch.float32, scale=True),
332
+ v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
333
+ ])
334
+
335
+ self.crop = SpatialCrop(_IMAGEBIND_SIZE, 3)
336
+
337
+ self.resampler = {} # todo for synchformer
338
+ self.sync_mel_spectrogram = torchaudio.transforms.MelSpectrogram(
339
+ sample_rate=16000,
340
+ win_length=400,
341
+ hop_length=160,
342
+ n_fft=1024,
343
+ n_mels=128,
344
+ )
345
+
346
+ # todo for imagebind audio
347
+ def load_and_transform_audio_data_for_ib(
348
+ self,
349
+ audio_path,
350
+ num_mel_bins=128,
351
+ target_length=204,
352
+ sample_rate=16000,
353
+ clip_duration=2,
354
+ clips_per_video=3,
355
+ mean=-4.268,
356
+ std=9.138,
357
+ ):
358
+
359
+ audio_outputs = []
360
+ clip_sampler = ConstantClipsPerVideoSampler(clip_duration=clip_duration,
361
+ clips_per_video=clips_per_video)
362
+
363
+ waveform, sr = torchaudio.load(audio_path)
364
+ if sample_rate != sr:
365
+ waveform = torchaudio.functional.resample(waveform, orig_freq=sr, new_freq=sample_rate)
366
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, waveform.size(1) / sample_rate)
367
+ all_clips = []
368
+ for clip_timepoints in all_clips_timepoints:
369
+ waveform_clip = waveform[
370
+ :,
371
+ int(clip_timepoints[0] * sample_rate):int(clip_timepoints[1] * sample_rate),
372
+ ]
373
+ waveform_melspec = waveform2melspec(waveform_clip, sample_rate, num_mel_bins,
374
+ target_length)
375
+ all_clips.append(waveform_melspec)
376
+
377
+ normalize = v2.Normalize(mean=[mean], std=[std])
378
+ all_clips = [normalize(ac) for ac in all_clips]
379
+
380
+ all_clips = torch.stack(all_clips, dim=0)
381
+ audio_outputs.append(all_clips)
382
+
383
+ return torch.stack(audio_outputs, dim=0)
384
+
385
+ # todo for synchformer audio
386
+ def load_and_transform_audio_data_for_sync(self, audio_path):
387
+ waveform, sr = torchaudio.load(audio_path)
388
+ waveform = waveform.mean(dim=0)
389
+
390
+ if sr != 16000:
391
+ if sr not in self.resampler:
392
+ self.resampler[sr] = torchaudio.transforms.Resample(sr, 16000)
393
+ waveform = self.resampler[sr](waveform)
394
+
395
+ waveform = waveform[:int(self.duration_sec * 16000)]
396
+ if waveform.shape[0] != int(self.duration_sec * 16000):
397
+ raise ValueError(f'Audio {audio_path} is too short')
398
+
399
+ waveform = waveform.squeeze()
400
+
401
+ return waveform
402
+
403
+ def sample(self, idx: int) -> dict[str, torch.Tensor]:
404
+ video_path = self.video_paths[idx] # todo for video path
405
+ audio_path = self.audio_paths[idx] # todo for audio path
406
+ caption = self.video_id_caption[video_path.stem] # todo May 9
407
+
408
+ # todo for audio extraction
409
+ ib_audio = self.load_and_transform_audio_data_for_ib(audio_path)
410
+
411
+ data = {
412
+ 'name': video_path.stem,
413
+ 'label': caption, # todo May 9
414
+ 'ib_audio': ib_audio,
415
+ }
416
+
417
+ return data
418
+
419
+ def __getitem__(self, idx: int) -> dict[str, torch.Tensor]:
420
+
421
+ try:
422
+ return self.sample(idx)
423
+ except Exception as e:
424
+ log.error(f'Error loading video {self.video_paths[idx]}: {e}')
425
+ return None
426
+
427
+ def __len__(self):
428
+ return len(self.video_paths)
reward_models/ib_sync_rewards/imagebind/data.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import logging
9
+ import math
10
+ import pkg_resources
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torchaudio
15
+ from PIL import Image
16
+ from ib_sync_rewards.imagebind.pytorchvideo import transforms as pv_transforms
17
+ from ib_sync_rewards.imagebind.pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler
18
+ from ib_sync_rewards.imagebind.pytorchvideo.data.encoded_video import EncodedVideo
19
+ from torchvision import transforms
20
+
21
+ from ib_sync_rewards.imagebind.models.multimodal_preprocessors import SimpleTokenizer
22
+
23
+ DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds
24
+
25
+ def normalize(clip, mean, std, inplace=False):
26
+ """
27
+ Args:
28
+ clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
29
+ mean (tuple): pixel RGB mean. Size is (3)
30
+ std (tuple): pixel standard deviation. Size is (3)
31
+ Returns:
32
+ normalized clip (torch.tensor): Size is (C, T, H, W)
33
+ """
34
+ if not len(clip.shape) == 4:
35
+ raise ValueError("clip should be a 4D torch.tensor")
36
+ if not inplace:
37
+ clip = clip.clone()
38
+ mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device)
39
+ std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device)
40
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
41
+ return clip
42
+
43
+ class NormalizeVideo:
44
+ """
45
+ Normalize the video clip by mean subtraction and division by standard deviation
46
+ Args:
47
+ mean (3-tuple): pixel RGB mean
48
+ std (3-tuple): pixel RGB standard deviation
49
+ inplace (boolean): whether do in-place normalization
50
+ """
51
+
52
+ def __init__(self, mean, std, inplace=False):
53
+ self.mean = mean
54
+ self.std = std
55
+ self.inplace = inplace
56
+
57
+ def __call__(self, clip):
58
+ """
59
+ Args:
60
+ clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W)
61
+ """
62
+ return normalize(clip, self.mean, self.std, self.inplace)
63
+
64
+ def __repr__(self) -> str:
65
+ return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})"
66
+
67
+ def return_bpe_path():
68
+ return pkg_resources.resource_filename(
69
+ "imagebind", "bpe/bpe_simple_vocab_16e6.txt.gz"
70
+ )
71
+
72
+
73
+ def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length):
74
+ # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102
75
+ waveform -= waveform.mean()
76
+ fbank = torchaudio.compliance.kaldi.fbank(
77
+ waveform,
78
+ htk_compat=True,
79
+ sample_frequency=sample_rate,
80
+ use_energy=False,
81
+ window_type="hanning",
82
+ num_mel_bins=num_mel_bins,
83
+ dither=0.0,
84
+ frame_length=25,
85
+ frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS,
86
+ )
87
+ # Convert to [mel_bins, num_frames] shape
88
+ fbank = fbank.transpose(0, 1)
89
+ # Pad to target_length
90
+ n_frames = fbank.size(1)
91
+ p = target_length - n_frames
92
+ # if p is too large (say >20%), flash a warning
93
+ if abs(p) / n_frames > 0.2:
94
+ logging.warning(
95
+ "Large gap between audio n_frames(%d) and "
96
+ "target_length (%d). Is the audio_target_length "
97
+ "setting correct?",
98
+ n_frames,
99
+ target_length,
100
+ )
101
+ # cut and pad
102
+ if p > 0:
103
+ fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0)
104
+ elif p < 0:
105
+ fbank = fbank[:, 0:target_length]
106
+ # Convert to [1, mel_bins, num_frames] shape, essentially like a 1
107
+ # channel image
108
+ fbank = fbank.unsqueeze(0)
109
+ return fbank
110
+
111
+
112
+ def get_clip_timepoints(clip_sampler, duration):
113
+ # Read out all clips in this video
114
+ all_clips_timepoints = []
115
+ is_last_clip = False
116
+ end = 0.0
117
+ while not is_last_clip:
118
+ start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None)
119
+ all_clips_timepoints.append((start, end))
120
+ return all_clips_timepoints
121
+
122
+
123
+ def load_and_transform_vision_data(image_paths, device):
124
+ if image_paths is None:
125
+ return None
126
+
127
+ image_outputs = []
128
+
129
+ data_transform = transforms.Compose(
130
+ [
131
+ transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
132
+ transforms.CenterCrop(224),
133
+ transforms.ToTensor(),
134
+ transforms.Normalize(
135
+ mean=(0.48145466, 0.4578275, 0.40821073),
136
+ std=(0.26862954, 0.26130258, 0.27577711),
137
+ ),
138
+ ]
139
+ )
140
+
141
+ for image_path in image_paths:
142
+ with open(image_path, "rb") as fopen:
143
+ image = Image.open(fopen).convert("RGB")
144
+
145
+ image = data_transform(image).to(device)
146
+ image_outputs.append(image)
147
+ return torch.stack(image_outputs, dim=0)
148
+
149
+
150
+ def load_and_transform_text(text, device):
151
+ if text is None:
152
+ return None
153
+ tokenizer = SimpleTokenizer(bpe_path=return_bpe_path())
154
+ tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text]
155
+ tokens = torch.cat(tokens, dim=0)
156
+ return tokens
157
+
158
+
159
+ def load_and_transform_audio_data(
160
+ audio_paths,
161
+ device,
162
+ num_mel_bins=128,
163
+ target_length=204,
164
+ sample_rate=16000,
165
+ clip_duration=2,
166
+ clips_per_video=3,
167
+ mean=-4.268,
168
+ std=9.138,
169
+ ):
170
+ if audio_paths is None:
171
+ return None
172
+
173
+ audio_outputs = []
174
+ clip_sampler = ConstantClipsPerVideoSampler(
175
+ clip_duration=clip_duration, clips_per_video=clips_per_video
176
+ )
177
+
178
+ for audio_path in audio_paths:
179
+ waveform, sr = torchaudio.load(audio_path)
180
+ if sample_rate != sr:
181
+ waveform = torchaudio.functional.resample(
182
+ waveform, orig_freq=sr, new_freq=sample_rate
183
+ )
184
+ all_clips_timepoints = get_clip_timepoints(
185
+ clip_sampler, waveform.size(1) / sample_rate
186
+ )
187
+ all_clips = []
188
+ for clip_timepoints in all_clips_timepoints:
189
+ waveform_clip = waveform[
190
+ :,
191
+ int(clip_timepoints[0] * sample_rate) : int(
192
+ clip_timepoints[1] * sample_rate
193
+ ),
194
+ ]
195
+ waveform_melspec = waveform2melspec(
196
+ waveform_clip, sample_rate, num_mel_bins, target_length
197
+ )
198
+ all_clips.append(waveform_melspec)
199
+
200
+ normalize = transforms.Normalize(mean=mean, std=std)
201
+ all_clips = [normalize(ac).to(device) for ac in all_clips]
202
+
203
+ all_clips = torch.stack(all_clips, dim=0)
204
+ audio_outputs.append(all_clips)
205
+
206
+ return torch.stack(audio_outputs, dim=0)
207
+
208
+
209
+ def crop_boxes(boxes, x_offset, y_offset):
210
+ """
211
+ Perform crop on the bounding boxes given the offsets.
212
+ Args:
213
+ boxes (ndarray or None): bounding boxes to perform crop. The dimension
214
+ is `num boxes` x 4.
215
+ x_offset (int): cropping offset in the x axis.
216
+ y_offset (int): cropping offset in the y axis.
217
+ Returns:
218
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
219
+ `num boxes` x 4.
220
+ """
221
+ cropped_boxes = boxes.copy()
222
+ cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
223
+ cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
224
+
225
+ return cropped_boxes
226
+
227
+
228
+ def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
229
+ """
230
+ Perform uniform spatial sampling on the images and corresponding boxes.
231
+ Args:
232
+ images (tensor): images to perform uniform crop. The dimension is
233
+ `num frames` x `channel` x `height` x `width`.
234
+ size (int): size of height and weight to crop the images.
235
+ spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
236
+ is larger than height. Or 0, 1, or 2 for top, center, and bottom
237
+ crop if height is larger than width.
238
+ boxes (ndarray or None): optional. Corresponding boxes to images.
239
+ Dimension is `num boxes` x 4.
240
+ scale_size (int): optinal. If not None, resize the images to scale_size before
241
+ performing any crop.
242
+ Returns:
243
+ cropped (tensor): images with dimension of
244
+ `num frames` x `channel` x `size` x `size`.
245
+ cropped_boxes (ndarray or None): the cropped boxes with dimension of
246
+ `num boxes` x 4.
247
+ """
248
+ assert spatial_idx in [0, 1, 2]
249
+ ndim = len(images.shape)
250
+ if ndim == 3:
251
+ images = images.unsqueeze(0)
252
+ height = images.shape[2]
253
+ width = images.shape[3]
254
+
255
+ if scale_size is not None:
256
+ if width <= height:
257
+ width, height = scale_size, int(height / width * scale_size)
258
+ else:
259
+ width, height = int(width / height * scale_size), scale_size
260
+ images = torch.nn.functional.interpolate(
261
+ images,
262
+ size=(height, width),
263
+ mode="bilinear",
264
+ align_corners=False,
265
+ )
266
+
267
+ y_offset = int(math.ceil((height - size) / 2))
268
+ x_offset = int(math.ceil((width - size) / 2))
269
+
270
+ if height > width:
271
+ if spatial_idx == 0:
272
+ y_offset = 0
273
+ elif spatial_idx == 2:
274
+ y_offset = height - size
275
+ else:
276
+ if spatial_idx == 0:
277
+ x_offset = 0
278
+ elif spatial_idx == 2:
279
+ x_offset = width - size
280
+ cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size]
281
+ cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
282
+ if ndim == 3:
283
+ cropped = cropped.squeeze(0)
284
+ return cropped, cropped_boxes
285
+
286
+
287
+ class SpatialCrop(nn.Module):
288
+ """
289
+ Convert the video into 3 smaller clips spatially. Must be used after the
290
+ temporal crops to get spatial crops, and should be used with
291
+ -2 in the spatial crop at the slowfast augmentation stage (so full
292
+ frames are passed in here). Will return a larger list with the
293
+ 3x spatial crops as well.
294
+ """
295
+
296
+ def __init__(self, crop_size: int = 224, num_crops: int = 3):
297
+ super().__init__()
298
+ self.crop_size = crop_size
299
+ if num_crops == 3:
300
+ self.crops_to_ext = [0, 1, 2]
301
+ self.flipped_crops_to_ext = []
302
+ elif num_crops == 1:
303
+ self.crops_to_ext = [1]
304
+ self.flipped_crops_to_ext = []
305
+ else:
306
+ raise NotImplementedError("Nothing else supported yet")
307
+
308
+ def forward(self, videos):
309
+ """
310
+ Args:
311
+ videos: A list of C, T, H, W videos.
312
+ Returns:
313
+ videos: A list with 3x the number of elements. Each video converted
314
+ to C, T, H', W' by spatial cropping.
315
+ """
316
+ assert isinstance(videos, list), "Must be a list of videos after temporal crops"
317
+ assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)"
318
+ res = []
319
+ for video in videos:
320
+ for spatial_idx in self.crops_to_ext:
321
+ res.append(uniform_crop(video, self.crop_size, spatial_idx)[0])
322
+ if not self.flipped_crops_to_ext:
323
+ continue
324
+ flipped_video = transforms.functional.hflip(video)
325
+ for spatial_idx in self.flipped_crops_to_ext:
326
+ res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0])
327
+ return res
328
+
329
+
330
+ def load_and_transform_video_data(
331
+ video_paths,
332
+ device,
333
+ clip_duration=2,
334
+ clips_per_video=5,
335
+ sample_rate=16000,
336
+ ):
337
+ if video_paths is None:
338
+ return None
339
+
340
+ video_outputs = []
341
+ video_transform = transforms.Compose(
342
+ [
343
+ pv_transforms.ShortSideScale(224),
344
+ NormalizeVideo(
345
+ mean=(0.48145466, 0.4578275, 0.40821073),
346
+ std=(0.26862954, 0.26130258, 0.27577711),
347
+ ),
348
+ ]
349
+ )
350
+
351
+ clip_sampler = ConstantClipsPerVideoSampler(
352
+ clip_duration=clip_duration, clips_per_video=clips_per_video
353
+ )
354
+ frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration)
355
+
356
+ for video_path in video_paths:
357
+ video = EncodedVideo.from_path(
358
+ video_path,
359
+ decoder="decord",
360
+ decode_audio=False,
361
+ **{"sample_rate": sample_rate},
362
+ )
363
+
364
+ all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration)
365
+
366
+ all_video = []
367
+ for clip_timepoints in all_clips_timepoints:
368
+ # Read the clip, get frames
369
+ clip = video.get_clip(clip_timepoints[0], clip_timepoints[1])
370
+ if clip is None:
371
+ raise ValueError("No clip found")
372
+ video_clip = frame_sampler(clip["video"])
373
+ video_clip = video_clip / 255.0 # since this is float, need 0-1
374
+
375
+ all_video.append(video_clip)
376
+
377
+ all_video = [video_transform(clip) for clip in all_video]
378
+ all_video = SpatialCrop(224, num_crops=3)(all_video)
379
+
380
+ all_video = torch.stack(all_video, dim=0)
381
+ video_outputs.append(all_video)
382
+
383
+ return torch.stack(video_outputs, dim=0).to(device)
reward_models/ib_sync_rewards/imagebind/models/__init__.py ADDED
File without changes
reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/deployment/common/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/deployment/mobile_cpu/transmuter/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytorchvideo.accelerator.deployment.common.model_transmuter import (
2
+ EFFICIENT_BLOCK_TRANSMUTER_REGISTRY,
3
+ )
4
+
5
+ from .transmuter_mobile_cpu import EFFICIENT_BLOCK_TRANSMUTER_MOBILE_CPU
6
+
7
+
8
+ EFFICIENT_BLOCK_TRANSMUTER_REGISTRY["mobile_cpu"] = (
9
+ EFFICIENT_BLOCK_TRANSMUTER_MOBILE_CPU
10
+ )
reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/efficient_blocks/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
reward_models/ib_sync_rewards/imagebind/pytorchvideo/accelerator/efficient_blocks/no_op_convert_block.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import torch.nn as nn
4
+
5
+ from .efficient_block_base import EfficientBlockBase
6
+
7
+
8
+ class NoOpConvertBlock(EfficientBlockBase):
9
+ """
10
+ This class provides an interface with EfficientBlockBase for modules that do not
11
+ need convert.
12
+ Args:
13
+ model (nn.Module): NoOpConvertBlock takes model as input and generate a wrapper
14
+ instance of EfficientBlockBase with same functionality as model, with no change
15
+ applied when convert() is called.
16
+ """
17
+
18
+ def __init__(self, model: nn.Module):
19
+ super().__init__()
20
+ self.model = model
21
+
22
+ def convert(self, *args, **kwargs):
23
+ pass
24
+
25
+ def forward(self, x):
26
+ return self.model(x)
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from .ava import Ava # noqa
4
+ from .charades import Charades # noqa
5
+ from .clip_sampling import ( # noqa; noqa
6
+ ClipSampler,
7
+ make_clip_sampler,
8
+ RandomClipSampler,
9
+ UniformClipSampler,
10
+ )
11
+ from .domsev import DomsevFrameDataset, DomsevVideoDataset # noqa
12
+ from .epic_kitchen_forecasting import EpicKitchenForecasting # noqa
13
+ from .epic_kitchen_recognition import EpicKitchenRecognition # noqa
14
+ from .hmdb51 import Hmdb51 # noqa
15
+ from .kinetics import Kinetics # noqa
16
+ from .labeled_video_dataset import labeled_video_dataset, LabeledVideoDataset # noqa
17
+ from .ssv2 import SSv2
18
+ from .ucf101 import Ucf101 # noqa
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/clip_sampling.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import random
4
+ from abc import ABC, abstractmethod
5
+ from fractions import Fraction
6
+ from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union
7
+
8
+
9
+ class ClipInfo(NamedTuple):
10
+ """
11
+ Named-tuple for clip information with:
12
+ clip_start_sec (Union[float, Fraction]): clip start time.
13
+ clip_end_sec (Union[float, Fraction]): clip end time.
14
+ clip_index (int): clip index in the video.
15
+ aug_index (int): augmentation index for the clip. Different augmentation methods
16
+ might generate multiple views for the same clip.
17
+ is_last_clip (bool): a bool specifying whether there are more clips to be
18
+ sampled from the video.
19
+ """
20
+
21
+ clip_start_sec: Union[float, Fraction]
22
+ clip_end_sec: Union[float, Fraction]
23
+ clip_index: int
24
+ aug_index: int
25
+ is_last_clip: bool
26
+
27
+
28
+ class ClipInfoList(NamedTuple):
29
+ """
30
+ Named-tuple for clip information with:
31
+ clip_start_sec (float): clip start time.
32
+ clip_end_sec (float): clip end time.
33
+ clip_index (int): clip index in the video.
34
+ aug_index (int): augmentation index for the clip. Different augmentation methods
35
+ might generate multiple views for the same clip.
36
+ is_last_clip (bool): a bool specifying whether there are more clips to be
37
+ sampled from the video.
38
+ """
39
+
40
+ clip_start_sec: List[float]
41
+ clip_end_sec: List[float]
42
+ clip_index: List[float]
43
+ aug_index: List[float]
44
+ is_last_clip: List[float]
45
+
46
+
47
+ class ClipSampler(ABC):
48
+ """
49
+ Interface for clip samplers that take a video time, previous sampled clip time,
50
+ and returns a named-tuple ``ClipInfo``.
51
+ """
52
+
53
+ def __init__(self, clip_duration: Union[float, Fraction]) -> None:
54
+ self._clip_duration = Fraction(clip_duration)
55
+ self._current_clip_index = 0
56
+ self._current_aug_index = 0
57
+
58
+ @abstractmethod
59
+ def __call__(
60
+ self,
61
+ last_clip_end_time: Union[float, Fraction],
62
+ video_duration: Union[float, Fraction],
63
+ annotation: Dict[str, Any],
64
+ ) -> ClipInfo:
65
+ pass
66
+
67
+ def reset(self) -> None:
68
+ """Resets any video-specific attributes in preperation for next video"""
69
+ pass
70
+
71
+
72
+ def make_clip_sampler(sampling_type: str, *args) -> ClipSampler:
73
+ """
74
+ Constructs the clip samplers found in ``pytorchvideo.data.clip_sampling`` from the
75
+ given arguments.
76
+
77
+ Args:
78
+ sampling_type (str): choose clip sampler to return. It has three options:
79
+
80
+ * uniform: constructs and return ``UniformClipSampler``
81
+ * random: construct and return ``RandomClipSampler``
82
+ * constant_clips_per_video: construct and return ``ConstantClipsPerVideoSampler``
83
+
84
+ *args: the args to pass to the chosen clip sampler constructor.
85
+ """
86
+ if sampling_type == "uniform":
87
+ return UniformClipSampler(*args)
88
+ elif sampling_type == "random":
89
+ return RandomClipSampler(*args)
90
+ elif sampling_type == "constant_clips_per_video":
91
+ return ConstantClipsPerVideoSampler(*args)
92
+ elif sampling_type == "random_multi":
93
+ return RandomMultiClipSampler(*args)
94
+ else:
95
+ raise NotImplementedError(f"{sampling_type} not supported")
96
+
97
+
98
+ class UniformClipSampler(ClipSampler):
99
+ """
100
+ Evenly splits the video into clips of size clip_duration.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ clip_duration: Union[float, Fraction],
106
+ stride: Optional[Union[float, Fraction]] = None,
107
+ backpad_last: bool = False,
108
+ eps: float = 1e-6,
109
+ ):
110
+ """
111
+ Args:
112
+ clip_duration (Union[float, Fraction]):
113
+ The length of the clip to sample (in seconds).
114
+ stride (Union[float, Fraction], optional):
115
+ The amount of seconds to offset the next clip by
116
+ default value of None is equivalent to no stride => stride == clip_duration.
117
+ eps (float):
118
+ Epsilon for floating point comparisons. Used to check the last clip.
119
+ backpad_last (bool):
120
+ Whether to include the last frame(s) by "back padding".
121
+
122
+ For instance, if we have a video of 39 frames (30 fps = 1.3s)
123
+ with a stride of 16 (0.533s) with a clip duration of 32 frames
124
+ (1.0667s). The clips will be (in frame numbers):
125
+
126
+ with backpad_last = False
127
+ - [0, 31]
128
+
129
+ with backpad_last = True
130
+ - [0, 31]
131
+ - [8, 39], this is "back-padded" from [16, 48] to fit the last window
132
+ Note that you can use Fraction for clip_duration and stride if you want to
133
+ avoid float precision issue and need accurate frames in each clip.
134
+ """
135
+ super().__init__(clip_duration)
136
+ self._stride = stride if stride is not None else self._clip_duration
137
+ self._eps = eps
138
+ self._backpad_last = backpad_last
139
+
140
+ assert self._stride > 0, "stride must be positive"
141
+
142
+ def _clip_start_end(
143
+ self,
144
+ last_clip_end_time: Union[float, Fraction],
145
+ video_duration: Union[float, Fraction],
146
+ backpad_last: bool,
147
+ ) -> Tuple[Fraction, Fraction]:
148
+ """
149
+ Helper to calculate the start/end clip with backpad logic
150
+ """
151
+ delta = self._stride - self._clip_duration
152
+ last_end_time = -delta if last_clip_end_time is None else last_clip_end_time
153
+ clip_start = Fraction(last_end_time + delta)
154
+ clip_end = Fraction(clip_start + self._clip_duration)
155
+ if backpad_last:
156
+ buffer_amount = max(0, clip_end - video_duration)
157
+ clip_start -= buffer_amount
158
+ clip_start = Fraction(max(0, clip_start)) # handle rounding
159
+ clip_end = Fraction(clip_start + self._clip_duration)
160
+
161
+ return clip_start, clip_end
162
+
163
+ def __call__(
164
+ self,
165
+ last_clip_end_time: Optional[float],
166
+ video_duration: float,
167
+ annotation: Dict[str, Any],
168
+ ) -> ClipInfo:
169
+ """
170
+ Args:
171
+ last_clip_end_time (float): the last clip end time sampled from this video. This
172
+ should be 0.0 if the video hasn't had clips sampled yet.
173
+ video_duration: (float): the duration of the video that's being sampled in seconds
174
+ annotation (Dict): Not used by this sampler.
175
+ Returns:
176
+ clip_info: (ClipInfo): includes the clip information (clip_start_time,
177
+ clip_end_time, clip_index, aug_index, is_last_clip), where the times are in
178
+ seconds and is_last_clip is False when there is still more of time in the video
179
+ to be sampled.
180
+ """
181
+ clip_start, clip_end = self._clip_start_end(
182
+ last_clip_end_time, video_duration, backpad_last=self._backpad_last
183
+ )
184
+
185
+ # if they both end at the same time - it's the last clip
186
+ _, next_clip_end = self._clip_start_end(
187
+ clip_end, video_duration, backpad_last=self._backpad_last
188
+ )
189
+ if self._backpad_last:
190
+ is_last_clip = abs(next_clip_end - clip_end) < self._eps
191
+ else:
192
+ is_last_clip = (next_clip_end - video_duration) > self._eps
193
+
194
+ clip_index = self._current_clip_index
195
+ self._current_clip_index += 1
196
+
197
+ if is_last_clip:
198
+ self.reset()
199
+
200
+ return ClipInfo(clip_start, clip_end, clip_index, 0, is_last_clip)
201
+
202
+ def reset(self):
203
+ self._current_clip_index = 0
204
+
205
+
206
+ class UniformClipSamplerTruncateFromStart(UniformClipSampler):
207
+ """
208
+ Evenly splits the video into clips of size clip_duration.
209
+ If truncation_duration is set, clips sampled from [0, truncation_duration].
210
+ If truncation_duration is not set, defaults to UniformClipSampler.
211
+ """
212
+
213
+ def __init__(
214
+ self,
215
+ clip_duration: Union[float, Fraction],
216
+ stride: Optional[Union[float, Fraction]] = None,
217
+ backpad_last: bool = False,
218
+ eps: float = 1e-6,
219
+ truncation_duration: float = None,
220
+ ) -> None:
221
+ super().__init__(clip_duration, stride, backpad_last, eps)
222
+ self.truncation_duration = truncation_duration
223
+
224
+ def __call__(
225
+ self,
226
+ last_clip_end_time: float,
227
+ video_duration: float,
228
+ annotation: Dict[str, Any],
229
+ ) -> ClipInfo:
230
+ truncated_video_duration = video_duration
231
+ if self.truncation_duration is not None:
232
+ truncated_video_duration = min(self.truncation_duration, video_duration)
233
+
234
+ return super().__call__(
235
+ last_clip_end_time, truncated_video_duration, annotation
236
+ )
237
+
238
+
239
+ class RandomClipSampler(ClipSampler):
240
+ """
241
+ Randomly samples clip of size clip_duration from the videos.
242
+ """
243
+
244
+ def __call__(
245
+ self,
246
+ last_clip_end_time: float,
247
+ video_duration: float,
248
+ annotation: Dict[str, Any],
249
+ ) -> ClipInfo:
250
+ """
251
+ Args:
252
+ last_clip_end_time (float): Not used for RandomClipSampler.
253
+ video_duration: (float): the duration (in seconds) for the video that's
254
+ being sampled
255
+ annotation (Dict): Not used by this sampler.
256
+ Returns:
257
+ clip_info (ClipInfo): includes the clip information of (clip_start_time,
258
+ clip_end_time, clip_index, aug_index, is_last_clip). The times are in seconds.
259
+ clip_index, aux_index and is_last_clip are always 0, 0 and True, respectively.
260
+
261
+ """
262
+ max_possible_clip_start = max(video_duration - self._clip_duration, 0)
263
+ clip_start_sec = Fraction(random.uniform(0, max_possible_clip_start))
264
+ return ClipInfo(
265
+ clip_start_sec, clip_start_sec + self._clip_duration, 0, 0, True
266
+ )
267
+
268
+
269
+ class RandomMultiClipSampler(RandomClipSampler):
270
+ """
271
+ Randomly samples multiple clips of size clip_duration from the videos.
272
+ """
273
+
274
+ def __init__(self, clip_duration: float, num_clips: int) -> None:
275
+ super().__init__(clip_duration)
276
+ self._num_clips = num_clips
277
+
278
+ def __call__(
279
+ self,
280
+ last_clip_end_time: Optional[float],
281
+ video_duration: float,
282
+ annotation: Dict[str, Any],
283
+ ) -> ClipInfoList:
284
+ (
285
+ clip_start_list,
286
+ clip_end_list,
287
+ clip_index_list,
288
+ aug_index_list,
289
+ is_last_clip_list,
290
+ ) = (
291
+ self._num_clips * [None],
292
+ self._num_clips * [None],
293
+ self._num_clips * [None],
294
+ self._num_clips * [None],
295
+ self._num_clips * [None],
296
+ )
297
+ for i in range(self._num_clips):
298
+ (
299
+ clip_start_list[i],
300
+ clip_end_list[i],
301
+ clip_index_list[i],
302
+ aug_index_list[i],
303
+ is_last_clip_list[i],
304
+ ) = super().__call__(last_clip_end_time, video_duration, annotation)
305
+
306
+ return ClipInfoList(
307
+ clip_start_list,
308
+ clip_end_list,
309
+ clip_index_list,
310
+ aug_index_list,
311
+ is_last_clip_list,
312
+ )
313
+
314
+
315
+ class RandomMultiClipSamplerTruncateFromStart(RandomMultiClipSampler):
316
+ """
317
+ Randomly samples multiple clips of size clip_duration from the videos.
318
+ If truncation_duration is set, clips sampled from [0, truncation_duration].
319
+ If truncation_duration is not set, defaults to RandomMultiClipSampler.
320
+ """
321
+
322
+ def __init__(
323
+ self, clip_duration: float, num_clips: int, truncation_duration: float = None
324
+ ) -> None:
325
+ super().__init__(clip_duration, num_clips)
326
+ self.truncation_duration = truncation_duration
327
+
328
+ def __call__(
329
+ self,
330
+ last_clip_end_time: Optional[float],
331
+ video_duration: float,
332
+ annotation: Dict[str, Any],
333
+ ) -> ClipInfoList:
334
+ truncated_video_duration = video_duration
335
+ if self.truncation_duration is not None:
336
+ truncated_video_duration = min(self.truncation_duration, video_duration)
337
+
338
+ return super().__call__(
339
+ last_clip_end_time, truncated_video_duration, annotation
340
+ )
341
+
342
+
343
+ class ConstantClipsPerVideoSampler(ClipSampler):
344
+ """
345
+ Evenly splits the video into clips_per_video increments and samples clips of size
346
+ clip_duration at these increments.
347
+ """
348
+
349
+ def __init__(
350
+ self, clip_duration: float, clips_per_video: int, augs_per_clip: int = 1
351
+ ) -> None:
352
+ super().__init__(clip_duration)
353
+ self._clips_per_video = clips_per_video
354
+ self._augs_per_clip = augs_per_clip
355
+
356
+ def __call__(
357
+ self,
358
+ last_clip_end_time: Optional[float],
359
+ video_duration: float,
360
+ annotation: Dict[str, Any],
361
+ ) -> ClipInfo:
362
+ """
363
+ Args:
364
+ last_clip_end_time (float): Not used for ConstantClipsPerVideoSampler.
365
+ video_duration: (float): the duration (in seconds) for the video that's
366
+ being sampled.
367
+ annotation (Dict): Not used by this sampler.
368
+ Returns:
369
+ a named-tuple `ClipInfo`: includes the clip information of (clip_start_time,
370
+ clip_end_time, clip_index, aug_index, is_last_clip). The times are in seconds.
371
+ is_last_clip is True after clips_per_video clips have been sampled or the end
372
+ of the video is reached.
373
+
374
+ """
375
+ max_possible_clip_start = Fraction(max(video_duration - self._clip_duration, 0))
376
+ uniform_clip = Fraction(
377
+ max_possible_clip_start, max(self._clips_per_video - 1, 1)
378
+ )
379
+ clip_start_sec = uniform_clip * self._current_clip_index
380
+ clip_index = self._current_clip_index
381
+ aug_index = self._current_aug_index
382
+
383
+ self._current_aug_index += 1
384
+ if self._current_aug_index >= self._augs_per_clip:
385
+ self._current_clip_index += 1
386
+ self._current_aug_index = 0
387
+
388
+ # Last clip is True if sampled self._clips_per_video or if end of video is reached.
389
+ is_last_clip = False
390
+ if (
391
+ self._current_clip_index >= self._clips_per_video
392
+ or uniform_clip * self._current_clip_index > max_possible_clip_start
393
+ ):
394
+ self._current_clip_index = 0
395
+ is_last_clip = True
396
+
397
+ if is_last_clip:
398
+ self.reset()
399
+
400
+ return ClipInfo(
401
+ clip_start_sec,
402
+ clip_start_sec + self._clip_duration,
403
+ clip_index,
404
+ aug_index,
405
+ is_last_clip,
406
+ )
407
+
408
+ def reset(self):
409
+ self._current_clip_index = 0
410
+ self._current_aug_index = 0
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/dataset_manifest_utils.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import datetime
4
+ import os
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from typing import Dict, Optional, Union
8
+
9
+ from ib_sync_rewards.imagebind.pytorchvideo.data.encoded_video import EncodedVideo
10
+ from ib_sync_rewards.imagebind.pytorchvideo.data.frame_video import FrameVideo
11
+ from ib_sync_rewards.imagebind.pytorchvideo.data.utils import (
12
+ DataclassFieldCaster,
13
+ load_dataclass_dict_from_csv,
14
+ save_dataclass_objs_to_headered_csv,
15
+ )
16
+ from ib_sync_rewards.imagebind.pytorchvideo.data.video import Video
17
+
18
+
19
+ @dataclass
20
+ class EncodedVideoInfo(DataclassFieldCaster):
21
+ """
22
+ Class representing the location of an available encoded video.
23
+ """
24
+
25
+ video_id: str
26
+ file_path: str
27
+
28
+
29
+ @dataclass
30
+ class VideoFrameInfo(DataclassFieldCaster):
31
+ """
32
+ Class representing the locations of all frames that compose a video.
33
+ """
34
+
35
+ video_id: str
36
+ location: str
37
+ frame_file_stem: str
38
+ frame_string_length: int
39
+ min_frame_number: int
40
+ max_frame_number: int
41
+ file_extension: str
42
+
43
+
44
+ @dataclass
45
+ class VideoInfo(DataclassFieldCaster):
46
+ """
47
+ Class representing the video-level metadata of a video from an arbitrary video dataset.
48
+ """
49
+
50
+ video_id: str
51
+ resolution: str
52
+ duration: float
53
+ fps: float
54
+
55
+
56
+ @dataclass
57
+ class VideoClipInfo(DataclassFieldCaster):
58
+ video_id: str
59
+ start_time: float
60
+ stop_time: float
61
+
62
+
63
+ @dataclass
64
+ class ImageFrameInfo(DataclassFieldCaster):
65
+ """
66
+ Class representing the metadata (and labels) for a single frame
67
+ """
68
+
69
+ video_id: str
70
+ frame_id: str
71
+ frame_number: int
72
+ frame_file_path: str
73
+
74
+
75
+ class VideoDatasetType(Enum):
76
+ Frame = 1
77
+ EncodedVideo = 2
78
+
79
+
80
+ class ImageDataset:
81
+ @staticmethod
82
+ def _load_images(
83
+ frame_manifest_file_path: Optional[str],
84
+ video_info_file_path: str,
85
+ multithreaded_io: bool,
86
+ ) -> Dict[str, ImageFrameInfo]:
87
+ video_infos: Dict[str, VideoInfo] = load_dataclass_dict_from_csv(
88
+ video_info_file_path, VideoInfo, "video_id"
89
+ )
90
+ video_frames: Dict[str, VideoFrameInfo] = load_dataclass_dict_from_csv(
91
+ frame_manifest_file_path, VideoFrameInfo, "video_id"
92
+ )
93
+ VideoDataset._remove_video_info_missing_or_incomplete_videos(
94
+ video_frames, video_infos
95
+ )
96
+
97
+ image_infos = {}
98
+ for video_id in video_infos:
99
+ frame_filepaths = VideoDataset._frame_number_to_filepaths(
100
+ video_id, video_frames, video_infos
101
+ )
102
+ video_info = video_infos[video_id]
103
+ video_frame_info = video_frames[video_info.video_id]
104
+ for frame_filepath, frame_number in zip(
105
+ frame_filepaths,
106
+ range(
107
+ video_frame_info.min_frame_number, video_frame_info.max_frame_number
108
+ ),
109
+ ):
110
+ frame_id = os.path.splitext(os.path.basename(frame_filepath))[0]
111
+ image_infos[frame_id] = ImageFrameInfo(
112
+ video_id, frame_id, frame_number, frame_filepath
113
+ )
114
+ return image_infos
115
+
116
+
117
+ class VideoDataset:
118
+ @staticmethod
119
+ def _load_videos(
120
+ video_data_manifest_file_path: Optional[str],
121
+ video_info_file_path: str,
122
+ multithreaded_io: bool,
123
+ dataset_type: VideoDatasetType,
124
+ ) -> Dict[str, Video]:
125
+ video_infos: Dict[str, VideoInfo] = load_dataclass_dict_from_csv(
126
+ video_info_file_path, VideoInfo, "video_id"
127
+ )
128
+ if dataset_type == VideoDatasetType.Frame:
129
+ return VideoDataset._load_frame_videos(
130
+ video_data_manifest_file_path, video_infos, multithreaded_io
131
+ )
132
+ elif dataset_type == VideoDatasetType.EncodedVideo:
133
+ return VideoDataset._load_encoded_videos(
134
+ video_data_manifest_file_path, video_infos
135
+ )
136
+
137
+ @staticmethod
138
+ def _load_frame_videos(
139
+ frame_manifest_file_path: str,
140
+ video_infos: Dict[str, VideoInfo],
141
+ multithreaded_io: bool,
142
+ ):
143
+ video_frames: Dict[str, VideoFrameInfo] = load_dataclass_dict_from_csv(
144
+ frame_manifest_file_path, VideoFrameInfo, "video_id"
145
+ )
146
+ VideoDataset._remove_video_info_missing_or_incomplete_videos(
147
+ video_frames, video_infos
148
+ )
149
+ return {
150
+ video_id: FrameVideo(
151
+ video_frame_paths=VideoDataset._frame_number_to_filepaths(
152
+ video_id, video_frames, video_infos
153
+ ),
154
+ duration=video_infos[video_id].duration,
155
+ fps=video_infos[video_id].fps,
156
+ multithreaded_io=multithreaded_io,
157
+ )
158
+ for video_id in video_infos
159
+ }
160
+
161
+ @staticmethod
162
+ def _load_encoded_videos(
163
+ encoded_video_manifest_file_path: str,
164
+ video_infos: Dict[str, VideoInfo],
165
+ ):
166
+ encoded_video_infos: Dict[str, EncodedVideoInfo] = load_dataclass_dict_from_csv(
167
+ encoded_video_manifest_file_path, EncodedVideoInfo, "video_id"
168
+ )
169
+ VideoDataset._remove_video_info_missing_or_incomplete_videos(
170
+ encoded_video_infos, video_infos
171
+ )
172
+
173
+ return {
174
+ video_id: EncodedVideo.from_path(encoded_video_info.file_path)
175
+ for video_id, encoded_video_info in encoded_video_infos.items()
176
+ }
177
+
178
+ @staticmethod
179
+ def _frame_number_to_filepaths(
180
+ video_id: str,
181
+ video_frames: Dict[str, VideoFrameInfo],
182
+ video_infos: Dict[str, VideoInfo],
183
+ ) -> Optional[str]:
184
+ video_info = video_infos[video_id]
185
+ video_frame_info = video_frames[video_info.video_id]
186
+
187
+ frame_filepaths = []
188
+ num_frames = (
189
+ video_frame_info.max_frame_number - video_frame_info.min_frame_number + 1
190
+ )
191
+ for frame_index in range(num_frames):
192
+ frame_number = frame_index + video_frame_info.min_frame_number
193
+ if (
194
+ frame_number < video_frame_info.min_frame_number
195
+ or frame_number > video_frame_info.max_frame_number
196
+ ):
197
+ return None
198
+
199
+ frame_path_index = str(frame_number)
200
+ frame_prefix = video_frame_info.frame_file_stem
201
+ num_zero_pad = (
202
+ video_frame_info.frame_string_length
203
+ - len(frame_path_index)
204
+ - len(frame_prefix)
205
+ )
206
+ zero_padding = "0" * num_zero_pad
207
+ frame_component = (
208
+ f"{frame_prefix}{zero_padding}{frame_path_index}"
209
+ f".{video_frame_info.file_extension}"
210
+ )
211
+ frame_filepaths.append(f"{video_frame_info.location}/{frame_component}")
212
+ return frame_filepaths
213
+
214
+ @staticmethod
215
+ def _remove_video_info_missing_or_incomplete_videos(
216
+ video_data_infos: Dict[str, Union[VideoFrameInfo, EncodedVideoInfo]],
217
+ video_infos: Dict[str, VideoInfo],
218
+ ) -> None:
219
+ # Avoid deletion keys from dict during iteration over keys
220
+ video_ids = list(video_infos)
221
+ for video_id in video_ids:
222
+ video_info = video_infos[video_id]
223
+
224
+ # Remove videos we have metadata for but don't have video data
225
+ if video_id not in video_data_infos:
226
+ del video_infos[video_id]
227
+ continue
228
+
229
+ # Remove videos we have metadata for but don't have the right number of frames
230
+ if type(video_data_infos[video_id]) == VideoFrameInfo:
231
+ video_frames_info = video_data_infos[video_id]
232
+ expected_frames = round(video_info.duration * video_info.fps)
233
+ num_frames = (
234
+ video_frames_info.max_frame_number
235
+ - video_frames_info.min_frame_number
236
+ )
237
+ if abs(num_frames - expected_frames) > video_info.fps:
238
+ del video_data_infos[video_id]
239
+ del video_infos[video_id]
240
+
241
+ video_ids = list(video_data_infos) # Avoid modifying dict during iteration
242
+ for video_id in video_ids:
243
+ # Remove videos we have video data for but don't have metadata
244
+ if video_id not in video_infos:
245
+ del video_data_infos[video_id]
246
+
247
+
248
+ def get_seconds_from_hms_time(time_str: str) -> float:
249
+ """
250
+ Get Seconds from timestamp of form 'HH:MM:SS'.
251
+
252
+ Args:
253
+ time_str (str)
254
+
255
+ Returns:
256
+ float of seconds
257
+
258
+ """
259
+ for fmt in ("%H:%M:%S.%f", "%H:%M:%S"):
260
+ try:
261
+ time_since_min_time = datetime.datetime.strptime(time_str, fmt)
262
+ min_time = datetime.datetime.strptime("", "")
263
+ return float((time_since_min_time - min_time).total_seconds())
264
+ except ValueError:
265
+ pass
266
+ raise ValueError(f"No valid data format found for provided string {time_str}.")
267
+
268
+
269
+ def save_encoded_video_manifest(
270
+ encoded_video_infos: Dict[str, EncodedVideoInfo], file_name: str = None
271
+ ) -> str:
272
+ """
273
+ Saves the encoded video dictionary as a csv file that can be read for future usage.
274
+
275
+ Args:
276
+ video_frames (Dict[str, EncodedVideoInfo]):
277
+ Dictionary mapping video_ids to metadata about the location of
278
+ their video data.
279
+
280
+ file_name (str):
281
+ location to save file (will be automatically generated if None).
282
+
283
+ Returns:
284
+ string of the filename where the video info is stored.
285
+ """
286
+ file_name = (
287
+ f"{os.getcwd()}/encoded_video_manifest.csv" if file_name is None else file_name
288
+ )
289
+ save_dataclass_objs_to_headered_csv(list(encoded_video_infos.values()), file_name)
290
+ return file_name
291
+
292
+
293
+ def save_video_frame_info(
294
+ video_frames: Dict[str, VideoFrameInfo], file_name: str = None
295
+ ) -> str:
296
+ """
297
+ Saves the video frame dictionary as a csv file that can be read for future usage.
298
+
299
+ Args:
300
+ video_frames (Dict[str, VideoFrameInfo]):
301
+ Dictionary mapping video_ids to metadata about the location of
302
+ their video frame files.
303
+
304
+ file_name (str):
305
+ location to save file (will be automatically generated if None).
306
+
307
+ Returns:
308
+ string of the filename where the video info is stored.
309
+ """
310
+ file_name = (
311
+ f"{os.getcwd()}/video_frame_metadata.csv" if file_name is None else file_name
312
+ )
313
+ save_dataclass_objs_to_headered_csv(list(video_frames.values()), file_name)
314
+ return file_name
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/decoder.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+ from enum import Enum
3
+
4
+
5
+ class DecoderType(Enum):
6
+ PYAV = "pyav"
7
+ TORCHVISION = "torchvision"
8
+ DECORD = "decord"
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/ego4d/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from .ego4d_dataset import Ego4dMomentsDataset
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import io
4
+ import logging
5
+ import pathlib
6
+ from typing import Any, Dict
7
+
8
+ from iopath.common.file_io import g_pathmgr
9
+ from ib_sync_rewards.imagebind.pytorchvideo.data.decoder import DecoderType
10
+
11
+ from .video import Video
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def select_video_class(decoder: str) -> Video:
18
+ """
19
+ Select the class for accessing clips based on provided decoder string
20
+
21
+ Args:
22
+ decoder (str): Defines what type of decoder used to decode a video.
23
+ """
24
+ if DecoderType(decoder) == DecoderType.PYAV:
25
+ from .encoded_video_pyav import EncodedVideoPyAV
26
+
27
+ video_cls = EncodedVideoPyAV
28
+ elif DecoderType(decoder) == DecoderType.TORCHVISION:
29
+ from .encoded_video_torchvision import EncodedVideoTorchVision
30
+
31
+ video_cls = EncodedVideoTorchVision
32
+ elif DecoderType(decoder) == DecoderType.DECORD:
33
+ from .encoded_video_decord import EncodedVideoDecord
34
+
35
+ video_cls = EncodedVideoDecord
36
+ else:
37
+ raise NotImplementedError(f"Unknown decoder type {decoder}")
38
+
39
+ return video_cls
40
+
41
+
42
+ class EncodedVideo(Video):
43
+ """
44
+ EncodedVideo is an abstraction for accessing clips from an encoded video.
45
+ It supports selective decoding when header information is available.
46
+ """
47
+
48
+ @classmethod
49
+ def from_path(
50
+ cls,
51
+ file_path: str,
52
+ decode_video: bool = True,
53
+ decode_audio: bool = True,
54
+ decoder: str = "pyav",
55
+ **other_args: Dict[str, Any],
56
+ ):
57
+ """
58
+ Fetches the given video path using PathManager (allowing remote uris to be
59
+ fetched) and constructs the EncodedVideo object.
60
+
61
+ Args:
62
+ file_path (str): a PathManager file-path.
63
+ """
64
+ # We read the file with PathManager so that we can read from remote uris.
65
+ with g_pathmgr.open(file_path, "rb") as fh:
66
+ video_file = io.BytesIO(fh.read())
67
+
68
+ video_cls = select_video_class(decoder)
69
+ return video_cls(
70
+ file=video_file,
71
+ video_name=pathlib.Path(file_path).name,
72
+ decode_video=decode_video,
73
+ decode_audio=decode_audio,
74
+ **other_args,
75
+ )
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_decord.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import logging
4
+ import math
5
+ from typing import BinaryIO, Dict, Optional, TypeVar
6
+
7
+ import torch
8
+
9
+ from .utils import thwc_to_cthw
10
+ from .video import Video
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ try:
16
+ import decord
17
+ except ImportError:
18
+ _HAS_DECORD = False
19
+ else:
20
+ _HAS_DECORD = True
21
+
22
+ if _HAS_DECORD:
23
+ decord.bridge.set_bridge("torch")
24
+
25
+ DecordDevice = TypeVar("DecordDevice")
26
+
27
+
28
+ class EncodedVideoDecord(Video):
29
+ """
30
+
31
+ Accessing clips from an encoded video using Decord video reading API
32
+ as the decoding backend. For more details, please refer to -
33
+ `Decord <https://github.com/dmlc/decord>`
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ file: BinaryIO,
39
+ video_name: Optional[str] = None,
40
+ decode_video: bool = True,
41
+ decode_audio: bool = True,
42
+ sample_rate: int = 44100,
43
+ mono: bool = True,
44
+ width: int = -1,
45
+ height: int = -1,
46
+ num_threads: int = 0,
47
+ fault_tol: int = -1,
48
+ ) -> None:
49
+ """
50
+ Args:
51
+ file (BinaryIO): a file-like object (e.g. io.BytesIO or io.StringIO) that
52
+ contains the encoded video.
53
+ video_name (str): An optional name assigned to the video.
54
+ decode_video (bool): If disabled, video is not decoded.
55
+ decode_audio (bool): If disabled, audio is not decoded.
56
+ sample_rate: int, default is -1
57
+ Desired output sample rate of the audio, unchanged if `-1` is specified.
58
+ mono: bool, default is True
59
+ Desired output channel layout of the audio. `True` is mono layout. `False`
60
+ is unchanged.
61
+ width : int, default is -1
62
+ Desired output width of the video, unchanged if `-1` is specified.
63
+ height : int, default is -1
64
+ Desired output height of the video, unchanged if `-1` is specified.
65
+ num_threads : int, default is 0
66
+ Number of decoding thread, auto if `0` is specified.
67
+ fault_tol : int, default is -1
68
+ The threshold of corupted and recovered frames. This is to prevent silent fault
69
+ tolerance when for example 50% frames of a video cannot be decoded and duplicate
70
+ frames are returned. You may find the fault tolerant feature sweet in many
71
+ cases, but not for training models. Say `N = # recovered frames`
72
+ If `fault_tol` < 0, nothing will happen.
73
+ If 0 < `fault_tol` < 1.0, if N > `fault_tol * len(video)`,
74
+ raise `DECORDLimitReachedError`.
75
+ If 1 < `fault_tol`, if N > `fault_tol`, raise `DECORDLimitReachedError`.
76
+ """
77
+ if not decode_video:
78
+ raise NotImplementedError()
79
+
80
+ self._decode_audio = decode_audio
81
+ self._video_name = video_name
82
+ if not _HAS_DECORD:
83
+ raise ImportError(
84
+ "decord is required to use EncodedVideoDecord decoder. Please "
85
+ "install with 'pip install decord' for CPU-only version and refer to"
86
+ "'https://github.com/dmlc/decord' for GPU-supported version"
87
+ )
88
+ try:
89
+ if self._decode_audio:
90
+ self._av_reader = decord.AVReader(
91
+ uri=file,
92
+ ctx=decord.cpu(0),
93
+ sample_rate=sample_rate,
94
+ mono=mono,
95
+ width=width,
96
+ height=height,
97
+ num_threads=num_threads,
98
+ fault_tol=fault_tol,
99
+ )
100
+ else:
101
+ self._av_reader = decord.VideoReader(
102
+ uri=file,
103
+ ctx=decord.cpu(0),
104
+ width=width,
105
+ height=height,
106
+ num_threads=num_threads,
107
+ fault_tol=fault_tol,
108
+ )
109
+ except Exception as e:
110
+ raise RuntimeError(f"Failed to open video {video_name} with Decord. {e}")
111
+
112
+ if self._decode_audio:
113
+ self._fps = self._av_reader._AVReader__video_reader.get_avg_fps()
114
+ else:
115
+ self._fps = self._av_reader.get_avg_fps()
116
+
117
+ self._duration = float(len(self._av_reader)) / float(self._fps)
118
+
119
+ @property
120
+ def name(self) -> Optional[str]:
121
+ """
122
+ Returns:
123
+ name: the name of the stored video if set.
124
+ """
125
+ return self._video_name
126
+
127
+ @property
128
+ def duration(self) -> float:
129
+ """
130
+ Returns:
131
+ duration: the video's duration/end-time in seconds.
132
+ """
133
+ return self._duration
134
+
135
+ def close(self):
136
+ if self._av_reader is not None:
137
+ del self._av_reader
138
+ self._av_reader = None
139
+
140
+ def get_clip(
141
+ self, start_sec: float, end_sec: float
142
+ ) -> Dict[str, Optional[torch.Tensor]]:
143
+ """
144
+ Retrieves frames from the encoded video at the specified start and end times
145
+ in seconds (the video always starts at 0 seconds).
146
+
147
+ Args:
148
+ start_sec (float): the clip start time in seconds
149
+ end_sec (float): the clip end time in seconds
150
+ Returns:
151
+ clip_data:
152
+ A dictionary mapping the entries at "video" and "audio" to a tensors.
153
+
154
+ "video": A tensor of the clip's RGB frames with shape:
155
+ (channel, time, height, width). The frames are of type torch.float32 and
156
+ in the range [0 - 255].
157
+
158
+ "audio": A tensor of the clip's audio samples with shape:
159
+ (samples). The samples are of type torch.float32 and
160
+ in the range [0 - 255].
161
+
162
+ Returns None if no video or audio found within time range.
163
+
164
+ """
165
+ if start_sec > end_sec or start_sec > self._duration:
166
+ raise RuntimeError(
167
+ f"Incorrect time window for Decord decoding for video: {self._video_name}."
168
+ )
169
+
170
+ start_idx = math.ceil(self._fps * start_sec)
171
+ end_idx = math.ceil(self._fps * end_sec)
172
+ end_idx = min(end_idx, len(self._av_reader))
173
+ frame_idxs = list(range(start_idx, end_idx))
174
+ audio = None
175
+
176
+ try:
177
+ outputs = self._av_reader.get_batch(frame_idxs)
178
+ except Exception as e:
179
+ logger.debug(f"Failed to decode video with Decord: {self._video_name}. {e}")
180
+ raise e
181
+
182
+ if self._decode_audio:
183
+ audio, video = outputs
184
+ if audio is not None:
185
+ audio = list(audio)
186
+ audio = torch.cat(audio, dim=1)
187
+ audio = torch.flatten(audio)
188
+ audio = audio.to(torch.float32)
189
+ else:
190
+ video = outputs
191
+
192
+ if video is not None:
193
+ video = video.to(torch.float32)
194
+ video = thwc_to_cthw(video)
195
+
196
+ return {
197
+ "video": video,
198
+ "audio": audio,
199
+ }
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_pyav.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import logging
4
+ import math
5
+ from fractions import Fraction
6
+ from typing import BinaryIO, Dict, List, Optional, Tuple, Union
7
+
8
+ import av
9
+ import numpy as np
10
+ import torch
11
+ from pytorchvideo.data.encoded_video import EncodedVideo
12
+
13
+ from .utils import pts_to_secs, secs_to_pts, thwc_to_cthw
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class EncodedVideoPyAV(EncodedVideo):
20
+ """
21
+ EncodedVideoPyAV is an abstraction for accessing clips from an encoded video using
22
+ PyAV as the decoding backend. It supports selective decoding when header information
23
+ is available.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ file: BinaryIO,
29
+ video_name: Optional[str] = None,
30
+ decode_video: bool = True,
31
+ decode_audio: bool = True,
32
+ perform_seek: bool = True,
33
+ ) -> None:
34
+ """
35
+ Args:
36
+ file (BinaryIO): a file-like object (e.g. io.BytesIO or io.StringIO) that
37
+ contains the encoded video.
38
+ perform_seek:
39
+ Whether or not to seek time to the underlying video container.
40
+
41
+ NOTE: seeks may be slow on larger files, e.g. on a networked filesystem
42
+ """
43
+ self.perform_seek = perform_seek
44
+ self._video_name = video_name
45
+ self._decode_video = decode_video
46
+ self._decode_audio = decode_audio
47
+
48
+ try:
49
+ self._container = av.open(file)
50
+ except Exception as e:
51
+ raise RuntimeError(f"Failed to open video {video_name}. {e}")
52
+
53
+ if self._container is None or len(self._container.streams.video) == 0:
54
+ raise RuntimeError(f"Video stream not found {video_name}")
55
+
56
+ # Retrieve video header information if available.
57
+ video_stream = self._container.streams.video[0]
58
+ self._video_time_base = video_stream.time_base
59
+ self._video_start_pts = video_stream.start_time
60
+ if self._video_start_pts is None:
61
+ self._video_start_pts = 0.0
62
+
63
+ video_duration = video_stream.duration
64
+
65
+ # Retrieve audio header information if available.
66
+ audio_duration = None
67
+ self._has_audio = None
68
+ if self._decode_audio:
69
+ self._has_audio = self._container.streams.audio
70
+ if self._has_audio:
71
+ self._audio_time_base = self._container.streams.audio[0].time_base
72
+ self._audio_start_pts = self._container.streams.audio[0].start_time
73
+ if self._audio_start_pts is None:
74
+ self._audio_start_pts = 0.0
75
+
76
+ audio_duration = self._container.streams.audio[0].duration
77
+
78
+ # If duration isn't found in header the whole video is decoded to
79
+ # determine the duration.
80
+ self._video, self._audio, self._selective_decoding = (None, None, True)
81
+ if audio_duration is None and video_duration is None:
82
+ self._selective_decoding = False
83
+ self._video, self._audio = self._pyav_decode_video()
84
+ if self._video is None:
85
+ raise RuntimeError("Unable to decode video stream")
86
+
87
+ video_duration = self._video[-1][1]
88
+ if self._audio is not None:
89
+ audio_duration = self._audio[-1][1]
90
+
91
+ # Take the largest duration of either video or duration stream.
92
+ if audio_duration is not None and video_duration is not None:
93
+ self._duration = max(
94
+ pts_to_secs(
95
+ video_duration, self._video_time_base, self._video_start_pts
96
+ ),
97
+ pts_to_secs(
98
+ audio_duration, self._audio_time_base, self._audio_start_pts
99
+ ),
100
+ )
101
+ elif video_duration is not None:
102
+ self._duration = pts_to_secs(
103
+ video_duration, self._video_time_base, self._video_start_pts
104
+ )
105
+
106
+ elif audio_duration is not None:
107
+ self._duration = pts_to_secs(
108
+ audio_duration, self._audio_time_base, self._audio_start_pts
109
+ )
110
+
111
+ @property
112
+ def rate(self) -> Union[str, Fraction]:
113
+ """
114
+ Returns:
115
+ rate: the frame rate of the video
116
+ """
117
+ return self._container.streams.video[0].rate
118
+
119
+ @property
120
+ def bit_rate(self) -> int:
121
+ """
122
+ Returns:
123
+ bit_rate: the bit rate of the underlying video
124
+ """
125
+ return self._container.streams.video[0].bit_rate
126
+
127
+ @property
128
+ def pix_fmt(self) -> int:
129
+ """
130
+ Returns:
131
+ pix_fmt: the pixel format of the underlying video
132
+ """
133
+ return self._container.streams.video[0].pix_fmt
134
+
135
+ @property
136
+ def name(self) -> Optional[str]:
137
+ """
138
+ Returns:
139
+ name: the name of the stored video if set.
140
+ """
141
+ return self._video_name
142
+
143
+ @property
144
+ def duration(self) -> float:
145
+ """
146
+ Returns:
147
+ duration: the video's duration/end-time in seconds.
148
+ """
149
+ return self._duration
150
+
151
+ def get_clip(
152
+ self, start_sec: float, end_sec: float
153
+ ) -> Dict[str, Optional[torch.Tensor]]:
154
+ """
155
+ Retrieves frames from the encoded video at the specified start and end times
156
+ in seconds (the video always starts at 0 seconds). Returned frames will be in
157
+ [start_sec, end_sec). Note that 1) if you want to avoid float precision issue
158
+ and need accurate frames, please use Fraction for start_sec and end_sec.
159
+ 2) As end_sec is exclusive, so you may need to use
160
+ `get_clip(start_sec, duration + EPS)` to get the last frame.
161
+
162
+ Args:
163
+ start_sec (float): the clip start time in seconds
164
+ end_sec (float): the clip end time in seconds
165
+ Returns:
166
+ clip_data:
167
+ A dictionary mapping the entries at "video" and "audio" to a tensors.
168
+
169
+ "video": A tensor of the clip's RGB frames with shape:
170
+ (channel, time, height, width). The frames are of type torch.float32 and
171
+ in the range [0 - 255].
172
+
173
+ "audio": A tensor of the clip's audio samples with shape:
174
+ (samples). The samples are of type torch.float32 and
175
+ in the range [0 - 255].
176
+
177
+ Returns None if no video or audio found within time range.
178
+
179
+ """
180
+ if self._selective_decoding:
181
+ self._video, self._audio = self._pyav_decode_video(start_sec, end_sec)
182
+
183
+ video_frames = None
184
+ if self._video is not None:
185
+ video_start_pts = secs_to_pts(
186
+ start_sec,
187
+ self._video_time_base,
188
+ self._video_start_pts,
189
+ round_mode="ceil",
190
+ )
191
+ video_end_pts = secs_to_pts(
192
+ end_sec,
193
+ self._video_time_base,
194
+ self._video_start_pts,
195
+ round_mode="ceil",
196
+ )
197
+
198
+ video_frames = [
199
+ f
200
+ for f, pts in self._video
201
+ if pts >= video_start_pts and pts < video_end_pts
202
+ ]
203
+
204
+ audio_samples = None
205
+ if self._has_audio and self._audio is not None:
206
+ audio_start_pts = secs_to_pts(
207
+ start_sec,
208
+ self._audio_time_base,
209
+ self._audio_start_pts,
210
+ round_mode="ceil",
211
+ )
212
+ audio_end_pts = secs_to_pts(
213
+ end_sec,
214
+ self._audio_time_base,
215
+ self._audio_start_pts,
216
+ round_mode="ceil",
217
+ )
218
+ audio_samples = [
219
+ f
220
+ for f, pts in self._audio
221
+ if pts >= audio_start_pts and pts < audio_end_pts
222
+ ]
223
+ audio_samples = torch.cat(audio_samples, axis=0)
224
+ audio_samples = audio_samples.to(torch.float32)
225
+
226
+ if video_frames is None or len(video_frames) == 0:
227
+ logger.debug(
228
+ f"No video found within {start_sec} and {end_sec} seconds. "
229
+ f"Video starts at time 0 and ends at {self.duration}."
230
+ )
231
+
232
+ video_frames = None
233
+
234
+ if video_frames is not None:
235
+ video_frames = thwc_to_cthw(torch.stack(video_frames)).to(torch.float32)
236
+
237
+ return {
238
+ "video": video_frames,
239
+ "audio": audio_samples,
240
+ }
241
+
242
+ def close(self):
243
+ """
244
+ Closes the internal video container.
245
+ """
246
+ if self._container is not None:
247
+ self._container.close()
248
+
249
+ def _pyav_decode_video(
250
+ self, start_secs: float = 0.0, end_secs: float = math.inf
251
+ ) -> float:
252
+ """
253
+ Selectively decodes a video between start_pts and end_pts in time units of the
254
+ self._video's timebase.
255
+ """
256
+ video_and_pts = None
257
+ audio_and_pts = None
258
+ try:
259
+ if self._decode_video:
260
+ pyav_video_frames, _ = _pyav_decode_stream(
261
+ self._container,
262
+ secs_to_pts(
263
+ start_secs,
264
+ self._video_time_base,
265
+ self._video_start_pts,
266
+ round_mode="ceil",
267
+ ),
268
+ secs_to_pts(
269
+ end_secs,
270
+ self._video_time_base,
271
+ self._video_start_pts,
272
+ round_mode="ceil",
273
+ ),
274
+ self._container.streams.video[0],
275
+ {"video": 0},
276
+ perform_seek=self.perform_seek,
277
+ )
278
+ if len(pyav_video_frames) > 0:
279
+ video_and_pts = [
280
+ (torch.from_numpy(frame.to_rgb().to_ndarray()), frame.pts)
281
+ for frame in pyav_video_frames
282
+ ]
283
+
284
+ if self._has_audio:
285
+ pyav_audio_frames, _ = _pyav_decode_stream(
286
+ self._container,
287
+ secs_to_pts(
288
+ start_secs,
289
+ self._audio_time_base,
290
+ self._audio_start_pts,
291
+ round_mode="ceil",
292
+ ),
293
+ secs_to_pts(
294
+ end_secs,
295
+ self._audio_time_base,
296
+ self._audio_start_pts,
297
+ round_mode="ceil",
298
+ ),
299
+ self._container.streams.audio[0],
300
+ {"audio": 0},
301
+ perform_seek=self.perform_seek,
302
+ )
303
+
304
+ if len(pyav_audio_frames) > 0:
305
+ audio_and_pts = [
306
+ (
307
+ torch.from_numpy(np.mean(frame.to_ndarray(), axis=0)),
308
+ frame.pts,
309
+ )
310
+ for frame in pyav_audio_frames
311
+ ]
312
+
313
+ except Exception as e:
314
+ logger.debug(f"Failed to decode video: {self._video_name}. {e}")
315
+
316
+ return video_and_pts, audio_and_pts
317
+
318
+
319
+ def _pyav_decode_stream(
320
+ container: av.container.input.InputContainer,
321
+ start_pts: int,
322
+ end_pts: int,
323
+ stream: av.video.stream.VideoStream,
324
+ stream_name: dict,
325
+ buffer_size: int = 0,
326
+ perform_seek: bool = True,
327
+ ) -> Tuple[List, float]:
328
+ """
329
+ Decode the video with PyAV decoder.
330
+ Args:
331
+ container (container): PyAV container.
332
+ start_pts (int): the starting Presentation TimeStamp to fetch the
333
+ video frames.
334
+ end_pts (int): the ending Presentation TimeStamp of the decoded frames.
335
+ stream (stream): PyAV stream.
336
+ stream_name (dict): a dictionary of streams. For example, {"video": 0}
337
+ means video stream at stream index 0.
338
+ Returns:
339
+ result (list): list of decoded frames.
340
+ max_pts (int): max Presentation TimeStamp of the video sequence.
341
+ """
342
+
343
+ # Seeking in the stream is imprecise. Thus, seek to an earlier pts by a
344
+ # margin pts.
345
+ margin = 1024
346
+
347
+ # NOTE:
348
+ # Don't want to seek if iterating through a video due to slow-downs. I
349
+ # believe this is some PyAV bug where seeking after a certain point causes
350
+ # major slow-downs
351
+ if perform_seek:
352
+ seek_offset = max(start_pts - margin, 0)
353
+ container.seek(int(seek_offset), any_frame=False, backward=True, stream=stream)
354
+ frames = {}
355
+ max_pts = 0
356
+ for frame in container.decode(**stream_name):
357
+ max_pts = max(max_pts, frame.pts)
358
+ if frame.pts >= start_pts and frame.pts < end_pts:
359
+ frames[frame.pts] = frame
360
+ elif frame.pts >= end_pts:
361
+ break
362
+
363
+ result = [frames[pts] for pts in sorted(frames)]
364
+ return result, max_pts
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/encoded_video_torchvision.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import logging
4
+ from fractions import Fraction
5
+ from typing import BinaryIO, Dict, Optional
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from .utils import pts_to_secs, secs_to_pts, thwc_to_cthw
11
+ from .video import Video
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class EncodedVideoTorchVision(Video):
18
+ """
19
+
20
+ Accessing clips from an encoded video using Torchvision video reading API
21
+ (torch.ops.video_reader.read_video_from_memory) as the decoding backend.
22
+ """
23
+
24
+ """
25
+ av_seek_frame is imprecise so seek to a timestamp earlier by a margin
26
+ The unit of margin is second
27
+ """
28
+ SEEK_FRAME_MARGIN = 0.25
29
+
30
+ def __init__(
31
+ self,
32
+ file: BinaryIO,
33
+ video_name: Optional[str] = None,
34
+ decode_video: bool = True,
35
+ decode_audio: bool = True,
36
+ ) -> None:
37
+ if not decode_video:
38
+ raise NotImplementedError()
39
+
40
+ self._video_tensor = torch.tensor(
41
+ np.frombuffer(file.getvalue(), dtype=np.uint8)
42
+ )
43
+ self._video_name = video_name
44
+ self._decode_audio = decode_audio
45
+
46
+ (
47
+ self._video,
48
+ self._video_time_base,
49
+ self._video_start_pts,
50
+ video_duration,
51
+ self._audio,
52
+ self._audio_time_base,
53
+ self._audio_start_pts,
54
+ audio_duration,
55
+ ) = self._torch_vision_decode_video()
56
+
57
+ # Take the largest duration of either video or duration stream.
58
+ if audio_duration is not None and video_duration is not None:
59
+ self._duration = max(
60
+ pts_to_secs(
61
+ video_duration, self._video_time_base, self._video_start_pts
62
+ ),
63
+ pts_to_secs(
64
+ audio_duration, self._audio_time_base, self._audio_start_pts
65
+ ),
66
+ )
67
+ elif video_duration is not None:
68
+ self._duration = pts_to_secs(
69
+ video_duration, self._video_time_base, self._video_start_pts
70
+ )
71
+
72
+ elif audio_duration is not None:
73
+ self._duration = pts_to_secs(
74
+ audio_duration, self._audio_time_base, self._audio_start_pts
75
+ )
76
+
77
+ @property
78
+ def name(self) -> Optional[str]:
79
+ """
80
+ Returns:
81
+ name: the name of the stored video if set.
82
+ """
83
+ return self._video_name
84
+
85
+ @property
86
+ def duration(self) -> float:
87
+ """
88
+ Returns:
89
+ duration: the video's duration/end-time in seconds.
90
+ """
91
+ return self._duration
92
+
93
+ def close(self):
94
+ pass
95
+
96
+ def get_clip(
97
+ self, start_sec: float, end_sec: float
98
+ ) -> Dict[str, Optional[torch.Tensor]]:
99
+ """
100
+ Retrieves frames from the encoded video at the specified start and end times
101
+ in seconds (the video always starts at 0 seconds). Returned frames will be in
102
+ [start_sec, end_sec). Note that 1) if you want to avoid float precision issue
103
+ and need accurate frames, please use Fraction for start_sec and end_sec.
104
+ 2) As end_sec is exclusive, so you may need to use
105
+ `get_clip(start_sec, duration + EPS)` to get the last frame.
106
+
107
+ Args:
108
+ start_sec (float): the clip start time in seconds
109
+ end_sec (float): the clip end time in seconds
110
+ Returns:
111
+ clip_data:
112
+ A dictionary mapping the entries at "video" and "audio" to a tensors.
113
+
114
+ "video": A tensor of the clip's RGB frames with shape:
115
+ (channel, time, height, width). The frames are of type torch.float32 and
116
+ in the range [0 - 255].
117
+
118
+ "audio": A tensor of the clip's audio samples with shape:
119
+ (samples). The samples are of type torch.float32 and
120
+ in the range [0 - 255].
121
+
122
+ Returns None if no video or audio found within time range.
123
+
124
+ """
125
+ video_frames = None
126
+ if self._video is not None:
127
+ video_start_pts = secs_to_pts(
128
+ start_sec,
129
+ self._video_time_base,
130
+ self._video_start_pts,
131
+ round_mode="ceil",
132
+ )
133
+ video_end_pts = secs_to_pts(
134
+ end_sec,
135
+ self._video_time_base,
136
+ self._video_start_pts,
137
+ round_mode="ceil",
138
+ )
139
+ video_frames = [
140
+ f
141
+ for f, pts in self._video
142
+ if pts >= video_start_pts and pts < video_end_pts
143
+ ]
144
+
145
+ audio_samples = None
146
+ if self._decode_audio and self._audio:
147
+ audio_start_pts = secs_to_pts(
148
+ start_sec,
149
+ self._audio_time_base,
150
+ self._audio_start_pts,
151
+ round_mode="ceil",
152
+ )
153
+ audio_end_pts = secs_to_pts(
154
+ end_sec,
155
+ self._audio_time_base,
156
+ self._audio_start_pts,
157
+ round_mode="ceil",
158
+ )
159
+ audio_samples = [
160
+ f
161
+ for f, pts in self._audio
162
+ if pts >= audio_start_pts and pts < audio_end_pts
163
+ ]
164
+ audio_samples = torch.cat(audio_samples, axis=0)
165
+ audio_samples = audio_samples.to(torch.float32)
166
+
167
+ if video_frames is None or len(video_frames) == 0:
168
+ logger.warning(
169
+ f"No video found within {start_sec} and {end_sec} seconds. "
170
+ f"Video starts at time 0 and ends at {self.duration}."
171
+ )
172
+
173
+ video_frames = None
174
+
175
+ if video_frames is not None:
176
+ video_frames = thwc_to_cthw(torch.stack(video_frames)).to(torch.float32)
177
+
178
+ return {
179
+ "video": video_frames,
180
+ "audio": audio_samples,
181
+ }
182
+
183
+ def _torch_vision_decode_video(
184
+ self, start_pts: int = 0, end_pts: int = -1
185
+ ) -> float:
186
+ """
187
+ Decode the video in the PTS range [start_pts, end_pts]
188
+ """
189
+ video_and_pts = None
190
+ audio_and_pts = None
191
+
192
+ width, height, min_dimension, max_dimension = 0, 0, 0, 0
193
+ video_start_pts, video_end_pts = start_pts, end_pts
194
+ video_timebase_num, video_timebase_den = 0, 1
195
+
196
+ samples, channels = 0, 0
197
+ audio_start_pts, audio_end_pts = start_pts, end_pts
198
+ audio_timebase_num, audio_timebase_den = 0, 1
199
+
200
+ try:
201
+ tv_result = torch.ops.video_reader.read_video_from_memory(
202
+ self._video_tensor,
203
+ self.SEEK_FRAME_MARGIN,
204
+ # Set getPtsOnly=0, i.e., read full video rather than just header
205
+ 0,
206
+ # Read video stream
207
+ 1,
208
+ width,
209
+ height,
210
+ min_dimension,
211
+ max_dimension,
212
+ video_start_pts,
213
+ video_end_pts,
214
+ video_timebase_num,
215
+ video_timebase_den,
216
+ # Read audio stream
217
+ self._decode_audio,
218
+ samples,
219
+ channels,
220
+ audio_start_pts,
221
+ audio_end_pts,
222
+ audio_timebase_num,
223
+ audio_timebase_den,
224
+ )
225
+ except Exception as e:
226
+ logger.warning(f"Failed to decode video of name {self._video_name}. {e}")
227
+ raise e
228
+
229
+ (
230
+ vframes,
231
+ vframes_pts,
232
+ vtimebase,
233
+ _,
234
+ vduration,
235
+ aframes,
236
+ aframe_pts,
237
+ atimebase,
238
+ _,
239
+ aduration,
240
+ ) = tv_result
241
+
242
+ if vduration < 0:
243
+ # No header information to infer video duration
244
+ video_duration = int(vframes_pts[-1])
245
+ else:
246
+ video_duration = int(vduration)
247
+
248
+ video_and_pts = list(zip(vframes, vframes_pts))
249
+ video_start_pts = int(vframes_pts[0])
250
+ video_time_base = Fraction(int(vtimebase[0]), int(vtimebase[1]))
251
+
252
+ audio_and_pts = None
253
+ audio_time_base = None
254
+ audio_start_pts = None
255
+ audio_duration = None
256
+ if self._decode_audio:
257
+ if aduration < 0:
258
+ # No header information to infer audio duration
259
+ audio_duration = int(aframe_pts[-1])
260
+ else:
261
+ audio_duration = int(aduration)
262
+
263
+ audio_and_pts = list(zip(aframes, aframe_pts))
264
+ audio_start_pts = int(aframe_pts[0])
265
+ audio_time_base = Fraction(int(atimebase[0]), int(atimebase[1]))
266
+
267
+ return (
268
+ video_and_pts,
269
+ video_time_base,
270
+ video_start_pts,
271
+ video_duration,
272
+ audio_and_pts,
273
+ audio_time_base,
274
+ audio_start_pts,
275
+ audio_duration,
276
+ )
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen/epic_kitchen_dataset.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import ast
4
+ from dataclasses import dataclass, fields as dataclass_fields
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ import torch
8
+ from ib_sync_rewards.imagebind.pytorchvideo.data.dataset_manifest_utils import (
9
+ EncodedVideoInfo,
10
+ get_seconds_from_hms_time,
11
+ VideoClipInfo,
12
+ VideoDataset,
13
+ VideoDatasetType,
14
+ VideoFrameInfo,
15
+ VideoInfo,
16
+ )
17
+ from ib_sync_rewards.imagebind.pytorchvideo.data.frame_video import FrameVideo
18
+ from ib_sync_rewards.imagebind.pytorchvideo.data.utils import DataclassFieldCaster, load_dataclass_dict_from_csv
19
+ from ib_sync_rewards.imagebind.pytorchvideo.data.video import Video
20
+
21
+
22
+ @dataclass
23
+ class ActionData(DataclassFieldCaster):
24
+ """
25
+ Class representing an action from the Epic Kitchen dataset.
26
+ """
27
+
28
+ participant_id: str
29
+ video_id: str
30
+ narration: str
31
+ start_timestamp: str
32
+ stop_timestamp: str
33
+ start_frame: int
34
+ stop_frame: int
35
+ verb: str
36
+ verb_class: int
37
+ noun: str
38
+ noun_class: int
39
+ all_nouns: list = DataclassFieldCaster.complex_initialized_dataclass_field(
40
+ ast.literal_eval
41
+ )
42
+ all_noun_classes: list = DataclassFieldCaster.complex_initialized_dataclass_field(
43
+ ast.literal_eval
44
+ )
45
+
46
+ @property
47
+ def start_time(self) -> float:
48
+ return get_seconds_from_hms_time(self.start_timestamp)
49
+
50
+ @property
51
+ def stop_time(self) -> float:
52
+ return get_seconds_from_hms_time(self.stop_timestamp)
53
+
54
+
55
+ class EpicKitchenDataset(torch.utils.data.Dataset):
56
+ """
57
+ Video dataset for EpicKitchen-55 Dataset
58
+ <https://epic-kitchens.github.io/2019/>
59
+
60
+ This dataset handles the loading, decoding, and configurable clip
61
+ sampling for the videos.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ video_info_file_path: str,
67
+ actions_file_path: str,
68
+ clip_sampler: Callable[
69
+ [Dict[str, Video], Dict[str, List[ActionData]]], List[VideoClipInfo]
70
+ ],
71
+ video_data_manifest_file_path: str,
72
+ dataset_type: VideoDatasetType = VideoDatasetType.Frame,
73
+ transform: Optional[Callable[[Dict[str, Any]], Any]] = None,
74
+ frame_filter: Optional[Callable[[List[int]], List[int]]] = None,
75
+ multithreaded_io: bool = True,
76
+ ) -> None:
77
+ f"""
78
+ Args:
79
+ video_info_file_path (str):
80
+ Path or URI to manifest with basic metadata of each video.
81
+ File must be a csv (w/header) with columns:
82
+ {[f.name for f in dataclass_fields(VideoInfo)]}
83
+
84
+ actions_file_path (str):
85
+ Path or URI to manifest with action annotations for each video.
86
+ File must ber a csv (w/header) with columns:
87
+ {[f.name for f in dataclass_fields(ActionData)]}
88
+
89
+ clip_sampler (Callable[[Dict[str, Video]], List[VideoClipInfo]]):
90
+ This callable takes as input all available videos and outputs a list of clips to
91
+ be loaded by the dataset.
92
+
93
+ video_data_manifest_file_path (str):
94
+ The path to a json file outlining the available video data for the
95
+ associated videos. File must be a csv (w/header) with columns:
96
+ {[f.name for f in dataclass_fields(VideoFrameInfo)]}
97
+
98
+ or
99
+ {[f.name for f in dataclass_fields(EncodedVideoInfo)]}
100
+
101
+ To generate this file from a directory of video frames, see helper
102
+ functions in Module: pytorchvideo.data.epic_kitchen.utils
103
+
104
+ dataset_type (VideoDatasetType): The dataformat in which dataset
105
+ video data is store (e.g. video frames, encoded video etc).
106
+
107
+ transform (Optional[Callable[[Dict[str, Any]], Any]]):
108
+ This callable is evaluated on the clip output before the clip is returned.
109
+ It can be used for user-defined preprocessing and augmentations to the clips.
110
+
111
+ The clip input is a dictionary with the following format:
112
+ {{
113
+ 'video': <video_tensor>,
114
+ 'audio': <audio_tensor>,
115
+ 'actions': <List[ActionData]>,
116
+ 'start_time': <float>,
117
+ 'stop_time': <float>
118
+ }}
119
+
120
+ If transform is None, the raw clip output in the above format is
121
+ returned unmodified.
122
+
123
+ frame_filter (Optional[Callable[[List[int]], List[int]]]):
124
+ This callable is evaluated on the set of available frame inidices to be
125
+ included in a sampled clip. This can be used to subselect frames within
126
+ a clip to be loaded.
127
+
128
+ multithreaded_io (bool):
129
+ Boolean to control whether parllelizable io operations are performed across
130
+ multiple threads.
131
+
132
+ """
133
+
134
+ torch._C._log_api_usage_once("PYTORCHVIDEO.dataset.EpicKitchenDataset.__init__")
135
+
136
+ assert video_info_file_path
137
+ assert actions_file_path
138
+ assert video_data_manifest_file_path
139
+ assert clip_sampler
140
+
141
+ # Populate video and metadata data providers
142
+ self._videos: Dict[str, Video] = VideoDataset._load_videos(
143
+ video_data_manifest_file_path,
144
+ video_info_file_path,
145
+ multithreaded_io,
146
+ dataset_type,
147
+ )
148
+
149
+ self._actions: Dict[str, List[ActionData]] = load_dataclass_dict_from_csv(
150
+ actions_file_path, ActionData, "video_id", list_per_key=True
151
+ )
152
+ # Sample datapoints
153
+ self._clips: List[VideoClipInfo] = clip_sampler(self._videos, self._actions)
154
+
155
+ self._transform = transform
156
+ self._frame_filter = frame_filter
157
+
158
+ def __getitem__(self, index) -> Dict[str, Any]:
159
+ """
160
+ Samples a video clip associated to the given index.
161
+
162
+ Args:
163
+ index (int): index for the video clip.
164
+
165
+ Returns:
166
+ A video clip with the following format if transform is None:
167
+ {{
168
+ 'video_id': <str>,
169
+ 'video': <video_tensor>,
170
+ 'audio': <audio_tensor>,
171
+ 'actions': <df[ActionData]>,
172
+ 'start_time': <float>,
173
+ 'stop_time': <float>
174
+ }}
175
+ Otherwise, the transform defines the clip output.
176
+ """
177
+ clip = self._clips[index]
178
+ video = self._videos[clip.video_id]
179
+
180
+ if isinstance(video, FrameVideo):
181
+ clip_dict = video.get_clip(
182
+ clip.start_time, clip.stop_time, self._frame_filter
183
+ )
184
+ else:
185
+ clip_dict = video.get_clip(clip.start_time, clip.stop_time)
186
+
187
+ clip_data = {
188
+ "video_id": clip.video_id,
189
+ **clip_dict,
190
+ "actions": self._actions[clip.video_id],
191
+ "start_time": clip.start_time,
192
+ "stop_time": clip.stop_time,
193
+ }
194
+
195
+ if self._transform:
196
+ clip_data = self._transform(clip_data)
197
+
198
+ return clip_data
199
+
200
+ def __len__(self) -> int:
201
+ """
202
+ Returns:
203
+ The number of video clips in the dataset.
204
+ """
205
+ return len(self._clips)
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen/utils.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Dict
4
+
5
+ from iopath.common.file_io import g_pathmgr
6
+ from ib_sync_rewards.imagebind.pytorchvideo.data.dataset_manifest_utils import EncodedVideoInfo, VideoFrameInfo
7
+ from ib_sync_rewards.imagebind.pytorchvideo.data.utils import optional_threaded_foreach
8
+
9
+
10
+ def build_frame_manifest_from_flat_directory(
11
+ data_directory_path: str, multithreaded: bool
12
+ ) -> Dict[str, VideoFrameInfo]:
13
+ """
14
+ Args:
15
+ data_directory_path (str): Path or URI to EpicKitchenDataset data.
16
+ Data at this path must be a folder of structure:
17
+ {
18
+ "{video_id}": [
19
+ "frame_{frame_number}.{file_extension}",
20
+ "frame_{frame_number}.{file_extension}",
21
+ "frame_{frame_number}.{file_extension}",
22
+ ...]
23
+ ...}
24
+ multithreaded (bool):
25
+ controls whether io operations are performed across multiple threads.
26
+
27
+ Returns:
28
+ Dictionary mapping video_id of available videos to the locations of their
29
+ underlying frame files.
30
+ """
31
+
32
+ video_frames = {}
33
+ video_ids = g_pathmgr.ls(str(data_directory_path))
34
+
35
+ def add_video_frames(video_id: str, video_path: str) -> None:
36
+ video_frame_file_names = sorted(g_pathmgr.ls(video_path))
37
+ for frame in video_frame_file_names:
38
+ file_extension = frame.split(".")[-1]
39
+ frame_name = frame[: -(len(file_extension) + 1)]
40
+ stem, path_frame_id = frame_name.split("_")
41
+ if video_id not in video_frames:
42
+ video_frames[video_id] = VideoFrameInfo(
43
+ video_id=video_id,
44
+ location=video_path,
45
+ frame_file_stem=f"{stem}_",
46
+ frame_string_length=len(frame_name),
47
+ min_frame_number=int(path_frame_id),
48
+ max_frame_number=int(path_frame_id),
49
+ file_extension=file_extension,
50
+ )
51
+ else:
52
+ video_frame_info = video_frames[video_id]
53
+ # Check that this new frame is of the same format as other frames for this video
54
+ # and that it is the next frame in order, if so update the frame info for this
55
+ # video to reflect there is an additional frame.
56
+ # We don't need to check video_id or frame_file_stem as they are function of
57
+ # video_id which is aligned within the dictionary
58
+ assert video_frame_info.frame_string_length == len(frame_name)
59
+ assert video_frame_info.location == video_path, (
60
+ f"Frames for {video_id} found in two paths: "
61
+ f"{video_frame_info.location} and {video_path}"
62
+ )
63
+ assert video_frame_info.max_frame_number + 1 == int(path_frame_id)
64
+ assert (
65
+ video_frame_info.file_extension == file_extension
66
+ ), f"Frames with two different file extensions found for video {video_id}"
67
+ video_frames[video_id] = VideoFrameInfo(
68
+ video_id=video_frame_info.video_id,
69
+ location=video_frame_info.location,
70
+ frame_file_stem=video_frame_info.frame_file_stem,
71
+ frame_string_length=video_frame_info.frame_string_length,
72
+ min_frame_number=video_frame_info.min_frame_number,
73
+ max_frame_number=int(path_frame_id), # Update
74
+ file_extension=video_frame_info.file_extension,
75
+ )
76
+
77
+ video_paths = [
78
+ (video_id, f"{data_directory_path}/{video_id}") for video_id in video_ids
79
+ ]
80
+ # Kick off frame indexing for all participants
81
+ optional_threaded_foreach(add_video_frames, video_paths, multithreaded)
82
+
83
+ return video_frames
84
+
85
+
86
+ def build_frame_manifest_from_nested_directory(
87
+ data_directory_path: str, multithreaded: bool
88
+ ) -> Dict[str, VideoFrameInfo]:
89
+ """
90
+ Args:
91
+ data_directory_path (str): Path or URI to EpicKitchenDataset data.
92
+ If this dataset is to load from the frame-based dataset:
93
+ Data at this path must be a folder of structure:
94
+ {
95
+ "{participant_id}" : [
96
+ "{participant_id}_{participant_video_id}_{frame_number}.{file_extension}",
97
+
98
+ ...],
99
+ ...}
100
+
101
+ multithreaded (bool):
102
+ controls whether io operations are performed across multiple threads.
103
+
104
+ Returns:
105
+ Dictionary mapping video_id of available videos to the locations of their
106
+ underlying frame files.
107
+ """
108
+
109
+ participant_ids = g_pathmgr.ls(str(data_directory_path))
110
+ video_frames = {}
111
+
112
+ # Create function to execute in parallel that lists files available for each participant
113
+ def add_participant_video_frames(
114
+ participant_id: str, participant_path: str
115
+ ) -> None:
116
+ participant_frames = sorted(g_pathmgr.ls(str(participant_path)))
117
+ for frame_file_name in participant_frames:
118
+ file_extension = frame_file_name.split(".")[-1]
119
+ frame_name = frame_file_name[: -(len(file_extension) + 1)]
120
+ [path_participant_id, path_video_id, path_frame_id] = frame_name.split("_")
121
+ assert path_participant_id == participant_id
122
+ video_id = f"{path_participant_id}_{path_video_id}"
123
+ if (
124
+ video_id not in video_frames
125
+ ): # This is the first frame we have seen from video w/ video_id
126
+ video_frames[video_id] = VideoFrameInfo(
127
+ video_id=video_id,
128
+ location=participant_path,
129
+ frame_file_stem=f"{video_id}_",
130
+ frame_string_length=len(frame_name),
131
+ min_frame_number=int(path_frame_id),
132
+ max_frame_number=int(path_frame_id),
133
+ file_extension=file_extension,
134
+ )
135
+ else:
136
+ video_frame_info = video_frames[video_id]
137
+ # Check that this new frame is of the same format as other frames for this video
138
+ # and that it is the next frame in order, if so update the frame info for this
139
+ # video to reflect there is an additional frame.
140
+ # We don't need to check video_id or frame_file_stem as they are function of
141
+ # video_id which is aligned within the dictionary
142
+ assert video_frame_info.frame_string_length == len(frame_name)
143
+ assert video_frame_info.location == participant_path, (
144
+ f"Frames for {video_id} found in two paths: "
145
+ f"{video_frame_info.location} and {participant_path}"
146
+ )
147
+ assert video_frame_info.max_frame_number + 1 == int(path_frame_id)
148
+ assert (
149
+ video_frame_info.file_extension == file_extension
150
+ ), f"Frames with two different file extensions found for video {video_id}"
151
+ video_frames[video_id] = VideoFrameInfo(
152
+ video_id=video_frame_info.video_id,
153
+ location=video_frame_info.location,
154
+ frame_file_stem=video_frame_info.frame_file_stem,
155
+ frame_string_length=video_frame_info.frame_string_length,
156
+ min_frame_number=video_frame_info.min_frame_number,
157
+ max_frame_number=int(path_frame_id), # Update
158
+ file_extension=video_frame_info.file_extension,
159
+ )
160
+
161
+ particpant_paths = [
162
+ (participant_id, f"{data_directory_path}/{participant_id}")
163
+ for participant_id in participant_ids
164
+ ]
165
+ # Kick off frame indexing for all participants
166
+ optional_threaded_foreach(
167
+ add_participant_video_frames, particpant_paths, multithreaded
168
+ )
169
+
170
+ return video_frames
171
+
172
+
173
+ def build_encoded_manifest_from_nested_directory(
174
+ data_directory_path: str,
175
+ ) -> Dict[str, EncodedVideoInfo]:
176
+ """
177
+ Creates a dictionary from video_id to EncodedVideoInfo for
178
+ encoded videos in the given directory.
179
+
180
+ Args:
181
+ data_directory_path (str): The folder to ls to find encoded
182
+ video files.
183
+
184
+ Returns:
185
+ Dict[str, EncodedVideoInfo] mapping video_id to EncodedVideoInfo
186
+ for each file in 'data_directory_path'
187
+ """
188
+ encoded_video_infos = {}
189
+ for participant_id in g_pathmgr.ls(data_directory_path):
190
+ participant_folder_path = f"{data_directory_path}/{participant_id}"
191
+ for video_file_name in g_pathmgr.ls(participant_folder_path):
192
+ video_id = video_file_name[:6]
193
+ video_full_path = f"{participant_folder_path}/{video_file_name}"
194
+ encoded_video_infos[video_id] = EncodedVideoInfo(video_id, video_full_path)
195
+ return encoded_video_infos
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/epic_kitchen_forecasting.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from dataclasses import fields as dataclass_fields
4
+ from enum import Enum
5
+ from typing import Any, Callable, Dict, List, Optional
6
+
7
+ import torch
8
+ from ib_sync_rewards.imagebind.pytorchvideo.data.dataset_manifest_utils import (
9
+ EncodedVideoInfo,
10
+ VideoClipInfo,
11
+ VideoDatasetType,
12
+ VideoFrameInfo,
13
+ VideoInfo,
14
+ )
15
+ from ib_sync_rewards.imagebind.pytorchvideo.data.epic_kitchen import ActionData, EpicKitchenDataset
16
+ from ib_sync_rewards.imagebind.pytorchvideo.data.video import Video
17
+
18
+
19
+ class ClipSampling(Enum):
20
+ Random = 1
21
+
22
+
23
+ class EpicKitchenForecasting(EpicKitchenDataset):
24
+ """
25
+ Action forecasting video data set for EpicKitchen-55 Dataset.
26
+ <https://epic-kitchens.github.io/2019/>
27
+
28
+ This dataset handles the loading, decoding, and clip sampling for the videos.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ video_info_file_path: str,
34
+ actions_file_path: str,
35
+ video_data_manifest_file_path: str,
36
+ clip_sampling: ClipSampling = ClipSampling.Random,
37
+ dataset_type: VideoDatasetType = VideoDatasetType.Frame,
38
+ seconds_per_clip: float = 2.0,
39
+ clip_time_stride: float = 10.0,
40
+ num_input_clips: int = 1,
41
+ frames_per_clip: Optional[int] = None,
42
+ num_forecast_actions: int = 1,
43
+ transform: Callable[[Dict[str, Any]], Any] = None,
44
+ multithreaded_io: bool = True,
45
+ ):
46
+ f"""
47
+ Args:
48
+ video_info_file_path (str):
49
+ Path or URI to manifest with basic metadata of each video.
50
+ File must be a csv (w/header) with columns:
51
+ {[f.name for f in dataclass_fields(VideoInfo)]}
52
+
53
+ actions_file_path (str):
54
+ Path or URI to manifest with action annotations for each video.
55
+ File must ber a csv (w/header) with columns:
56
+ {[f.name for f in dataclass_fields(ActionData)]}
57
+
58
+ video_data_manifest_file_path (str):
59
+ The path to a json file outlining the available video data for the
60
+ associated videos. File must be a csv (w/header) with columns either:
61
+
62
+ For Frame Videos:
63
+ {[f.name for f in dataclass_fields(VideoFrameInfo)]}
64
+
65
+ For Encoded Videos:
66
+ {[f.name for f in dataclass_fields(EncodedVideoInfo)]}
67
+
68
+ To generate this file from a directory of video frames, see helper
69
+ functions in Module: pytorchvideo.data.epic_kitchen.utils
70
+
71
+ clip_sampling (ClipSampling):
72
+ The type of sampling to perform to perform on the videos of the dataset.
73
+
74
+ dataset_type (VideoDatasetType): The dataformat in which dataset
75
+ video data is store (e.g. video frames, encoded video etc).
76
+
77
+ seconds_per_clip (float): The length of each sampled subclip in seconds.
78
+
79
+ clip_time_stride (float): The time difference in seconds between the start of
80
+ each input subclip.
81
+
82
+ num_input_clips (int): The number of subclips to be included in the input
83
+ video data.
84
+
85
+ frames_per_clip (Optional[int]): The number of frames per clip to sample.
86
+ If None, all frames in the clip will be included.
87
+
88
+ num_forecast_actions (int): The number of actions to be included in the
89
+ action vector.
90
+
91
+ transform (Callable[[Dict[str, Any]], Any]):
92
+ This callable is evaluated on the clip output before the clip is returned.
93
+ It can be used for user-defined preprocessing and augmentations to the clips.
94
+ The clip input is a dictionary with the following format:
95
+ {{
96
+ 'video_id': <str>,
97
+ 'video': <video_tensor>,
98
+ 'audio': <audio_tensor>,
99
+ 'label': <List[ActionData]>,
100
+ 'start_time': <float>,
101
+ 'stop_time': <float>
102
+ }}
103
+
104
+ If transform is None, the raw clip output in the above format is
105
+ returned unmodified.
106
+
107
+ multithreaded_io (bool):
108
+ Boolean to control whether parllelizable io operations are performed across
109
+ multiple threads.
110
+ """
111
+ define_clip_structure_fn = (
112
+ EpicKitchenForecasting._define_clip_structure_generator(
113
+ clip_sampling,
114
+ seconds_per_clip,
115
+ clip_time_stride,
116
+ num_input_clips,
117
+ num_forecast_actions,
118
+ )
119
+ )
120
+ frame_filter = (
121
+ EpicKitchenForecasting._frame_filter_generator(
122
+ frames_per_clip, seconds_per_clip, clip_time_stride, num_input_clips
123
+ )
124
+ if frames_per_clip is not None
125
+ else None
126
+ )
127
+ transform = EpicKitchenForecasting._transform_generator(
128
+ transform, num_forecast_actions, frames_per_clip, num_input_clips
129
+ )
130
+
131
+ super().__init__(
132
+ video_info_file_path=video_info_file_path,
133
+ actions_file_path=actions_file_path,
134
+ video_data_manifest_file_path=video_data_manifest_file_path,
135
+ dataset_type=dataset_type,
136
+ transform=transform,
137
+ frame_filter=frame_filter,
138
+ clip_sampler=define_clip_structure_fn,
139
+ multithreaded_io=multithreaded_io,
140
+ )
141
+
142
+ @staticmethod
143
+ def _transform_generator(
144
+ transform: Callable[[Dict[str, Any]], Dict[str, Any]],
145
+ num_forecast_actions: int,
146
+ frames_per_clip: int,
147
+ num_input_clips: int,
148
+ ) -> Callable[[Dict[str, Any]], Dict[str, Any]]:
149
+ """
150
+ Args:
151
+ transform (Callable[[Dict[str, Any]], Dict[str, Any]]): A function that performs
152
+ any operation on a clip before it is returned in the default transform function.
153
+ num_forecast_actions: (int) The number of actions to be included in the
154
+ action vector.
155
+ frames_per_clip (int): The number of frames per clip to sample.
156
+ num_input_clips (int): The number of subclips to be included in the video data.
157
+
158
+ Returns:
159
+ A function that performs any operation on a clip and returns the transformed clip.
160
+ """
161
+
162
+ def transform_clip(clip: Dict[str, Any]) -> Dict[str, Any]:
163
+ assert all(
164
+ clip["actions"][i].start_time <= clip["actions"][i + 1].start_time
165
+ for i in range(len(clip["actions"]) - 1)
166
+ ), "Actions must be sorted"
167
+ next_k_actions: List[ActionData] = [
168
+ a for a in clip["actions"] if (a.start_time > clip["stop_time"])
169
+ ][:num_forecast_actions]
170
+ clip["actions"] = next_k_actions
171
+
172
+ assert clip["video"].size()[1] == num_input_clips * frames_per_clip
173
+ clip_video_tensor = torch.stack(
174
+ [
175
+ clip["video"][
176
+ :, (i * frames_per_clip) : ((i + 1) * frames_per_clip), :, :
177
+ ]
178
+ for i in range(num_input_clips)
179
+ ]
180
+ )
181
+ clip["video"] = clip_video_tensor
182
+
183
+ for key in clip:
184
+ if clip[key] is None:
185
+ clip[key] = torch.tensor([])
186
+
187
+ if transform:
188
+ clip = transform(clip)
189
+
190
+ return clip
191
+
192
+ return transform_clip
193
+
194
+ @staticmethod
195
+ def _frame_filter_generator(
196
+ frames_per_clip: int,
197
+ seconds_per_clip: float,
198
+ clip_time_stride: float,
199
+ num_input_clips: int,
200
+ ) -> Callable[[List[int]], List[int]]:
201
+ """
202
+ Args:
203
+ frames_per_clip (int): The number of frames per clip to sample.
204
+ seconds_per_clip (float): The length of each sampled subclip in seconds.
205
+ clip_time_stride (float): The time difference in seconds between the start of
206
+ each input subclip.
207
+ num_input_clips (int): The number of subclips to be included in the video data.
208
+
209
+ Returns:
210
+ A function that takes in a list of frame indicies and outputs a subsampled list.
211
+ """
212
+ time_window_length = seconds_per_clip + (num_input_clips - 1) * clip_time_stride
213
+ desired_frames_per_second = frames_per_clip / seconds_per_clip
214
+
215
+ def frame_filter(frame_indices: List[int]) -> List[int]:
216
+ num_available_frames_for_all_clips = len(frame_indices)
217
+ available_frames_per_second = (
218
+ num_available_frames_for_all_clips / time_window_length
219
+ )
220
+ intra_clip_sampling_stride = int(
221
+ available_frames_per_second // desired_frames_per_second
222
+ )
223
+ selected_frames = set()
224
+ for i in range(num_input_clips):
225
+ clip_start_index = int(
226
+ i * clip_time_stride * available_frames_per_second
227
+ )
228
+ for j in range(frames_per_clip):
229
+ selected_frames.add(
230
+ clip_start_index + j * intra_clip_sampling_stride
231
+ )
232
+ return [x for i, x in enumerate(frame_indices) if i in selected_frames]
233
+
234
+ return frame_filter
235
+
236
+ @staticmethod
237
+ def _define_clip_structure_generator(
238
+ clip_sampling: str,
239
+ seconds_per_clip: float,
240
+ clip_time_stride: float,
241
+ num_input_clips: int,
242
+ num_forecast_actions: int,
243
+ ) -> Callable[[Dict[str, Video], Dict[str, List[ActionData]]], List[VideoClipInfo]]:
244
+ """
245
+ Args:
246
+ clip_sampling (ClipSampling):
247
+ The type of sampling to perform to perform on the videos of the dataset.
248
+ seconds_per_clip (float): The length of each sampled clip in seconds.
249
+ clip_time_stride: The time difference in seconds between the start of
250
+ each input subclip.
251
+ num_input_clips (int): The number of subclips to be included in the video data.
252
+ num_forecast_actions (int): The number of actions to be included in the
253
+ action vector.
254
+
255
+ Returns:
256
+ A function that takes a dictionary of videos and outputs a list of sampled
257
+ clips.
258
+ """
259
+ # TODO(T77683480)
260
+ if not clip_sampling == ClipSampling.Random:
261
+ raise NotImplementedError(
262
+ f"Only {ClipSampling.Random} is implemented. "
263
+ f"{clip_sampling} not implemented."
264
+ )
265
+
266
+ time_window_length = seconds_per_clip + (num_input_clips - 1) * clip_time_stride
267
+
268
+ def define_clip_structure(
269
+ videos: Dict[str, Video], video_actions: Dict[str, List[ActionData]]
270
+ ) -> List[VideoClipInfo]:
271
+ candidate_sample_clips = []
272
+ for video_id, actions in video_actions.items():
273
+ for i, action in enumerate(actions[: (-1 * num_forecast_actions)]):
274
+ # Only actions with num_forecast_actions after to predict
275
+ # Confirm there are >= num_forecast_actions available
276
+ # (it is possible for actions to overlap)
277
+ number_valid_actions = 0
278
+ for j in range(i + 1, len(actions)):
279
+ if actions[j].start_time > action.stop_time:
280
+ number_valid_actions += 1
281
+ if number_valid_actions == num_forecast_actions:
282
+ if (
283
+ action.start_time - time_window_length >= 0
284
+ ): # Only add clips that have the full input video available
285
+ candidate_sample_clips.append(
286
+ VideoClipInfo(
287
+ video_id,
288
+ action.stop_time - time_window_length,
289
+ action.stop_time,
290
+ )
291
+ )
292
+ break
293
+ return candidate_sample_clips
294
+
295
+ return define_clip_structure
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/frame_video.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import math
7
+ import os
8
+ import re
9
+ import time
10
+ from typing import Callable, Dict, List, Optional
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.utils.data
15
+ from iopath.common.file_io import g_pathmgr
16
+ from ib_sync_rewards.imagebind.pytorchvideo.data.utils import optional_threaded_foreach
17
+
18
+ from .utils import thwc_to_cthw
19
+ from .video import Video
20
+
21
+
22
+ try:
23
+ import cv2
24
+ except ImportError:
25
+ _HAS_CV2 = False
26
+ else:
27
+ _HAS_CV2 = True
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class FrameVideo(Video):
34
+ """
35
+ FrameVideo is an abstractions for accessing clips based on their start and end
36
+ time for a video where each frame is stored as an image. PathManager is used for
37
+ frame image reading, allowing non-local uri's to be used.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ duration: float,
43
+ fps: float,
44
+ video_frame_to_path_fn: Callable[[int], str] = None,
45
+ video_frame_paths: List[str] = None,
46
+ multithreaded_io: bool = False,
47
+ ) -> None:
48
+ """
49
+ Args:
50
+ duration (float): the duration of the video in seconds.
51
+ fps (float): the target fps for the video. This is needed to link the frames
52
+ to a second timestamp in the video.
53
+ video_frame_to_path_fn (Callable[[int], str]): a function that maps from a frame
54
+ index integer to the file path where the frame is located.
55
+ video_frame_paths (List[str]): Dictionary of frame paths for each index of a video.
56
+ multithreaded_io (bool): controls whether parllelizable io operations are
57
+ performed across multiple threads.
58
+ """
59
+ if not _HAS_CV2:
60
+ raise ImportError(
61
+ "opencv2 is required to use FrameVideo. Please "
62
+ "install with 'pip install opencv-python'"
63
+ )
64
+
65
+ self._duration = duration
66
+ self._fps = fps
67
+ self._multithreaded_io = multithreaded_io
68
+
69
+ assert (video_frame_to_path_fn is None) != (
70
+ video_frame_paths is None
71
+ ), "Only one of video_frame_to_path_fn or video_frame_paths can be provided"
72
+ self._video_frame_to_path_fn = video_frame_to_path_fn
73
+ self._video_frame_paths = video_frame_paths
74
+
75
+ # Set the pathname to the parent directory of the first frame.
76
+ self._name = os.path.basename(
77
+ os.path.dirname(self._video_frame_to_path(frame_index=0))
78
+ )
79
+
80
+ @classmethod
81
+ def from_directory(
82
+ cls,
83
+ path: str,
84
+ fps: float = 30.0,
85
+ multithreaded_io=False,
86
+ path_order_cache: Optional[Dict[str, List[str]]] = None,
87
+ ):
88
+ """
89
+ Args:
90
+ path (str): path to frame video directory.
91
+ fps (float): the target fps for the video. This is needed to link the frames
92
+ to a second timestamp in the video.
93
+ multithreaded_io (bool): controls whether parllelizable io operations are
94
+ performed across multiple threads.
95
+ path_order_cache (dict): An optional mapping from directory-path to list
96
+ of frames in the directory in numerical order. Used for speedup by
97
+ caching the frame paths.
98
+ """
99
+ if path_order_cache is not None and path in path_order_cache:
100
+ return cls.from_frame_paths(path_order_cache[path], fps, multithreaded_io)
101
+
102
+ assert g_pathmgr.isdir(path), f"{path} is not a directory"
103
+ rel_frame_paths = g_pathmgr.ls(path)
104
+
105
+ def natural_keys(text):
106
+ return [int(c) if c.isdigit() else c for c in re.split("(\d+)", text)]
107
+
108
+ rel_frame_paths.sort(key=natural_keys)
109
+ frame_paths = [os.path.join(path, f) for f in rel_frame_paths]
110
+ if path_order_cache is not None:
111
+ path_order_cache[path] = frame_paths
112
+ return cls.from_frame_paths(frame_paths, fps, multithreaded_io)
113
+
114
+ @classmethod
115
+ def from_frame_paths(
116
+ cls,
117
+ video_frame_paths: List[str],
118
+ fps: float = 30.0,
119
+ multithreaded_io: bool = False,
120
+ ):
121
+ """
122
+ Args:
123
+ video_frame_paths (List[str]): a list of paths to each frames in the video.
124
+ fps (float): the target fps for the video. This is needed to link the frames
125
+ to a second timestamp in the video.
126
+ multithreaded_io (bool): controls whether parllelizable io operations are
127
+ performed across multiple threads.
128
+ """
129
+ assert len(video_frame_paths) != 0, "video_frame_paths is empty"
130
+ return cls(
131
+ len(video_frame_paths) / fps,
132
+ fps,
133
+ video_frame_paths=video_frame_paths,
134
+ multithreaded_io=multithreaded_io,
135
+ )
136
+
137
+ @property
138
+ def name(self) -> float:
139
+ return self._name
140
+
141
+ @property
142
+ def duration(self) -> float:
143
+ """
144
+ Returns:
145
+ duration: the video's duration/end-time in seconds.
146
+ """
147
+ return self._duration
148
+
149
+ def _get_frame_index_for_time(self, time_sec: float) -> int:
150
+ return math.ceil(self._fps * time_sec)
151
+
152
+ def get_clip(
153
+ self,
154
+ start_sec: float,
155
+ end_sec: float,
156
+ frame_filter: Optional[Callable[[List[int]], List[int]]] = None,
157
+ ) -> Dict[str, Optional[torch.Tensor]]:
158
+ """
159
+ Retrieves frames from the stored video at the specified start and end times
160
+ in seconds (the video always starts at 0 seconds). Returned frames will be
161
+ in [start_sec, end_sec). Given that PathManager may
162
+ be fetching the frames from network storage, to handle transient errors, frame
163
+ reading is retried N times. Note that as end_sec is exclusive, so you may need
164
+ to use `get_clip(start_sec, duration + EPS)` to get the last frame.
165
+
166
+ Args:
167
+ start_sec (float): the clip start time in seconds
168
+ end_sec (float): the clip end time in seconds
169
+ frame_filter (Optional[Callable[List[int], List[int]]]):
170
+ function to subsample frames in a clip before loading.
171
+ If None, no subsampling is peformed.
172
+ Returns:
173
+ clip_frames: A tensor of the clip's RGB frames with shape:
174
+ (channel, time, height, width). The frames are of type torch.float32 and
175
+ in the range [0 - 255]. Raises an exception if unable to load images.
176
+
177
+ clip_data:
178
+ "video": A tensor of the clip's RGB frames with shape:
179
+ (channel, time, height, width). The frames are of type torch.float32 and
180
+ in the range [0 - 255]. Raises an exception if unable to load images.
181
+
182
+ "frame_indices": A list of indices for each frame relative to all frames in the
183
+ video.
184
+
185
+ Returns None if no frames are found.
186
+ """
187
+ if start_sec < 0 or start_sec > self._duration:
188
+ logger.warning(
189
+ f"No frames found within {start_sec} and {end_sec} seconds. Video starts"
190
+ f"at time 0 and ends at {self._duration}."
191
+ )
192
+ return None
193
+
194
+ end_sec = min(end_sec, self._duration)
195
+
196
+ start_frame_index = self._get_frame_index_for_time(start_sec)
197
+ end_frame_index = min(
198
+ self._get_frame_index_for_time(end_sec), len(self._video_frame_paths)
199
+ )
200
+ frame_indices = list(range(start_frame_index, end_frame_index))
201
+ # Frame filter function to allow for subsampling before loading
202
+ if frame_filter:
203
+ frame_indices = frame_filter(frame_indices)
204
+
205
+ clip_paths = [self._video_frame_to_path(i) for i in frame_indices]
206
+ clip_frames = _load_images_with_retries(
207
+ clip_paths, multithreaded=self._multithreaded_io
208
+ )
209
+ clip_frames = thwc_to_cthw(clip_frames).to(torch.float32)
210
+ return {"video": clip_frames, "frame_indices": frame_indices, "audio": None}
211
+
212
+ def _video_frame_to_path(self, frame_index: int) -> str:
213
+ if self._video_frame_to_path_fn:
214
+ return self._video_frame_to_path_fn(frame_index)
215
+ elif self._video_frame_paths:
216
+ return self._video_frame_paths[frame_index]
217
+ else:
218
+ raise Exception(
219
+ "One of _video_frame_to_path_fn or _video_frame_paths must be set"
220
+ )
221
+
222
+
223
+ def _load_images_with_retries(
224
+ image_paths: List[str], num_retries: int = 10, multithreaded: bool = True
225
+ ) -> torch.Tensor:
226
+ """
227
+ Loads the given image paths using PathManager, decodes them as RGB images and
228
+ returns them as a stacked tensors.
229
+ Args:
230
+ image_paths (List[str]): a list of paths to images.
231
+ num_retries (int): number of times to retry image reading to handle transient error.
232
+ multithreaded (bool): if images are fetched via multiple threads in parallel.
233
+ Returns:
234
+ A tensor of the clip's RGB frames with shape:
235
+ (time, height, width, channel). The frames are of type torch.uint8 and
236
+ in the range [0 - 255]. Raises an exception if unable to load images.
237
+ """
238
+ imgs = [None for i in image_paths]
239
+
240
+ def fetch_image(image_index: int, image_path: str) -> None:
241
+ for i in range(num_retries):
242
+ with g_pathmgr.open(image_path, "rb") as f:
243
+ img_str = np.frombuffer(f.read(), np.uint8)
244
+ img_bgr = cv2.imdecode(img_str, flags=cv2.IMREAD_COLOR)
245
+ img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
246
+ if img_rgb is not None:
247
+ imgs[image_index] = img_rgb
248
+ return
249
+ else:
250
+ logging.warning(f"Reading attempt {i}/{num_retries} failed.")
251
+ time.sleep(1e-6)
252
+
253
+ optional_threaded_foreach(fetch_image, enumerate(image_paths), multithreaded)
254
+
255
+ if any((img is None for img in imgs)):
256
+ raise Exception("Failed to load images from {}".format(image_paths))
257
+
258
+ return torch.as_tensor(np.stack(imgs))
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/hmdb51.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import pathlib
8
+ from typing import Any, Callable, List, Optional, Tuple, Type, Union
9
+
10
+ import torch
11
+ import torch.utils.data
12
+ from iopath.common.file_io import g_pathmgr
13
+
14
+ from .clip_sampling import ClipSampler
15
+ from .labeled_video_dataset import LabeledVideoDataset
16
+
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class Hmdb51LabeledVideoPaths:
22
+ """
23
+ Pre-processor for Hmbd51 dataset mentioned here -
24
+ https://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/
25
+
26
+ This dataset consists of classwise folds with each class consisting of 3
27
+ folds (splits).
28
+
29
+ The videos directory is of the format,
30
+ video_dir_path/class_x/<somevideo_name>.avi
31
+ ...
32
+ video_dir_path/class_y/<somevideo_name>.avi
33
+
34
+ The splits/fold directory is of the format,
35
+ folds_dir_path/class_x_test_split_1.txt
36
+ folds_dir_path/class_x_test_split_2.txt
37
+ folds_dir_path/class_x_test_split_3.txt
38
+ ...
39
+ folds_dir_path/class_y_test_split_1.txt
40
+ folds_dir_path/class_y_test_split_2.txt
41
+ folds_dir_path/class_y_test_split_3.txt
42
+
43
+ And each text file in the splits directory class_x_test_split_<1 or 2 or 3>.txt
44
+ <a video as in video_dir_path/class_x> <0 or 1 or 2>
45
+ where 0,1,2 corresponds to unused, train split respectively.
46
+
47
+ Each video has name of format
48
+ <some_name>_<tag1>_<tag2>_<tag_3>_<tag4>_<tag5>_<some_id>.avi
49
+ For more details on tags -
50
+ https://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/
51
+ """
52
+
53
+ _allowed_splits = [1, 2, 3]
54
+ _split_type_dict = {"train": 1, "test": 2, "unused": 0}
55
+
56
+ @classmethod
57
+ def from_dir(
58
+ cls, data_path: str, split_id: int = 1, split_type: str = "train"
59
+ ) -> Hmdb51LabeledVideoPaths:
60
+ """
61
+ Factory function that creates Hmdb51LabeledVideoPaths object form a splits/folds
62
+ directory.
63
+
64
+ Args:
65
+ data_path (str): The path to the splits/folds directory of HMDB51.
66
+ split_id (int): Fold id to be loaded. Belongs to [1,2,3]
67
+ split_type (str): Split/Fold type to be loaded. It belongs to one of the
68
+ following,
69
+ - "train"
70
+ - "test"
71
+ - "unused" (This is a small set of videos that are neither
72
+ of part of test or train fold.)
73
+ """
74
+ data_path = pathlib.Path(data_path)
75
+ if not data_path.is_dir():
76
+ return RuntimeError(f"{data_path} not found or is not a directory.")
77
+ if not int(split_id) in cls._allowed_splits:
78
+ return RuntimeError(
79
+ f"{split_id} not found in allowed split id's {cls._allowed_splits}."
80
+ )
81
+ file_name_format = "_test_split" + str(int(split_id))
82
+ file_paths = sorted(
83
+ (
84
+ f
85
+ for f in data_path.iterdir()
86
+ if f.is_file() and f.suffix == ".txt" and file_name_format in f.stem
87
+ )
88
+ )
89
+ return cls.from_csvs(file_paths, split_type)
90
+
91
+ @classmethod
92
+ def from_csvs(
93
+ cls, file_paths: List[Union[pathlib.Path, str]], split_type: str = "train"
94
+ ) -> Hmdb51LabeledVideoPaths:
95
+ """
96
+ Factory function that creates Hmdb51LabeledVideoPaths object form a list of
97
+ split files of .txt type
98
+
99
+ Args:
100
+ file_paths (List[Union[pathlib.Path, str]]) : The path to the splits/folds
101
+ directory of HMDB51.
102
+ split_type (str): Split/Fold type to be loaded.
103
+ - "train"
104
+ - "test"
105
+ - "unused"
106
+ """
107
+ video_paths_and_label = []
108
+ for file_path in file_paths:
109
+ file_path = pathlib.Path(file_path)
110
+ assert g_pathmgr.exists(file_path), f"{file_path} not found."
111
+ if not (file_path.suffix == ".txt" and "_test_split" in file_path.stem):
112
+ return RuntimeError(f"Ivalid file: {file_path}")
113
+
114
+ action_name = "_"
115
+ action_name = action_name.join((file_path.stem).split("_")[:-2])
116
+ with g_pathmgr.open(file_path, "r") as f:
117
+ for path_label in f.read().splitlines():
118
+ line_split = path_label.rsplit(None, 1)
119
+
120
+ if not int(line_split[1]) == cls._split_type_dict[split_type]:
121
+ continue
122
+
123
+ file_path = os.path.join(action_name, line_split[0])
124
+ meta_tags = line_split[0].split("_")[-6:-1]
125
+ video_paths_and_label.append(
126
+ (file_path, {"label": action_name, "meta_tags": meta_tags})
127
+ )
128
+
129
+ assert (
130
+ len(video_paths_and_label) > 0
131
+ ), f"Failed to load dataset from {file_path}."
132
+ return cls(video_paths_and_label)
133
+
134
+ def __init__(
135
+ self, paths_and_labels: List[Tuple[str, Optional[dict]]], path_prefix=""
136
+ ) -> None:
137
+ """
138
+ Args:
139
+ paths_and_labels [(str, int)]: a list of tuples containing the video
140
+ path and integer label.
141
+ """
142
+ self._paths_and_labels = paths_and_labels
143
+ self._path_prefix = path_prefix
144
+
145
+ def path_prefix(self, prefix):
146
+ self._path_prefix = prefix
147
+
148
+ path_prefix = property(None, path_prefix)
149
+
150
+ def __getitem__(self, index: int) -> Tuple[str, dict]:
151
+ """
152
+ Args:
153
+ index (int): the path and label index.
154
+
155
+ Returns:
156
+ The path and label tuple for the given index.
157
+ """
158
+ path, label = self._paths_and_labels[index]
159
+ return (os.path.join(self._path_prefix, path), label)
160
+
161
+ def __len__(self) -> int:
162
+ """
163
+ Returns:
164
+ The number of video paths and label pairs.
165
+ """
166
+ return len(self._paths_and_labels)
167
+
168
+
169
+ def Hmdb51(
170
+ data_path: pathlib.Path,
171
+ clip_sampler: ClipSampler,
172
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
173
+ transform: Optional[Callable[[dict], Any]] = None,
174
+ video_path_prefix: str = "",
175
+ split_id: int = 1,
176
+ split_type: str = "train",
177
+ decode_audio=True,
178
+ decoder: str = "pyav",
179
+ ) -> LabeledVideoDataset:
180
+ """
181
+ A helper function to create ``LabeledVideoDataset`` object for HMDB51 dataset
182
+
183
+ Args:
184
+ data_path (pathlib.Path): Path to the data. The path type defines how the data
185
+ should be read:
186
+
187
+ * For a file path, the file is read and each line is parsed into a
188
+ video path and label.
189
+ * For a directory, the directory structure defines the classes
190
+ (i.e. each subdirectory is a class).
191
+
192
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
193
+ video. See the clip sampling documentation for more information.
194
+
195
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
196
+ video container. This defines the order videos are decoded and,
197
+ if necessary, the distributed split.
198
+
199
+ transform (Callable): This callable is evaluated on the clip output before
200
+ the clip is returned. It can be used for user defined preprocessing and
201
+ augmentations to the clips. See the ``LabeledVideoDataset`` class for
202
+ clip output format.
203
+
204
+ video_path_prefix (str): Path to root directory with the videos that are
205
+ loaded in LabeledVideoDataset. All the video paths before loading
206
+ are prefixed with this path.
207
+
208
+ split_id (int): Fold id to be loaded. Options are 1, 2 or 3
209
+
210
+ split_type (str): Split/Fold type to be loaded. Options are ("train", "test" or
211
+ "unused")
212
+
213
+ decoder (str): Defines which backend should be used to decode videos.
214
+ """
215
+
216
+ torch._C._log_api_usage_once("PYTORCHVIDEO.dataset.Hmdb51")
217
+
218
+ labeled_video_paths = Hmdb51LabeledVideoPaths.from_dir(
219
+ data_path, split_id=split_id, split_type=split_type
220
+ )
221
+ labeled_video_paths.path_prefix = video_path_prefix
222
+ dataset = LabeledVideoDataset(
223
+ labeled_video_paths,
224
+ clip_sampler,
225
+ video_sampler,
226
+ transform,
227
+ decode_audio=decode_audio,
228
+ decoder=decoder,
229
+ )
230
+
231
+ return dataset
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/json_dataset.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ from typing import Any, Callable, Dict, Optional, Type
7
+
8
+ import torch
9
+ from iopath.common.file_io import g_pathmgr
10
+ from ib_sync_rewards.imagebind.pytorchvideo.data.clip_sampling import ClipInfo, ClipSampler
11
+ from ib_sync_rewards.imagebind.pytorchvideo.data.labeled_video_dataset import LabeledVideoDataset
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def video_only_dataset(
18
+ data_path: str,
19
+ clip_sampler: ClipSampler,
20
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
21
+ transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
22
+ video_path_prefix: str = "",
23
+ decode_audio: bool = True,
24
+ decoder: str = "pyav",
25
+ ):
26
+ """
27
+ Builds a LabeledVideoDataset with no annotations from a json file with the following
28
+ format:
29
+
30
+ .. code-block:: text
31
+
32
+ {
33
+ "video_name1": {...}
34
+ "video_name2": {...}
35
+ ....
36
+ "video_nameN": {...}
37
+ }
38
+
39
+ Args:
40
+ labeled_video_paths (List[Tuple[str, Optional[dict]]]): List containing
41
+ video file paths and associated labels. If video paths are a folder
42
+ it's interpreted as a frame video, otherwise it must be an encoded
43
+ video.
44
+
45
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
46
+ video. See the clip sampling documentation for more information.
47
+
48
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
49
+ video container. This defines the order videos are decoded and,
50
+ if necessary, the distributed split.
51
+
52
+ transform (Callable): This callable is evaluated on the clip output before
53
+ the clip is returned. It can be used for user defined preprocessing and
54
+ augmentations on the clips. The clip output format is described in __next__().
55
+
56
+ decode_audio (bool): If True, also decode audio from video.
57
+
58
+ decoder (str): Defines what type of decoder used to decode a video. Not used for
59
+ frame videos.
60
+ """
61
+
62
+ torch._C._log_api_usage_once("PYTORCHVIDEO.dataset.json_dataset.video_only_dataset")
63
+
64
+ if g_pathmgr.isfile(data_path):
65
+ try:
66
+ with g_pathmgr.open(data_path, "r") as f:
67
+ annotations = json.load(f)
68
+ except Exception:
69
+ raise FileNotFoundError(f"{data_path} must be json for Ego4D dataset")
70
+
71
+ # LabeledVideoDataset requires the data to be list of tuples with format:
72
+ # (video_paths, annotation_dict), for no annotations we just pass in an empty dict.
73
+ video_paths = [
74
+ (os.path.join(video_path_prefix, x), {}) for x in annotations.keys()
75
+ ]
76
+ else:
77
+ raise FileNotFoundError(f"{data_path} not found.")
78
+
79
+ dataset = LabeledVideoDataset(
80
+ video_paths,
81
+ clip_sampler,
82
+ video_sampler,
83
+ transform,
84
+ decode_audio=decode_audio,
85
+ decoder=decoder,
86
+ )
87
+ return dataset
88
+
89
+
90
+ def clip_recognition_dataset(
91
+ data_path: str,
92
+ clip_sampler: ClipSampler,
93
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
94
+ transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
95
+ video_path_prefix: str = "",
96
+ decode_audio: bool = True,
97
+ decoder: str = "pyav",
98
+ ):
99
+ """
100
+ Builds a LabeledVideoDataset with noun, verb annotations from a json file with the following
101
+ format:
102
+
103
+ .. code-block:: text
104
+
105
+ {
106
+ "video_name1": {
107
+ {
108
+ "benchmarks": {
109
+ "forecasting_hands_objects": [
110
+ {
111
+ "critical_frame_selection_parent_start_sec": <start_sec>
112
+ "critical_frame_selection_parent_end_sec": <end_sec>
113
+ {
114
+ "taxonomy: {
115
+ "noun": <label>,
116
+ "verb": <label>,
117
+ }
118
+ }
119
+ },
120
+ {
121
+ ...
122
+ }
123
+ ]
124
+ }
125
+ }
126
+ }
127
+ "video_name2": {...}
128
+ ....
129
+ "video_nameN": {...}
130
+ }
131
+
132
+ Args:
133
+ labeled_video_paths (List[Tuple[str, Optional[dict]]]): List containing
134
+ video file paths and associated labels. If video paths are a folder
135
+ it's interpreted as a frame video, otherwise it must be an encoded
136
+ video.
137
+
138
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
139
+ video. See the clip sampling documentation for more information.
140
+
141
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
142
+ video container. This defines the order videos are decoded and,
143
+ if necessary, the distributed split.
144
+
145
+ transform (Callable): This callable is evaluated on the clip output before
146
+ the clip is returned. It can be used for user defined preprocessing and
147
+ augmentations on the clips. The clip output format is described in __next__().
148
+
149
+ decode_audio (bool): If True, also decode audio from video.
150
+
151
+ decoder (str): Defines what type of decoder used to decode a video. Not used for
152
+ frame videos.
153
+ """
154
+ if g_pathmgr.isfile(data_path):
155
+ try:
156
+ with g_pathmgr.open(data_path, "r") as f:
157
+ annotations = json.load(f)
158
+ except Exception:
159
+ raise FileNotFoundError(f"{data_path} must be json for Ego4D dataset")
160
+
161
+ # LabeledVideoDataset requires the data to be list of tuples with format:
162
+ # (video_paths, annotation_dict), for no annotations we just pass in an empty dict.
163
+ untrimmed_clip_annotations = []
164
+ for video_name, child in annotations.items():
165
+ video_path = os.path.join(video_path_prefix, video_name)
166
+ for clip_annotation in child["benchmarks"]["forecasting_hands_objects"]:
167
+ clip_start = clip_annotation[
168
+ "critical_frame_selection_parent_start_sec"
169
+ ]
170
+ clip_end = clip_annotation["critical_frame_selection_parent_end_sec"]
171
+ taxonomy = clip_annotation["taxonomy"]
172
+ noun_label = taxonomy["noun"]
173
+ verb_label = taxonomy["verb"]
174
+ verb_unsure = taxonomy["verb_unsure"]
175
+ noun_unsure = taxonomy["noun_unsure"]
176
+ if (
177
+ noun_label is None
178
+ or verb_label is None
179
+ or verb_unsure
180
+ or noun_unsure
181
+ ):
182
+ continue
183
+
184
+ untrimmed_clip_annotations.append(
185
+ (
186
+ video_path,
187
+ {
188
+ "clip_start_sec": clip_start,
189
+ "clip_end_sec": clip_end,
190
+ "noun_label": noun_label,
191
+ "verb_label": verb_label,
192
+ },
193
+ )
194
+ )
195
+ else:
196
+ raise FileNotFoundError(f"{data_path} not found.")
197
+
198
+ # Map noun and verb key words to unique index.
199
+ def map_labels_to_index(label_name):
200
+ labels = list({info[label_name] for _, info in untrimmed_clip_annotations})
201
+ label_to_idx = {label: i for i, label in enumerate(labels)}
202
+ for i in range(len(untrimmed_clip_annotations)):
203
+ label = untrimmed_clip_annotations[i][1][label_name]
204
+ untrimmed_clip_annotations[i][1][label_name] = label_to_idx[label]
205
+
206
+ map_labels_to_index("noun_label")
207
+ map_labels_to_index("verb_label")
208
+
209
+ dataset = LabeledVideoDataset(
210
+ untrimmed_clip_annotations,
211
+ UntrimmedClipSampler(clip_sampler),
212
+ video_sampler,
213
+ transform,
214
+ decode_audio=decode_audio,
215
+ decoder=decoder,
216
+ )
217
+ return dataset
218
+
219
+
220
+ class UntrimmedClipSampler:
221
+ """
222
+ A wrapper for adapting untrimmed annotated clips from the json_dataset to the
223
+ standard `pytorchvideo.data.ClipSampler` expected format. Specifically, for each
224
+ clip it uses the provided `clip_sampler` to sample between "clip_start_sec" and
225
+ "clip_end_sec" from the json_dataset clip annotation.
226
+ """
227
+
228
+ def __init__(self, clip_sampler: ClipSampler) -> None:
229
+ """
230
+ Args:
231
+ clip_sampler (`pytorchvideo.data.ClipSampler`): Strategy used for sampling
232
+ between the untrimmed clip boundary.
233
+ """
234
+ self._trimmed_clip_sampler = clip_sampler
235
+
236
+ def __call__(
237
+ self, last_clip_time: float, video_duration: float, clip_info: Dict[str, Any]
238
+ ) -> ClipInfo:
239
+ clip_start_boundary = clip_info["clip_start_sec"]
240
+ clip_end_boundary = clip_info["clip_end_sec"]
241
+ duration = clip_start_boundary - clip_end_boundary
242
+
243
+ # Sample between 0 and duration of untrimmed clip, then add back start boundary.
244
+ clip_info = self._trimmed_clip_sampler(last_clip_time, duration, clip_info)
245
+ return ClipInfo(
246
+ clip_info.clip_start_sec + clip_start_boundary,
247
+ clip_info.clip_end_sec + clip_start_boundary,
248
+ clip_info.clip_index,
249
+ clip_info.aug_index,
250
+ clip_info.is_last_clip,
251
+ )
252
+
253
+ def reset(self) -> None:
254
+ pass
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/labeled_video_dataset.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from __future__ import annotations
4
+
5
+ import gc
6
+ import logging
7
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Type
8
+
9
+ import torch.utils.data
10
+ from ib_sync_rewards.imagebind.pytorchvideo.data.clip_sampling import ClipSampler
11
+ from ib_sync_rewards.imagebind.pytorchvideo.data.video import VideoPathHandler
12
+
13
+ from .labeled_video_paths import LabeledVideoPaths
14
+ from .utils import MultiProcessSampler
15
+
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class LabeledVideoDataset(torch.utils.data.IterableDataset):
21
+ """
22
+ LabeledVideoDataset handles the storage, loading, decoding and clip sampling for a
23
+ video dataset. It assumes each video is stored as either an encoded video
24
+ (e.g. mp4, avi) or a frame video (e.g. a folder of jpg, or png)
25
+ """
26
+
27
+ _MAX_CONSECUTIVE_FAILURES = 10
28
+
29
+ def __init__(
30
+ self,
31
+ labeled_video_paths: List[Tuple[str, Optional[dict]]],
32
+ clip_sampler: ClipSampler,
33
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
34
+ transform: Optional[Callable[[dict], Any]] = None,
35
+ decode_audio: bool = True,
36
+ decode_video: bool = True,
37
+ decoder: str = "pyav",
38
+ ) -> None:
39
+ """
40
+ Args:
41
+ labeled_video_paths (List[Tuple[str, Optional[dict]]]): List containing
42
+ video file paths and associated labels. If video paths are a folder
43
+ it's interpreted as a frame video, otherwise it must be an encoded
44
+ video.
45
+
46
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
47
+ video. See the clip sampling documentation for more information.
48
+
49
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
50
+ video container. This defines the order videos are decoded and,
51
+ if necessary, the distributed split.
52
+
53
+ transform (Callable): This callable is evaluated on the clip output before
54
+ the clip is returned. It can be used for user defined preprocessing and
55
+ augmentations on the clips. The clip output format is described in __next__().
56
+
57
+ decode_audio (bool): If True, decode audio from video.
58
+
59
+ decode_video (bool): If True, decode video frames from a video container.
60
+
61
+ decoder (str): Defines what type of decoder used to decode a video. Not used for
62
+ frame videos.
63
+ """
64
+ self._decode_audio = decode_audio
65
+ self._decode_video = decode_video
66
+ self._transform = transform
67
+ self._clip_sampler = clip_sampler
68
+ self._labeled_videos = labeled_video_paths
69
+ self._decoder = decoder
70
+
71
+ # If a RandomSampler is used we need to pass in a custom random generator that
72
+ # ensures all PyTorch multiprocess workers have the same random seed.
73
+ self._video_random_generator = None
74
+ if video_sampler == torch.utils.data.RandomSampler:
75
+ self._video_random_generator = torch.Generator()
76
+ self._video_sampler = video_sampler(
77
+ self._labeled_videos, generator=self._video_random_generator
78
+ )
79
+ else:
80
+ self._video_sampler = video_sampler(self._labeled_videos)
81
+
82
+ self._video_sampler_iter = None # Initialized on first call to self.__next__()
83
+
84
+ # Depending on the clip sampler type, we may want to sample multiple clips
85
+ # from one video. In that case, we keep the store video, label and previous sampled
86
+ # clip time in these variables.
87
+ self._loaded_video_label = None
88
+ self._loaded_clip = None
89
+ self._last_clip_end_time = None
90
+ self.video_path_handler = VideoPathHandler()
91
+
92
+ @property
93
+ def video_sampler(self):
94
+ """
95
+ Returns:
96
+ The video sampler that defines video sample order. Note that you'll need to
97
+ use this property to set the epoch for a torch.utils.data.DistributedSampler.
98
+ """
99
+ return self._video_sampler
100
+
101
+ @property
102
+ def num_videos(self):
103
+ """
104
+ Returns:
105
+ Number of videos in dataset.
106
+ """
107
+ return len(self.video_sampler)
108
+
109
+ def __next__(self) -> dict:
110
+ """
111
+ Retrieves the next clip based on the clip sampling strategy and video sampler.
112
+
113
+ Returns:
114
+ A dictionary with the following format.
115
+
116
+ .. code-block:: text
117
+
118
+ {
119
+ 'video': <video_tensor>,
120
+ 'label': <index_label>,
121
+ 'video_label': <index_label>
122
+ 'video_index': <video_index>,
123
+ 'clip_index': <clip_index>,
124
+ 'aug_index': <aug_index>,
125
+ }
126
+ """
127
+ if not self._video_sampler_iter:
128
+ # Setup MultiProcessSampler here - after PyTorch DataLoader workers are spawned.
129
+ self._video_sampler_iter = iter(MultiProcessSampler(self._video_sampler))
130
+
131
+ for i_try in range(self._MAX_CONSECUTIVE_FAILURES):
132
+ # Reuse previously stored video if there are still clips to be sampled from
133
+ # the last loaded video.
134
+ if self._loaded_video_label:
135
+ video, info_dict, video_index = self._loaded_video_label
136
+ else:
137
+ video_index = next(self._video_sampler_iter)
138
+ try:
139
+ video_path, info_dict = self._labeled_videos[video_index]
140
+ video = self.video_path_handler.video_from_path(
141
+ video_path,
142
+ decode_audio=self._decode_audio,
143
+ decode_video=self._decode_video,
144
+ decoder=self._decoder,
145
+ )
146
+ self._loaded_video_label = (video, info_dict, video_index)
147
+ except Exception as e:
148
+ logger.debug(
149
+ "Failed to load video with error: {}; trial {}".format(
150
+ e,
151
+ i_try,
152
+ )
153
+ )
154
+ logger.exception("Video load exception")
155
+ continue
156
+
157
+ (
158
+ clip_start,
159
+ clip_end,
160
+ clip_index,
161
+ aug_index,
162
+ is_last_clip,
163
+ ) = self._clip_sampler(self._last_clip_end_time, video.duration, info_dict)
164
+
165
+ if isinstance(clip_start, list): # multi-clip in each sample
166
+ # Only load the clips once and reuse previously stored clips if there are multiple
167
+ # views for augmentations to perform on the same clips.
168
+ if aug_index[0] == 0:
169
+ self._loaded_clip = {}
170
+ loaded_clip_list = []
171
+ for i in range(len(clip_start)):
172
+ clip_dict = video.get_clip(clip_start[i], clip_end[i])
173
+ if clip_dict is None or clip_dict["video"] is None:
174
+ self._loaded_clip = None
175
+ break
176
+ loaded_clip_list.append(clip_dict)
177
+
178
+ if self._loaded_clip is not None:
179
+ for key in loaded_clip_list[0].keys():
180
+ self._loaded_clip[key] = [x[key] for x in loaded_clip_list]
181
+
182
+ else: # single clip case
183
+ # Only load the clip once and reuse previously stored clip if there are multiple
184
+ # views for augmentations to perform on the same clip.
185
+ if aug_index == 0:
186
+ self._loaded_clip = video.get_clip(clip_start, clip_end)
187
+
188
+ self._last_clip_end_time = clip_end
189
+
190
+ video_is_null = (
191
+ self._loaded_clip is None or self._loaded_clip["video"] is None
192
+ )
193
+ if (
194
+ is_last_clip[-1] if isinstance(is_last_clip, list) else is_last_clip
195
+ ) or video_is_null:
196
+ # Close the loaded encoded video and reset the last sampled clip time ready
197
+ # to sample a new video on the next iteration.
198
+ self._loaded_video_label[0].close()
199
+ self._loaded_video_label = None
200
+ self._last_clip_end_time = None
201
+ self._clip_sampler.reset()
202
+
203
+ # Force garbage collection to release video container immediately
204
+ # otherwise memory can spike.
205
+ gc.collect()
206
+
207
+ if video_is_null:
208
+ logger.debug(
209
+ "Failed to load clip {}; trial {}".format(video.name, i_try)
210
+ )
211
+ continue
212
+
213
+ frames = self._loaded_clip["video"]
214
+ audio_samples = self._loaded_clip["audio"]
215
+ sample_dict = {
216
+ "video": frames,
217
+ "video_name": video.name,
218
+ "video_index": video_index,
219
+ "clip_index": clip_index,
220
+ "aug_index": aug_index,
221
+ **info_dict,
222
+ **({"audio": audio_samples} if audio_samples is not None else {}),
223
+ }
224
+ if self._transform is not None:
225
+ sample_dict = self._transform(sample_dict)
226
+
227
+ # User can force dataset to continue by returning None in transform.
228
+ if sample_dict is None:
229
+ continue
230
+
231
+ return sample_dict
232
+ else:
233
+ raise RuntimeError(
234
+ f"Failed to load video after {self._MAX_CONSECUTIVE_FAILURES} retries."
235
+ )
236
+
237
+ def __iter__(self):
238
+ self._video_sampler_iter = None # Reset video sampler
239
+
240
+ # If we're in a PyTorch DataLoader multiprocessing context, we need to use the
241
+ # same seed for each worker's RandomSampler generator. The workers at each
242
+ # __iter__ call are created from the unique value: worker_info.seed - worker_info.id,
243
+ # which we can use for this seed.
244
+ worker_info = torch.utils.data.get_worker_info()
245
+ if self._video_random_generator is not None and worker_info is not None:
246
+ base_seed = worker_info.seed - worker_info.id
247
+ self._video_random_generator.manual_seed(base_seed)
248
+
249
+ return self
250
+
251
+
252
+ def labeled_video_dataset(
253
+ data_path: str,
254
+ clip_sampler: ClipSampler,
255
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
256
+ transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
257
+ video_path_prefix: str = "",
258
+ decode_audio: bool = True,
259
+ decoder: str = "pyav",
260
+ ) -> LabeledVideoDataset:
261
+ """
262
+ A helper function to create ``LabeledVideoDataset`` object for Ucf101 and Kinetics datasets.
263
+
264
+ Args:
265
+ data_path (str): Path to the data. The path type defines how the data
266
+ should be read:
267
+
268
+ * For a file path, the file is read and each line is parsed into a
269
+ video path and label.
270
+ * For a directory, the directory structure defines the classes
271
+ (i.e. each subdirectory is a class).
272
+
273
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
274
+ video. See the clip sampling documentation for more information.
275
+
276
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
277
+ video container. This defines the order videos are decoded and,
278
+ if necessary, the distributed split.
279
+
280
+ transform (Callable): This callable is evaluated on the clip output before
281
+ the clip is returned. It can be used for user defined preprocessing and
282
+ augmentations to the clips. See the ``LabeledVideoDataset`` class for clip
283
+ output format.
284
+
285
+ video_path_prefix (str): Path to root directory with the videos that are
286
+ loaded in ``LabeledVideoDataset``. All the video paths before loading
287
+ are prefixed with this path.
288
+
289
+ decode_audio (bool): If True, also decode audio from video.
290
+
291
+ decoder (str): Defines what type of decoder used to decode a video.
292
+
293
+ """
294
+ labeled_video_paths = LabeledVideoPaths.from_path(data_path)
295
+ labeled_video_paths.path_prefix = video_path_prefix
296
+ dataset = LabeledVideoDataset(
297
+ labeled_video_paths,
298
+ clip_sampler,
299
+ video_sampler,
300
+ transform,
301
+ decode_audio=decode_audio,
302
+ decoder=decoder,
303
+ )
304
+ return dataset
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/labeled_video_paths.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import pathlib
7
+ from typing import List, Optional, Tuple
8
+
9
+ from iopath.common.file_io import g_pathmgr
10
+ from torchvision.datasets.folder import make_dataset
11
+
12
+
13
+ class LabeledVideoPaths:
14
+ """
15
+ LabeledVideoPaths contains pairs of video path and integer index label.
16
+ """
17
+
18
+ @classmethod
19
+ def from_path(cls, data_path: str) -> LabeledVideoPaths:
20
+ """
21
+ Factory function that creates a LabeledVideoPaths object depending on the path
22
+ type.
23
+ - If it is a directory path it uses the LabeledVideoPaths.from_directory function.
24
+ - If it's a file it uses the LabeledVideoPaths.from_csv file.
25
+ Args:
26
+ file_path (str): The path to the file to be read.
27
+ """
28
+
29
+ if g_pathmgr.isfile(data_path):
30
+ return LabeledVideoPaths.from_csv(data_path)
31
+ elif g_pathmgr.isdir(data_path):
32
+ return LabeledVideoPaths.from_directory(data_path)
33
+ else:
34
+ raise FileNotFoundError(f"{data_path} not found.")
35
+
36
+ @classmethod
37
+ def from_csv(cls, file_path: str) -> LabeledVideoPaths:
38
+ """
39
+ Factory function that creates a LabeledVideoPaths object by reading a file with the
40
+ following format:
41
+ <path> <integer_label>
42
+ ...
43
+ <path> <integer_label>
44
+
45
+ Args:
46
+ file_path (str): The path to the file to be read.
47
+ """
48
+ assert g_pathmgr.exists(file_path), f"{file_path} not found."
49
+ video_paths_and_label = []
50
+ with g_pathmgr.open(file_path, "r") as f:
51
+ for path_label in f.read().splitlines():
52
+ line_split = path_label.rsplit(None, 1)
53
+
54
+ # The video path file may not contain labels (e.g. for a test split). We
55
+ # assume this is the case if only 1 path is found and set the label to
56
+ # -1 if so.
57
+ if len(line_split) == 1:
58
+ file_path = line_split[0]
59
+ label = -1
60
+ else:
61
+ file_path, label = line_split
62
+
63
+ video_paths_and_label.append((file_path, int(label)))
64
+
65
+ assert (
66
+ len(video_paths_and_label) > 0
67
+ ), f"Failed to load dataset from {file_path}."
68
+ return cls(video_paths_and_label)
69
+
70
+ @classmethod
71
+ def from_directory(cls, dir_path: str) -> LabeledVideoPaths:
72
+ """
73
+ Factory function that creates a LabeledVideoPaths object by parsing the structure
74
+ of the given directory's subdirectories into the classification labels. It
75
+ expects the directory format to be the following:
76
+ dir_path/<class_name>/<video_name>.mp4
77
+
78
+ Classes are indexed from 0 to the number of classes, alphabetically.
79
+
80
+ E.g.
81
+ dir_path/class_x/xxx.ext
82
+ dir_path/class_x/xxy.ext
83
+ dir_path/class_x/xxz.ext
84
+ dir_path/class_y/123.ext
85
+ dir_path/class_y/nsdf3.ext
86
+ dir_path/class_y/asd932_.ext
87
+
88
+ Would produce two classes labeled 0 and 1 with 3 videos paths associated with each.
89
+
90
+ Args:
91
+ dir_path (str): Root directory to the video class directories .
92
+ """
93
+ assert g_pathmgr.exists(dir_path), f"{dir_path} not found."
94
+
95
+ # Find all classes based on directory names. These classes are then sorted and indexed
96
+ # from 0 to the number of classes.
97
+ classes = sorted(
98
+ (f.name for f in pathlib.Path(dir_path).iterdir() if f.is_dir())
99
+ )
100
+ class_to_idx = {classes[i]: i for i in range(len(classes))}
101
+ video_paths_and_label = make_dataset(
102
+ dir_path, class_to_idx, extensions=("mp4", "avi")
103
+ )
104
+ assert (
105
+ len(video_paths_and_label) > 0
106
+ ), f"Failed to load dataset from {dir_path}."
107
+ return cls(video_paths_and_label)
108
+
109
+ def __init__(
110
+ self, paths_and_labels: List[Tuple[str, Optional[int]]], path_prefix=""
111
+ ) -> None:
112
+ """
113
+ Args:
114
+ paths_and_labels [(str, int)]: a list of tuples containing the video
115
+ path and integer label.
116
+ """
117
+ self._paths_and_labels = paths_and_labels
118
+ self._path_prefix = path_prefix
119
+
120
+ def path_prefix(self, prefix):
121
+ self._path_prefix = prefix
122
+
123
+ path_prefix = property(None, path_prefix)
124
+
125
+ def __getitem__(self, index: int) -> Tuple[str, int]:
126
+ """
127
+ Args:
128
+ index (int): the path and label index.
129
+
130
+ Returns:
131
+ The path and label tuple for the given index.
132
+ """
133
+ path, label = self._paths_and_labels[index]
134
+ return (os.path.join(self._path_prefix, path), {"label": label})
135
+
136
+ def __len__(self) -> int:
137
+ """
138
+ Returns:
139
+ The number of video paths and label pairs.
140
+ """
141
+ return len(self._paths_and_labels)
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/ucf101.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Any, Callable, Dict, Optional, Type
4
+
5
+ import torch
6
+ from ib_sync_rewards.imagebind.pytorchvideo.data.clip_sampling import ClipSampler
7
+
8
+ from .labeled_video_dataset import labeled_video_dataset, LabeledVideoDataset
9
+
10
+
11
+ """
12
+ Action recognition video dataset for UCF101
13
+ <https://www.crcv.ucf.edu/data/UCF101.php>
14
+ """
15
+
16
+
17
+ def Ucf101(
18
+ data_path: str,
19
+ clip_sampler: ClipSampler,
20
+ video_sampler: Type[torch.utils.data.Sampler] = torch.utils.data.RandomSampler,
21
+ transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
22
+ video_path_prefix: str = "",
23
+ decode_audio: bool = True,
24
+ decoder: str = "pyav",
25
+ ) -> LabeledVideoDataset:
26
+ """
27
+ A helper function to create ``LabeledVideoDataset`` object for the Ucf101 dataset.
28
+
29
+ Args:
30
+ data_path (str): Path to the data. The path type defines how the data
31
+ should be read:
32
+
33
+ * For a file path, the file is read and each line is parsed into a
34
+ video path and label.
35
+ * For a directory, the directory structure defines the classes
36
+ (i.e. each subdirectory is a class).
37
+
38
+ clip_sampler (ClipSampler): Defines how clips should be sampled from each
39
+ video. See the clip sampling documentation for more information.
40
+
41
+ video_sampler (Type[torch.utils.data.Sampler]): Sampler for the internal
42
+ video container. This defines the order videos are decoded and,
43
+ if necessary, the distributed split.
44
+
45
+ transform (Callable): This callable is evaluated on the clip output before
46
+ the clip is returned. It can be used for user defined preprocessing and
47
+ augmentations to the clips. See the ``LabeledVideoDataset`` class for clip
48
+ output format.
49
+
50
+ video_path_prefix (str): Path to root directory with the videos that are
51
+ loaded in ``LabeledVideoDataset``. All the video paths before loading
52
+ are prefixed with this path.
53
+
54
+ decode_audio (bool): If True, also decode audio from video.
55
+
56
+ decoder (str): Defines what type of decoder used to decode a video.
57
+
58
+ """
59
+
60
+ torch._C._log_api_usage_once("PYTORCHVIDEO.dataset.Ucf101")
61
+
62
+ return labeled_video_dataset(
63
+ data_path,
64
+ clip_sampler,
65
+ video_sampler,
66
+ transform,
67
+ video_path_prefix,
68
+ decode_audio,
69
+ decoder,
70
+ )
reward_models/ib_sync_rewards/imagebind/pytorchvideo/data/video.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import BinaryIO, Dict, Optional
5
+
6
+ import torch
7
+ from iopath.common.file_io import g_pathmgr
8
+
9
+
10
+ class VideoPathHandler:
11
+ """
12
+ Utility class that handles all deciphering and caching of video paths for
13
+ encoded and frame videos.
14
+ """
15
+
16
+ def __init__(self) -> None:
17
+ # Pathmanager isn't guaranteed to be in correct order,
18
+ # sorting is expensive, so we cache paths in case of frame video and reuse.
19
+ self.path_order_cache = {}
20
+
21
+ def video_from_path(
22
+ self, filepath, decode_video=True, decode_audio=False, decoder="pyav", fps=30
23
+ ):
24
+ try:
25
+ is_file = g_pathmgr.isfile(filepath)
26
+ is_dir = g_pathmgr.isdir(filepath)
27
+ except NotImplementedError:
28
+ # Not all PathManager handlers support is{file,dir} functions, when this is the
29
+ # case, we default to assuming the path is a file.
30
+ is_file = True
31
+ is_dir = False
32
+
33
+ if is_file:
34
+ from pytorchvideo.data.encoded_video import EncodedVideo
35
+
36
+ return EncodedVideo.from_path(
37
+ filepath,
38
+ decode_video=decode_video,
39
+ decode_audio=decode_audio,
40
+ decoder=decoder,
41
+ )
42
+ elif is_dir:
43
+ from pytorchvideo.data.frame_video import FrameVideo
44
+
45
+ assert not decode_audio, "decode_audio must be False when using FrameVideo"
46
+ return FrameVideo.from_directory(
47
+ filepath, fps, path_order_cache=self.path_order_cache
48
+ )
49
+ else:
50
+ raise FileNotFoundError(f"{filepath} not found.")
51
+
52
+
53
+ class Video(ABC):
54
+ """
55
+ Video provides an interface to access clips from a video container.
56
+ """
57
+
58
+ @abstractmethod
59
+ def __init__(
60
+ self,
61
+ file: BinaryIO,
62
+ video_name: Optional[str] = None,
63
+ decode_audio: bool = True,
64
+ ) -> None:
65
+ """
66
+ Args:
67
+ file (BinaryIO): a file-like object (e.g. io.BytesIO or io.StringIO) that
68
+ contains the encoded video.
69
+ """
70
+ pass
71
+
72
+ @property
73
+ @abstractmethod
74
+ def duration(self) -> float:
75
+ """
76
+ Returns:
77
+ duration of the video in seconds
78
+ """
79
+ pass
80
+
81
+ @abstractmethod
82
+ def get_clip(
83
+ self, start_sec: float, end_sec: float
84
+ ) -> Dict[str, Optional[torch.Tensor]]:
85
+ """
86
+ Retrieves frames from the internal video at the specified start and end times
87
+ in seconds (the video always starts at 0 seconds).
88
+
89
+ Args:
90
+ start_sec (float): the clip start time in seconds
91
+ end_sec (float): the clip end time in seconds
92
+ Returns:
93
+ video_data_dictonary: A dictionary mapping strings to tensor of the clip's
94
+ underlying data.
95
+
96
+ """
97
+ pass
98
+
99
+ def close(self):
100
+ pass
reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/accelerator/mobile_cpu/conv_helper.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ """
4
+ This file contains helper classes for building conv3d efficient blocks.
5
+ The helper classes are intended to be instantiated inside efficient block,
6
+ not to be used by user to build network.
7
+ """
8
+
9
+ from copy import deepcopy
10
+ from typing import Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+
15
+
16
+ class _Reshape(nn.Module):
17
+ """
18
+ Helper class to implement data reshape as a module.
19
+ Args:
20
+ reshape_size (tuple): size of data after reshape.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ reshape_size: Tuple,
26
+ ):
27
+ super().__init__()
28
+ self.reshape_size = reshape_size
29
+
30
+ def forward(self, x):
31
+ return torch.reshape(x, self.reshape_size)
32
+
33
+
34
+ class _SkipConnectMul(nn.Module):
35
+ """
36
+ Helper class to implement skip multiplication.
37
+ Args:
38
+ layer (nn.Module): layer for skip multiplication. With input x, _SkipConnectMul
39
+ implements layer(x)*x.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ layer: nn.Module,
45
+ ):
46
+ super().__init__()
47
+ self.layer = layer
48
+ self.mul_func = nn.quantized.FloatFunctional()
49
+
50
+ def forward(self, x):
51
+ return self.mul_func.mul(x, self.layer(x))
52
+
53
+
54
+ class _Conv3dTemporalKernel3Decomposed(nn.Module):
55
+ """
56
+ Helper class for decomposing conv3d with temporal kernel of 3 into equivalent conv2ds.
57
+ In conv3d with temporal kernel 3 and input I, for output temporal index of t (O[:,:,t,:,:]),
58
+ the conv can be expressed as:
59
+ O[:,:,t,:,:] = conv3d(I[:,:,t:t+3,:,:])
60
+ = conv2d_0(I[:,:,t,:,:]) + conv2d_1(I[:,:,t+1,:,:]) + conv2d_2(I[:,:,t+2,:,:])
61
+ If bias is considered:
62
+ O[:,:,t,:,:] = conv3d_w_bias(I[:,:,t:t+3,:,:])
63
+ = conv2d_0_wo_bias(I[:,:,t,:,:])
64
+ + conv2d_1_w_bias(I[:,:,t+1,:,:]) + conv2d_2_wo_bias(I[:,:,t+2,:,:])
65
+ The input Conv3d also needs zero padding of size 1 in temporal dimension.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ conv3d_in: nn.Conv3d,
71
+ input_THW_tuple: Tuple,
72
+ ):
73
+ """
74
+ Args:
75
+ conv3d_in (nn.Module): input nn.Conv3d module to be converted
76
+ into equivalent conv2d.
77
+ input_THW_tuple (tuple): input THW size for conv3d_in during forward.
78
+ """
79
+ super().__init__()
80
+ assert conv3d_in.padding[0] == 1, (
81
+ "_Conv3dTemporalKernel3Eq only support temporal padding of 1, "
82
+ f"but got {conv3d_in.padding[0]}"
83
+ )
84
+ assert conv3d_in.padding_mode == "zeros", (
85
+ "_Conv3dTemporalKernel3Eq only support zero padding, "
86
+ f"but got {conv3d_in.padding_mode}"
87
+ )
88
+ self._input_THW_tuple = input_THW_tuple
89
+ padding_2d = conv3d_in.padding[1:]
90
+ in_channels = conv3d_in.in_channels
91
+ out_channels = conv3d_in.out_channels
92
+ kernel_size = conv3d_in.kernel_size[1:]
93
+ groups = conv3d_in.groups
94
+ stride_2d = conv3d_in.stride[1:]
95
+ # Create 3 conv2d to emulate conv3d.
96
+ if (
97
+ self._input_THW_tuple[0] > 1
98
+ ): # Those two conv2d are needed only when temporal input > 1.
99
+ self._conv2d_3_3_0 = nn.Conv2d(
100
+ in_channels,
101
+ out_channels,
102
+ kernel_size=kernel_size,
103
+ padding=padding_2d,
104
+ stride=stride_2d,
105
+ groups=groups,
106
+ bias=False,
107
+ )
108
+ self._conv2d_3_3_2 = nn.Conv2d(
109
+ in_channels,
110
+ out_channels,
111
+ kernel_size=kernel_size,
112
+ padding=padding_2d,
113
+ stride=stride_2d,
114
+ groups=groups,
115
+ bias=False,
116
+ )
117
+ self._conv2d_3_3_1 = nn.Conv2d(
118
+ in_channels,
119
+ out_channels,
120
+ kernel_size=kernel_size,
121
+ padding=padding_2d,
122
+ stride=stride_2d,
123
+ groups=groups,
124
+ bias=(conv3d_in.bias is not None),
125
+ )
126
+
127
+ state_dict = conv3d_in.state_dict()
128
+ state_dict_1 = deepcopy(state_dict)
129
+ state_dict_1["weight"] = state_dict["weight"][:, :, 1]
130
+ self._conv2d_3_3_1.load_state_dict(state_dict_1)
131
+
132
+ if self._input_THW_tuple[0] > 1:
133
+ state_dict_0 = deepcopy(state_dict)
134
+ state_dict_0["weight"] = state_dict["weight"][:, :, 0]
135
+ if conv3d_in.bias is not None:
136
+ """
137
+ Don't need bias for other conv2d instances to avoid duplicated addition of bias.
138
+ """
139
+ state_dict_0.pop("bias")
140
+ self._conv2d_3_3_0.load_state_dict(state_dict_0)
141
+
142
+ state_dict_2 = deepcopy(state_dict)
143
+ state_dict_2["weight"] = state_dict["weight"][:, :, 2]
144
+ if conv3d_in.bias is not None:
145
+ state_dict_2.pop("bias")
146
+ self._conv2d_3_3_2.load_state_dict(state_dict_2)
147
+
148
+ self._add_funcs = nn.ModuleList(
149
+ [
150
+ nn.quantized.FloatFunctional()
151
+ for _ in range(2 * (self._input_THW_tuple[0] - 1))
152
+ ]
153
+ )
154
+ self._cat_func = nn.quantized.FloatFunctional()
155
+
156
+ def forward(self, x):
157
+ """
158
+ Use three conv2d to emulate conv3d.
159
+ This forward assumes zero padding of size 1 in temporal dimension.
160
+ """
161
+ if self._input_THW_tuple[0] > 1:
162
+ out_tensor_list = []
163
+ """
164
+ First output plane in temporal dimension,
165
+ conv2d_3_3_0 is skipped due to zero padding.
166
+ """
167
+ cur_tensor = (
168
+ self._add_funcs[0]
169
+ .add(self._conv2d_3_3_1(x[:, :, 0]), self._conv2d_3_3_2(x[:, :, 1]))
170
+ .unsqueeze(2)
171
+ )
172
+ out_tensor_list.append(cur_tensor)
173
+ for idx in range(2, self._input_THW_tuple[0]):
174
+ cur_tensor = (
175
+ self._add_funcs[2 * idx - 3]
176
+ .add(
177
+ self._add_funcs[2 * idx - 2].add(
178
+ self._conv2d_3_3_0(x[:, :, idx - 2]),
179
+ self._conv2d_3_3_1(x[:, :, idx - 1]),
180
+ ),
181
+ self._conv2d_3_3_2(x[:, :, idx]),
182
+ )
183
+ .unsqueeze(2)
184
+ )
185
+ out_tensor_list.append(cur_tensor)
186
+ """
187
+ Last output plane in temporal domain, conv2d_3_3_2 is skipped due to zero padding.
188
+ """
189
+ cur_tensor = (
190
+ self._add_funcs[-1]
191
+ .add(self._conv2d_3_3_0(x[:, :, -2]), self._conv2d_3_3_1(x[:, :, -1]))
192
+ .unsqueeze(2)
193
+ )
194
+ out_tensor_list.append(cur_tensor)
195
+ return self._cat_func.cat(out_tensor_list, 2)
196
+ else: # Degenerated to simple conv2d
197
+ return self._conv2d_3_3_1(x[:, :, 0]).unsqueeze(2)
198
+
199
+
200
+ class _Conv3dTemporalKernel5Decomposed(nn.Module):
201
+ """
202
+ Helper class for decomposing conv3d with kernel size of (5, k, k) into equivalent conv2ds.
203
+ In such conv3d and input I, for output temporal index of t (O[:,:,t,:,:]), the conv
204
+ can be expressed as:
205
+ O[:,:,t,:,:] = conv3d(I[:,:,t:t+5,:,:])
206
+ = conv2d_0(I[:,:,t,:,:]) + conv2d_1(I[:,:,t+1,:,:]) + conv2d_2(I[:,:,t+2,:,:])
207
+ + conv2d_3(I[:,:,t+3,:,:]) + conv2d_4(I[:,:,t+4,:,:])
208
+ If bias is considered:
209
+ O[:,:,t,:,:] = conv3d_w_bias(I[:,:,t:t+3,:,:])
210
+ = conv2d_0_wo_bias(I[:,:,t,:,:])
211
+ + conv2d_1_wo_bias(I[:,:,t+1,:,:]) + conv2d_2_w_bias(I[:,:,t+2,:,:])
212
+ + conv2d_3_wo_bias(I[:,:,t+1,:,:]) + conv2d_4_wo_bias(I[:,:,t+2,:,:])
213
+ The input Conv3d also needs zero padding of size 2 in temporal dimension at begin and end.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ conv3d_in: nn.Conv3d,
219
+ thw_shape: Tuple[int, int, int],
220
+ ):
221
+ """
222
+ Args:
223
+ conv3d_in (nn.Module): input nn.Conv3d module to be converted
224
+ into equivalent conv2d.
225
+ thw_shape (tuple): input THW size for conv3d_in during forward.
226
+ """
227
+ super().__init__()
228
+ assert conv3d_in.padding[0] == 2, (
229
+ "_Conv3dTemporalKernel5Eq only support temporal padding of 2, "
230
+ f"but got {conv3d_in.padding[0]}"
231
+ )
232
+ assert conv3d_in.padding_mode == "zeros", (
233
+ "_Conv3dTemporalKernel5Eq only support zero padding, "
234
+ f"but got {conv3d_in.padding_mode}"
235
+ )
236
+ self._thw_shape = thw_shape
237
+ padding_2d = conv3d_in.padding[1:]
238
+ in_channels = conv3d_in.in_channels
239
+ out_channels = conv3d_in.out_channels
240
+ kernel_size = conv3d_in.kernel_size[1:]
241
+ groups = conv3d_in.groups
242
+ stride_2d = conv3d_in.stride[1:]
243
+ # Create 3 conv2d to emulate conv3d.
244
+ t, h, w = self._thw_shape
245
+ args_dict = {
246
+ "in_channels": in_channels,
247
+ "out_channels": out_channels,
248
+ "kernel_size": kernel_size,
249
+ "padding": padding_2d,
250
+ "stride": stride_2d,
251
+ "groups": groups,
252
+ }
253
+
254
+ for iter_idx in range(5):
255
+ if iter_idx != 2:
256
+ if t > 1: # Those four conv2d are needed only when temporal input > 1.
257
+ self.add_module(
258
+ f"_conv2d_{iter_idx}", nn.Conv2d(**args_dict, bias=False)
259
+ )
260
+ else: # _conv2d_2 is needed for all circumstances.
261
+ self.add_module(
262
+ f"_conv2d_{iter_idx}",
263
+ nn.Conv2d(**args_dict, bias=(conv3d_in.bias is not None)),
264
+ )
265
+
266
+ # State dict for _conv2d_2
267
+ original_state_dict = conv3d_in.state_dict()
268
+ state_dict_to_load = deepcopy(original_state_dict)
269
+ state_dict_to_load["weight"] = original_state_dict["weight"][:, :, 2]
270
+ self._conv2d_2.load_state_dict(state_dict_to_load)
271
+
272
+ if t > 1:
273
+ if conv3d_in.bias is not None:
274
+ # Don't need bias for other conv2d instances to avoid duplicated
275
+ # addition of bias.
276
+ state_dict_to_load.pop("bias")
277
+ # State dict for _conv2d_0, _conv2d_1, _conv2d_3, _conv2d_4
278
+ state_dict_to_load["weight"] = original_state_dict["weight"][:, :, 0]
279
+ self._conv2d_0.load_state_dict(state_dict_to_load)
280
+
281
+ state_dict_to_load["weight"] = original_state_dict["weight"][:, :, 1]
282
+ self._conv2d_1.load_state_dict(state_dict_to_load)
283
+
284
+ state_dict_to_load["weight"] = original_state_dict["weight"][:, :, 3]
285
+ self._conv2d_3.load_state_dict(state_dict_to_load)
286
+
287
+ state_dict_to_load["weight"] = original_state_dict["weight"][:, :, 4]
288
+ self._conv2d_4.load_state_dict(state_dict_to_load)
289
+ # Elementwise add are needed in forward function, use nn.quantized.FloatFunctional()
290
+ # for better quantization support. One convolution needs at most 4 elementwise adds
291
+ # without zero padding; for boundary planes fewer elementwise adds are needed.
292
+ # See forward() for more details.
293
+ self._add_funcs = nn.ModuleList(
294
+ [nn.quantized.FloatFunctional() for _ in range(4 * t - 6)]
295
+ )
296
+ self._cat_func = nn.quantized.FloatFunctional()
297
+
298
+ def forward(self, x):
299
+ """
300
+ Use three conv2d to emulate conv3d.
301
+ Args:
302
+ x (torch.Tensor): 5D tensor of (B, C, T, H, W)
303
+ """
304
+ t, h, w = self._thw_shape
305
+ out_tensor_list = []
306
+ if (
307
+ t == 1
308
+ ): # Degenerated to simple conv2d, but make sure output still has T dimension
309
+ return self._conv2d_2(x[:, :, 0]).unsqueeze(2)
310
+ elif t == 2:
311
+ # out_tensor_list[0]: conv2d_1_1_0, conv2d_1_1_1 and conv2d_1_1_4 are
312
+ # applied to zero padding.
313
+ cur_tensor = (
314
+ self._add_funcs[0]
315
+ .add(self._conv2d_2(x[:, :, 0]), self._conv2d_3(x[:, :, 1]))
316
+ .unsqueeze(2)
317
+ )
318
+ out_tensor_list.append(cur_tensor)
319
+ # out_tensor_list[1]: conv2d_1_1_0, conv2d_1_1_3 and conv2d_1_1_4 are
320
+ # applied to zero padding.
321
+
322
+ cur_tensor = (
323
+ self._add_funcs[1]
324
+ .add(self._conv2d_1(x[:, :, 0]), self._conv2d_2(x[:, :, 1]))
325
+ .unsqueeze(2)
326
+ )
327
+ out_tensor_list.append(cur_tensor)
328
+ elif t == 3:
329
+ # out_tensor_list[0]: conv2d_1_1_0, conv2d_1_1_1 are applied to zero padding.
330
+ cur_tensor = (
331
+ self._add_funcs[0]
332
+ .add(
333
+ self._add_funcs[1].add(
334
+ self._conv2d_2(x[:, :, 0]), self._conv2d_3(x[:, :, 1])
335
+ ),
336
+ self._conv2d_4(x[:, :, 2]),
337
+ )
338
+ .unsqueeze(2)
339
+ )
340
+ out_tensor_list.append(cur_tensor)
341
+ # out_tensor_list[1]: conv2d_1_1_0, conv2d_1_1_4 are applied to zero padding.
342
+ cur_tensor = (
343
+ self._add_funcs[2]
344
+ .add(
345
+ self._add_funcs[3].add(
346
+ self._conv2d_1(x[:, :, 0]), self._conv2d_2(x[:, :, 1])
347
+ ),
348
+ self._conv2d_3(x[:, :, 2]),
349
+ )
350
+ .unsqueeze(2)
351
+ )
352
+ out_tensor_list.append(cur_tensor)
353
+ # out_tensor_list[2]: conv2d_1_1_3, conv2d_1_1_4 are applied to zero padding.
354
+ cur_tensor = (
355
+ self._add_funcs[4]
356
+ .add(
357
+ self._add_funcs[5].add(
358
+ self._conv2d_0(x[:, :, 0]), self._conv2d_1(x[:, :, 1])
359
+ ),
360
+ self._conv2d_2(x[:, :, 2]),
361
+ )
362
+ .unsqueeze(2)
363
+ )
364
+ out_tensor_list.append(cur_tensor)
365
+ elif t == 4:
366
+ # out_tensor_list[0]: conv2d_1_1_0, conv2d_1_1_1 are applied to zero padding.
367
+ cur_tensor = (
368
+ self._add_funcs[0]
369
+ .add(
370
+ self._add_funcs[1].add(
371
+ self._conv2d_2(x[:, :, 0]), self._conv2d_3(x[:, :, 1])
372
+ ),
373
+ self._conv2d_4(x[:, :, 2]),
374
+ )
375
+ .unsqueeze(2)
376
+ )
377
+ out_tensor_list.append(cur_tensor)
378
+ # out_tensor_list[1]: conv2d_1_1_0 is applied to zero padding.
379
+ cur_tensor = (
380
+ self._add_funcs[2]
381
+ .add(
382
+ self._add_funcs[3].add(
383
+ self._add_funcs[4].add(
384
+ self._conv2d_1(x[:, :, 0]),
385
+ self._conv2d_2(x[:, :, 1]),
386
+ ),
387
+ self._conv2d_3(x[:, :, 2]),
388
+ ),
389
+ self._conv2d_4(x[:, :, 3]),
390
+ )
391
+ .unsqueeze(2)
392
+ )
393
+ out_tensor_list.append(cur_tensor)
394
+ # out_tensor_list[2]: conv2d_1_1_4 is applied to zero padding.
395
+ cur_tensor = (
396
+ self._add_funcs[5]
397
+ .add(
398
+ self._add_funcs[6].add(
399
+ self._add_funcs[7].add(
400
+ self._conv2d_0(x[:, :, 0]),
401
+ self._conv2d_1(x[:, :, 1]),
402
+ ),
403
+ self._conv2d_2(x[:, :, 2]),
404
+ ),
405
+ self._conv2d_3(x[:, :, 3]),
406
+ )
407
+ .unsqueeze(2)
408
+ )
409
+ out_tensor_list.append(cur_tensor)
410
+ # out_tensor_list[3]: conv2d_1_1_3, conv2d_1_1_4 are applied to zero padding.
411
+ cur_tensor = (
412
+ self._add_funcs[8]
413
+ .add(
414
+ self._add_funcs[9].add(
415
+ self._conv2d_0(x[:, :, 1]), self._conv2d_1(x[:, :, 2])
416
+ ),
417
+ self._conv2d_2(x[:, :, 3]),
418
+ )
419
+ .unsqueeze(2)
420
+ )
421
+ out_tensor_list.append(cur_tensor)
422
+ else: # t >= 5
423
+ # out_tensor_list[0]: conv2d_1_1_0, conv2d_1_1_1 are applied to zero padding.
424
+ add_func_idx_base = 0
425
+ cur_tensor = (
426
+ self._add_funcs[add_func_idx_base]
427
+ .add(
428
+ self._add_funcs[add_func_idx_base + 1].add(
429
+ self._conv2d_2(x[:, :, 0]), self._conv2d_3(x[:, :, 1])
430
+ ),
431
+ self._conv2d_4(x[:, :, 2]),
432
+ )
433
+ .unsqueeze(2)
434
+ )
435
+ out_tensor_list.append(cur_tensor)
436
+ add_func_idx_base += 2
437
+ # out_tensor_list[1]: conv2d_1_1_0 is applied to zero padding.
438
+ cur_tensor = (
439
+ self._add_funcs[add_func_idx_base]
440
+ .add(
441
+ self._add_funcs[add_func_idx_base + 1].add(
442
+ self._add_funcs[add_func_idx_base + 2].add(
443
+ self._conv2d_1(x[:, :, 0]),
444
+ self._conv2d_2(x[:, :, 1]),
445
+ ),
446
+ self._conv2d_3(x[:, :, 2]),
447
+ ),
448
+ self._conv2d_4(x[:, :, 3]),
449
+ )
450
+ .unsqueeze(2)
451
+ )
452
+ out_tensor_list.append(cur_tensor)
453
+ add_func_idx_base += 3
454
+ # out_tensor_list[2:-2]: zero padding has no effect.
455
+ for idx in range(4, t):
456
+ cur_tensor = (
457
+ self._add_funcs[add_func_idx_base]
458
+ .add(
459
+ self._add_funcs[add_func_idx_base + 1].add(
460
+ self._add_funcs[add_func_idx_base + 2].add(
461
+ self._add_funcs[add_func_idx_base + 3].add(
462
+ self._conv2d_0(x[:, :, idx - 4]),
463
+ self._conv2d_1(x[:, :, idx - 3]),
464
+ ),
465
+ self._conv2d_2(x[:, :, idx - 2]),
466
+ ),
467
+ self._conv2d_3(x[:, :, idx - 1]),
468
+ ),
469
+ self._conv2d_4(x[:, :, idx]),
470
+ )
471
+ .unsqueeze(2)
472
+ )
473
+ out_tensor_list.append(cur_tensor)
474
+ add_func_idx_base += 4
475
+ # out_tensor_list[-2]: conv2d_1_1_4 is applied to zero padding.
476
+ cur_tensor = (
477
+ self._add_funcs[add_func_idx_base]
478
+ .add(
479
+ self._add_funcs[add_func_idx_base + 1].add(
480
+ self._add_funcs[add_func_idx_base + 2].add(
481
+ self._conv2d_0(x[:, :, -4]),
482
+ self._conv2d_1(x[:, :, -3]),
483
+ ),
484
+ self._conv2d_2(x[:, :, -2]),
485
+ ),
486
+ self._conv2d_3(x[:, :, -1]),
487
+ )
488
+ .unsqueeze(2)
489
+ )
490
+ out_tensor_list.append(cur_tensor)
491
+ add_func_idx_base += 3
492
+ # out_tensor_list[-1]: conv2d_1_1_3, conv2d_1_1_4 are applied to zero padding.
493
+ cur_tensor = (
494
+ self._add_funcs[add_func_idx_base]
495
+ .add(
496
+ self._add_funcs[add_func_idx_base + 1].add(
497
+ self._conv2d_0(x[:, :, -3]),
498
+ self._conv2d_1(x[:, :, -2]),
499
+ ),
500
+ self._conv2d_2(x[:, :, -1]),
501
+ )
502
+ .unsqueeze(2)
503
+ )
504
+ out_tensor_list.append(cur_tensor)
505
+ return self._cat_func.cat(out_tensor_list, 2)
506
+
507
+
508
+ class _Conv3dTemporalKernel1Decomposed(nn.Module):
509
+ """
510
+ Helper class for decomposing conv3d with temporal kernel of 1 into conv2d on
511
+ multiple temporal planes.
512
+ In conv3d with temporal kernel 1 and input I, for output temporal index of t (O[:,:,t,:,:]),
513
+ the conv can be expressed as:
514
+ O[:,:,t,:,:] = conv3d(I[:,:,t,:,:])
515
+ = conv2d(I[:,:,t,:,:])
516
+ The full output can be obtained by concat O[:,:,t,:,:] for t in 0...T,
517
+ where T is the length of I in temporal dimension.
518
+ """
519
+
520
+ def __init__(
521
+ self,
522
+ conv3d_eq: nn.Conv3d,
523
+ input_THW_tuple: Tuple,
524
+ ):
525
+ """
526
+ Args:
527
+ conv3d_eq (nn.Module): input nn.Conv3d module to be converted
528
+ into equivalent conv2d.
529
+ input_THW_tuple (tuple): input THW size for conv3d_eq during forward.
530
+ """
531
+ super().__init__()
532
+ # create equivalent conv2d module
533
+ in_channels = conv3d_eq.in_channels
534
+ out_channels = conv3d_eq.out_channels
535
+ bias_flag = conv3d_eq.bias is not None
536
+ self.conv2d_eq = nn.Conv2d(
537
+ in_channels,
538
+ out_channels,
539
+ kernel_size=(conv3d_eq.kernel_size[1], conv3d_eq.kernel_size[2]),
540
+ stride=(conv3d_eq.stride[1], conv3d_eq.stride[2]),
541
+ groups=conv3d_eq.groups,
542
+ bias=bias_flag,
543
+ padding=(conv3d_eq.padding[1], conv3d_eq.padding[2]),
544
+ dilation=(conv3d_eq.dilation[1], conv3d_eq.dilation[2]),
545
+ )
546
+ state_dict = conv3d_eq.state_dict()
547
+ state_dict["weight"] = state_dict["weight"].squeeze(2)
548
+ self.conv2d_eq.load_state_dict(state_dict)
549
+ self.input_THW_tuple = input_THW_tuple
550
+
551
+ def forward(self, x):
552
+ out_tensor_list = []
553
+ for idx in range(self.input_THW_tuple[0]):
554
+ cur_tensor = self.conv2d_eq(x[:, :, idx]).unsqueeze(2)
555
+ out_tensor_list.append(cur_tensor)
556
+ return torch.cat(out_tensor_list, 2)
reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/accelerator/mobile_cpu/convolutions.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ import logging
4
+ from collections import OrderedDict
5
+ from typing import Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from pytorchvideo.accelerator.efficient_blocks.efficient_block_base import (
10
+ EfficientBlockBase,
11
+ )
12
+
13
+ from .activation_functions import supported_act_functions
14
+ from .conv_helper import (
15
+ _Conv3dTemporalKernel1Decomposed,
16
+ _Conv3dTemporalKernel3Decomposed,
17
+ _Conv3dTemporalKernel5Decomposed,
18
+ _Reshape,
19
+ )
20
+
21
+
22
+ TORCH_VERSION: Tuple[int, ...] = tuple(int(x) for x in torch.__version__.split(".")[:2])
23
+ if TORCH_VERSION >= (1, 11):
24
+ from torch.ao.quantization import fuse_modules
25
+ else:
26
+ from torch.quantization import fuse_modules
27
+
28
+
29
+ class Conv3dPwBnAct(EfficientBlockBase):
30
+ """
31
+ Implements Conv3d + Bn + Activation for pointwise layers.
32
+ The conv layer has fixed kernel_size = (1,1,1),
33
+ groups = 1, padding = 0, stride = 1, dilation = 1.
34
+
35
+ Input
36
+ |
37
+
38
+ conv3d (1x1x1)
39
+
40
+ BatchNorm (optional)
41
+
42
+ Activation
43
+
44
+ Conv3dPwBnAct is in original form (for training) once instantiated. User can
45
+ call convert() method to convert it into deployable form for deployment.
46
+
47
+ convert_flag variable is to record whether the Conv3dPwBnAct instance
48
+ has been converted; Conv3dPwBnAct is in original form if convert_flag is false,
49
+ while it is in deployable form if convert_flag is true.
50
+
51
+ Current implementation of this layer in QNNPACK is very efficient.
52
+ Args:
53
+ in_channels (int): number of input channels for conv3d 1x1x1.
54
+ out_channels (int): number of output channels for conv3d 1x1x1.
55
+ bias (bool): if true, use bias for conv.
56
+ activation (str): applies selected activation from supported_act_functions.
57
+ See activation_functions.py for more info about supported activations.
58
+ Currently ReLU ('relu'), Swish ('swish'), Hardswish ('hswish'), Identity
59
+ ('identity') are supported.
60
+ use_bn (bool): if true, use batchnorm.
61
+ norm_eps (float): epsilon for batchnorm.
62
+ norm_momentum (float): momentum for batchnorm.
63
+
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ in_channels: int,
69
+ out_channels: int,
70
+ bias=False,
71
+ activation: str = "relu",
72
+ use_bn=True,
73
+ norm_eps: float = 1e-5,
74
+ norm_momentum: float = 0.1,
75
+ ):
76
+ super().__init__()
77
+ self._in_channels = in_channels
78
+ self._out_channels = out_channels
79
+ self.act = activation
80
+ kernel = OrderedDict()
81
+ kernel["conv"] = nn.Conv3d(in_channels, out_channels, kernel_size=1, bias=bias)
82
+ if use_bn:
83
+ kernel["bn"] = nn.BatchNorm3d(
84
+ out_channels, eps=norm_eps, momentum=norm_momentum
85
+ )
86
+ assert (
87
+ activation in supported_act_functions
88
+ ), f"Conv3dPwBnAct: {activation} is not in supported_act_functions."
89
+ kernel["act"] = supported_act_functions[activation]()
90
+ self.kernel = nn.Sequential(kernel)
91
+ self.convert_flag = False
92
+
93
+ def convert(
94
+ self,
95
+ input_blob_size: Tuple,
96
+ convert_for_quantize: bool = False,
97
+ native_conv3d_op_qnnpack: bool = False,
98
+ **kwargs,
99
+ ):
100
+ """
101
+ Converts the block into efficient form.
102
+ For fp32 operation, or quantized but with older version of QNNPACK w/o native int8
103
+ Conv3d support, this function converts Conv3d into equivalent Conv2d for Pytorch
104
+ Mobile deployment.
105
+ The Conv3d -> Conv2d conversion is done by first fuse conv3d with bn,
106
+ convert conv3d into equivalent conv2d, and optionally fuse conv2d with relu.
107
+ After conversion, the forwarding of this module becomes:
108
+ Input (5d tensor) --> reshape (4d tensor) --> conv2d (4d tensor)
109
+ --> reshape (5d tensor) --> output (5d tensor)
110
+
111
+ For quantized operation on new version of QNNPACK with native int8 Conv3d, this
112
+ function will only apply operator fusion.
113
+ Args:
114
+ input_blob_size (tuple): blob size at the input of Conv3dPwBnAct instance.
115
+ convert_for_quantize (bool): whether this module is intended to be quantized.
116
+ native_conv3d_op_qnnpack (bool): whether the QNNPACK version has native int8
117
+ Conv3d.
118
+ kwargs (any): any extra keyword arguments from upstream unused by convert().
119
+ """
120
+ assert (
121
+ self.convert_flag is False
122
+ ), "Conv3dPwBnAct: already converted, cannot be converted again"
123
+ self.kernel.eval()
124
+ # First fuse conv and bn if bn exists.
125
+ if hasattr(self.kernel, "bn"):
126
+ self.kernel = fuse_modules(self.kernel, ["conv", "bn"])
127
+ # If user intends to quantize the module and their QNNPACK comes with native int8 Conv3d,
128
+ # then we just need to do fusion.
129
+ if convert_for_quantize and native_conv3d_op_qnnpack:
130
+ if self.act == "relu":
131
+ self.kernel = fuse_modules(self.kernel, ["conv", "act.act"])
132
+ # Set new kernel in eval mode again
133
+ self.kernel.eval()
134
+ # Else, for fp32 operation or for int8 but with older version of QNNPACK w/o native int8 Conv3d,
135
+ # we need to unfold Conv3d into Conv2ds.
136
+ else:
137
+ batch_size = input_blob_size[0]
138
+ input_THW_tuple = input_blob_size[2:]
139
+ self._input_tensor_reshape_size = (
140
+ batch_size,
141
+ self._in_channels, # C
142
+ input_THW_tuple[0] * input_THW_tuple[1], # T*H
143
+ input_THW_tuple[2], # W
144
+ )
145
+ self._output_tensor_size = (
146
+ batch_size,
147
+ self._out_channels, # C
148
+ input_THW_tuple[0], # T
149
+ input_THW_tuple[1], # H
150
+ input_THW_tuple[2], # W
151
+ )
152
+ conv2d_eq = nn.Conv2d(
153
+ self._in_channels,
154
+ self._out_channels,
155
+ kernel_size=1,
156
+ bias=(self.kernel.conv.bias is not None),
157
+ )
158
+ conv_state_dict = self.kernel.conv.state_dict()
159
+ conv_state_dict["weight"] = conv_state_dict["weight"].squeeze(2)
160
+ conv2d_eq.load_state_dict(conv_state_dict)
161
+ self.kernel.conv = conv2d_eq
162
+ # Convert activatiopn function
163
+ self.kernel.act.convert(input_blob_size, **kwargs)
164
+ # Fuse act with conv after conv3d -> conv2d if act is relu
165
+ if self.act == "relu":
166
+ self.kernel = fuse_modules(self.kernel, ["conv", "act.act"])
167
+ # Insert reshape layers before/after conv2d
168
+ self.kernel = nn.Sequential(
169
+ _Reshape(self._input_tensor_reshape_size),
170
+ self.kernel,
171
+ _Reshape(self._output_tensor_size),
172
+ )
173
+ # Set new kernel in eval mode again
174
+ self.kernel.eval()
175
+ self.convert_flag = True
176
+
177
+ def forward(self, x):
178
+ x = self.kernel(x)
179
+ return x
180
+
181
+
182
+ class Conv3d3x3x3DwBnAct(EfficientBlockBase):
183
+ """
184
+ Implements Conv3d (3x3x3 dw) + (optional) Bn + Activation layers.
185
+ The conv layer has fixed kernel_size = (3,3,3), depthwise, zero padding size of
186
+ (1,1,1), temporal stride = 1, dilation = 1
187
+
188
+ Input
189
+ |
190
+
191
+ conv3d (3x3x3 dw)
192
+
193
+ BatchNorm (optional)
194
+
195
+ Activation
196
+
197
+ Current implementation of this layer in QNNPACK is reasonably efficient.
198
+
199
+ convert_flag variable is to record whether the Conv3d3x3x3DwBnAct instance
200
+ has been converted; Conv3d3x3x3DwBnAct is in original form if convert_flag is false,
201
+ while it is in deployable form if convert_flag is true.
202
+
203
+ Args:
204
+ in_channels (int): number of channels for conv3d 3x3x3 dw.
205
+ spatial_stride (tuple length of 2): spatial stride for conv.
206
+ bias (bool): if true, use bias for conv.
207
+ activation (str): applies selected activation from supported_act_functions.
208
+ See activation_functions.py for more info about supported activations.
209
+ Currently ReLU ('relu'), Swish ('swish'), Hardswish ('hswish'), Identity
210
+ ('identity') are supported.
211
+ use_bn (bool): if true, use batchnorm.
212
+ norm_eps (float): epsilon for batchnorm.
213
+ norm_momentum (float): momentum for batchnorm.
214
+
215
+ Current implementation of this layer in Pytorch Mobile is efficient.
216
+ Sidenote: QNNPACK has best support for dw with 3x3 spatial kernel.
217
+ For other spatial kernels like 7x7 dw, the efficiency may be lower.
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ in_channels: int,
223
+ spatial_stride: int = 1,
224
+ bias=False,
225
+ activation: str = "relu",
226
+ use_bn=True,
227
+ norm_eps: float = 1e-5,
228
+ norm_momentum: float = 0.1,
229
+ ):
230
+ super().__init__()
231
+ kernel = OrderedDict()
232
+ conv_stride = (1, spatial_stride, spatial_stride)
233
+ kernel["conv"] = nn.Conv3d(
234
+ in_channels,
235
+ in_channels,
236
+ kernel_size=(3, 3, 3),
237
+ stride=conv_stride,
238
+ groups=in_channels,
239
+ padding=1,
240
+ bias=bias,
241
+ )
242
+ if use_bn:
243
+ kernel["bn"] = nn.BatchNorm3d(
244
+ in_channels, eps=norm_eps, momentum=norm_momentum
245
+ )
246
+ assert (
247
+ activation in supported_act_functions
248
+ ), f"Conv3d3x3x3DwBnAct: {activation} is not in supported_act_functions."
249
+ kernel["act"] = supported_act_functions[activation]()
250
+ self.kernel = nn.Sequential(kernel)
251
+
252
+ self.convert_flag = False
253
+
254
+ def convert(
255
+ self,
256
+ input_blob_size: Tuple,
257
+ convert_for_quantize: bool = False,
258
+ native_conv3d_op_qnnpack: bool = False,
259
+ **kwargs,
260
+ ):
261
+ """
262
+ Converts the block into efficient form.
263
+ For fp32 operation, or quantized but with older version of QNNPACK w/o native int8
264
+ Conv3d support, this function converts Conv3d into equivalent Conv2d for Pytorch
265
+ Mobile deployment.
266
+ For quantized operation on new version of QNNPACK with native int8 Conv3d, this
267
+ function will only apply operator fusion.
268
+ Args:
269
+ input_blob_size (tuple): blob size at the input of Conv3d3x3x3DwBnAct
270
+ instance during forward.
271
+ convert_for_quantize (bool): whether this module is intended to be quantized.
272
+ native_conv3d_op_qnnpack (bool): whether the QNNPACK version has native int8
273
+ Conv3d.
274
+ kwargs (any): any keyword argument (unused).
275
+ """
276
+ assert (
277
+ self.convert_flag is False
278
+ ), "Conv3d3x3x3DwBnAct: already converted, cannot be converted twice."
279
+ self.kernel.eval()
280
+ # Fuse conv and bn if bn exists.
281
+ if hasattr(self.kernel, "bn"):
282
+ self.kernel = fuse_modules(self.kernel, ["conv", "bn"])
283
+ # Convert Conv3d into equivalent Conv2d if using fp32 operation (convert_for_quantize
284
+ # is False) or not using QNNPACK native conv3d (native_conv3d_op_qnnpack is False)
285
+ if (convert_for_quantize is False) or (native_conv3d_op_qnnpack is False):
286
+ self.kernel.conv = _Conv3dTemporalKernel3Decomposed(
287
+ self.kernel.conv, input_blob_size[2:]
288
+ )
289
+ # Convert activatiopn function
290
+ self.kernel.act.convert(input_blob_size, **kwargs)
291
+ """
292
+ Since conv3d is converted into multiple conv2d,
293
+ will not fuse conv with act to keep arithmetic equivalency.
294
+ """
295
+ self.convert_flag = True
296
+ # Set new kernel in eval mode again
297
+ self.kernel.eval()
298
+
299
+ def forward(self, x):
300
+ x = self.kernel(x)
301
+ return x
302
+
303
+
304
+ class Conv3dTemporalKernel1BnAct(EfficientBlockBase):
305
+ """
306
+ Implements Conv3d + Bn + Activation where Conv3d has temporal kernel of 1.
307
+ The conv layer has padding[0] = 0, stride[0] = 1, dilation[0] = 1.
308
+
309
+ Input
310
+ |
311
+
312
+ conv3d (1xkxk)
313
+
314
+ BatchNorm (optional)
315
+
316
+ Activation
317
+
318
+ Current implementation of this layer in QNNPACK is reasonably efficient
319
+ (not as efficient as Conv3dPwBnAct for 1x1x1 kernel).
320
+ Args:
321
+ in_channels (int): number of input channels for conv3d 1x1x1.
322
+ out_channels (int): number of output channels for conv3d 1x1x1.
323
+ bias (bool): if true, use bias for conv.
324
+ groups (int): number of groups for conv.
325
+ spstial_kernel (int): spatial kernel for conv3d.
326
+ spstial_stride (int): spatial stride for conv3d.
327
+ spatial_padding (int): spatial padding for conv3d.
328
+ spatial_dilation (int): spatial dilation for conv3d.
329
+ activation (str): applies selected activation from supported_act_functions.
330
+ See activation_functions.py for more info about supported activations.
331
+ Currently ReLU ('relu'), Swish ('swish'), Hardswish ('hswish'), Identity
332
+ ('identity') are supported.
333
+ use_bn (bool): if true, use batchnorm.
334
+ norm_eps (float): epsilon for batchnorm.
335
+ norm_momentum (float): momentum for batchnorm.
336
+
337
+ """
338
+
339
+ def __init__(
340
+ self,
341
+ in_channels: int,
342
+ out_channels: int,
343
+ bias=False,
344
+ groups: int = 1,
345
+ spatial_kernel: int = 1,
346
+ spatial_stride: int = 1,
347
+ spatial_padding: int = 0,
348
+ spatial_dilation: int = 1,
349
+ activation: str = "relu",
350
+ use_bn=True,
351
+ norm_eps: float = 1e-5,
352
+ norm_momentum: float = 0.1,
353
+ ):
354
+ super().__init__()
355
+
356
+ kernel_size = (1, spatial_kernel, spatial_kernel)
357
+ stride = (1, spatial_stride, spatial_stride)
358
+ padding = (0, spatial_padding, spatial_padding)
359
+ dilation = (1, spatial_dilation, spatial_dilation)
360
+ kernel = OrderedDict()
361
+ kernel["conv"] = nn.Conv3d(
362
+ in_channels,
363
+ out_channels,
364
+ kernel_size=kernel_size,
365
+ padding=padding,
366
+ stride=stride,
367
+ dilation=dilation,
368
+ groups=groups,
369
+ bias=bias,
370
+ )
371
+ if use_bn:
372
+ kernel["bn"] = nn.BatchNorm3d(
373
+ out_channels, eps=norm_eps, momentum=norm_momentum
374
+ )
375
+ assert (
376
+ activation in supported_act_functions
377
+ ), f"Conv3dTemporalKernel1BnAct: {activation} is not in supported_act_functions."
378
+ kernel["act"] = supported_act_functions[activation]()
379
+ self.kernel = nn.Sequential(kernel)
380
+
381
+ self.convert_flag = False
382
+
383
+ def convert(
384
+ self,
385
+ input_blob_size: Tuple,
386
+ **kwargs,
387
+ ):
388
+ """
389
+ Converts Conv3d into equivalent Conv2d for QNNPACK deployment.
390
+ This conversion is done by first fuse conv3d with bn,
391
+ convert conv3d into equivalent conv2d,
392
+ and optionally fuse conv2d with relu.
393
+ Args:
394
+ input_blob_size (tuple): blob size at the input of
395
+ Conv3dTemporalKernel1BnAct instance during forward.
396
+ kwargs (any): any keyword argument (unused).
397
+ """
398
+ assert (
399
+ self.convert_flag is False
400
+ ), "Conv3dTemporalKernel1BnAct: already converted, cannot be converted again"
401
+ self.kernel.eval()
402
+ # First fuse conv and bn if bn exists.
403
+ if hasattr(self.kernel, "bn"):
404
+ self.kernel = fuse_modules(self.kernel, ["conv", "bn"])
405
+
406
+ self.kernel.conv = _Conv3dTemporalKernel1Decomposed(
407
+ self.kernel.conv, input_blob_size[2:]
408
+ )
409
+ # Convert activatiopn function
410
+ self.kernel.act.convert(input_blob_size, **kwargs)
411
+
412
+ self.convert_flag = True
413
+ # Set new kernel in eval mode again
414
+ self.kernel.eval()
415
+
416
+ def forward(self, x):
417
+ x = self.kernel(x)
418
+ return x
419
+
420
+
421
+ class Conv3d3x1x1BnAct(EfficientBlockBase):
422
+ """
423
+ Implements Conv3d (3x1x1) + (optional) Bn + Activation for pointwise layers.
424
+ The conv layer has fixed kernel of (3, 1, 1), zero padding size of
425
+ (1, 0, 0), stride = (1, 1, 1), dilation = 1.
426
+
427
+ Input
428
+ |
429
+
430
+ conv3d (3x1x1)
431
+
432
+ BatchNorm (optional)
433
+
434
+ Activation
435
+
436
+ For regular convolution (i.e., groups=1), current implementation of this layer in
437
+ QNNPACK is reasonably efficient.
438
+ For depthwise convolution (i.e., groups=out_channels), current implementation of this
439
+ layer in QNNPACK is not efficient as Conv3d3x3x3DwBnRelu, as QNNPACK does not have
440
+ optimization for 1x1 depthwise convolution. The latencies of fp32 operation are similar
441
+ for Conv3d3x1x1BnAct and Conv3d3x3x3DwBnRelu, while with int8 operation Conv3d3x1x1BnAct
442
+ is 1.5X slower than Conv3d3x3x3DwBnRelu.
443
+
444
+ self.convert_flag property records whether the Conv3d3x1x1BnAct instance has been
445
+ converted; Conv3d3x1x1BnAct is in original form if convert_flag is false, while it
446
+ is in deployable form if convert_flag is true.
447
+
448
+ Args:
449
+ in_channels (int): number of input channels for conv3d 3x1x1.
450
+ out_channels (int): number of output channels for conv3d 3x1x1.
451
+ groups (int): number of groups for conv.
452
+ bias (bool): if true, use bias for conv.
453
+ activation (str): applies selected activation from supported_act_functions.
454
+ See activation_functions.py for more info about supported activations.
455
+ Currently ReLU ('relu'), Swish ('swish'), Hardswish ('hswish'), Identity
456
+ ('identity') are supported.
457
+ use_bn (bool): if true, use batchnorm.
458
+ norm_eps (float): epsilon for batchnorm.
459
+ norm_momentum (float): momentum for batchnorm.
460
+
461
+ """
462
+
463
+ def __init__(
464
+ self,
465
+ in_channels: int,
466
+ out_channels: int,
467
+ groups: int = 1,
468
+ bias=False,
469
+ activation: str = "relu",
470
+ use_bn=True,
471
+ norm_eps=1e-5,
472
+ norm_momentum=0.1,
473
+ ):
474
+ super().__init__()
475
+ kernel = OrderedDict()
476
+ kernel["conv"] = nn.Conv3d(
477
+ in_channels,
478
+ out_channels,
479
+ kernel_size=(3, 1, 1),
480
+ groups=groups,
481
+ padding=(1, 0, 0),
482
+ bias=bias,
483
+ )
484
+
485
+ if groups == out_channels:
486
+ logging.warning(
487
+ (
488
+ "Conv3d3x1x1BnAct has low efficiency for depthwise conv. "
489
+ "Consider using Conv3d3x3x3DwBnRelu instead."
490
+ )
491
+ )
492
+
493
+ if use_bn:
494
+ kernel["bn"] = nn.BatchNorm3d(
495
+ out_channels, eps=norm_eps, momentum=norm_momentum
496
+ )
497
+ assert (
498
+ activation in supported_act_functions
499
+ ), f"Conv3d3x1x1BnAct: {activation} is not in supported_act_functions."
500
+ kernel["act"] = supported_act_functions[activation]()
501
+ self.kernel = nn.Sequential(kernel)
502
+ self.convert_flag = False
503
+
504
+ def convert(
505
+ self,
506
+ input_blob_size,
507
+ **kwargs,
508
+ ):
509
+ """
510
+ Converts Conv3d into equivalent Conv2d for Pytorch Mobile deployment
511
+
512
+ """
513
+ assert (
514
+ self.convert_flag is False
515
+ ), "Conv3d3x1x1BnAct: already converted, cannot be converted twice"
516
+ self.kernel.eval()
517
+ # Fuse conv and bn if bn exists.
518
+ if hasattr(self.kernel, "bn"):
519
+ self.kernel = fuse_modules(self.kernel, ["conv", "bn"])
520
+ self.kernel.conv = _Conv3dTemporalKernel3Decomposed(
521
+ self.kernel.conv, input_blob_size[2:]
522
+ )
523
+ # Convert activation function
524
+ self.kernel.act.convert(input_blob_size, **kwargs)
525
+ # Since conv3d is converted into multiple conv2d, will not fuse conv with relu
526
+ # to keep arithmetic equivalency.
527
+ self.convert_flag = True
528
+ self.kernel.eval()
529
+
530
+ def forward(self, x):
531
+ x = self.kernel(x)
532
+ return x
533
+
534
+
535
+ class Conv3d5x1x1BnAct(EfficientBlockBase):
536
+ """
537
+ Implements Conv3d (5x1x1) + (optional) Bn + Activation for pointwise layers.
538
+ The conv layer has fixed kernel of (5, 1, 1), zero padding size of
539
+ (2, 0, 0), stride = (1, 1, 1), dilation = 1.
540
+
541
+ Input
542
+ |
543
+
544
+ conv3d (5x1x1)
545
+
546
+ BatchNorm (optional)
547
+
548
+ Activation
549
+
550
+ For regular convolution (i.e., groups=1), current implementation of this layer in
551
+ QNNPACK is reasonably efficient.
552
+
553
+ self.convert_flag property records whether the Conv3d5x1x1BnAct instance has been
554
+ converted; Conv3d5x1x1BnAct is in original form if convert_flag is false, while it
555
+ is in deployable form if convert_flag is true.
556
+
557
+ Args:
558
+ in_channels (int): number of input channels for conv3d 3x1x1.
559
+ out_channels (int): number of output channels for conv3d 3x1x1.
560
+ groups (int): number of groups for conv.
561
+ bias (bool): if true, use bias for conv.
562
+ activation (str): applies selected activation from supported_act_functions.
563
+ See activation_functions.py for more info about supported activations.
564
+ Currently ReLU ('relu'), Swish ('swish'), Hardswish ('hswish'), Identity
565
+ ('identity') are supported.
566
+ use_bn (bool): if true, use batchnorm.
567
+ norm_eps (float): epsilon for batchnorm.
568
+ norm_momentum (float): momentum for batchnorm.
569
+
570
+ """
571
+
572
+ def __init__(
573
+ self,
574
+ in_channels: int,
575
+ out_channels: int,
576
+ groups: int = 1,
577
+ bias=False,
578
+ activation: str = "relu",
579
+ use_bn=True,
580
+ norm_eps=1e-5,
581
+ norm_momentum=0.1,
582
+ ):
583
+ super().__init__()
584
+ kernel = OrderedDict()
585
+ kernel["conv"] = nn.Conv3d(
586
+ in_channels,
587
+ out_channels,
588
+ kernel_size=(5, 1, 1),
589
+ groups=groups,
590
+ padding=(2, 0, 0),
591
+ bias=bias,
592
+ )
593
+
594
+ if use_bn:
595
+ kernel["bn"] = nn.BatchNorm3d(
596
+ out_channels, eps=norm_eps, momentum=norm_momentum
597
+ )
598
+ assert (
599
+ activation in supported_act_functions
600
+ ), f"Conv3d5x1x1BnAct: {activation} is not in supported_act_functions."
601
+ kernel["act"] = supported_act_functions[activation]()
602
+ self.kernel = nn.Sequential(kernel)
603
+ self.convert_flag = False
604
+
605
+ def convert(self, input_blob_size, **kwargs):
606
+ """
607
+ Converts Conv3d into equivalent Conv2d for Pytorch Mobile deployment
608
+
609
+ """
610
+ assert (
611
+ self.convert_flag is False
612
+ ), "Conv3d5x1x1BnAct: already converted, cannot be converted twice"
613
+ self.kernel.eval()
614
+ # Fuse conv and bn if bn exists.
615
+ if hasattr(self.kernel, "bn"):
616
+ self.kernel = fuse_modules(self.kernel, ["conv", "bn"])
617
+ self.kernel.conv = _Conv3dTemporalKernel5Decomposed(
618
+ self.kernel.conv, input_blob_size[2:]
619
+ )
620
+ # Convert activatiopn function
621
+ self.kernel.act.convert(input_blob_size, **kwargs)
622
+ # Since conv3d is converted into multiple conv2d, will not fuse conv with relu
623
+ # to keep arithmetic equivalency.
624
+ self.convert_flag = True
625
+ self.kernel.eval()
626
+
627
+ def forward(self, x):
628
+ x = self.kernel(x)
629
+ return x
reward_models/ib_sync_rewards/imagebind/pytorchvideo/layers/fusion.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Callable, List
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+
9
+ """
10
+ Fusion layers are nn.Modules that take a list of Tensors (e.g. from a multi-stream
11
+ architecture), and return a single fused Tensor. This file has several
12
+ different types of fusion layers and a factory function "make_fusion_layer" to
13
+ construct them.
14
+ """
15
+
16
+
17
+ def make_fusion_layer(method: str, feature_dims: List[int]):
18
+ """
19
+ Args:
20
+ method (str): the fusion method to be constructed. Options:
21
+ - 'concat'
22
+ - 'temporal_concat'
23
+ - 'max'
24
+ - 'sum'
25
+ - 'prod'
26
+
27
+ feature_dims (List[int]): the first argument of all fusion layers. It holds a list
28
+ of required feature_dims for each tensor input (where the tensor inputs are of
29
+ shape (batch_size, seq_len, feature_dim)). The list order must corresponds to
30
+ the tensor order passed to forward(...).
31
+ """
32
+ if method == "concat":
33
+ return ConcatFusion(feature_dims)
34
+ elif method == "temporal_concat":
35
+ return TemporalConcatFusion(feature_dims)
36
+ elif method == "max":
37
+ return ReduceFusion(feature_dims, lambda x: torch.max(x, dim=0).values)
38
+ elif method == "sum":
39
+ return ReduceFusion(feature_dims, lambda x: torch.sum(x, dim=0))
40
+ elif method == "prod":
41
+ return ReduceFusion(feature_dims, lambda x: torch.prod(x, dim=0))
42
+ else:
43
+ raise NotImplementedError(f"Fusion {method} not available.")
44
+
45
+
46
+ class ConcatFusion(nn.Module):
47
+ """
48
+ Concatenates all inputs by their last dimension. The resulting tensor last dim will be
49
+ the sum of the last dimension of all input tensors.
50
+ """
51
+
52
+ def __init__(self, feature_dims: List[int]):
53
+ super().__init__()
54
+ _verify_feature_dim(feature_dims)
55
+ self._output_dim = sum(feature_dims)
56
+
57
+ @property
58
+ def output_dim(self):
59
+ """
60
+ Last dimension size of forward(..) tensor output.
61
+ """
62
+ return self._output_dim
63
+
64
+ def forward(self, input_list: List[torch.Tensor]) -> torch.Tensor:
65
+ """
66
+ Args:
67
+ input_list (List[torch.Tensor]): a list of tensors of shape
68
+ (batch_size, seq_len, feature_dim).
69
+
70
+ Returns:
71
+ Tensor of shape (batch_size, seq_len, sum(feature_dims)) where sum(feature_dims)
72
+ is the sum of all input feature_dims.
73
+ """
74
+ return torch.cat(input_list, dim=-1)
75
+
76
+
77
+ class TemporalConcatFusion(nn.Module):
78
+ """
79
+ Concatenates all inputs by their temporal dimension which is assumed to be dim=1.
80
+ """
81
+
82
+ def __init__(self, feature_dims: List[int]):
83
+ super().__init__()
84
+ _verify_feature_dim(feature_dims)
85
+
86
+ # All input dimensions must be the same
87
+ self._output_dim = max(feature_dims)
88
+ assert self._output_dim == min(feature_dims)
89
+
90
+ @property
91
+ def output_dim(self):
92
+ """
93
+ Last dimension size of forward(..) tensor output.
94
+ """
95
+ return self._output_dim
96
+
97
+ def forward(self, input_list: List[torch.Tensor]) -> torch.Tensor:
98
+ """
99
+ Args:
100
+ input_list (List[torch.Tensor]): a list of tensors of shape
101
+ (batch_size, seq_len, feature_dim)
102
+
103
+ Returns:
104
+ Tensor of shape (batch_size, sum(seq_len), feature_dim) where sum(seq_len) is
105
+ the sum of all input tensors.
106
+ """
107
+ return torch.cat(input_list, dim=1)
108
+
109
+
110
+ class ReduceFusion(nn.Module):
111
+ """
112
+ Generic fusion method which takes a callable which takes the list of input tensors
113
+ and expects a single tensor to be used. This class can be used to implement fusion
114
+ methods like "sum", "max" and "prod".
115
+ """
116
+
117
+ def __init__(
118
+ self, feature_dims: List[int], reduce_fn: Callable[[torch.Tensor], torch.Tensor]
119
+ ):
120
+ super().__init__()
121
+ _verify_feature_dim(feature_dims)
122
+ self.reduce_fn = reduce_fn
123
+
124
+ # All input dimensions must be the same
125
+ self._output_dim = max(feature_dims)
126
+ assert self._output_dim == min(feature_dims)
127
+
128
+ @property
129
+ def output_dim(self):
130
+ """
131
+ Last dimension size of forward(..) tensor output.
132
+ """
133
+ return self._output_dim
134
+
135
+ def forward(self, input_list: List[torch.Tensor]) -> torch.Tensor:
136
+ """
137
+ Args:
138
+ input_list (List[torch.Tensor]): a list of tensors of shape
139
+ (batch_size, seq_len, feature_dim).
140
+
141
+ Returns:
142
+ Tensor of shape (batch_size, seq_len, feature_dim).
143
+ """
144
+ return self.reduce_fn(torch.stack(input_list))
145
+
146
+
147
+ def _verify_feature_dim(feature_dims: List[int]):
148
+ assert isinstance(feature_dims, list)
149
+ assert all(x > 0 for x in feature_dims)
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/accelerator/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/accelerator/mobile_cpu/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/csn.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Callable, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from pytorchvideo.models.head import create_res_basic_head
8
+ from pytorchvideo.models.resnet import create_bottleneck_block, create_res_stage, Net
9
+ from pytorchvideo.models.stem import create_res_basic_stem
10
+
11
+
12
+ def create_csn(
13
+ *,
14
+ # Input clip configs.
15
+ input_channel: int = 3,
16
+ # Model configs.
17
+ model_depth: int = 50,
18
+ model_num_class: int = 400,
19
+ dropout_rate: float = 0,
20
+ # Normalization configs.
21
+ norm: Callable = nn.BatchNorm3d,
22
+ # Activation configs.
23
+ activation: Callable = nn.ReLU,
24
+ # Stem configs.
25
+ stem_dim_out: int = 64,
26
+ stem_conv_kernel_size: Tuple[int] = (3, 7, 7),
27
+ stem_conv_stride: Tuple[int] = (1, 2, 2),
28
+ stem_pool: Callable = None,
29
+ stem_pool_kernel_size: Tuple[int] = (1, 3, 3),
30
+ stem_pool_stride: Tuple[int] = (1, 2, 2),
31
+ # Stage configs.
32
+ stage_conv_a_kernel_size: Tuple[int] = (1, 1, 1),
33
+ stage_conv_b_kernel_size: Tuple[int] = (3, 3, 3),
34
+ stage_conv_b_width_per_group: int = 1,
35
+ stage_spatial_stride: Tuple[int] = (1, 2, 2, 2),
36
+ stage_temporal_stride: Tuple[int] = (1, 2, 2, 2),
37
+ bottleneck: Callable = create_bottleneck_block,
38
+ bottleneck_ratio: int = 4,
39
+ # Head configs.
40
+ head_pool: Callable = nn.AvgPool3d,
41
+ head_pool_kernel_size: Tuple[int] = (1, 7, 7),
42
+ head_output_size: Tuple[int] = (1, 1, 1),
43
+ head_activation: Callable = None,
44
+ head_output_with_global_average: bool = True,
45
+ ) -> nn.Module:
46
+ """
47
+ Build Channel-Separated Convolutional Networks (CSN):
48
+ Video classification with channel-separated convolutional networks.
49
+ Du Tran, Heng Wang, Lorenzo Torresani, Matt Feiszli. ICCV 2019.
50
+
51
+ CSN follows the ResNet style architecture including three parts: Stem,
52
+ Stages and Head. The three parts are assembled in the following order:
53
+
54
+ ::
55
+
56
+ Input
57
+
58
+ Stem
59
+
60
+ Stage 1
61
+
62
+ .
63
+ .
64
+ .
65
+
66
+ Stage N
67
+
68
+ Head
69
+
70
+ CSN uses depthwise convolution. To further reduce the computational cost, it uses
71
+ low resolution (112x112), short clips (4 frames), different striding and kernel
72
+ size, etc.
73
+
74
+ Args:
75
+
76
+ input_channel (int): number of channels for the input video clip.
77
+
78
+ model_depth (int): the depth of the resnet. Options include: 50, 101, 152.
79
+ model_num_class (int): the number of classes for the video dataset.
80
+ dropout_rate (float): dropout rate.
81
+
82
+ norm (callable): a callable that constructs normalization layer.
83
+
84
+ activation (callable): a callable that constructs activation layer.
85
+
86
+ stem_dim_out (int): output channel size to stem.
87
+ stem_conv_kernel_size (tuple): convolutional kernel size(s) of stem.
88
+ stem_conv_stride (tuple): convolutional stride size(s) of stem.
89
+ stem_pool (callable): a callable that constructs resnet head pooling layer.
90
+ stem_pool_kernel_size (tuple): pooling kernel size(s).
91
+ stem_pool_stride (tuple): pooling stride size(s).
92
+
93
+ stage_conv_a_kernel_size (tuple): convolutional kernel size(s) for conv_a.
94
+ stage_conv_b_kernel_size (tuple): convolutional kernel size(s) for conv_b.
95
+ stage_conv_b_width_per_group(int): the width of each group for conv_b. Set
96
+ it to 1 for depthwise convolution.
97
+ stage_spatial_stride (tuple): the spatial stride for each stage.
98
+ stage_temporal_stride (tuple): the temporal stride for each stage.
99
+ bottleneck (callable): a callable that constructs bottleneck block layer.
100
+ Examples include: create_bottleneck_block.
101
+ bottleneck_ratio (int): the ratio between inner and outer dimensions for
102
+ the bottleneck block.
103
+
104
+ head_pool (callable): a callable that constructs resnet head pooling layer.
105
+ head_pool_kernel_size (tuple): the pooling kernel size.
106
+ head_output_size (tuple): the size of output tensor for head.
107
+ head_activation (callable): a callable that constructs activation layer.
108
+ head_output_with_global_average (bool): if True, perform global averaging on
109
+ the head output.
110
+
111
+ Returns:
112
+ (nn.Module): the csn model.
113
+ """
114
+
115
+ torch._C._log_api_usage_once("PYTORCHVIDEO.model.create_csn")
116
+
117
+ # Number of blocks for different stages given the model depth.
118
+ _MODEL_STAGE_DEPTH = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3), 152: (3, 8, 36, 3)}
119
+
120
+ # Given a model depth, get the number of blocks for each stage.
121
+ assert (
122
+ model_depth in _MODEL_STAGE_DEPTH.keys()
123
+ ), f"{model_depth} is not in {_MODEL_STAGE_DEPTH.keys()}"
124
+ stage_depths = _MODEL_STAGE_DEPTH[model_depth]
125
+
126
+ blocks = []
127
+ # Create stem for CSN.
128
+ stem = create_res_basic_stem(
129
+ in_channels=input_channel,
130
+ out_channels=stem_dim_out,
131
+ conv_kernel_size=stem_conv_kernel_size,
132
+ conv_stride=stem_conv_stride,
133
+ conv_padding=[size // 2 for size in stem_conv_kernel_size],
134
+ pool=stem_pool,
135
+ pool_kernel_size=stem_pool_kernel_size,
136
+ pool_stride=stem_pool_stride,
137
+ pool_padding=[size // 2 for size in stem_pool_kernel_size],
138
+ norm=norm,
139
+ activation=activation,
140
+ )
141
+ blocks.append(stem)
142
+
143
+ stage_dim_in = stem_dim_out
144
+ stage_dim_out = stage_dim_in * 4
145
+
146
+ # Create each stage for CSN.
147
+ for idx in range(len(stage_depths)):
148
+ stage_dim_inner = stage_dim_out // bottleneck_ratio
149
+ depth = stage_depths[idx]
150
+
151
+ stage_conv_b_stride = (
152
+ stage_temporal_stride[idx],
153
+ stage_spatial_stride[idx],
154
+ stage_spatial_stride[idx],
155
+ )
156
+
157
+ stage = create_res_stage(
158
+ depth=depth,
159
+ dim_in=stage_dim_in,
160
+ dim_inner=stage_dim_inner,
161
+ dim_out=stage_dim_out,
162
+ bottleneck=bottleneck,
163
+ conv_a_kernel_size=stage_conv_a_kernel_size,
164
+ conv_a_stride=(1, 1, 1),
165
+ conv_a_padding=[size // 2 for size in stage_conv_a_kernel_size],
166
+ conv_b_kernel_size=stage_conv_b_kernel_size,
167
+ conv_b_stride=stage_conv_b_stride,
168
+ conv_b_padding=[size // 2 for size in stage_conv_b_kernel_size],
169
+ conv_b_num_groups=(stage_dim_inner // stage_conv_b_width_per_group),
170
+ conv_b_dilation=(1, 1, 1),
171
+ norm=norm,
172
+ activation=activation,
173
+ )
174
+
175
+ blocks.append(stage)
176
+ stage_dim_in = stage_dim_out
177
+ stage_dim_out = stage_dim_out * 2
178
+
179
+ # Create head for CSN.
180
+ head = create_res_basic_head(
181
+ in_features=stage_dim_in,
182
+ out_features=model_num_class,
183
+ pool=head_pool,
184
+ output_size=head_output_size,
185
+ pool_kernel_size=head_pool_kernel_size,
186
+ dropout_rate=dropout_rate,
187
+ activation=head_activation,
188
+ output_with_global_average=head_output_with_global_average,
189
+ )
190
+ blocks.append(head)
191
+ return Net(blocks=nn.ModuleList(blocks))
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from .csn import csn_r101
4
+ from .efficient_x3d_mobile_cpu import efficient_x3d_s, efficient_x3d_xs
5
+ from .r2plus1d import r2plus1d_r50
6
+ from .resnet import c2d_r50, i3d_r50, slow_r50, slow_r50_detection
7
+ from .slowfast import (
8
+ slowfast_16x8_r101_50_50,
9
+ slowfast_r101,
10
+ slowfast_r50,
11
+ slowfast_r50_detection,
12
+ )
13
+ from .vision_transformers import mvit_base_16, mvit_base_16x4, mvit_base_32x3
14
+ from .x3d import x3d_l, x3d_m, x3d_s, x3d_xs
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/csn.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Any
4
+
5
+ import torch.nn as nn
6
+ from pytorchvideo.models.csn import create_csn
7
+ from torch.hub import load_state_dict_from_url
8
+
9
+
10
+ """
11
+ Channel-Separated Convolutional Network models for video recognition.
12
+ """
13
+
14
+ root_dir = "https://dl.fbaipublicfiles.com/pytorchvideo/model_zoo/kinetics"
15
+ checkpoint_paths = {
16
+ "csn_r101": f"{root_dir}/CSN_32x2_R101.pyth",
17
+ }
18
+
19
+
20
+ def csn_r101(
21
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
22
+ ) -> nn.Module:
23
+ r"""
24
+ Channel-Separated Convolutional Networks (CSN) R101 model architecture [1]
25
+ with pretrained weights based on 32x2 setting on the Kinetics dataset.
26
+ Model with pretrained weights has top1 accuracy of 77.0 (trained on 16x8 GPUs).
27
+
28
+ [1] "Video classification with channel-separated convolutional networks"
29
+ Du Tran, Heng Wang, Lorenzo Torresani, Matt Feiszli. ICCV 2019.
30
+ https://arxiv.org/abs/1904.02811
31
+
32
+ Args:
33
+ pretrained (bool): If True, returns a model pre-trained on the Kinetics dataset
34
+ progress (bool): If True, displays a progress bar of the download to stderr
35
+ kwargs: use these to modify any of the other model settings. All the
36
+ options are defined in pytorchvideo/models/resnet.py
37
+
38
+ NOTE: to use the pretrained model, do not modify the model configuration
39
+ via the kwargs. Only modify settings via kwargs to initialize a new model
40
+ without pretrained weights.
41
+ """
42
+ model = create_csn(
43
+ model_depth=101,
44
+ stem_pool=nn.MaxPool3d,
45
+ head_pool_kernel_size=(4, 7, 7),
46
+ **kwargs,
47
+ )
48
+
49
+ if pretrained:
50
+ path = checkpoint_paths["csn_r101"]
51
+ # All models are loaded onto CPU by default
52
+ checkpoint = load_state_dict_from_url(
53
+ path, progress=progress, map_location="cpu"
54
+ )
55
+ state_dict = checkpoint["model_state"]
56
+ model.load_state_dict(state_dict)
57
+
58
+ return model
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/efficient_x3d_mobile_cpu.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Any, Optional
4
+
5
+ import torch.nn as nn
6
+ from pytorchvideo.models.accelerator.mobile_cpu.efficient_x3d import create_x3d
7
+ from torch.hub import load_state_dict_from_url
8
+
9
+
10
+ _root_dir = "https://dl.fbaipublicfiles.com/pytorchvideo/model_zoo/kinetics"
11
+ _checkpoint_paths = {
12
+ "efficient_x3d_xs": f"{_root_dir}/efficient_x3d_xs_original_form.pyth",
13
+ "efficient_x3d_s": f"{_root_dir}/efficient_x3d_s_original_form.pyth",
14
+ }
15
+
16
+
17
+ def _efficient_x3d(
18
+ pretrained: bool = False,
19
+ progress: bool = True,
20
+ checkpoint_path: Optional[str] = None,
21
+ # Model params
22
+ expansion: str = "XS",
23
+ **kwargs: Any,
24
+ ) -> nn.Module:
25
+ model = create_x3d(
26
+ expansion=expansion,
27
+ **kwargs,
28
+ )
29
+
30
+ if pretrained and checkpoint_path is not None:
31
+ # All models are loaded onto CPU by default
32
+ state_dict = load_state_dict_from_url(
33
+ checkpoint_path, progress=progress, map_location="cpu"
34
+ )
35
+ model.load_state_dict(state_dict)
36
+
37
+ return model
38
+
39
+
40
+ def efficient_x3d_xs(pretrained: bool = False, progress: bool = True, **kwargs):
41
+ r"""
42
+ X3D-XS model architectures [1] with pretrained weights trained
43
+ on the Kinetics dataset with efficient implementation for mobile cpu.
44
+
45
+ [1] Christoph Feichtenhofer, "X3D: Expanding Architectures for
46
+ Efficient Video Recognition." https://arxiv.org/abs/2004.04730
47
+
48
+ Args:
49
+ pretrained (bool): If True, returns a model pre-trained on Kinetcis-400 dataset
50
+ progress (bool): If True, displays a progress bar of the download to stderr
51
+ To modify any other model settings, specify them in the kwargs.
52
+ All the args are defined in pytorchvideo/models/x3d.py
53
+ """
54
+ return _efficient_x3d(
55
+ pretrained=pretrained,
56
+ progress=progress,
57
+ checkpoint_path=_checkpoint_paths["efficient_x3d_xs"],
58
+ expansion="XS",
59
+ **kwargs,
60
+ )
61
+
62
+
63
+ def efficient_x3d_s(pretrained: bool = False, progress: bool = True, **kwargs):
64
+ r"""
65
+ X3D-S model architectures [1] with pretrained weights trained
66
+ on the Kinetics dataset with efficient implementation for mobile cpu.
67
+
68
+ [1] Christoph Feichtenhofer, "X3D: Expanding Architectures for
69
+ Efficient Video Recognition." https://arxiv.org/abs/2004.04730
70
+
71
+ Args:
72
+ pretrained (bool): If True, returns a model pre-trained on Kinetcis-400 dataset
73
+ progress (bool): If True, displays a progress bar of the download to stderr
74
+ To modify any other model settings, specify them in the kwargs.
75
+ All the args are defined in pytorchvideo/models/x3d.py
76
+ """
77
+ return _efficient_x3d(
78
+ pretrained=pretrained,
79
+ progress=progress,
80
+ checkpoint_path=_checkpoint_paths["efficient_x3d_s"],
81
+ expansion="S",
82
+ **kwargs,
83
+ )
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/r2plus1d.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Any
4
+
5
+ import torch.nn as nn
6
+ from pytorchvideo.models.r2plus1d import create_r2plus1d
7
+ from torch.hub import load_state_dict_from_url
8
+
9
+
10
+ """
11
+ R(2+1)D style models for video recognition.
12
+ """
13
+
14
+ root_dir = "https://dl.fbaipublicfiles.com/pytorchvideo/model_zoo/kinetics"
15
+ checkpoint_paths = {
16
+ "r2plus1d_r50": f"{root_dir}/R2PLUS1D_16x4_R50.pyth",
17
+ }
18
+
19
+
20
+ def r2plus1d_r50(
21
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
22
+ ) -> nn.Module:
23
+ r"""
24
+
25
+ R(2+1)D model architecture from [1] with pretrained weights based on 16x4 setting
26
+ on the Kinetics dataset. Model with pretrained weights has top1 accuracy of 76.01.
27
+ (trained on 8*8 GPUs)
28
+
29
+ [1] "A closer look at spatiotemporal convolutions for action recognition"
30
+ Du Tran, Heng Wang, Lorenzo Torresani, Jamie Ray, Yann LeCun, Manohar Paluri. CVPR 2018.
31
+ https://arxiv.org/abs/1711.11248
32
+
33
+ Args:
34
+ pretrained (bool): If True, returns a model pre-trained on the Kinetics dataset
35
+ progress (bool): If True, displays a progress bar of the download to stderr
36
+ kwargs: use these to modify any of the other model settings. All the
37
+ options are defined in pytorchvideo/models/resnet.py
38
+
39
+ NOTE: to use the pretrained model, do not modify the model configuration
40
+ via the kwargs. Only modify settings via kwargs to initialize a new model
41
+ without pretrained weights.
42
+ """
43
+ model = create_r2plus1d(dropout_rate=0.5, **kwargs)
44
+
45
+ if pretrained:
46
+ path = checkpoint_paths["r2plus1d_r50"]
47
+ # All models are loaded onto CPU by default
48
+ checkpoint = load_state_dict_from_url(
49
+ path, progress=progress, map_location="cpu"
50
+ )
51
+ state_dict = checkpoint["model_state"]
52
+ model.load_state_dict(state_dict)
53
+
54
+ return model
reward_models/ib_sync_rewards/imagebind/pytorchvideo/models/hub/resnet.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
+
3
+ from typing import Any, Callable
4
+
5
+ import torch.nn as nn
6
+ from pytorchvideo.models.resnet import create_resnet, create_resnet_with_roi_head
7
+ from torch.hub import load_state_dict_from_url
8
+
9
+
10
+ """
11
+ ResNet style models for video recognition.
12
+ """
13
+
14
+ root_dir = "https://dl.fbaipublicfiles.com/pytorchvideo/model_zoo"
15
+ checkpoint_paths = {
16
+ "slow_r50": f"{root_dir}/kinetics/SLOW_8x8_R50.pyth",
17
+ "slow_r50_detection": f"{root_dir}/ava/SLOW_4x16_R50_DETECTION.pyth",
18
+ "c2d_r50": f"{root_dir}/kinetics/C2D_8x8_R50.pyth",
19
+ "i3d_r50": f"{root_dir}/kinetics/I3D_8x8_R50.pyth",
20
+ }
21
+
22
+
23
+ def _resnet(
24
+ pretrained: bool = False,
25
+ progress: bool = True,
26
+ checkpoint_path: str = "",
27
+ model_builder: Callable = create_resnet,
28
+ **kwargs: Any,
29
+ ) -> nn.Module:
30
+ model = model_builder(**kwargs)
31
+ if pretrained:
32
+ # All models are loaded onto CPU by default
33
+ checkpoint = load_state_dict_from_url(
34
+ checkpoint_path, progress=progress, map_location="cpu"
35
+ )
36
+ state_dict = checkpoint["model_state"]
37
+ model.load_state_dict(state_dict)
38
+ return model
39
+
40
+
41
+ def slow_r50(
42
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
43
+ ) -> nn.Module:
44
+ r"""
45
+ Slow R50 model architecture [1] with pretrained weights based on 8x8 setting
46
+ on the Kinetics dataset. Model with pretrained weights has top1 accuracy of 74.58.
47
+
48
+ [1] "SlowFast Networks for Video Recognition"
49
+ Christoph Feichtenhofer et al
50
+ https://arxiv.org/pdf/1812.03982.pdf
51
+
52
+ Args:
53
+ pretrained (bool): If True, returns a model pre-trained on the Kinetics dataset
54
+ progress (bool): If True, displays a progress bar of the download to stderr
55
+ kwargs: use these to modify any of the other model settings. All the
56
+ options are defined in pytorchvideo/models/resnet.py
57
+
58
+ NOTE: to use the pretrained model, do not modify the model configuration
59
+ via the kwargs. Only modify settings via kwargs to initialize a new model
60
+ without pretrained weights.
61
+ """
62
+ return _resnet(
63
+ pretrained=pretrained,
64
+ progress=progress,
65
+ checkpoint_path=checkpoint_paths["slow_r50"],
66
+ stem_conv_kernel_size=(1, 7, 7),
67
+ head_pool_kernel_size=(8, 7, 7),
68
+ model_depth=50,
69
+ **kwargs,
70
+ )
71
+
72
+
73
+ def slow_r50_detection(
74
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
75
+ ) -> nn.Module:
76
+ r"""
77
+ Slow R50 model architecture [1] with pretrained weights based on 4x16 setting.
78
+ The model is initially trained on Kinetics dataset for classification and later
79
+ finetuned on AVA dataset for detection.
80
+
81
+ [1] Christoph Feichtenhofer et al, "SlowFast Networks for Video Recognition"
82
+ https://arxiv.org/pdf/1812.03982.pdf
83
+ """
84
+ return _resnet(
85
+ pretrained=pretrained,
86
+ progress=progress,
87
+ checkpoint_path=checkpoint_paths["slow_r50_detection"],
88
+ model_builder=create_resnet_with_roi_head,
89
+ **kwargs,
90
+ )
91
+
92
+
93
+ def c2d_r50(
94
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
95
+ ) -> nn.Module:
96
+ r"""
97
+ C2D R50 model architecture with pretrained weights based on 8x8 setting
98
+ on the Kinetics dataset. Model with pretrained weights has top1 accuracy of 71.46.
99
+
100
+ Args:
101
+ pretrained (bool): If True, returns a model pre-trained on the Kinetics dataset
102
+ progress (bool): If True, displays a progress bar of the download to stderr
103
+ kwargs: use these to modify any of the other model settings. All the
104
+ options are defined in pytorchvideo/models/resnet.py
105
+
106
+ NOTE: to use the pretrained model, do not modify the model configuration
107
+ via the kwargs. Only modify settings via kwargs to initialize a new model
108
+ without pretrained weights.
109
+ """
110
+ return _resnet(
111
+ pretrained=pretrained,
112
+ progress=progress,
113
+ checkpoint_path=checkpoint_paths["c2d_r50"],
114
+ stem_conv_kernel_size=(1, 7, 7),
115
+ stage1_pool=nn.MaxPool3d,
116
+ stage_conv_a_kernel_size=(
117
+ (1, 1, 1),
118
+ (1, 1, 1),
119
+ (1, 1, 1),
120
+ (1, 1, 1),
121
+ ),
122
+ **kwargs,
123
+ )
124
+
125
+
126
+ def i3d_r50(
127
+ pretrained: bool = False, progress: bool = True, **kwargs: Any
128
+ ) -> nn.Module:
129
+ r"""
130
+ I3D R50 model architecture from [1] with pretrained weights based on 8x8 setting
131
+ on the Kinetics dataset. Model with pretrained weights has top1 accuracy of 73.27.
132
+
133
+ [1] "Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset"
134
+ Joao Carreira, Andrew Zisserman
135
+ https://arxiv.org/abs/1705.07750
136
+
137
+ Args:
138
+ pretrained (bool): If True, returns a model pre-trained on the Kinetics dataset
139
+ progress (bool): If True, displays a progress bar of the download to stderr
140
+ kwargs: use these to modify any of the other model settings. All the
141
+ options are defined in pytorchvideo/models/resnet.py
142
+
143
+ NOTE: to use the pretrained model, do not modify the model configuration
144
+ via the kwargs. Only modify settings via kwargs to initialize a new model
145
+ without pretrained weights.
146
+ """
147
+ return _resnet(
148
+ pretrained=pretrained,
149
+ progress=progress,
150
+ checkpoint_path=checkpoint_paths["i3d_r50"],
151
+ stem_conv_kernel_size=(5, 7, 7),
152
+ stage1_pool=nn.MaxPool3d,
153
+ stage_conv_a_kernel_size=(
154
+ (3, 1, 1),
155
+ [(3, 1, 1), (1, 1, 1)],
156
+ [(3, 1, 1), (1, 1, 1)],
157
+ [(1, 1, 1), (3, 1, 1)],
158
+ ),
159
+ **kwargs,
160
+ )