-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvcd.py
1892 lines (1663 loc) · 106 KB
/
vcd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import psutil
import gc
import json
from decord import VideoReader, cpu
from PIL import Image
from sklearn.metrics.cluster import silhouette_score
from threadpoolctl import threadpool_limits
from utilities.clustering import cluster_features, cluster_dataset
import models.hide_seek.tcow as tcow
from models.hide_seek.tcow.data.data_vis import *
from models.hide_seek.tcow.data.data_utils import *
from models.hide_seek.tcow.eval.metrics import calculate_metrics_mask_track, calculate_weighted_averages
def random_color():
"""Generate a random color"""
return [random.randint(0, 255) for _ in range(3)]
class VideoConceptDiscovery(object):
"""Discovering video concepts.
"""
def __init__(self, args, model,):
self.args = args
self.model = model
# initialize transforms depending on the model
self.initialize_transforms()
# load dataset (optionally can be cached)
if args.dataset == 'kubric':
if not 'timesformer' in self.args.model:
cached_file_path = os.path.join(self.args.kubric_path, 'val', '{}Frames_Max{}.pkl'.format(model.num_frames, args.max_num_videos))
else:
cached_file_path = os.path.join(self.args.kubric_path, 'val', 'Max{}.pkl'.format(self.args.max_num_videos))
self.cached_file_path = cached_file_path
if os.path.exists(cached_file_path) and not self.args.force_reload_videos:
try:
with open(cached_file_path, 'rb') as f:
self.dataset = pickle.load(f)
except:
print('Failed to load cached file, reloading videos...')
self.dataset = self.load_kubric_videos()
else:
self.dataset = self.load_kubric_videos()
elif args.dataset == 'ssv2':
if 'timesformer' in args.model:
cached_file_path = os.path.join(self.args.ssv2_path, '{}_Max{}_{}_{}.pkl'.format(self.args.target_class, self.args.max_num_videos, 'train' if self.args.use_train else 'val', 'tcow')).replace(' ', '_')
else:
cached_file_path = os.path.join(self.args.ssv2_path, '{}_Max{}_{}.pkl'.format(self.args.target_class, self.args.max_num_videos, 'train' if self.args.use_train else 'val')).replace(' ', '_')
print(cached_file_path)
self.cached_file_path = cached_file_path
if os.path.exists(cached_file_path) and not self.args.force_reload_videos:
try:
with open(cached_file_path, 'rb') as f:
self.dataset = pickle.load(f)
except:
print('Failed to load cached file, reloading videos...')
self.dataset = self.load_ssv2_videos()
else:
self.dataset = self.load_ssv2_videos()
# save pkl file
with open(cached_file_path, 'wb') as f:
pickle.dump(self.dataset, f)
elif 'davis16' in args.dataset:
cached_file_path = os.path.join(self.args.davis16_path, 'Max{}.pkl'.format(self.args.max_num_videos)).replace(' ', '_')
print(cached_file_path)
self.cached_file_path = cached_file_path
if os.path.exists(cached_file_path) and not self.args.force_reload_videos:
try:
with open(cached_file_path, 'rb') as f:
self.dataset = pickle.load(f)
except:
print('Failed to load cached file, reloading videos...')
self.dataset = self.load_davis16_videos()
else:
self.dataset = self.load_davis16_videos()
# save pkl file
with open(cached_file_path, 'wb') as f:
pickle.dump(self.dataset, f)
else:
raise NotImplementedError
# save pkl file
if args.dataset_cache:
with open(cached_file_path, 'wb') as f:
pickle.dump(self.dataset, f)
def initialize_transforms(self):
if 'vidmae' in self.args.model:
self.frame_width = self.model.default_cfg['input_size'][1]
self.frame_height = self.model.default_cfg['input_size'][2]
self.normalize = torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
elif 'intern' in self.args.model:
self.frame_width = 224
self.frame_height = 224
elif 'timesformer' in self.args.model:
self.frame_width = 320
self.frame_height = 240
# resize transformers for segmentation masks
self.post_resize_smooth = torchvision.transforms.Resize(
(self.frame_height, self.frame_width),
interpolation=torchvision.transforms.InterpolationMode.BILINEAR)
self.post_resize_nearest = torchvision.transforms.Resize(
(self.frame_height, self.frame_width),
interpolation=torchvision.transforms.InterpolationMode.NEAREST)
# resize transformers for video
self.pre_upsample = torch.nn.Upsample(
size=(int(self.model.num_frames*self.args.temporal_resize_factor), int(self.frame_height*self.args.spatial_resize_factor), int(self.frame_width*self.args.spatial_resize_factor)),
mode='trilinear', align_corners=True)
self.post_upsample = torch.nn.Upsample(
size=(int(self.model.num_frames), int(self.frame_height), int(self.frame_width)),
mode='nearest')
# set up multiclass setting
if len(self.args.target_class_idxs) > 1:
self.multiclass = True
self.args.target_class = '_'.join([str(x) for x in sorted(self.args.target_class_idxs)])
else:
self.multiclass = False
def load_davis16_videos(self, sampling_rate=2, num_frames=16):
# get video names
videos = glob.glob(os.path.join(self.args.davis16_path, 'JPEGImages/480p/*'))
dataset = []
self.video_names = []
self.labels = []
self.seeker_query_labels = []
train_cls_list = ['bear', 'bmx-bumps', 'boat', 'breakdance-flare', 'bus', 'car-turn', 'dance-jump', 'dog-agility', 'drift-turn', 'elephant', 'flamingo', 'hike', 'hockey', 'horsejump-low', 'kite-walk', 'lucia', 'mallard-fly', 'mallard-water', 'motocross-bumps', 'motorbike', 'paragliding', 'rhino', 'rollerblade', 'scooter-gray', 'soccerball', 'stroller', 'surf', 'swing', 'tennis', 'train']
try:
sampling_rate = self.model.sampling_rate
num_frames = self.model.num_frames
except:
pass
for vid_num, frame_path in enumerate(videos):
# get label
vid_name = frame_path.split('/')[-1]
if 'val' in self.args.dataset:
if vid_name.split('_')[0] in train_cls_list:
continue
frame_paths = sorted(glob.glob(os.path.join(frame_path, '*.jpg')))
frames = [torch.tensor(plt.imread(frame)) for frame in frame_paths]
labels = [torch.tensor(plt.imread(frame.replace('JPEGImages/480p', 'Annotations/480p').replace('jpg', 'png'))) for frame in frame_paths]
# sample frames every self.model.args.sampling_rate frames
if not self.args.process_full_video:
frames = frames[::sampling_rate]
labels = labels[::sampling_rate]
if len(frames) < num_frames:
continue
if not self.args.process_full_video:
frames = frames[:num_frames]
labels = labels[:num_frames]
rgb_video = torch.stack(frames).permute(3, 0, 1, 2) / 255.0
rgb_video = self.post_resize_smooth(rgb_video)
# select only first channel if there are more than one
for label_num, label in enumerate(labels):
if len(label.shape) > 2:
label = label[:,:,0]
# replace label
labels[label_num] = label
labels = torch.stack(labels)
labels = self.post_resize_nearest(labels)
dataset.append(rgb_video)
self.labels.append(labels)
# stack 29 frames of zeros after the first frame
zeros = torch.zeros((num_frames-1, labels.shape[-2] , labels.shape[-1]))
query_label = torch.cat([labels[0].unsqueeze(0), zeros], dim=0).unsqueeze(0)
self.seeker_query_labels.append(query_label)
self.video_names.append(vid_name)
if len(dataset) == self.args.max_num_videos:
break
if not self.args.process_full_video:
dataset = torch.stack(dataset, dim=0) # n x c x t x h x w
return dataset
def load_ssv2_videos(self):
# get class names
label_path = os.path.join(self.args.ssv2_path, 'something-something-v2-labels.json')
with open(label_path, 'r') as f:
label_dict = json.load(f)
idx_to_label = {v: k for k, v in label_dict.items()}
if self.multiclass:
cls_idx = [x for i, x in enumerate(label_dict) if i in self.args.target_class_idxs]
else:
cls_idx = label_dict[self.args.target_class]
self.target_label_id = int(cls_idx)
# open validation file
if self.args.use_train:
data_path = os.path.join(self.args.ssv2_path, 'something-something-v2-train.json')
else:
data_path = os.path.join(self.args.ssv2_path, 'something-something-v2-validation.json')
with open(data_path, 'r') as f:
data_dict = json.load(f)
# get videos for target class
video_ids = []
video_labels = []
if self.multiclass:
for idx in self.args.target_class_idxs:
target_class = idx_to_label[str(idx)]
video_ids += [x['id'] for x in data_dict if x['template'].replace('[something]', 'something').replace('[something in it]', 'something in it') == target_class]
video_labels += [idx for x in data_dict if x['template'].replace('[something]', 'something').replace('[something in it]', 'something in it') == target_class]
else:
video_ids = [x['id'] for x in data_dict if x['template'].replace('[something]', 'something') == self.args.target_class]
video_labels = [cls_idx for x in data_dict if x['template'].replace('[something]', 'something') == self.args.target_class]
videos = [('{}/20bn-something-something-v2/{}.webm'.format(self.args.ssv2_path, video_ids[x]), video_labels[x]) for x in range(len(video_ids))]
random.shuffle(videos)
dataset = []
self.list_video_ids = []
save_frames = []
self.seeker_query_labels = []
self.labels = []
for vid_num, data in enumerate(videos):
video = data[0]
label = data[1]
try:
vr = VideoReader(video, num_threads=1, ctx=cpu(0),width = self.frame_width, height = self.frame_height)
except:
continue
frames = []
for i in range(len(vr)):
frame = vr[i]
try:
frames.append(torch.tensor(frame.asnumpy()))
except:
frames.append(torch.tensor(frame))
# sample frames every self.model.args.sampling_rate frames
frames = frames[::self.model.sampling_rate]
if len(frames) < self.model.num_frames:
continue
frames = frames[:self.model.num_frames]
try:
if 'timesformer' in self.args.model:
# open up labels
label_path = os.path.join('ssv2_labels', 'first_frame_labels', self.args.target_class, data[0].split('/')[-1].split('.')[0],'0_gt.png').replace(' ', '_')
label = np.array(Image.open(label_path))[:,:,:3]
label_binary = torch.tensor(np.where(label.sum(2)==765, 0, 1)).unsqueeze(0).unsqueeze(0)
zeros = torch.zeros((1, self.model.num_frames-1, label_binary.shape[-2] , label_binary.shape[-1]))
label_binary = torch.cat([label_binary, zeros], dim=1).unsqueeze(0)
self.seeker_query_labels.append(label_binary)
except:
print('no label found for {}'.format(data[0]))
save_frames.append(frames)
rgb_video = torch.stack(frames).permute(3, 0, 1, 2)/255.0
dataset.append(rgb_video)
self.labels.append(label)
self.list_video_ids.append(int(data[0].split('/')[-1].split('.')[0]))
if len(dataset) == self.args.max_num_videos:
break
dataset = torch.stack(dataset, dim=0) # n x c x t x h x w
return dataset
def load_kubric_videos(self, perturb_idx=0, view_idx=0, frame_inds_load=36, frame_inds_clip=30, stride=1):
frame_inds_load = list(range(0, frame_inds_load * stride, stride))
frame_inds_clip = list(range(0, frame_inds_clip * stride, stride))
# load kubric videos
video_paths = [path for path in glob.glob(os.path.join(self.args.kubric_path, 'val/*')) if 'pkl' not in path]
random.shuffle(video_paths)
video_paths = video_paths[:self.args.max_num_videos]
if self.args.max_num_videos == 2:
# video_paths = ['/data/kubcon_v10/val/kubcon_v10_scn03743', '/data/kubcon_v10/val/kubcon_v10_scn03760']
# video_paths = ['/data/kubcon_v10/val/kubcon_v10_scn03693', '/data/kubcon_v10/val/kubcon_v10_scn03717']
video_paths = ['/data/kubcon_v10/val/kubcon_v10_scn03725', '/data/kubcon_v10/val/kubcon_v10_scn03781']
if self.args.max_num_videos == 1:
video_paths = ['/data/kubcon_v10/val/kubcon_v10_scn03760']
full_pv_rgb_tf = []
full_pv_segm_tf = []
full_pv_depth_tf = []
full_pv_flow_tf = []
full_pv_div_segm_tf = []
full_pv_inst_count = []
full_traject_retval_tf = []
full_scene_dp = []
for vid_num, path in enumerate(video_paths):
# only load max_num_videos
if vid_num == self.args.max_num_videos:
break
scene_dn = path.split('/')[-1]
cache_fp = path
frames_dp = os.path.join(path, f'frames_p{perturb_idx}_v{view_idx}')
metadata_fp = os.path.join(path, scene_dn + f'_p{perturb_idx}_v{view_idx}.json')
with open(metadata_fp, 'r') as f:
metadata = json.load(f)
data_ranges_fp = os.path.join(frames_dp, 'data_ranges.json')
with open(data_ranges_fp, 'r') as f:
data_ranges = json.load(f)
K = metadata['scene']['num_valo_instances']
pv_rgb = []
pv_segm = []
pv_depth = []
pv_flow = []
for k, t in enumerate(frame_inds_load):
rgb_fp = os.path.join(frames_dp, f'rgba_{t:05d}.png')
segm_fp = os.path.join(frames_dp, f'segmentation_{t:05d}.png')
depth_fp = os.path.join(frames_dp, f'depth_{t:05d}.tiff')
flow_fp = os.path.join(frames_dp, f'forward_flow_{t:05d}.png')
rgb = plt.imread(rgb_fp)[..., 0:3] # (H, W, 3) floats.
segm = plt.imread(segm_fp)[..., 0:3] # (H, W, 3) floats.
depthm = imageio.imread(depth_fp, format="tiff") # (H, W, 1) floats.
flowm = plt.imread(flow_fp)[..., 0:2] # (H, W, 2) floats.
pv_rgb.append(rgb)
pv_segm.append(segm)
pv_depth.append(depthm)
pv_flow.append(flowm)
pv_rgb = np.stack(pv_rgb, axis=0) # (Tv, Hf, Wf, 3) floats in [0, 1].
pv_segm = np.stack(pv_segm, axis=0)
pv_depth = np.stack(pv_depth, axis=0)
pv_flow = np.stack(pv_flow, axis=0)
flow_min = data_ranges['forward_flow']['min']
flow_max = data_ranges['forward_flow']['max']
pv_flow = (pv_flow * (flow_max - flow_min)) + flow_min
pv_segm = segm_rgb_to_ids_kubric(pv_segm) # (Tv, Hf, Wf, 1) ints in [0, inf).
pv_div_segm = []
for f, t in enumerate(frame_inds_load):
per_inst_div_segm = []
for k in range(K):
cur_div_segm_fp = os.path.join(
frames_dp, f'divided_segmentation_{k:03d}_{t:05d}.png')
cur_div_segm = plt.imread(cur_div_segm_fp)[..., :3] # (H, W, 3) floats.
cur_div_segm = (cur_div_segm.sum(axis=-1) > 0.1).astype(np.uint8)
# (H, W) ints in [0, 1].
per_inst_div_segm.append(cur_div_segm)
div_segm = np.stack(per_inst_div_segm, axis=-1) # (H, W, K) bytes in [0, 1].
pv_div_segm.append(div_segm)
pv_div_segm = np.stack(pv_div_segm, axis=0)
pv_rgb_tf = rearrange(torch.tensor(pv_rgb, dtype=torch.float32), 'T H W C -> C T H W')
pv_segm_tf = rearrange(torch.tensor(pv_segm, dtype=torch.uint8), 'T H W C -> C T H W')
try:
pv_depth_tf = rearrange(torch.tensor(pv_depth, dtype=torch.uint8), 'T H W C -> C T H W')
except:
pv_depth_tf = rearrange(torch.tensor(pv_depth, dtype=torch.uint8).unsqueeze(-1), 'T H W C -> C T H W')
pv_flow_tf = rearrange(torch.tensor(pv_flow, dtype=torch.float32), 'T H W C -> C T H W')
pv_div_segm_tf = rearrange(torch.tensor(pv_div_segm, dtype=torch.uint8), 'T H W K -> K T H W')
traject_retval = dict()
occl_fracs = get_thing_occl_fracs_numpy(pv_segm, pv_div_segm)
(occl_cont_dag, relative_order, reconst_pv_segm, reconst_error) = \
get_thing_occl_cont_dag(pv_segm, pv_div_segm, metadata, frame_inds_load)
# Add annotation metadata to traject_retval, useful for evaluation.
traject_retval['occl_fracs'] = occl_fracs # (K, Tv, 3).
traject_retval['occl_cont_dag'] = occl_cont_dag # (Tv, K, K, 3).
traject_retval['query_time'] = 0
modalities_noaug = {'rgb': pv_rgb_tf, 'segm': pv_segm_tf, 'div_segm': pv_div_segm_tf,
'depth': pv_depth_tf, 'flow': pv_flow_tf}
modalities_aug = dict()
for modality, raw_frames_untrim in modalities_noaug.items():
raw_frames = raw_frames_untrim[:, frame_inds_clip, :, :]
distort_frames = rearrange(raw_frames, 'C T H W -> T C H W')
if 'segm' in modality or 'mask' in modality:
# Segmentation masks have integer values.
resize_frames = self.post_resize_nearest(distort_frames)
else:
# RGB, depth, object coordinates.
resize_frames = self.post_resize_smooth(distort_frames)
resize_frames = rearrange(resize_frames, 'T C H W -> C T H W')
modalities_aug[modality] = resize_frames
# modalities_noaug = {'rgb': pv_rgb_tf, 'segm': pv_segm_tf, 'div_segm': pv_div_segm_tf}
pv_rgb_tf, pv_segm_tf, pv_div_segm_tf, pv_depth_tf, pv_flow_tf = modalities_aug['rgb'], modalities_aug['segm'], modalities_aug['div_segm'], modalities_aug['depth'], modalities_aug['flow']
traject_retval_tf = copy.deepcopy(traject_retval)
occl_fracs_tf = get_thing_occl_fracs_torch(pv_segm_tf, pv_div_segm_tf)
occl_cont_dag_tf = traject_retval['occl_cont_dag'][frame_inds_clip]
desirability_tf = self._get_thing_traject_desirability(pv_div_segm_tf, occl_fracs_tf, traject_retval['query_time'])
(traject_retval_tf['occl_fracs'], _) = pad_div_numpy(
traject_retval_tf['occl_fracs'], [0], max_size=36)
# (K, Tv, 3) => (M, Tv, 3). NOTE: Avoid using this because of possible Tv/Tc confusion.
(traject_retval_tf['occl_fracs_tf'], _) = pad_div_numpy(
occl_fracs_tf, [0], max_size=36)
# (K, Tc, 3) => (M, Tc, 3).
(traject_retval_tf['occl_cont_dag'], _) = pad_div_numpy(
traject_retval_tf['occl_cont_dag'], [1, 2], max_size=36)
# (Tv, K, K, 3) => (Tv, M, M, 3). NOTE: Avoid using this because of possible Tv/Tc confusion.
(traject_retval_tf['occl_cont_dag_tf'], _) = pad_div_numpy(
occl_cont_dag_tf, [1, 2], max_size=36)
# (Tc, K, K, 3) => (Tc, M, M, 3).
(traject_retval_tf['desirability_tf'], _) = pad_div_numpy(
desirability_tf, [0], max_size=36)
(pv_div_segm_tf, _) = tcow.data.data_utils.pad_div_torch(
pv_div_segm_tf, [0], max_size=36)
pv_inst_count = torch.tensor([K], dtype=torch.int32)
full_pv_rgb_tf.append(pv_rgb_tf)
full_pv_segm_tf.append(pv_segm_tf)
full_pv_div_segm_tf.append(pv_div_segm_tf)
full_pv_depth_tf.append(pv_depth_tf)
full_pv_flow_tf.append(pv_flow_tf)
full_pv_inst_count.append(pv_inst_count)
full_traject_retval_tf.append(traject_retval_tf)
full_scene_dp.append([path])
# if 'timesformer' in self.args.model:
# start_frame = 0
# end_frame = 30
# else:
# start_frame = 7
# end_frame = 7 + self.model.num_frames
concept_retval = dict()
# concept_retval['augs_params'] = augs_params # dict.
# concept_retval['frame_inds_direct'] = frame_inds_direct # (Tc).
# concept_retval['camera_K_tf'] = camera_K_tf # (Tc, 3, 3) or (1).
# concept_retval['camera_R_tf'] = camera_R_tf # (Tc, 4, 4) or (1).
concept_retval['traject_retval_tf'] = full_traject_retval_tf # dict; has occl_cont_dag_tf etc.
concept_retval['pv_rgb_tf'] = torch.stack(full_pv_rgb_tf, dim=0) # (n, 3, Tc, Hf, Wf).
# concept_retval['pv_depth_tf'] = pv_depth_tf # (1, Tc, Hf, Wf).
concept_retval['pv_segm_tf'] = torch.stack(full_pv_segm_tf, dim=0) # (n, 1, Tc, Hf, Wf).
concept_retval['pv_depth_tf'] = torch.stack(full_pv_depth_tf, dim=0) # (n, 1, Tc, Hf, Wf).
concept_retval['pv_flow_tf'] = torch.stack(full_pv_flow_tf, dim=0) # (n, 1, Tc, Hf, Wf).
# concept_retval['pv_coords_tf'] = pv_coords_tf # (3, Tc, Hf, Wf).
# concept_retval['pv_xyz_tf'] = pv_xyz_tf # (3, Tc, Hf, Wf) or (1).
concept_retval['pv_div_segm_tf'] = torch.stack(full_pv_div_segm_tf, dim=0) # (n, M, Tc, Hf, Wf) or (1).
concept_retval['pv_inst_count'] = torch.stack(full_pv_inst_count, dim=0) # (1).
concept_retval['full_scene_dp'] = full_scene_dp # (1).
concept_retval['seeker_query_mask'] = []
return concept_retval
def _get_thing_traject_desirability(self, div_segm, occl_fracs, query_time):
'''
NOTE: Some desirability values will be negative, which is a signal for pipeline that they
should be always skipped.
:param div_segm (K, Tc, Hf, Wf) tensor of uint8 in [0, 1].
:param occl_fracs (K, Tc, 3) array of float32 with (f, v, t).
:param query_time (int).
:return desirability (K, 7) array of float32.
'''
(K, T, H, W) = div_segm.shape
desirability = np.zeros((K, 7)) # Q = K = number of VALO foreground instances.
for k in range(K):
# Determine the average soft occlusion percentage (strictly by other objects) over time;
# out-of-frame does not count.
avg_occl_frac = np.mean(occl_fracs[k, :, 0])
# Measure total variation of visible mask (normalized by its area) over time. This
# suggests complex motion, rotation, and/or dynamic occlusion patterns.
# NOTE: Unfortunately, this has a bias towards things with holes in them.
delta_mask = torch.abs(div_segm[k, 1:] - div_segm[k, :-1]).type(torch.float32)
delta_mask = (delta_mask != 0).type(torch.float32)
max_area = div_segm[k].sum(dim=(1, 2)).max().item() / (H * W)
old_total_var_mask = torch.mean(delta_mask).item() * 100.0
norm_total_var_mask = torch.mean(delta_mask).item() / (max_area + 1e-6)
# Ensure we avoid tracking insignificant objects by imposing a soft threshold on the
# minimum number of visible pixels. The factor implies that if we are below 1% of the
# image dimension on average, a strong penalty is applied.
significance_hard = np.mean(occl_fracs[k, :, 1])
significance_hard = min(significance_hard * 10000.0, 1.0) - 1.0
# Similarly, ensure that the instance is visible by at least 2% of the image dimension
# in the first frame, since we are doing supervised tracking.
init_vis_size_soft = np.mean(occl_fracs[k, query_time, 1])
init_vis_size_hard = min(init_vis_size_soft * 2500.0, 1.0) - 1.0
# NEW:
# Prefer objects that are mostly visible at query time, to avoid tricking the tracker
# into thinking that we almost always have to segment more than just the given pixels.
init_vis_rel_soft = 1.0 - np.mean(occl_fracs[k, query_time, 0])
# Finally, same as the above, but enforce at least 20% visibility with strong penalty.
init_vis_rel_hard = min(init_vis_rel_soft * 5.0, 1.0) - 1.0
# Use weighted sum of all metrics, but also remember constituents.
weighted = avg_occl_frac * 3.0 + norm_total_var_mask * 4.0 + \
significance_hard * 64.0 + init_vis_size_hard * 256.0 + init_vis_rel_soft * 1.0 + \
init_vis_rel_hard * 16.0
desirability[k, :] = [weighted, avg_occl_frac, norm_total_var_mask, significance_hard,
init_vis_size_hard, init_vis_rel_soft, init_vis_rel_hard]
return desirability
def tcow_timesformer_forward(self, vid_idx, keep_all=False):
# hard coded stuff
qt_idx = 0
b = 0
B = 1
Qs = 1
seeker_input = self.dataset['pv_rgb_tf'][vid_idx].unsqueeze(0).cuda()
all_segm = self.dataset['pv_segm_tf'][vid_idx].unsqueeze(0).cuda()
all_div_segm = self.dataset['pv_div_segm_tf'][vid_idx].unsqueeze(0).cuda()
inst_count = self.dataset['pv_inst_count'][vid_idx].unsqueeze(0)
target_desirability = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['desirability_tf']).unsqueeze(0)
occl_fracs = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['occl_fracs_tf']).unsqueeze(0)
occl_cont_dag = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['occl_cont_dag_tf']).unsqueeze(0)
scene_dp = self.dataset['full_scene_dp'][vid_idx]
# Sample either random or biased queries.
sel_query_inds = tcow.utils.my_utils.sample_query_inds(
B, Qs, inst_count, target_desirability, self.model.train_args, 'cuda', 'test')
query_idx = sel_query_inds[:, 0]
seeker_query_mask = torch.zeros_like(all_segm, dtype=torch.uint8) # (B, 1, T, Hf, Wf).
seeker_query_mask[b, 0, qt_idx] = (all_segm[b, 0, qt_idx] == query_idx[b] + 1)
# Prepare query mask and ground truths.
(seeker_query_mask, snitch_occl_by_ptr, full_occl_cont_id, target_mask,
target_flags) = tcow.data.data_utils.fill_kubric_query_target_mask_flags(
all_segm, all_div_segm, query_idx, qt_idx, occl_fracs, occl_cont_dag, scene_dp,
None, self.model.train_args, 'cuda', 'test')
del full_occl_cont_id, all_segm, all_div_segm, occl_cont_dag, scene_dp
# add things to dataset for logging if they were missed, this works with cacheing and non-cached datasets
if keep_all:
try:
self.dataset['seeker_query_mask'].append(seeker_query_mask.cpu())
self.dataset['target_mask'].append(target_mask.cpu())
except:
self.dataset['seeker_query_mask'] = [seeker_query_mask.cpu()]
self.dataset['target_mask'] = [target_mask.cpu()]
# forward pass:
(output_mask, output_flags, features) = self.model(seeker_input, seeker_query_mask)
# debug - visualize the output of the model
# t = 13
# plt.imshow(seeker_input[0][:, t].permute(1, 2, 0).cpu());plt.show()
# plt.imshow(output_mask[0].sigmoid()[0][t].cpu());plt.show()
try:
if self.args.save_prediction:
# seeker_input -> T H W C
# output_mask -> B T H W
# make output mask between 0 and 1
output_mask = output_mask.sigmoid()
(Qs, Cmt) = target_mask.shape[:2]
query_border = self.draw_segm_borders(np.array(seeker_query_mask.detach().cpu()[0, 0][..., None]), fill_white=False)
snitch_border = self.draw_segm_borders(np.array(target_mask.detach().cpu()[0, 0][..., None]), fill_white=False) if Cmt >= 1 else np.zeros_like(output_mask[0, 0], dtype=np.bool)
vis_snitch = self.create_model_output_snitch_video(np.array(seeker_input[0].detach().cpu().permute(1,2,3,0)), np.array(output_mask[0].detach().cpu()), query_border, snitch_border,
grayscale=False)
# save video
prediction_save_dir = os.path.join(self.args.save_dir, 'predictions')
if not os.path.exists(prediction_save_dir):
os.makedirs(prediction_save_dir, exist_ok=True)
save_file = os.path.join(prediction_save_dir, f'{vid_idx}.mp4')
self.save_video(vis_snitch, save_file, fps=6)
# save frames
prediction_frame_save_dir = os.path.join(self.args.save_dir, 'prediction_frames')
if not os.path.exists(prediction_frame_save_dir):
os.makedirs(prediction_frame_save_dir, exist_ok=True)
prediction_frame_video_save_dir = os.path.join(prediction_frame_save_dir, f'{vid_idx}')
if not os.path.exists(prediction_frame_video_save_dir):
os.makedirs(prediction_frame_video_save_dir, exist_ok=True)
for frame_idx in range(vis_snitch.shape[0]):
img = Image.fromarray((vis_snitch[frame_idx] * 255).astype(np.uint8))
img.save(os.path.join(prediction_frame_video_save_dir, 'frame_{}.png'.format(frame_idx)))
except:
pass
model_retval = {}
# all_target_flags.append(target_flags) # (B, T, 3).
# target_flags = torch.stack([target_flags], dim=1) # (B, Qs, T, 3).
model_retval['target_flags'] = torch.stack([target_flags], dim=1).cuda() # (B, Qs, T, 3).
# snitch_occl_by_ptr = torch.stack([snitch_occl_by_ptr], dim=1) # (B, Qs, 1, T, Hf, Wf).
model_retval['snitch_occl_by_ptr'] = torch.stack([snitch_occl_by_ptr], dim=1).cuda()
cur_occl_fracs = occl_fracs[:, query_idx, :, :].diagonal(0, 0, 1)
cur_occl_fracs = rearrange(cur_occl_fracs, 'T V B -> B T V') # (B, T, 3).
sel_occl_fracs = torch.stack([cur_occl_fracs], dim=1) # (B, Qs, T, 3).
model_retval['sel_occl_fracs'] = sel_occl_fracs.cuda() # (B, Qs, T, 3).
return output_mask, output_flags, target_mask, features, model_retval
def get_target_mask(self, vid_idx):
# hard coded stuff
qt_idx = 0
b = 0
B = 1
Qs = 1
# seeker_input = self.dataset['pv_rgb_tf'][vid_idx].unsqueeze(0).cuda()
all_segm = self.dataset['pv_segm_tf'][vid_idx].unsqueeze(0).cuda()
all_div_segm = self.dataset['pv_div_segm_tf'][vid_idx].unsqueeze(0).cuda()
inst_count = self.dataset['pv_inst_count'][vid_idx].unsqueeze(0)
target_desirability = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['desirability_tf']).unsqueeze(
0)
occl_fracs = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['occl_fracs_tf']).unsqueeze(0)
occl_cont_dag = torch.tensor(self.dataset['traject_retval_tf'][vid_idx]['occl_cont_dag_tf']).unsqueeze(0)
scene_dp = self.dataset['full_scene_dp'][vid_idx]
# Sample either random or biased queries.
sel_query_inds = tcow.utils.my_utils.sample_query_inds(
B, Qs, inst_count, target_desirability, None, 'cuda', 'test')
query_idx = sel_query_inds[:, 0]
seeker_query_mask = torch.zeros_like(all_segm, dtype=torch.uint8) # (B, 1, T, Hf, Wf).
seeker_query_mask[b, 0, qt_idx] = (all_segm[b, 0, qt_idx] == query_idx[b] + 1)
# Prepare query mask and ground truths.
(seeker_query_mask, snitch_occl_by_ptr, full_occl_cont_id, target_mask,
target_flags) = tcow.data.data_utils.fill_kubric_query_target_mask_flags(
all_segm, all_div_segm, query_idx, qt_idx, occl_fracs, occl_cont_dag, scene_dp,
None, self.model.train_args, 'cuda', 'test')
del full_occl_cont_id, all_segm, all_div_segm, occl_cont_dag, scene_dp
# add things to dataset for logging if they were missed, this works with cacheing and non-cached datasets
try:
self.dataset['seeker_query_mask'].append(seeker_query_mask.cpu())
self.dataset['target_mask'].append(target_mask.cpu())
except:
self.dataset['seeker_query_mask'] = [seeker_query_mask.cpu()]
self.dataset['target_mask'] = [target_mask.cpu()]
def get_layer_activations(self, num_videos):
'''
Get layer activations for the given number of videos
:param num_videos:
:return:
'''
self.outputs = []
preds = []
results = {'mean_snitch_iou': [],
'mean_occl_mask_iou': [],
'mean_cont_mask_iou': [],
}
with torch.no_grad():
if 'pre' in self.args.model:
# initialize mask
mask = torch.zeros((1, 1568)).cuda().type(torch.bool)
self.layer_activations = {k: [] for k in self.args.cluster_layer}
for vid_idx in range(num_videos):
if 'timesformer' in self.args.model:
if 'kubric' in self.args.dataset:
output_mask, output_flags, target_mask, features, model_retval = self.tcow_timesformer_forward(vid_idx, keep_all=True)
model_retval = {
'output_mask': output_mask.unsqueeze(0),
'target_mask': target_mask.unsqueeze(0)
}
metrics_retval = calculate_metrics_mask_track(data_retval=None, model_retval=model_retval,
source_name='kubric')
# put all values to cpu
metrics_retval = {k: v.cpu() for k, v in metrics_retval.items()}
metrics_retval = calculate_weighted_averages(metrics_retvals=[metrics_retval])
metrics_retval = {k: float(v) for k, v in metrics_retval.items()}
for metric in results.keys():
if metrics_retval[metric] != -1:
results[metric].append(metrics_retval[metric])
# debug metrics
# self.outputs.append(output_mask.cpu())
# output_mask_binary = (output_mask > 0.0).bool()
# target_mask_binary = (target_mask > 0.5).bool() # (B, Q?, 1/3, T, Hf, Wf).
#
# # snitch iou
# snitch_output_mask = output_mask_binary[:, 0, :, :, :]
# snitch_target_mask = target_mask_binary[:, 0, :, :, :]
# snitch_iou = (snitch_output_mask & snitch_target_mask).sum() / (snitch_output_mask | snitch_target_mask).sum()
# results['mean_snitch_iou'].append(snitch_iou.item())
#
# # occl mask iou
# occl_output_mask = output_mask_binary[:, 1, :, :, :]
# occl_target_mask = target_mask_binary[:, 1, :, :, :]
# occl_iou = (occl_output_mask & occl_target_mask).sum() / (occl_output_mask | occl_target_mask).sum()
# results['mean_occl_mask_iou'].append(occl_iou.item())
#
# # cont mask iou
# cont_output_mask = output_mask_binary[:, 2, :, :, :]
# cont_target_mask = target_mask_binary[:, 2, :, :, :]
# cont_iou = (cont_output_mask & cont_target_mask).sum() / (cont_output_mask | cont_target_mask).sum()
# results['mean_cont_mask_iou'].append(cont_iou.item())
else:
if 'davis' not in self.args.dataset:
video = self.post_resize_smooth(self.dataset[vid_idx]).unsqueeze(0).cuda()
seeker_query_mask = self.post_resize_nearest(self.seeker_query_labels[vid_idx].squeeze(0)).unsqueeze(0).cuda()
else:
video = self.dataset[vid_idx].unsqueeze(0).cuda()
seeker_query_mask = self.seeker_query_labels[vid_idx].unsqueeze(0).cuda()
(output_mask, output_flags, features) = self.model(video, seeker_query_mask)
output_mask_binary = (output_mask > 0.0).bool().cpu()
self.outputs.append(output_mask_binary)
elif 'vidmae' in self.args.model:
# preprocess video
if self.args.dataset == 'kubric':
video = self.dataset['pv_rgb_tf'][vid_idx].permute(1,0,2,3)
self.get_target_mask(vid_idx)
start_frame = int((30-self.model.num_frames)/2)
video = video[start_frame:start_frame+self.model.num_frames]
else:
video = self.dataset[vid_idx].permute(1,0,2,3)
video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1,0,2,3)
video = video.unsqueeze(0).cuda()
if 'pre' in self.args.model:
_, features = self.model(video, mask)
else:
_, features = self.model(video)
elif 'intern' in self.args.model:
video = self.dataset[vid_idx]
video = self.model.transform(video).unsqueeze(0).cuda()
_, features = self.model.encode_video(video)
# video_features = self.model.encode_video(video)
# debug -> working!
# text_cand = [self.args.target_class, "an airplane is flying", "a dog is chasing a ball"]
# text = self.model.tokenize(text_cand).cuda()
# text_features = self.model.encode_text(text)
# video_features = torch.nn.functional.normalize(video_features, dim=1)
# text_features = torch.nn.functional.normalize(text_features, dim=1)
# t = self.model.logit_scale.exp()
# probs = (video_features @ text_features.T * t).softmax(dim=-1).cpu().numpy()
#
# print("Label probs: ") # [[9.5619422e-01 4.3805469e-02 2.0393253e-07]]
# for t, p in zip(text_cand, probs[0]):
# print("{:30s}: {:.4f}".format(t, p))
# print()
else:
raise NotImplementedError
# features.shape = num_layers x channels x num_heads x time x height x width
for layer_idx, layer in enumerate(self.args.cluster_layer):
self.layer_activations[layer].append(features[layer_idx])
if len(preds) > 0:
# print layers
print('Layers perturbed: ', self.args.cluster_layer)
# print accuracy of predictions
print(f'Classification accuracy: {np.mean(np.array(preds) == np.array(self.labels))}')
exit()
def get_layer_activations_full_video(self, num_videos):
if self.args.process_full_video:
self.chunk_overlap_sizes = []
self.outputs = []
preds = []
results = {'mean_snitch_iou': [],
'mean_occl_mask_iou': [],
'mean_cont_mask_iou': [],
}
with torch.no_grad():
if 'pre' in self.args.model:
# initialize mask
mask = torch.zeros((1, 1568)).cuda().type(torch.bool)
self.layer_activations = {k: [] for k in self.args.cluster_layer}
for vid_idx in range(num_videos):
if 'timesformer' in self.args.model:
if 'kubric' in self.args.dataset:
output_mask, output_flags, target_mask, features, model_retval = self.tcow_timesformer_forward(
vid_idx, keep_all=True)
self.outputs.append(output_mask.cpu())
model_retval = {
'output_mask': output_mask.unsqueeze(0),
'target_mask': target_mask.unsqueeze(0)
}
metrics_retval = calculate_metrics_mask_track(data_retval=None, model_retval=model_retval,
source_name='kubric')
# put all values to cpu
metrics_retval = {k: v.cpu() for k, v in metrics_retval.items()}
metrics_retval = calculate_weighted_averages(metrics_retvals=[metrics_retval])
metrics_retval = {k: float(v) for k, v in metrics_retval.items()}
for metric in results.keys():
if metrics_retval[metric] != -1:
results[metric].append(metrics_retval[metric])
# shitty metrics
# output_mask_binary = (output_mask > 0.0).bool()
# target_mask_binary = (target_mask > 0.5).bool() # (B, Q?, 1/3, T, Hf, Wf).
#
# # snitch iou
# snitch_output_mask = output_mask_binary[:, 0, :, :, :]
# snitch_target_mask = target_mask_binary[:, 0, :, :, :]
# snitch_iou = (snitch_output_mask & snitch_target_mask).sum() / (snitch_output_mask | snitch_target_mask).sum()
# results['mean_snitch_iou'].append(snitch_iou.item())
#
# # occl mask iou
# occl_output_mask = output_mask_binary[:, 1, :, :, :]
# occl_target_mask = target_mask_binary[:, 1, :, :, :]
# occl_iou = (occl_output_mask & occl_target_mask).sum() / (occl_output_mask | occl_target_mask).sum()
# results['mean_occl_mask_iou'].append(occl_iou.item())
#
# # cont mask iou
# cont_output_mask = output_mask_binary[:, 2, :, :, :]
# cont_target_mask = target_mask_binary[:, 2, :, :, :]
# cont_iou = (cont_output_mask & cont_target_mask).sum() / (cont_output_mask | cont_target_mask).sum()
# results['mean_cont_mask_iou'].append(cont_iou.item())
else:
if 'davis' not in self.args.dataset:
video = self.post_resize_smooth(self.dataset[vid_idx]).unsqueeze(0).cuda()
seeker_query_mask = self.post_resize_nearest(
self.seeker_query_labels[vid_idx].squeeze(0)).unsqueeze(0).cuda()
else:
video = self.dataset[vid_idx].unsqueeze(0).cuda()
if self.args.process_full_video:
# divide up frames into self.model.num_frames chunks
video_chunks = []
for i in range(0, video.shape[2], self.model.num_frames):
if i == 0:
video_chunks.append(video[:, :, i:i + self.model.num_frames])
else:
# grab the last frame of the previous prediction
video_chunks.append(video[:, :, i - 1:i - 1 + self.model.num_frames])
# record remainder
self.chunk_overlap_sizes.append(
video.shape[2] % self.model.num_frames) # don't really need to record this in advance...
# remove last chunk if it is not the right size
if video_chunks[-1].shape[2] != self.model.num_frames:
# replace with the last self.model.num_frames frame
video_chunks[-1] = video[:,:, -self.model.num_frames:]
# process each chunk
for video_chunk_idx, video_chunk in enumerate(video_chunks):
video_chunk = video_chunk.cuda()
if video_chunk_idx == 0:
seeker_query_mask = self.seeker_query_labels[vid_idx].unsqueeze(0).cuda()
elif video_chunk_idx == len(video_chunks) - 1:
# for last prediction, need to grab the query 30 frames from the end of the video
seeker_query_mask[:,0,0] = final_predicted_mask[:,0,-(30-self.chunk_overlap_sizes[vid_idx])]
else:
# grab the last frame of the previous prediction
seeker_query_mask[:,0] = output_mask_binary[:,0].float()
(output_mask, output_flags, features) = self.model(video_chunk, seeker_query_mask)
output_mask_binary = (output_mask > 0.0).bool().cpu()
# if first chunk, initialize combined feature
if video_chunk_idx == 0:
combined_feature = features
final_predicted_mask = output_mask_binary
# check if last feature
elif video_chunk_idx == len(video_chunks) - 1:
feature_chunk_overlap = int(self.chunk_overlap_sizes[vid_idx])
# slice and concat video to remove overlap
combined_feature = [torch.cat([combined_feature[layer_chunk_idx],features[layer_chunk_idx][:, :, :,:feature_chunk_overlap]], dim=3) for layer_chunk_idx in range(len(features))]
if feature_chunk_overlap == 0:
final_predicted_mask = torch.cat([final_predicted_mask, output_mask_binary], dim=2)
else:
final_predicted_mask = torch.cat([final_predicted_mask, output_mask_binary[:,:,:feature_chunk_overlap]], dim=2)
else:
final_predicted_mask = torch.cat([final_predicted_mask, output_mask_binary], dim=2)
# concat along time dimension
for layer_chunk_idx in range(len(features)):
combined_feature[layer_chunk_idx] = torch.cat(
[combined_feature[layer_chunk_idx], features[layer_chunk_idx]], dim=3)
features = combined_feature
else:
seeker_query_mask = self.seeker_query_labels[vid_idx].unsqueeze(0).cuda()
(output_mask, output_flags, features) = self.model(video, seeker_query_mask)
final_predicted_mask = (output_mask > 0.0).bool().cpu()
self.outputs.append(final_predicted_mask)
elif 'vidmae' in self.args.model:
# preprocess video
video = self.dataset[vid_idx].permute(1, 0, 2, 3)
video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1, 0, 2, 3)
if self.args.process_full_video:
# divide up frames into self.model.num_frames chunks
video_chunks = list(torch.split(video, self.model.num_frames, dim=1))
# record remainder
self.chunk_overlap_sizes.append(video.shape[1] % self.model.num_frames) # don't really need to record this in advance...
# remove last chunk if it is not the right size
if video_chunks[-1].shape[1] != self.model.num_frames:
# replace with the last self.model.num_frames frames
video_chunks[-1] = video[:, -self.model.num_frames:]
# process each chunk
for video_chunk_idx, video_chunk in enumerate(video_chunks):
video_chunk = video_chunk.unsqueeze(0).cuda()
if 'pre' in self.args.model:
_, features = self.model(video_chunk, mask)
else:
_, features = self.model(video_chunk)
# if first chunk, initialize combined feature
if video_chunk_idx == 0:
combined_feature = features
# check if last feature
elif video_chunk_idx == len(video_chunks) - 1:
feature_chunk_overlap = int(self.chunk_overlap_sizes[vid_idx]/2)
# slice and concat video to remove overlap
combined_feature = [torch.cat([combined_feature[layer_chunk_idx], features[layer_chunk_idx][:,:,:,:feature_chunk_overlap]], dim=3) for layer_chunk_idx in range(len(features))]
else:
# concat along time dimension
for layer_chunk_idx in range(len(features)):
combined_feature[layer_chunk_idx] = torch.cat([combined_feature[layer_chunk_idx], features[layer_chunk_idx]], dim=3)
features = combined_feature
else:
video = video.unsqueeze(0).cuda()
if 'pre' in self.args.model:
_, features = self.model(video, mask)
else:
_, features = self.model(video)
# preds.append(_.argmax().item())
elif 'svt' in self.args.model:
video = self.dataset[vid_idx].permute(1, 0, 2, 3)
video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1, 0, 2, 3)
video = video.unsqueeze(0).cuda()
_, features = self.model(video)
elif 'mme' in self.args.model:
video = self.dataset[vid_idx].permute(1, 0, 2, 3)
video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1, 0, 2, 3)
video = video.unsqueeze(0).cuda()
if 'pre' in self.args.model:
_, features = self.model(video, mask)
else:
_, features = self.model(video)
elif 'tf_og' in self.args.model:
video = self.dataset[vid_idx].permute(1, 0, 2, 3)
video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1, 0, 2, 3)
video = video.unsqueeze(0).cuda()
_, features = self.model(video)
elif 'intern' in self.args.model:
video = self.dataset[vid_idx]
video = self.model.transform(video)
if self.args.process_full_video:
# divide up frames into self.model.num_frames chunks
video_chunks = list(torch.split(video, self.model.num_frames, dim=1))
# record remainder
self.chunk_overlap_sizes.append(
video.shape[1] % self.model.num_frames) # don't really need to record this in advance...
# remove last chunk if it is not the right size
if video_chunks[-1].shape[1] != self.model.num_frames:
# replace with the last self.model.num_frames frames
video_chunks[-1] = video[:, -self.model.num_frames:]
# process each chunk
for video_chunk_idx, video_chunk in enumerate(video_chunks):
video_chunk = video_chunk.unsqueeze(0).cuda()
_, features = self.model.encode_video(video_chunk)
# if first chunk, initialize combined feature
if video_chunk_idx == 0:
combined_feature = features
# check if last feature
elif video_chunk_idx == len(video_chunks) - 1:
feature_chunk_overlap = int(self.chunk_overlap_sizes[vid_idx])
# slice and concat video to remove overlap
combined_feature = [torch.cat([combined_feature[layer_chunk_idx],
features[layer_chunk_idx][:, :, :,
:feature_chunk_overlap]], dim=3) for layer_chunk_idx in
range(len(features))]
else:
# concat along time dimension
for layer_chunk_idx in range(len(features)):
combined_feature[layer_chunk_idx] = torch.cat(
[combined_feature[layer_chunk_idx], features[layer_chunk_idx]], dim=3)
features = combined_feature
else:
_, features = self.model.encode_video(video.unsqueeze(0).cuda())
# video_features = self.model.encode_video(video)
# debug -> working!
# text_cand = [self.args.target_class, "an airplane is flying", "a dog is chasing a ball"]
# text = self.model.tokenize(text_cand).cuda()
# text_features = self.model.encode_text(text)
# video_features = torch.nn.functional.normalize(video_features, dim=1)
# text_features = torch.nn.functional.normalize(text_features, dim=1)
# t = self.model.logit_scale.exp()
# probs = (video_features @ text_features.T * t).softmax(dim=-1).cpu().numpy()
#
# print("Label probs: ") # [[9.5619422e-01 4.3805469e-02 2.0393253e-07]]
# for t, p in zip(text_cand, probs[0]):
# print("{:30s}: {:.4f}".format(t, p))
# print()
elif 'jepa' in self.args.model:
# video = self.dataset[vid_idx].permute(1,0,2,3)
# video = torch.stack([self.normalize(vid) for vid in video], dim=0).permute(1,0,2,3)
# video = video.unsqueeze(0).cuda()
# _, features = self.model(video)
# preprocess video