FSFM-3C commited on
Commit
b32e831
·
1 Parent(s): c4644b7
app.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+ # pip uninstall nvidia_cublas_cu11
8
+
9
+ import sys
10
+ sys.path.append('..')
11
+ import os
12
+ os.system(f'pip install dlib')
13
+ import torch
14
+ import numpy as np
15
+ from PIL import Image
16
+ from torch.nn import functional as F
17
+
18
+ import gradio as gr
19
+
20
+ import models_vit
21
+ from util.datasets import build_dataset
22
+ import argparse
23
+ from engine_finetune import test_all
24
+ import dlib
25
+ from huggingface_hub import hf_hub_download
26
+
27
+
28
+ P = os.path.abspath(__file__)
29
+ FRAME_SAVE_PATH = os.path.join(P[:-6], 'frame')
30
+ CKPT_SAVE_PATH = os.path.join(P[:-6], 'checkpoints')
31
+ CKPT_LIST = ['DfD Checkpoint_Fine-tuned on FF++',
32
+ 'FAS Checkpoint_Fine-tuned on MCIO']
33
+ CKPT_NAME = {'DfD Checkpoint_Fine-tuned on FF++': 'finetuned_models/FF++_c23_32frames/checkpoint-min_val_loss.pth',
34
+ 'FAS Checkpoint_Fine-tuned on MCIO': 'finetuned_models/MCIO_protocol/Both_MCIO/checkpoint-min_val_loss.pth' }
35
+ os.makedirs(FRAME_SAVE_PATH, exist_ok=True)
36
+ os.makedirs(CKPT_SAVE_PATH, exist_ok=True)
37
+
38
+
39
+ def get_args_parser():
40
+ parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False)
41
+ parser.add_argument('--batch_size', default=64, type=int,
42
+ help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus')
43
+ parser.add_argument('--epochs', default=50, type=int)
44
+ parser.add_argument('--accum_iter', default=1, type=int,
45
+ help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)')
46
+
47
+ # Model parameters
48
+ parser.add_argument('--model', default='vit_large_patch16', type=str, metavar='MODEL',
49
+ help='Name of model to train')
50
+
51
+ parser.add_argument('--input_size', default=224, type=int,
52
+ help='images input size')
53
+ parser.add_argument('--normalize_from_IMN', action='store_true',
54
+ help='cal mean and std from imagenet, else from pretrain datasets')
55
+ parser.set_defaults(normalize_from_IMN=True)
56
+ parser.add_argument('--apply_simple_augment', action='store_true',
57
+ help='apply simple data augment')
58
+
59
+ parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT',
60
+ help='Drop path rate (default: 0.1)')
61
+
62
+ # Optimizer parameters
63
+ parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM',
64
+ help='Clip gradient norm (default: None, no clipping)')
65
+ parser.add_argument('--weight_decay', type=float, default=0.05,
66
+ help='weight decay (default: 0.05)')
67
+
68
+ parser.add_argument('--lr', type=float, default=None, metavar='LR',
69
+ help='learning rate (absolute lr)')
70
+ parser.add_argument('--blr', type=float, default=1e-3, metavar='LR',
71
+ help='base learning rate: absolute_lr = base_lr * total_batch_size / 256')
72
+ parser.add_argument('--layer_decay', type=float, default=0.75,
73
+ help='layer-wise lr decay from ELECTRA/BEiT')
74
+
75
+ parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR',
76
+ help='lower lr bound for cyclic schedulers that hit 0')
77
+
78
+ parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N',
79
+ help='epochs to warmup LR')
80
+
81
+ # Augmentation parameters
82
+ parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT',
83
+ help='Color jitter factor (enabled only when not using Auto/RandAug)')
84
+ parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME',
85
+ help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'),
86
+ parser.add_argument('--smoothing', type=float, default=0.1,
87
+ help='Label smoothing (default: 0.1)')
88
+
89
+ # * Random Erase params
90
+ parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT',
91
+ help='Random erase prob (default: 0.25)')
92
+ parser.add_argument('--remode', type=str, default='pixel',
93
+ help='Random erase mode (default: "pixel")')
94
+ parser.add_argument('--recount', type=int, default=1,
95
+ help='Random erase count (default: 1)')
96
+ parser.add_argument('--resplit', action='store_true', default=False,
97
+ help='Do not random erase first (clean) augmentation split')
98
+
99
+ # * Mixup params
100
+ parser.add_argument('--mixup', type=float, default=0,
101
+ help='mixup alpha, mixup enabled if > 0.')
102
+ parser.add_argument('--cutmix', type=float, default=0,
103
+ help='cutmix alpha, cutmix enabled if > 0.')
104
+ parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None,
105
+ help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')
106
+ parser.add_argument('--mixup_prob', type=float, default=1.0,
107
+ help='Probability of performing mixup or cutmix when either/both is enabled')
108
+ parser.add_argument('--mixup_switch_prob', type=float, default=0.5,
109
+ help='Probability of switching to cutmix when both mixup and cutmix enabled')
110
+ parser.add_argument('--mixup_mode', type=str, default='batch',
111
+ help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"')
112
+
113
+ # * Finetuning params
114
+ parser.add_argument('--finetune', default='',
115
+ help='finetune from checkpoint')
116
+ parser.add_argument('--global_pool', action='store_true')
117
+ parser.set_defaults(global_pool=True)
118
+ parser.add_argument('--cls_token', action='store_false', dest='global_pool',
119
+ help='Use class token instead of global pool for classification')
120
+
121
+ # Dataset parameters
122
+ parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str,
123
+ help='dataset path')
124
+ parser.add_argument('--nb_classes', default=1000, type=int,
125
+ help='number of the classification types')
126
+
127
+ parser.add_argument('--output_dir', default='',
128
+ help='path where to save, empty for no saving')
129
+ parser.add_argument('--log_dir', default='',
130
+ help='path where to tensorboard log')
131
+ parser.add_argument('--device', default='cuda',
132
+ help='device to use for training / testing')
133
+ parser.add_argument('--seed', default=0, type=int)
134
+ parser.add_argument('--resume', default='',
135
+ help='resume from checkpoint')
136
+
137
+ parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
138
+ help='start epoch')
139
+ parser.add_argument('--eval', action='store_true',
140
+ help='Perform evaluation only')
141
+ parser.set_defaults(eval=True)
142
+ parser.add_argument('--dist_eval', action='store_true', default=False,
143
+ help='Enabling distributed evaluation (recommended during training for faster monitor')
144
+ parser.add_argument('--num_workers', default=10, type=int)
145
+ parser.add_argument('--pin_mem', action='store_true',
146
+ help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
147
+ parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
148
+ parser.set_defaults(pin_mem=True)
149
+
150
+ # distributed training parameters
151
+ parser.add_argument('--world_size', default=1, type=int,
152
+ help='number of distributed processes')
153
+ parser.add_argument('--local_rank', default=-1, type=int)
154
+ parser.add_argument('--dist_on_itp', action='store_true')
155
+ parser.add_argument('--dist_url', default='env://',
156
+ help='url used to set up distributed training')
157
+
158
+ return parser
159
+
160
+
161
+ args = get_args_parser()
162
+ args = args.parse_args()
163
+ args.nb_classes = 2
164
+
165
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
166
+
167
+ model = models_vit.__dict__['vit_base_patch16'](
168
+ num_classes=args.nb_classes,
169
+ drop_path_rate=args.drop_path,
170
+ global_pool=args.global_pool,
171
+ )
172
+
173
+ def load_model(ckpt):
174
+ if ckpt=='hoose from here':
175
+ return gr.update()
176
+ args.resume = os.path.join(CKPT_SAVE_PATH, ckpt)
177
+ if os.path.isfile(args.resume) == False:
178
+ hf_hub_download(local_dir=CKPT_SAVE_PATH,
179
+ repo_id='Wolowolo/fsfm-3c',
180
+ filename=ckpt)
181
+ checkpoint = torch.load(args.resume, map_location='cpu')
182
+ model.load_state_dict(checkpoint['model'])
183
+ return gr.update()
184
+
185
+
186
+ def get_boundingbox(face, width, height, minsize=None):
187
+ """
188
+ From FF++:
189
+ https://github.com/ondyari/FaceForensics/blob/master/classification/detect_from_video.py
190
+ Expects a dlib face to generate a quadratic bounding box.
191
+ :param face: dlib face class
192
+ :param width: frame width
193
+ :param height: frame height
194
+ :param cfg.face_scale: bounding box size multiplier to get a bigger face region
195
+ :param minsize: set minimum bounding box size
196
+ :return: x, y, bounding_box_size in opencv form
197
+ """
198
+ x1 = face.left()
199
+ y1 = face.top()
200
+ x2 = face.right()
201
+ y2 = face.bottom()
202
+ size_bb = int(max(x2 - x1, y2 - y1) * 1.3)
203
+ if minsize:
204
+ if size_bb < minsize:
205
+ size_bb = minsize
206
+ center_x, center_y = (x1 + x2) // 2, (y1 + y2) // 2
207
+
208
+ # Check for out of bounds, x-y top left corner
209
+ x1 = max(int(center_x - size_bb // 2), 0)
210
+ y1 = max(int(center_y - size_bb // 2), 0)
211
+ # Check for too big bb size for given x, y
212
+ size_bb = min(width - x1, size_bb)
213
+ size_bb = min(height - y1, size_bb)
214
+
215
+ return x1, y1, size_bb
216
+
217
+
218
+ def extract_face(frame):
219
+ face_detector = dlib.get_frontal_face_detector()
220
+ image = np.array(frame.convert('RGB'))
221
+ faces = face_detector(image, 1)
222
+ if len(faces) > 0:
223
+ # For now only take the biggest face
224
+ face = faces[0]
225
+ # Face crop and rescale(follow FF++)
226
+ x, y, size = get_boundingbox(face, image.shape[1], image.shape[0])
227
+ # Get the landmarks/parts for the face in box d only with the five key points
228
+ cropped_face = image[y:y + size, x:x + size]
229
+ # cropped_face = cv2.resize(cropped_face, (224, 224), interpolation=cv2.INTER_CUBIC)
230
+ return Image.fromarray(cropped_face)
231
+ else:
232
+ return None
233
+
234
+
235
+ def get_frame_index_uniform_sample(total_frame_num, extract_frame_num):
236
+ interval = np.linspace(0, total_frame_num - 1, num=extract_frame_num, dtype=int)
237
+ return interval.tolist()
238
+
239
+
240
+ import cv2
241
+ def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None, device='cpu'):
242
+ """
243
+ 1) extract specific num of frames from videos in [1st(index 0) frame, last frame] with uniform sample interval
244
+ 2) extract face from frame with specific enlarge size
245
+ """
246
+ video_capture = cv2.VideoCapture(src_video)
247
+ total_frames = video_capture.get(7)
248
+
249
+ # extract from the 1st(index 0) frame
250
+ if num_frames is not None:
251
+ frame_indices = get_frame_index_uniform_sample(total_frames, num_frames)
252
+ else:
253
+ frame_indices = range(int(total_frames))
254
+
255
+ for frame_index in frame_indices:
256
+ video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
257
+ ret, frame = video_capture.read()
258
+ image = Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
259
+ img = extract_face(image)
260
+ if img == None:
261
+ continue
262
+ img = img.resize((224, 224), Image.BICUBIC)
263
+ if not ret:
264
+ continue
265
+ save_img_name = f"frame_{frame_index}.png"
266
+
267
+ img.save(os.path.join(dst_path, '0', save_img_name))
268
+ # cv2.imwrite(os.path.join(dst_path, '0', save_img_name), frame)
269
+
270
+ video_capture.release()
271
+ # cv2.destroyAllWindows()
272
+
273
+
274
+ def FSFM3C_video_detection(video):
275
+ model.to(device)
276
+
277
+ # extract frames
278
+ num_frames = 32
279
+
280
+ files = os.listdir(FRAME_SAVE_PATH)
281
+ num_files = len(files)
282
+ frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
283
+ os.makedirs(frame_path, exist_ok=True)
284
+ os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
285
+ extract_face_from_fixed_num_frames(video, frame_path, num_frames=num_frames, device=device)
286
+
287
+ args.data_path = frame_path
288
+ args.batch_size = 32
289
+ dataset_val = build_dataset(is_train=False, args=args)
290
+ sampler_val = torch.utils.data.SequentialSampler(dataset_val)
291
+ data_loader_val = torch.utils.data.DataLoader(
292
+ dataset_val, sampler=sampler_val,
293
+ batch_size=args.batch_size,
294
+ num_workers=args.num_workers,
295
+ pin_memory=args.pin_mem,
296
+ drop_last=False
297
+ )
298
+
299
+ frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
300
+
301
+ return video_y_pred_list
302
+
303
+
304
+ def FSFM3C_image_detection(image):
305
+ model.to(device)
306
+
307
+ files = os.listdir(FRAME_SAVE_PATH)
308
+ num_files = len(files)
309
+ frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
310
+ os.makedirs(frame_path, exist_ok=True)
311
+ os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
312
+
313
+ save_img_name = f"frame_0.png"
314
+ img = extract_face(image)
315
+ if img is None:
316
+ return ['Invalid Input']
317
+ img = img.resize((224, 224), Image.BICUBIC)
318
+ img.save(os.path.join(frame_path, '0', save_img_name))
319
+
320
+ args.data_path = frame_path
321
+ args.batch_size = 1
322
+ dataset_val = build_dataset(is_train=False, args=args)
323
+ sampler_val = torch.utils.data.SequentialSampler(dataset_val)
324
+ data_loader_val = torch.utils.data.DataLoader(
325
+ dataset_val, sampler=sampler_val,
326
+ batch_size=args.batch_size,
327
+ num_workers=args.num_workers,
328
+ pin_memory=args.pin_mem,
329
+ drop_last=False
330
+ )
331
+
332
+ frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
333
+
334
+ return video_y_pred_list
335
+
336
+
337
+ # WebUI
338
+ with gr.Blocks() as demo:
339
+ gr.HTML("<h1 style='text-align: center;'>🦱 Real Facial Image&Video Detection <br> Against Face Forgery and Spoofing (Deepfake/Diffusion/Presentation-attacks)</h1>")
340
+ gr.Markdown("# ---Based on the fine-tuned model that is pre-trained from [FSFM-3C](https://fsfm-3c.github.io/)")
341
+
342
+ gr.Markdown("## Release <br>"
343
+ "V1.0 [2024-12] (Current): <br>"
344
+ "[1] Create this page with basic detectors (simply fine-tuned models that follow the paper implementation): <br> "
345
+ " - DfD Checkpoint_Fine-tuned on FF++: FSFM VIT-B fine-tuned on the FF++ (c23, train&val sets, 32 frames per video, 4 manipulations) dataset <br>"
346
+ " - FAS Checkpoint_Fine-tuned on MCIO: FSFM VIT-B fine-tuned on the MCIO datasets (2 frames per video) <br> "
347
+ " Performance is limited because no any optimization of data, models, hyperparameters, etc. is done for downstream tasks")
348
+
349
+ gr.Markdown("### TODO: We will soon update practical models, and optimized interfaces, and provide more functions such as visualizations, a unified detector, and multi-modal diagnosis.")
350
+
351
+ gr.Markdown("> Please provide an <b>image</b> or a <b>video (<100s </b>, default to uniform sampling 32 frames)</b> for detection:")
352
+
353
+
354
+ with gr.Column():
355
+ ckpt_select_dropdown = gr.Dropdown(
356
+ label = "Select the Model Checkpoint for Detection (🖱️ below)",
357
+ choices = ['choose from here'] + CKPT_LIST + ['Continuously updating...'],
358
+ multiselect = False,
359
+ value = 'choose from here',
360
+ interactive = True,
361
+ )
362
+ with gr.Row(elem_classes="center-align"):
363
+ with gr.Column(scale=5):
364
+ gr.Markdown(
365
+ "## Image Detection"
366
+ )
367
+ image = gr.Image(label="Upload/Capture/Paste your image", type="pil")
368
+ image_submit_btn = gr.Button("Submit")
369
+ output_results_image = gr.Textbox(label="Detection Result")
370
+ with gr.Column(scale=5):
371
+ gr.Markdown(
372
+ "## Video Detection"
373
+ )
374
+ video = gr.Video(label="Upload/Capture your video")
375
+ video_submit_btn = gr.Button("Submit")
376
+ output_results_video = gr.Textbox(label="Detection Result")
377
+
378
+ image_submit_btn.click(
379
+ fn=FSFM3C_image_detection,
380
+ inputs=[image],
381
+ outputs=[output_results_image],
382
+ )
383
+ video_submit_btn.click(
384
+ fn=FSFM3C_video_detection,
385
+ inputs=[video],
386
+ outputs=[output_results_video],
387
+ )
388
+ ckpt_select_dropdown.change(
389
+ fn=load_model,
390
+ inputs=[ckpt_select_dropdown],
391
+ outputs=[ckpt_select_dropdown],
392
+ )
393
+
394
+
395
+ if __name__ == "__main__":
396
+ gr.close_all()
397
+ demo.queue()
398
+ demo.launch()
engine_finetune.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import math
9
+ import sys
10
+ from typing import Iterable, Optional
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ from timm.data import Mixup
16
+ from timm.utils import accuracy
17
+
18
+ import util.misc as misc
19
+ import util.lr_sched as lr_sched
20
+ from util.metrics import *
21
+
22
+ import torch.nn.functional as F
23
+
24
+
25
+ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
26
+ data_loader: Iterable, optimizer: torch.optim.Optimizer,
27
+ device: torch.device, epoch: int, loss_scaler, max_norm: float = 0,
28
+ mixup_fn: Optional[Mixup] = None, log_writer=None,
29
+ args=None):
30
+ model.train(True)
31
+ metric_logger = misc.MetricLogger(delimiter=" ")
32
+ metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
33
+ header = 'Epoch: [{}]'.format(epoch)
34
+ print_freq = 20
35
+
36
+ accum_iter = args.accum_iter
37
+
38
+ optimizer.zero_grad()
39
+
40
+ if log_writer is not None:
41
+ print('log_dir: {}'.format(log_writer.log_dir))
42
+
43
+ for data_iter_step, (samples, targets) in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
44
+
45
+ # we use a per iteration (instead of per epoch) lr scheduler
46
+ if data_iter_step % accum_iter == 0:
47
+ lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
48
+
49
+ samples = samples.to(device, non_blocking=True)
50
+ targets = targets.to(device, non_blocking=True)
51
+
52
+ if mixup_fn is not None:
53
+ samples, targets = mixup_fn(samples, targets)
54
+
55
+ with torch.cuda.amp.autocast():
56
+ # outputs = model(samples)
57
+ outputs = model(samples).to(device, non_blocking=True) # modified
58
+ loss = criterion(outputs, targets)
59
+
60
+ loss_value = loss.item()
61
+
62
+ if not math.isfinite(loss_value):
63
+ print("Loss is {}, stopping training".format(loss_value))
64
+ sys.exit(1)
65
+
66
+ loss /= accum_iter
67
+ loss_scaler(loss, optimizer, clip_grad=max_norm,
68
+ parameters=model.parameters(), create_graph=False,
69
+ update_grad=(data_iter_step + 1) % accum_iter == 0)
70
+ if (data_iter_step + 1) % accum_iter == 0:
71
+ optimizer.zero_grad()
72
+
73
+ torch.cuda.synchronize()
74
+
75
+ metric_logger.update(loss=loss_value)
76
+ min_lr = 10.
77
+ max_lr = 0.
78
+ for group in optimizer.param_groups:
79
+ min_lr = min(min_lr, group["lr"])
80
+ max_lr = max(max_lr, group["lr"])
81
+
82
+ metric_logger.update(lr=max_lr)
83
+
84
+ loss_value_reduce = misc.all_reduce_mean(loss_value)
85
+ if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
86
+ """ We use epoch_1000x as the x-axis in tensorboard.
87
+ This calibrates different curves when batch size changes.
88
+ """
89
+ epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
90
+ log_writer.add_scalar('loss', loss_value_reduce, epoch_1000x)
91
+ log_writer.add_scalar('lr', max_lr, epoch_1000x)
92
+
93
+ # gather the stats from all processes
94
+ metric_logger.synchronize_between_processes()
95
+ print("Averaged stats:", metric_logger)
96
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
97
+
98
+
99
+ @torch.no_grad()
100
+ def evaluate(data_loader, model, device):
101
+ criterion = torch.nn.CrossEntropyLoss()
102
+
103
+ metric_logger = misc.MetricLogger(delimiter=" ")
104
+ header = 'Test:'
105
+
106
+ # switch to evaluation mode
107
+ model.eval()
108
+
109
+ for batch in metric_logger.log_every(data_loader, 10, header):
110
+ images = batch[0]
111
+ target = batch[-1]
112
+ images = images.to(device, non_blocking=True)
113
+ target = target.to(device, non_blocking=True)
114
+
115
+ # compute output
116
+ with torch.cuda.amp.autocast():
117
+ # output = model(images)
118
+ output = model(images).to(device, non_blocking=True) # modified
119
+ loss = criterion(output, target)
120
+
121
+ # acc1, acc5 = accuracy(output, target, topk=(1, 5))
122
+ acc = float(accuracy(output, target, topk=(1,))[0])
123
+ preds = (F.softmax(output, dim=1)[:, 1].detach().cpu().numpy())
124
+ trues = (target.detach().cpu().numpy())
125
+ auc_score = roc_auc_score(trues, preds) * 100.
126
+
127
+ batch_size = images.shape[0]
128
+ metric_logger.update(loss=loss.item())
129
+ # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)
130
+ # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
131
+ metric_logger.meters['acc'].update(acc, n=batch_size)
132
+ metric_logger.meters['auc'].update(auc_score, n=batch_size)
133
+
134
+ # gather the stats from all processes
135
+ metric_logger.synchronize_between_processes()
136
+ # print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'
137
+ # .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))
138
+ print('* Acc {acc.global_avg:.3f} Auc {auc.global_avg:.3f} loss {losses.global_avg:.3f}'
139
+ .format(acc=metric_logger.acc, auc=metric_logger.auc, losses=metric_logger.loss))
140
+
141
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
142
+
143
+
144
+ @torch.no_grad()
145
+ def test_ori(data_loader, model, device):
146
+ criterion = torch.nn.CrossEntropyLoss()
147
+
148
+ metric_logger = misc.MetricLogger(delimiter=" ")
149
+ header = 'Test:'
150
+
151
+ # switch to evaluation mode
152
+ model.eval()
153
+
154
+ labels = np.array([])
155
+ preds = np.array([])
156
+
157
+ for batch in metric_logger.log_every(data_loader, 10, header):
158
+ images = batch[0]
159
+ target = batch[-1]
160
+ images = images.to(device, non_blocking=True)
161
+ target = target.to(device, non_blocking=True)
162
+
163
+ # compute output
164
+ with torch.cuda.amp.autocast():
165
+ # output = model(images)
166
+ output = model(images).to(device, non_blocking=True) # modified
167
+ loss = criterion(output, target)
168
+
169
+ # acc1, acc5 = accuracy(output, target, topk=(1, 5))
170
+ acc = float(accuracy(output, target, topk=(1,))[0])
171
+ pred = (F.softmax(output, dim=1)[:, 1].detach().cpu().numpy())
172
+ preds = np.append(preds, pred)
173
+ label = (target.detach().cpu().numpy())
174
+ labels = np.append(labels, label)
175
+
176
+ batch_size = images.shape[0]
177
+ metric_logger.update(loss=loss.item())
178
+ # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)
179
+ # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
180
+ metric_logger.meters['acc'].update(acc, n=batch_size)
181
+
182
+ # gather the stats from all processes
183
+ metric_logger.synchronize_between_processes()
184
+ # print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'
185
+ # .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))
186
+ auc_score = roc_auc_score(labels, preds) * 100.
187
+ metric_logger.meters['auc'].update(auc_score)
188
+ print('* Acc {acc.global_avg:.3f} Auc {auc.global_avg:.3f} loss {losses.global_avg:.3f}'
189
+ .format(acc=metric_logger.acc, auc=metric_logger.auc, losses=metric_logger.loss))
190
+
191
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
192
+
193
+
194
+ @torch.no_grad()
195
+ def test(data_loader, model, device):
196
+ criterion = torch.nn.CrossEntropyLoss()
197
+
198
+ metric_logger = misc.MetricLogger(delimiter=" ")
199
+ header = 'Test:'
200
+
201
+ # switch to evaluation mode
202
+ model.eval()
203
+
204
+ frame_labels = np.array([]) # int label
205
+ frame_preds = np.array([]) # pred logit
206
+ frame_y_preds = np.array([]) # pred int
207
+
208
+ # for batch in metric_logger.log_every(data_loader, print_freq=len(data_loader), header=header):
209
+ for batch in data_loader:
210
+ images = batch[0] # torch.Size([BS, C, H, W])
211
+ target = batch[1] # torch.Size([BS])
212
+
213
+ images = images.to(device, non_blocking=True)
214
+ target = target.to(device, non_blocking=True)
215
+
216
+ # compute output
217
+ with torch.cuda.amp.autocast():
218
+ # output = model(images)
219
+ output = model(images).to(device, non_blocking=True) # modified
220
+ loss = criterion(output, target)
221
+
222
+ frame_pred = (F.softmax(output, dim=1)[:, 1].detach().cpu().numpy())
223
+ frame_preds = np.append(frame_preds, frame_pred)
224
+
225
+ frame_y_pred = np.argmax(output.detach().cpu().numpy(), axis=1)
226
+ frame_y_preds = np.append(frame_y_preds, frame_y_pred)
227
+
228
+ frame_label = (target.detach().cpu().numpy())
229
+ frame_labels = np.append(frame_labels, frame_label)
230
+
231
+ metric_logger.update(loss=loss.item())
232
+
233
+ # gather the stats from all processes
234
+ metric_logger.synchronize_between_processes()
235
+ metric_logger.meters['frame_acc'].update(frame_level_acc(frame_labels, frame_y_preds))
236
+ metric_logger.meters['frame_balanced_acc'].update(frame_level_balanced_acc(frame_labels, frame_y_preds))
237
+ metric_logger.meters['frame_auc'].update(frame_level_auc(frame_labels, frame_preds))
238
+ metric_logger.meters['frame_eer'].update(frame_level_eer(frame_labels, frame_preds))
239
+
240
+ print('*[------FRAME-LEVEL------] \n'
241
+ 'Acc {frame_acc.global_avg:.3f} Balanced_Acc {frame_balanced_acc.global_avg:.3f} '
242
+ 'Auc {frame_auc.global_avg:.3f} EER {frame_eer.global_avg:.3f} loss {losses.global_avg:.3f}'
243
+ .format(frame_acc=metric_logger.frame_acc, frame_balanced_acc=metric_logger.frame_balanced_acc,
244
+ frame_auc=metric_logger.frame_auc, frame_eer=metric_logger.frame_eer, losses=metric_logger.loss))
245
+
246
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
247
+
248
+
249
+ @torch.no_grad()
250
+ def test_all(data_loader, model, device):
251
+ criterion = torch.nn.CrossEntropyLoss()
252
+
253
+ metric_logger = misc.MetricLogger(delimiter=" ")
254
+ header = 'Test:'
255
+
256
+ # switch to evaluation mode
257
+ model.eval()
258
+
259
+ frame_labels = np.array([]) # int label
260
+ frame_preds = np.array([]) # pred logit
261
+ frame_y_preds = np.array([]) # pred int
262
+ video_names_list = list()
263
+
264
+ # for batch in metric_logger.log_every(data_loader, print_freq=len(data_loader), header=header):
265
+ for batch in data_loader:
266
+ images = batch[0] # torch.Size([BS, C, H, W])
267
+ target = batch[1] # torch.Size([BS])
268
+ video_name = batch[-1] # list[BS]
269
+
270
+ images = images.to(device, non_blocking=True)
271
+ target = target.to(device, non_blocking=True)
272
+
273
+ # compute output
274
+ # with torch.cuda.amp.autocast():
275
+ # output = model(images)
276
+ output = model(images).to(device, non_blocking=True) # modified
277
+ loss = criterion(output, target)
278
+
279
+ frame_pred = (F.softmax(output, dim=1)[:, 1].detach().cpu().numpy())
280
+ frame_preds = np.append(frame_preds, frame_pred)
281
+
282
+ frame_y_pred = np.argmax(output.detach().cpu().numpy(), axis=1)
283
+ frame_y_preds = np.append(frame_y_preds, frame_y_pred)
284
+
285
+ frame_label = (target.detach().cpu().numpy())
286
+ frame_labels = np.append(frame_labels, frame_label)
287
+
288
+ video_names_list.extend(list(video_name))
289
+
290
+ metric_logger.update(loss=loss.item())
291
+
292
+ # gather the stats from all processes
293
+ # metric_logger.synchronize_between_processes()
294
+ # metric_logger.meters['frame_acc'].update(frame_level_acc(frame_labels, frame_y_preds))
295
+ # metric_logger.meters['frame_balanced_acc'].update(frame_level_balanced_acc(frame_labels, frame_y_preds))
296
+ # metric_logger.meters['frame_auc'].update(frame_level_auc(frame_labels, frame_preds))
297
+ # metric_logger.meters['frame_eer'].update(frame_level_eer(frame_labels, frame_preds))
298
+
299
+ # print('*[------FRAME-LEVEL------] \n'
300
+ # 'Acc {frame_acc.global_avg:.3f} Balanced_Acc {frame_balanced_acc.global_avg:.3f} '
301
+ # 'Auc {frame_auc.global_avg:.3f} EER {frame_eer.global_avg:.3f} loss {losses.global_avg:.3f}'
302
+ # .format(frame_acc=metric_logger.frame_acc, frame_balanced_acc=metric_logger.frame_balanced_acc,
303
+ # frame_auc=metric_logger.frame_auc, frame_eer=metric_logger.frame_eer, losses=metric_logger.loss))
304
+
305
+ # video-level metrics:
306
+ frame_labels_list = frame_labels.tolist()
307
+ frame_preds_list = frame_preds.tolist()
308
+
309
+ video_label_list, video_pred_list, video_y_pred_list = get_video_level_label_pred(frame_labels_list, video_names_list, frame_preds_list)
310
+ # print(len(video_label_list), len(video_pred_list), len(video_y_pred_list))
311
+ # metric_logger.meters['video_acc'].update(video_level_acc(video_label_list, video_y_pred_list))
312
+ # metric_logger.meters['video_balanced_acc'].update(video_level_balanced_acc(video_label_list, video_y_pred_list))
313
+ # metric_logger.meters['video_auc'].update(video_level_auc(video_label_list, video_pred_list))
314
+ # metric_logger.meters['video_eer'].update(frame_level_eer(video_label_list, video_pred_list))
315
+
316
+ # print('*[------VIDEO-LEVEL------] \n'
317
+ # 'Acc {video_acc.global_avg:.3f} Balanced_Acc {video_balanced_acc.global_avg:.3f} '
318
+ # 'Auc {video_auc.global_avg:.3f} EER {video_eer.global_avg:.3f}'
319
+ # .format(video_acc=metric_logger.video_acc, video_balanced_acc=metric_logger.video_balanced_acc,
320
+ # video_auc=metric_logger.video_auc, video_eer=metric_logger.video_eer))
321
+
322
+ # return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
323
+ return frame_preds_list, video_y_pred_list
models_vit.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ from functools import partial
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+
13
+ import timm.models.vision_transformer
14
+
15
+
16
+ class VisionTransformer(timm.models.vision_transformer.VisionTransformer):
17
+ """ Vision Transformer with support for global average pooling
18
+ """
19
+ def __init__(self, global_pool=False, **kwargs):
20
+ super(VisionTransformer, self).__init__(**kwargs)
21
+
22
+ self.global_pool = global_pool
23
+ if self.global_pool:
24
+ norm_layer = kwargs['norm_layer']
25
+ embed_dim = kwargs['embed_dim']
26
+ self.fc_norm = norm_layer(embed_dim)
27
+
28
+ del self.norm # remove the original norm
29
+
30
+ def forward_features(self, x):
31
+ B = x.shape[0]
32
+ x = self.patch_embed(x)
33
+
34
+ cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
35
+ x = torch.cat((cls_tokens, x), dim=1)
36
+ x = x + self.pos_embed
37
+ x = self.pos_drop(x)
38
+
39
+ for blk in self.blocks:
40
+ x = blk(x)
41
+
42
+ if self.global_pool:
43
+ x = x[:, 1:, :].mean(dim=1) # global pool without cls token
44
+ outcome = self.fc_norm(x)
45
+ else:
46
+ x = self.norm(x)
47
+ outcome = x[:, 0]
48
+
49
+ return outcome
50
+
51
+
52
+ def vit_small_patch16(**kwargs):
53
+ model = VisionTransformer(
54
+ patch_size=16, embed_dim=384, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, # ViT-small config in MOCO_V3
55
+ # patch_size=16, embed_dim=768, depth=8, num_heads=8, mlp_ratio=3, qkv_bias=True, # ViT-small config in timm
56
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
57
+ return model
58
+
59
+
60
+ def vit_base_patch16(**kwargs):
61
+ model = VisionTransformer(
62
+ patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,
63
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
64
+ return model
65
+
66
+
67
+ def vit_large_patch16(**kwargs):
68
+ model = VisionTransformer(
69
+ patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, qkv_bias=True,
70
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
71
+ return model
72
+
73
+
74
+ def vit_huge_patch14(**kwargs):
75
+ model = VisionTransformer(
76
+ patch_size=14, embed_dim=1280, depth=32, num_heads=16, mlp_ratio=4, qkv_bias=True,
77
+ norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
78
+ return model
79
+
80
+
81
+ # class VisionTransformerWithProjector(VisionTransformer):
82
+ # def __init__(self, vit_model, model_encoder, feat_cl_dim=128):
83
+ # super(VisionTransformerWithProjector, self).__init__()
84
+ # self.encoder = vit_model
85
+ # embed_dim = {'vit_base_patch16': 768, 'vit_large_patch16': 1024, 'vit_huge_patch14': 1280}
86
+ # self.projection_head = nn.Sequential(
87
+ # nn.Linear(embed_dim[model_encoder], embed_dim[model_encoder]),
88
+ # nn.ReLU(inplace=True),
89
+ # nn.Linear(embed_dim[model_encoder], feat_cl_dim)
90
+ # )
91
+ #
92
+ # def forward(self, x):
93
+ # x = self.encoder(x)
94
+ # latent_cl = self.projection_head(x) # [N, feat_cl_dim]
95
+ # features = nn.functional.normalize(latent_cl, dim=-1) # [N, feat_cl_dim]
96
+ # return features
requirements.txt ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ annotated-types==0.7.0
3
+ anyio==4.6.2.post1
4
+ certifi==2024.8.30
5
+ charset-normalizer==3.4.0
6
+ click==8.1.7
7
+ contourpy==1.3.0
8
+ cycler==0.12.1
9
+ # dlib==19.24.6
10
+ exceptiongroup==1.2.2
11
+ fastapi==0.115.5
12
+ ffmpy==0.4.0
13
+ filelock==3.16.1
14
+ fonttools==4.55.0
15
+ fsspec==2024.10.0
16
+ gradio==4.44.1
17
+ gradio_client==1.3.0
18
+ h11==0.14.0
19
+ httpcore==1.0.7
20
+ httpx==0.27.2
21
+ huggingface-hub==0.26.2
22
+ idna==3.10
23
+ imageio==2.36.0
24
+ importlib_resources==6.4.5
25
+ Jinja2==3.1.4
26
+ joblib==1.4.2
27
+ kiwisolver==1.4.7
28
+ lazy_loader==0.4
29
+ markdown-it-py==3.0.0
30
+ MarkupSafe==2.1.5
31
+ matplotlib==3.9.2
32
+ mdurl==0.1.2
33
+ networkx==3.2.1
34
+ numpy==1.24.4
35
+ nvidia-cuda-nvrtc-cu11==11.7.99
36
+ nvidia-cuda-runtime-cu11==11.7.99
37
+ nvidia-cudnn-cu11==8.5.0.96
38
+ opencv-python==4.10.0.84
39
+ orjson==3.10.11
40
+ packaging==24.2
41
+ pandas==2.2.3
42
+ pillow==10.4.0
43
+ pydantic==2.9.2
44
+ pydantic_core==2.23.4
45
+ pydub==0.25.1
46
+ Pygments==2.18.0
47
+ pyparsing==3.2.0
48
+ python-dateutil==2.9.0.post0
49
+ python-multipart==0.0.17
50
+ pytz==2024.2
51
+ PyYAML==6.0.2
52
+ requests==2.32.3
53
+ rich==13.9.4
54
+ ruff==0.7.4
55
+ scikit-image==0.24.0
56
+ scikit-learn==1.5.2
57
+ scipy==1.13.1
58
+ semantic-version==2.10.0
59
+ shellingham==1.5.4
60
+ six==1.16.0
61
+ sniffio==1.3.1
62
+ starlette==0.41.2
63
+ threadpoolctl==3.5.0
64
+ tifffile==2024.8.30
65
+ timm==0.4.5
66
+ tomlkit==0.12.0
67
+ torch==1.13.1
68
+ torchvision==0.14.1
69
+ tqdm==4.67.0
70
+ typer==0.13.0
71
+ typing_extensions==4.12.2
72
+ tzdata==2024.2
73
+ urllib3==2.2.3
74
+ uvicorn==0.32.0
75
+ validators==0.34.0
76
+ websockets==12.0
77
+ zipp==3.21.0
util/crop.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import math
9
+
10
+ import torch
11
+
12
+ from torchvision import transforms
13
+ from torchvision.transforms import functional as F
14
+
15
+
16
+ class RandomResizedCrop(transforms.RandomResizedCrop):
17
+ """
18
+ RandomResizedCrop for matching TF/TPU implementation: no for-loop is used.
19
+ This may lead to results different with torchvision's version.
20
+ Following BYOL's TF code:
21
+ https://github.com/deepmind/deepmind-research/blob/master/byol/utils/dataset.py#L206
22
+ """
23
+ @staticmethod
24
+ def get_params(img, scale, ratio):
25
+ width, height = F._get_image_size(img)
26
+ area = height * width
27
+
28
+ target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item()
29
+ log_ratio = torch.log(torch.tensor(ratio))
30
+ aspect_ratio = torch.exp(
31
+ torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
32
+ ).item()
33
+
34
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
35
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
36
+
37
+ w = min(w, width)
38
+ h = min(h, height)
39
+
40
+ i = torch.randint(0, height - h + 1, size=(1,)).item()
41
+ j = torch.randint(0, width - w + 1, size=(1,)).item()
42
+
43
+ return i, j, h, w
util/datasets.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import os
9
+ import json
10
+ import shutil
11
+
12
+ from torchvision import datasets, transforms
13
+
14
+ from timm.data import create_transform
15
+ from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
16
+
17
+ import numpy as np
18
+ from PIL import Image
19
+ import random
20
+ import torch
21
+ from torch.utils.data import DataLoader, Dataset, ConcatDataset
22
+ from torchvision import transforms
23
+ from torch.nn import functional as F
24
+
25
+
26
+ class collate_fn_crfrp:
27
+ def __init__(self, input_size=224, patch_size=16, mask_ratio=0.75):
28
+ self.img_size = input_size
29
+ self.patch_size = patch_size
30
+ self.num_patches_axis = input_size // patch_size
31
+ self.num_patches = (input_size // patch_size) ** 2
32
+ self.mask_ratio = mask_ratio
33
+
34
+ # --------------------------------------------------------------------------
35
+ # self.facial_region_group = [
36
+ # [2], # right eyebrow
37
+ # [3], # left eyebrow
38
+ # [4], # right eye
39
+ # [5], # left eye
40
+ # [6], # nose
41
+ # [7, 8], # upper mouth
42
+ # [8, 9], # lower mouth
43
+ # [10, 1, 0], # facial boundaries
44
+ # [10], # hair
45
+ # [1], # facial skin
46
+ # [0] # background
47
+ # ]
48
+ self.facial_region_group = [
49
+ [2, 3], # eyebrows
50
+ [4, 5], # eyes
51
+ [6], # nose
52
+ [7, 8, 9], # mouth
53
+ [10, 1, 0], # face boundaries
54
+ [10], # hair
55
+ [1], # facial skin
56
+ [0] # background
57
+ ] # ['background', 'face', 'rb', 'lb', 're', 'le', 'nose', 'ulip', 'imouth', 'llip', 'hair']
58
+
59
+ def __call__(self, samples):
60
+ image, img_mask, facial_region_mask, random_specific_facial_region \
61
+ = self.CRFR_P_masking(samples, specified_facial_region=None)
62
+
63
+ return {'image': image, 'img_mask': img_mask, 'specific_facial_region_mask': facial_region_mask}
64
+
65
+ # # using following code if using different data augmentation for target view
66
+ # image, img_mask, facial_region_mask, random_specific_facial_region \
67
+ # = self.CRFR_P_masking(samples, specified_facial_region=None)
68
+ # image_cl, img_mask_cl, facial_region_mask_cl, random_specific_facial_region_cl \
69
+ # = self.CRFR_P_masking(samples, specified_facial_region=random_specific_facial_region)
70
+ #
71
+ # return {'image': image, 'img_mask': img_mask, 'specific_facial_region_mask': facial_region_mask,
72
+ # 'image_cl': image_cl, 'img_mask_cl': img_mask_cl, 'specific_facial_region_mask_cl': facial_region_mask_cl}
73
+
74
+ def CRFR_P_masking(self, samples, specified_facial_region=None):
75
+ image = torch.stack([sample['image'] for sample in samples]) # torch.Size([bs, 3, 224, 224])
76
+ parsing_map = torch.stack([sample['parsing_map'] for sample in samples]) # torch.Size([bs, 1, 224, 224])
77
+ parsing_map = parsing_map.squeeze(1) # torch.Size([BS, 1, 224, 224]) → torch.Size([BS, 224, 224])
78
+
79
+ # covering a randomly select facial_region_group and get fr_mask(masking all patches include this region)
80
+ facial_region_mask = torch.zeros(parsing_map.size(0), self.num_patches_axis, self.num_patches_axis,
81
+ dtype=torch.float32) # torch.Size([BS, H/P, W/P])
82
+ facial_region_mask, random_specific_facial_region \
83
+ = self.masking_all_patches_in_random_specific_facial_region(parsing_map, facial_region_mask)
84
+ # torch.Size([num_patches,]), list
85
+
86
+ img_mask, facial_region_mask \
87
+ = self.variable_proportional_masking(parsing_map, facial_region_mask, random_specific_facial_region)
88
+ # torch.Size([num_patches,]), torch.Size([num_patches,])
89
+
90
+ del parsing_map
91
+ return image, img_mask, facial_region_mask, random_specific_facial_region
92
+
93
+ def masking_all_patches_in_random_specific_facial_region(self, parsing_map, facial_region_mask,
94
+ # specified_facial_region=None
95
+ ):
96
+ # while True:
97
+ # random_specific_facial_region = random.choice(self.facial_region_group[:-2])
98
+ # if random_specific_facial_region != specified_facial_region:
99
+ # break
100
+ random_specific_facial_region = random.choice(self.facial_region_group[:-2])
101
+ if random_specific_facial_region == [10, 1, 0]: # facial boundaries, 10-hair 1-skin 0-background
102
+ # True for hair(10) or bg(0) patches:
103
+ patch_hair_bg = F.max_pool2d(((parsing_map == 10) + (parsing_map == 0)).float(),
104
+ kernel_size=self.patch_size)
105
+ # True for skin(1) patches:
106
+ patch_skin = F.max_pool2d((parsing_map == 1).float(), kernel_size=self.patch_size)
107
+ # skin&hair or skin&bg is defined as facial boundaries:
108
+ facial_region_mask = (patch_hair_bg.bool() & patch_skin.bool()).float()
109
+ else:
110
+ for facial_region_index in random_specific_facial_region:
111
+ facial_region_mask = torch.maximum(facial_region_mask,
112
+ F.max_pool2d((parsing_map == facial_region_index).float(),
113
+ kernel_size=self.patch_size))
114
+
115
+ return facial_region_mask.view(parsing_map.size(0), -1), random_specific_facial_region
116
+
117
+ def variable_proportional_masking(self, parsing_map, facial_region_mask, random_specific_facial_region):
118
+ img_mask = facial_region_mask.clone()
119
+
120
+ # proportional masking patches in other regions
121
+ other_facial_region_group = [region for region in self.facial_region_group if
122
+ region != random_specific_facial_region]
123
+ # print(other_facial_region_group)
124
+ for i in range(facial_region_mask.size(0)): # iterate each map in BS
125
+ num_mask_to_change = (self.mask_ratio * self.num_patches - facial_region_mask[i].sum(dim=-1)).int()
126
+ # mask_change_to = 1 if num_mask_to_change >= 0 else 0
127
+ mask_change_to = torch.clamp(num_mask_to_change, 0, 1).item()
128
+
129
+ if mask_change_to == 1:
130
+ # proportional masking patches in other facial regions according to the corresponding ratio
131
+ mask_ratio_other_fr = (
132
+ num_mask_to_change / (self.num_patches - facial_region_mask[i].sum(dim=-1)))
133
+
134
+ masked_patches = facial_region_mask[i].clone()
135
+ for other_fr in other_facial_region_group:
136
+ to_mask_patches = torch.zeros(1, self.num_patches_axis, self.num_patches_axis,
137
+ dtype=torch.float32)
138
+ if other_fr == [10, 1, 0]:
139
+ patch_hair_bg = F.max_pool2d(
140
+ ((parsing_map[i].unsqueeze(0) == 10) + (parsing_map[i].unsqueeze(0) == 0)).float(),
141
+ kernel_size=self.patch_size)
142
+ patch_skin = F.max_pool2d((parsing_map[i].unsqueeze(0) == 1).float(),
143
+ kernel_size=self.patch_size)
144
+ # skin&hair or skin&bg defined as facial boundaries:
145
+ to_mask_patches = (patch_hair_bg.bool() & patch_skin.bool()).float()
146
+ else:
147
+ for facial_region_index in other_fr:
148
+ to_mask_patches = torch.maximum(to_mask_patches,
149
+ F.max_pool2d((parsing_map[i].unsqueeze(
150
+ 0) == facial_region_index).float(),
151
+ kernel_size=self.patch_size))
152
+
153
+ # ignore already masked patches:
154
+ to_mask_patches = (to_mask_patches.view(-1) - masked_patches) > 0
155
+ select_indices = to_mask_patches.nonzero(as_tuple=False).view(-1)
156
+ change_indices = torch.randperm(len(select_indices))[
157
+ :torch.round(to_mask_patches.sum() * mask_ratio_other_fr).int()]
158
+ img_mask[i, select_indices[change_indices]] = mask_change_to
159
+ # prevent overlap
160
+ masked_patches = masked_patches + to_mask_patches.float()
161
+
162
+ # mask/unmask patch from other facial regions to get img_mask with fixed size
163
+ num_mask_to_change = (self.mask_ratio * self.num_patches - img_mask[i].sum(dim=-1)).int()
164
+ # mask_change_to = 1 if num_mask_to_change >= 0 else 0
165
+ mask_change_to = torch.clamp(num_mask_to_change, 0, 1).item()
166
+ # prevent unmasking facial_region_mask
167
+ select_indices = ((img_mask[i] + facial_region_mask[i]) == (1 - mask_change_to)).nonzero(
168
+ as_tuple=False).view(-1)
169
+ change_indices = torch.randperm(len(select_indices))[:torch.abs(num_mask_to_change)]
170
+ img_mask[i, select_indices[change_indices]] = mask_change_to
171
+
172
+ else:
173
+ # Extreme situations:
174
+ # if fr_mask is already over(>=) num_patches*mask_ratio, unmask it to get img_mask with fixed ratio
175
+ select_indices = (facial_region_mask[i] == (1 - mask_change_to)).nonzero(as_tuple=False).view(-1)
176
+ change_indices = torch.randperm(len(select_indices))[:torch.abs(num_mask_to_change)]
177
+ img_mask[i, select_indices[change_indices]] = mask_change_to
178
+ facial_region_mask[i] = img_mask[i]
179
+
180
+ return img_mask, facial_region_mask
181
+
182
+
183
+ class FaceParsingDataset(Dataset):
184
+ def __init__(self, root, transform=None):
185
+ self.root_dir = root
186
+ self.transform = transform
187
+ self.image_folder = os.path.join(root, 'images')
188
+ self.parsing_map_folder = os.path.join(root, 'parsing_maps')
189
+ self.image_names = os.listdir(self.image_folder)
190
+
191
+ def __len__(self):
192
+ return len(self.image_names)
193
+
194
+ def __getitem__(self, idx):
195
+ img_name = os.path.join(self.image_folder, self.image_names[idx])
196
+ parsing_map_name = os.path.join(self.parsing_map_folder, self.image_names[idx].replace('.png', '.npy'))
197
+
198
+ image = Image.open(img_name).convert("RGB")
199
+ parsing_map_np = np.load(parsing_map_name)
200
+
201
+ if self.transform:
202
+ image = self.transform(image)
203
+
204
+ # Convert mask to tensor
205
+ parsing_map = torch.from_numpy(parsing_map_np)
206
+ del parsing_map_np # may save mem
207
+
208
+ return {'image': image, 'parsing_map': parsing_map}
209
+
210
+
211
+ class TestImageFolder(datasets.ImageFolder):
212
+ def __init__(self, root, transform=None, target_transform=None):
213
+ super(TestImageFolder, self).__init__(root, transform, target_transform)
214
+
215
+ def __getitem__(self, index):
216
+ # Call the parent class method to load image and label
217
+ original_tuple = super(TestImageFolder, self).__getitem__(index)
218
+
219
+ # Get the video name
220
+ video_name = self.imgs[index][0].split('/')[-1].split('_frame_')[0] # the separator of video name
221
+
222
+ # Extend the tuple to include video name
223
+ extended_tuple = (original_tuple + (video_name,))
224
+
225
+ return extended_tuple
226
+
227
+
228
+ def get_mean_std(args):
229
+ print('dataset_paths:', args.data_path)
230
+ transform = transforms.Compose([transforms.ToTensor(),
231
+ transforms.Resize((args.input_size, args.input_size),
232
+ interpolation=transforms.InterpolationMode.BICUBIC)])
233
+
234
+ if len(args.data_path) > 1:
235
+ pretrain_datasets = [FaceParsingDataset(root=path, transform=transform) for path in args.data_path]
236
+ dataset_pretrain = ConcatDataset(pretrain_datasets)
237
+ else:
238
+ pretrain_datasets = args.data_path[0]
239
+ dataset_pretrain = FaceParsingDataset(root=pretrain_datasets, transform=transform)
240
+
241
+ print('Compute mean and variance for pretraining data.')
242
+ print('len(dataset_train): ', len(dataset_pretrain))
243
+
244
+ loader = DataLoader(
245
+ dataset_pretrain,
246
+ batch_size=args.batch_size,
247
+ num_workers=args.num_workers,
248
+ pin_memory=args.pin_mem,
249
+ drop_last=True,
250
+ )
251
+
252
+ channels_sum, channels_squared_sum, num_batches = 0, 0, 0
253
+ for sample in loader:
254
+ data = sample['image']
255
+ channels_sum += torch.mean(data, dim=[0, 2, 3])
256
+ channels_squared_sum += torch.mean(data ** 2, dim=[0, 2, 3])
257
+ num_batches += 1
258
+
259
+ mean = channels_sum / num_batches
260
+ std = (channels_squared_sum / num_batches - mean ** 2) ** 0.5
261
+
262
+ print(f'train dataset mean%: {mean.numpy()} std: %{std.numpy()} ')
263
+ del pretrain_datasets, dataset_pretrain, loader
264
+ return mean.numpy(), std.numpy()
265
+
266
+
267
+ def build_dataset(is_train, args):
268
+ transform = build_transform(is_train, args)
269
+ dataset = datasets.ImageFolder(args.data_path, transform=transform)
270
+ # if args.eval:
271
+ # # no loading training set
272
+ # root = os.path.join(args.data_path, 'test' if is_train else 'test')
273
+ # dataset = TestImageFolder(root, transform=transform)
274
+ # else:
275
+ # root = os.path.join(args.data_path, 'train' if is_train else 'val')
276
+ # dataset = datasets.ImageFolder(root, transform=transform)
277
+ # print(dataset)
278
+
279
+ return dataset
280
+
281
+
282
+ def build_transform(is_train, args):
283
+ if args.normalize_from_IMN:
284
+ mean = IMAGENET_DEFAULT_MEAN
285
+ std = IMAGENET_DEFAULT_STD
286
+ # print(f'mean:{mean}, std:{std}')
287
+ else:
288
+ if not os.path.exists(os.path.join(args.output_dir, "/pretrain_ds_mean_std.txt")) and not args.eval:
289
+ shutil.copyfile(os.path.dirname(args.finetune) + '/pretrain_ds_mean_std.txt',
290
+ os.path.join(args.output_dir) + '/pretrain_ds_mean_std.txt')
291
+ with open(os.path.join(os.path.dirname(args.resume)) + '/pretrain_ds_mean_std.txt' if args.eval
292
+ else os.path.join(args.output_dir) + '/pretrain_ds_mean_std.txt', 'r') as file:
293
+ ds_stat = json.loads(file.readline())
294
+ mean = ds_stat['mean']
295
+ std = ds_stat['std']
296
+ # print(f'mean:{mean}, std:{std}')
297
+
298
+ if args.apply_simple_augment:
299
+ if is_train:
300
+ # this should always dispatch to transforms_imagenet_train
301
+ transform = create_transform(
302
+ input_size=args.input_size,
303
+ is_training=True,
304
+ color_jitter=args.color_jitter,
305
+ auto_augment=args.aa,
306
+ interpolation=transforms.InterpolationMode.BICUBIC,
307
+ re_prob=args.reprob,
308
+ re_mode=args.remode,
309
+ re_count=args.recount,
310
+ mean=mean,
311
+ std=std,
312
+ )
313
+ return transform
314
+
315
+ # no augment / eval transform
316
+ t = []
317
+ if args.input_size <= 224:
318
+ crop_pct = 224 / 256
319
+ else:
320
+ crop_pct = 1.0
321
+ size = int(args.input_size / crop_pct) # 256
322
+ t.append(
323
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BICUBIC),
324
+ # to maintain same ratio w.r.t. 224 images
325
+ )
326
+ t.append(transforms.CenterCrop(args.input_size)) # 224
327
+
328
+ t.append(transforms.ToTensor())
329
+ t.append(transforms.Normalize(mean, std))
330
+ return transforms.Compose(t)
331
+
332
+ else:
333
+ t = []
334
+ if args.input_size < 224:
335
+ crop_pct = input_size / 224
336
+ else:
337
+ crop_pct = 1.0
338
+ size = int(args.input_size / crop_pct) # size = 224
339
+ t.append(
340
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BICUBIC),
341
+ # to maintain same ratio w.r.t. 224 images
342
+ )
343
+ # t.append(
344
+ # transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC),
345
+ # # to maintain same ratio w.r.t. 224 images
346
+ # )
347
+
348
+ t.append(transforms.ToTensor())
349
+ t.append(transforms.Normalize(mean, std))
350
+ return transforms.Compose(t)
util/lars.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import torch
9
+
10
+
11
+ class LARS(torch.optim.Optimizer):
12
+ """
13
+ LARS optimizer, no rate scaling or weight decay for parameters <= 1D.
14
+ """
15
+ def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001):
16
+ defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_coefficient)
17
+ super().__init__(params, defaults)
18
+
19
+ @torch.no_grad()
20
+ def step(self):
21
+ for g in self.param_groups:
22
+ for p in g['params']:
23
+ dp = p.grad
24
+
25
+ if dp is None:
26
+ continue
27
+
28
+ if p.ndim > 1: # if not normalization gamma/beta or bias
29
+ dp = dp.add(p, alpha=g['weight_decay'])
30
+ param_norm = torch.norm(p)
31
+ update_norm = torch.norm(dp)
32
+ one = torch.ones_like(param_norm)
33
+ q = torch.where(param_norm > 0.,
34
+ torch.where(update_norm > 0,
35
+ (g['trust_coefficient'] * param_norm / update_norm), one),
36
+ one)
37
+ dp = dp.mul(q)
38
+
39
+ param_state = self.state[p]
40
+ if 'mu' not in param_state:
41
+ param_state['mu'] = torch.zeros_like(p)
42
+ mu = param_state['mu']
43
+ mu.mul_(g['momentum']).add_(dp)
44
+ p.add_(mu, alpha=-g['lr'])
util/loss_contrastive.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ from __future__ import print_function
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import math
13
+
14
+
15
+ class SimSiamLoss(nn.Module):
16
+ def __init__(self):
17
+ super(SimSiamLoss, self).__init__()
18
+ self.criterion = nn.CosineSimilarity(dim=1)
19
+
20
+ def forward(self, cl_features):
21
+
22
+ if len(cl_features.shape) < 3:
23
+ raise ValueError('`features` needs to be [bsz, n_views, ...],'
24
+ 'at least 3 dimensions are required')
25
+ if len(cl_features.shape) > 3:
26
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], -1) # [BS, 2, feat_cl_dim]
27
+
28
+ cl_features_1 = cl_features[:, 0] # [BS, feat_cl_dim]
29
+ cl_features_2 = cl_features[:, 1] # [BS, feat_cl_dim]
30
+ loss = -(self.criterion(cl_features_1, cl_features_2).mean()) * 0.5
31
+
32
+ # if not math.isfinite(loss):
33
+ # print(cl_features_1, '\n', cl_features_2)
34
+ # print(self.criterion(cl_features_1, cl_features_2))
35
+
36
+ return loss
37
+
38
+
39
+ class BYOLLoss(nn.Module):
40
+ def __init__(self):
41
+ super(BYOLLoss, self).__init__()
42
+
43
+ @staticmethod
44
+ def forward(cl_features):
45
+
46
+ if len(cl_features.shape) < 3:
47
+ raise ValueError('`features` needs to be [bsz, n_views, ...],'
48
+ 'at least 3 dimensions are required')
49
+ if len(cl_features.shape) > 3:
50
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], -1) # [BS, 2, feat_cl_dim]
51
+
52
+ cl_features_1 = cl_features[:, 0] # [BS, feat_cl_dim]
53
+ cl_features_2 = cl_features[:, 1] # [BS, feat_cl_dim]
54
+ loss = 2 - 2 * (cl_features_1 * cl_features_2).sum(dim=-1)
55
+ # loss = 1 - (cl_features_1 * cl_features_2).sum(dim=-1)
56
+ loss = loss.mean()
57
+
58
+ if not math.isfinite(loss):
59
+ print(cl_features_1, '\n', cl_features_2)
60
+ print(2 - 2 * (cl_features_1 * cl_features_2).sum(dim=-1))
61
+
62
+ return loss
63
+
64
+
65
+ # different implementation of InfoNCELoss, including MOCOV3Loss; SupConLoss
66
+ class InfoNCELoss(nn.Module):
67
+ def __init__(self, temperature=0.1, contrast_sample='all'):
68
+ """
69
+ from CMAE: https://github.com/ZhichengHuang/CMAE/issues/5
70
+ :param temperature: 0.1 0.5 1.0, 1.5 2.0
71
+ """
72
+ super(InfoNCELoss, self).__init__()
73
+ self.temperature = temperature
74
+ self.criterion = nn.CrossEntropyLoss()
75
+ self.contrast_sample = contrast_sample
76
+
77
+ def forward(self, cl_features):
78
+ """
79
+ Args:
80
+ :param cl_features: : hidden vector of shape [bsz, n_views, ...]
81
+ Returns:
82
+ A loss scalar.
83
+ """
84
+ device = (torch.device('cuda')
85
+ if cl_features.is_cuda
86
+ else torch.device('cpu'))
87
+
88
+ if len(cl_features.shape) < 3:
89
+ raise ValueError('`features` needs to be [bsz, n_views, ...],'
90
+ 'at least 3 dimensions are required')
91
+ if len(cl_features.shape) > 3:
92
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], -1) # [BS, 2, feat_cl_dim]
93
+
94
+ cl_features_1 = cl_features[:, 0] # [BS, feat_cl_dim]
95
+ cl_features_2 = cl_features[:, 1] # [BS, feat_cl_dim]
96
+ score_all = torch.matmul(cl_features_1, cl_features_2.transpose(1, 0)) # [BS, BS]
97
+ score_all = score_all / self.temperature
98
+ bs = score_all.size(0)
99
+
100
+ if self.contrast_sample == 'all':
101
+ score = score_all
102
+ elif self.contrast_sample == 'positive':
103
+ mask = torch.eye(bs, dtype=torch.float).to(device) # torch.Size([BS, BS])
104
+ score = score_all * mask
105
+ else:
106
+ raise ValueError('Contrastive sample: all{pos&neg} or positive(positive)')
107
+
108
+ # label = (torch.arange(bs, dtype=torch.long) +
109
+ # bs * torch.distributed.get_rank()).to(device)
110
+ label = torch.arange(bs, dtype=torch.long).to(device)
111
+
112
+ loss = 2 * self.temperature * self.criterion(score, label)
113
+
114
+ if not math.isfinite(loss):
115
+ print(cl_features_1, '\n', cl_features_2)
116
+ print(score_all, '\n', score, '\n', mask)
117
+
118
+ return loss
119
+
120
+
121
+ class MOCOV3Loss(nn.Module):
122
+ def __init__(self, temperature=0.1):
123
+ super(MOCOV3Loss, self).__init__()
124
+ self.temperature = temperature
125
+
126
+ def forward(self, cl_features):
127
+
128
+ if len(cl_features.shape) < 3:
129
+ raise ValueError('`features` needs to be [bsz, n_views, ...],'
130
+ 'at least 3 dimensions are required')
131
+ if len(cl_features.shape) > 3:
132
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], -1) # [BS, 2, feat_cl_dim]
133
+
134
+ cl_features_1 = cl_features[:, 0] # [BS, feat_cl_dim]
135
+ cl_features_2 = cl_features[:, 1] # [BS, feat_cl_dim]
136
+
137
+ # normalize
138
+ cl_features_1 = nn.functional.normalize(cl_features_1, dim=1)
139
+ cl_features_2 = nn.functional.normalize(cl_features_2, dim=1)
140
+ # Einstein sum is more intuitive
141
+ logits = torch.einsum('nc,mc->nm', [cl_features_1, cl_features_2]) / self.temperature
142
+ N = logits.shape[0]
143
+ labels = (torch.arange(N, dtype=torch.long)).cuda()
144
+ return nn.CrossEntropyLoss()(logits, labels) * (2 * self.temperature)
145
+
146
+
147
+ class SupConLoss(nn.Module):
148
+ """
149
+ from: https://github.com/HobbitLong/SupContrast
150
+ Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
151
+ It also supports the unsupervised contrastive loss in SimCLR"""
152
+ def __init__(self, temperature=0.1, contrast_mode='all', contrast_sample='all',
153
+ base_temperature=0.1):
154
+ super(SupConLoss, self).__init__()
155
+ self.temperature = temperature
156
+ self.contrast_mode = contrast_mode
157
+ self.contrast_sample = contrast_sample
158
+ self.base_temperature = base_temperature
159
+
160
+ def forward(self, features, labels=None, mask=None):
161
+ """Compute loss for model. If both `labels` and `mask` are None,
162
+ it degenerates to SimCLR unsupervised loss:
163
+ https://arxiv.org/pdf/2002.05709.pdf
164
+
165
+ Args:
166
+ features: hidden vector of shape [bsz, n_views, ...].
167
+ labels: ground truth of shape [bsz].
168
+ mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
169
+ has the same class as sample i. Can be asymmetric.
170
+ Returns:
171
+ A loss scalar.
172
+ """
173
+ device = (torch.device('cuda')
174
+ if features.is_cuda
175
+ else torch.device('cpu'))
176
+
177
+ if len(features.shape) < 3:
178
+ raise ValueError('`features` needs to be [bsz, n_views, ...],'
179
+ 'at least 3 dimensions are required')
180
+ if len(features.shape) > 3:
181
+ features = features.view(features.shape[0], features.shape[1], -1) # [BS, 2, feat_cl_dim]
182
+
183
+ batch_size = features.shape[0]
184
+ if labels is not None and mask is not None:
185
+ raise ValueError('Cannot define both `labels` and `mask`')
186
+ elif labels is None and mask is None:
187
+ mask = torch.eye(batch_size, dtype=torch.float32).to(device) # torch.Size([BS, BS])
188
+ elif labels is not None:
189
+ labels = labels.contiguous().view(-1, 1)
190
+ if labels.shape[0] != batch_size:
191
+ raise ValueError('Num of labels does not match num of features')
192
+ mask = torch.eq(labels, labels.T).float().to(device)
193
+ else:
194
+ mask = mask.float().to(device)
195
+
196
+ contrast_count = features.shape[1] # contrast_count(2)
197
+ contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0) # [BS*contrast_count, D]
198
+ if self.contrast_mode == 'one':
199
+ anchor_feature = features[:, 0] # [BS, D]
200
+ anchor_count = 1
201
+ elif self.contrast_mode == 'all':
202
+ anchor_feature = contrast_feature # [BS*contrast_count, D]
203
+ anchor_count = contrast_count
204
+ else:
205
+ raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
206
+
207
+ # compute logits
208
+ anchor_dot_contrast = torch.div(
209
+ torch.matmul(anchor_feature, contrast_feature.T),
210
+ self.temperature) # [BS*contrast_count, BS*contrast_count]
211
+ # for numerical stability
212
+ logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True) # [BS*contrast_count, 1]
213
+ logits = anchor_dot_contrast - logits_max.detach() # [BS*contrast_count, BS*contrast_count]
214
+
215
+ # tile mask
216
+ mask = mask.repeat(anchor_count, contrast_count) # [BS*anchor_count, BS*contrast_count]
217
+ # mask-out self-contrast cases
218
+ logits_mask = torch.scatter(
219
+ torch.ones_like(mask),
220
+ 1,
221
+ torch.arange(batch_size * anchor_count).view(-1, 1).to(device),
222
+ 0
223
+ ) # [BS*anchor_count, BS*contrast_count]
224
+ mask = mask * logits_mask # [BS*anchor_count, BS*contrast_count]
225
+
226
+ """
227
+ logits_mask is used to get the denominator(positives and negatives).
228
+ mask is used to get the numerator(positives). mask is applied to log_prob.
229
+ """
230
+
231
+ # compute log_prob,logits_mask is contrast anchor with both positives and negatives
232
+ exp_logits = torch.exp(logits) * logits_mask # [BS*anchor_count, BS*contrast_count]
233
+ # compute log_prob,logits_mask is contrast anchor with negatives, i.e., denominator only negatives contrast:
234
+ # exp_logits = torch.exp(logits) * (logits_mask-mask)
235
+
236
+ if self.contrast_sample == 'all':
237
+ log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True)) # [BS*anchor_count, BS*anchor_count]
238
+ # compute mean of log-likelihood over positive
239
+ mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1) # [BS*anchor_count]
240
+ elif self.contrast_sample == 'positive':
241
+ mean_log_prob_pos = (mask * logits).sum(1) / mask.sum(1)
242
+ else:
243
+ raise ValueError('Contrastive sample: all{pos&neg} or positive(positive)')
244
+
245
+ # loss
246
+ loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
247
+ loss = loss.view(anchor_count, batch_size).mean()
248
+
249
+ return loss
250
+
251
+
252
+ class InfoNCELossPatchLevel(nn.Module):
253
+ """
254
+ test: ref ConMIM: https://github.com/TencentARC/ConMIM.
255
+ """
256
+ def __init__(self, temperature=0.1, contrast_sample='all'):
257
+ """
258
+ :param temperature: 0.1 0.5 1.0, 1.5 2.0
259
+ """
260
+ super(InfoNCELossPatchLevel, self).__init__()
261
+ self.temperature = temperature
262
+ self.criterion = nn.CrossEntropyLoss()
263
+ self.contrast_sample = contrast_sample
264
+
265
+ self.facial_region_group = [
266
+ [2, 3], # eyebrows
267
+ [4, 5], # eyes
268
+ [6], # nose
269
+ [7, 8, 9], # mouth
270
+ [10, 1, 0], # face boundaries
271
+ [10], # hair
272
+ [1], # facial skin
273
+ [0] # background
274
+ ]
275
+
276
+ def forward(self, cl_features, parsing_map=None):
277
+ """
278
+ Args:
279
+ :param parsing_map:
280
+ :param cl_features: : hidden vector of shape [bsz, n_views, ...]
281
+ Returns:
282
+ A loss scalar.
283
+ """
284
+ device = (torch.device('cuda')
285
+ if cl_features.is_cuda
286
+ else torch.device('cpu'))
287
+
288
+ if len(cl_features.shape) < 4:
289
+ raise ValueError('`features` needs to be [bsz, n_views, n_cl_patches, ...],'
290
+ 'at least 4 dimensions are required')
291
+ if len(cl_features.shape) > 4:
292
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], cl_features.shape[2], -1)
293
+ # [BS, 2, num_cl_patches, feat_cl_dim]
294
+
295
+ cl_features_1 = cl_features[:, 0]
296
+ cl_features_2 = cl_features[:, 1]
297
+ score = torch.matmul(cl_features_1, cl_features_2.permute(0, 2, 1)) # [BS, num_cl_patches, num_cl_patches]
298
+ score = score / self.temperature
299
+ bs = score.size(0)
300
+ num_cl_patches = score.size(1)
301
+
302
+ if self.contrast_sample == 'all':
303
+ score = score
304
+ elif self.contrast_sample == 'positive':
305
+ mask = torch.eye(num_cl_patches, dtype=torch.float32) # torch.Size([num_cl_patches, num_cl_patches])
306
+ mask_batch = mask.unsqueeze(0).expand(bs, -1).to(device) # [bs, num_cl_patches, num_cl_patches]
307
+ score = score*mask_batch
308
+ elif self.contrast_sample == 'region':
309
+ cl_features_1_fr = []
310
+ cl_features_2_fr = []
311
+ for facial_region_index in self.facial_region_group:
312
+ fr_mask = (parsing_map == facial_region_index).unsqueeze(2).expand(-1, -1, cl_features_1.size(-1))
313
+ cl_features_1_fr.append((cl_features_1 * fr_mask).mean(dim=1, keepdim=False))
314
+ cl_features_2_fr.append((cl_features_1 * fr_mask).mean(dim=1, keepdim=False))
315
+ cl_features_1_fr = torch.stack(cl_features_1_fr, dim=1)
316
+ cl_features_2_fr = torch.stack(cl_features_2_fr, dim=1)
317
+ score = torch.matmul(cl_features_1_fr, cl_features_2_fr.permute(0, 2, 1)) # [BS, 8, 8]
318
+ score = score / self.temperature
319
+ # mask = torch.eye(cl_features_1_fr.size(1), dtype=torch.bool)
320
+ # torch.Size([cl_features_1_fr.size(1), cl_features_1_fr.size(1)])
321
+ # mask_batch = mask.unsqueeze(0).expand(bs, -1).to(device)
322
+ # [bs, cl_features_1_fr.size(1), cl_features_1_fr.size(1)]
323
+ # score = score*mask_batch
324
+ label = torch.arange(cl_features_1_fr.size(1), dtype=torch.long).to(device)
325
+ labels_batch = label.unsqueeze(0).expand(bs, -1)
326
+ loss = 2 * self.temperature * self.criterion(score, labels_batch)
327
+ return loss
328
+ else:
329
+ raise ValueError('Contrastive sample: all{pos&neg} or positive(positive)')
330
+
331
+ # label = (torch.arange(bs, dtype=torch.long) +
332
+ # bs * torch.distributed.get_rank()).to(device)
333
+ label = torch.arange(num_cl_patches, dtype=torch.long).to(device)
334
+ labels_batch = label.unsqueeze(0).expand(bs, -1)
335
+
336
+ loss = 2 * self.temperature * self.criterion(score, labels_batch)
337
+
338
+ return loss
339
+
340
+
341
+ class MSELoss(nn.Module):
342
+ """
343
+ test: unused
344
+ """
345
+ def __init__(self):
346
+ super(MSELoss, self).__init__()
347
+
348
+ @staticmethod
349
+ def forward(cl_features):
350
+
351
+ if len(cl_features.shape) < 3:
352
+ raise ValueError('`features` needs to be [bsz, n_views, n_patches, ...],'
353
+ 'at least 3 dimensions are required')
354
+ if len(cl_features.shape) > 3:
355
+ cl_features = cl_features.view(cl_features.shape[0], cl_features.shape[1], -1) # [BS, 2, feat_cl_dim]
356
+
357
+ cl_features_1 = cl_features[:, 0].float() # [BS, feat_cl_dim]
358
+ cl_features_2 = cl_features[:, 1].float() # [BS, feat_cl_dim]
359
+
360
+ return torch.nn.functional.mse_loss(cl_features_1, cl_features_2, reduction='mean')
util/lr_decay.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import json
9
+
10
+
11
+ def param_groups_lrd(model, weight_decay=0.05, no_weight_decay_list=[], layer_decay=.75):
12
+ """
13
+ Parameter groups for layer-wise lr decay
14
+ Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L58
15
+ """
16
+ param_group_names = {}
17
+ param_groups = {}
18
+
19
+ num_layers = len(model.blocks) + 1
20
+
21
+ layer_scales = list(layer_decay ** (num_layers - i) for i in range(num_layers + 1))
22
+
23
+ for n, p in model.named_parameters():
24
+ if not p.requires_grad:
25
+ continue
26
+
27
+ # no decay: all 1D parameters and model specific ones
28
+ if p.ndim == 1 or n in no_weight_decay_list:
29
+ g_decay = "no_decay"
30
+ this_decay = 0.
31
+ else:
32
+ g_decay = "decay"
33
+ this_decay = weight_decay
34
+
35
+ layer_id = get_layer_id_for_vit(n, num_layers)
36
+ group_name = "layer_%d_%s" % (layer_id, g_decay)
37
+
38
+ if group_name not in param_group_names:
39
+ this_scale = layer_scales[layer_id]
40
+
41
+ param_group_names[group_name] = {
42
+ "lr_scale": this_scale,
43
+ "weight_decay": this_decay,
44
+ "params": [],
45
+ }
46
+ param_groups[group_name] = {
47
+ "lr_scale": this_scale,
48
+ "weight_decay": this_decay,
49
+ "params": [],
50
+ }
51
+
52
+ param_group_names[group_name]["params"].append(n)
53
+ param_groups[group_name]["params"].append(p)
54
+
55
+ # print("parameter groups: \n%s" % json.dumps(param_group_names, indent=2))
56
+
57
+ return list(param_groups.values())
58
+
59
+
60
+ def get_layer_id_for_vit(name, num_layers):
61
+ """
62
+ Assign a parameter with its layer id
63
+ Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
64
+ """
65
+ if name in ['cls_token', 'pos_embed']:
66
+ return 0
67
+ elif name.startswith('patch_embed'):
68
+ return 0
69
+ elif name.startswith('blocks'):
70
+ return int(name.split('.')[1]) + 1
71
+ else:
72
+ return num_layers
util/lr_sched.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import math
9
+ import numpy as np
10
+
11
+
12
+ def adjust_learning_rate(optimizer, epoch, args):
13
+ """Decay the learning rate with half-cycle cosine after warmup"""
14
+ if epoch < args.warmup_epochs:
15
+ lr = args.lr * epoch / args.warmup_epochs
16
+ else:
17
+ lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \
18
+ (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))
19
+ for param_group in optimizer.param_groups:
20
+ if "lr_scale" in param_group:
21
+ param_group["lr"] = lr * param_group["lr_scale"]
22
+ else:
23
+ param_group["lr"] = lr
24
+ return lr
25
+
26
+
27
+ def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0,
28
+ start_warmup_value=0, warmup_steps=-1):
29
+ warmup_schedule = np.array([])
30
+ warmup_iters = warmup_epochs * niter_per_ep
31
+ if warmup_steps > 0:
32
+ warmup_iters = warmup_steps
33
+ print("Set warmup steps = %d" % warmup_iters)
34
+ if warmup_epochs > 0:
35
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
36
+
37
+ iters = np.arange(epochs * niter_per_ep - warmup_iters)
38
+ schedule = np.array(
39
+ [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters])
40
+
41
+ schedule = np.concatenate((warmup_schedule, schedule))
42
+
43
+ assert len(schedule) == epochs * niter_per_ep
44
+ return schedule
util/metrics.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ from sklearn.metrics import roc_auc_score
9
+ from sklearn.metrics import roc_curve
10
+ from sklearn.metrics import auc, accuracy_score, balanced_accuracy_score
11
+ from scipy.optimize import brentq
12
+ from scipy.interpolate import interp1d
13
+
14
+
15
+ def frame_level_acc(labels, y_preds):
16
+ return accuracy_score(labels, y_preds) * 100.
17
+
18
+
19
+ def frame_level_balanced_acc(labels, y_preds):
20
+ return balanced_accuracy_score(labels, y_preds) * 100.
21
+
22
+
23
+ def frame_level_auc(labels, preds):
24
+ return roc_auc_score(labels, preds) * 100.
25
+
26
+
27
+ def frame_level_eer(labels, preds):
28
+ # 推荐;更正确的,MaskRelation(TIFS23也是)
29
+ fpr, tpr, thresholds = roc_curve(labels, preds, pos_label=1) # 如果标签不是二进制的,则应显式地给出pos_标签
30
+ eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)
31
+ # eer_thresh = interp1d(fpr, thresholds)(eer)
32
+ return eer
33
+
34
+
35
+ # def frame_level_eer(labels, preds):
36
+ # fpr, tpr, thresholds = roc_curve(labels, preds, pos_label=1)
37
+ # eer_threshold = thresholds[(fpr + (1 - tpr)).argmin()]
38
+ # fpr_eer = fpr[thresholds == eer_threshold][0]
39
+ # fnr_eer = 1 - tpr[thresholds == eer_threshold][0]
40
+ # eer = (fpr_eer + fnr_eer) / 2
41
+ # metric_logger.meters['eer'].update(eer)
42
+ # return eer, eer_thresh
43
+
44
+
45
+ def get_video_level_label_pred(f_label_list, v_name_list, f_pred_list):
46
+ """
47
+ References:
48
+ CADDM: https://github.com/megvii-research/CADDM
49
+ """
50
+ video_res_dict = dict()
51
+ video_pred_list = list()
52
+ video_y_pred_list = list()
53
+ video_label_list = list()
54
+ # summarize all the results for each video
55
+ for label, video, score in zip(f_label_list, v_name_list, f_pred_list):
56
+ if video not in video_res_dict.keys():
57
+ video_res_dict[video] = {"scores": [score], "label": label}
58
+ else:
59
+ video_res_dict[video]["scores"].append(score)
60
+ # get the score and label for each video
61
+ for video, res in video_res_dict.items():
62
+ score = sum(res['scores']) / len(res['scores'])
63
+ label = res['label']
64
+ video_pred_list.append(score)
65
+ video_label_list.append(label)
66
+ video_y_pred_list.append(score >= 0.5)
67
+
68
+ return video_label_list, video_pred_list, video_y_pred_list
69
+
70
+
71
+ def video_level_acc(video_label_list, video_y_pred_list):
72
+ return accuracy_score(video_label_list, video_y_pred_list) * 100.
73
+
74
+
75
+ def video_level_balanced_acc(video_label_list, video_y_pred_list):
76
+ return balanced_accuracy_score(video_label_list, video_y_pred_list) * 100.
77
+
78
+
79
+ def video_level_auc(video_label_list, video_pred_list):
80
+ return roc_auc_score(video_label_list, video_pred_list) * 100.
81
+
82
+
83
+ def video_level_eer(video_label_list, video_pred_list):
84
+ # 推荐;更正确的,MaskRelation(TIFS23也是)
85
+ fpr, tpr, thresholds = roc_curve(video_label_list, video_pred_list, pos_label=1) # 如果标签不是二进制的,则应显式地给出pos_标签
86
+ v_eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)
87
+ # eer_thresh = interp1d(fpr, thresholds)(eer)
88
+ return v_eer
util/misc.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import builtins
9
+ import datetime
10
+ import os
11
+ import time
12
+ from collections import defaultdict, deque
13
+ from pathlib import Path
14
+
15
+ import torch
16
+ import torch.distributed as dist
17
+ from torch import inf
18
+
19
+
20
+ class SmoothedValue(object):
21
+ """Track a series of values and provide access to smoothed values over a
22
+ window or the global series average.
23
+ """
24
+
25
+ def __init__(self, window_size=20, fmt=None):
26
+ if fmt is None:
27
+ fmt = "{median:.4f} ({global_avg:.4f})"
28
+ self.deque = deque(maxlen=window_size)
29
+ self.total = 0.0
30
+ self.count = 0
31
+ self.fmt = fmt
32
+
33
+ def update(self, value, n=1):
34
+ self.deque.append(value)
35
+ self.count += n
36
+ self.total += value * n
37
+
38
+ def synchronize_between_processes(self):
39
+ """
40
+ Warning: does not synchronize the deque!
41
+ """
42
+ if not is_dist_avail_and_initialized():
43
+ return
44
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
45
+ dist.barrier()
46
+ dist.all_reduce(t)
47
+ t = t.tolist()
48
+ self.count = int(t[0])
49
+ self.total = t[1]
50
+
51
+ @property
52
+ def median(self):
53
+ d = torch.tensor(list(self.deque))
54
+ return d.median().item()
55
+
56
+ @property
57
+ def avg(self):
58
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
59
+ return d.mean().item()
60
+
61
+ @property
62
+ def global_avg(self):
63
+ return self.total / self.count
64
+
65
+ @property
66
+ def max(self):
67
+ return max(self.deque)
68
+
69
+ @property
70
+ def value(self):
71
+ return self.deque[-1]
72
+
73
+ def __str__(self):
74
+ return self.fmt.format(
75
+ median=self.median,
76
+ avg=self.avg,
77
+ global_avg=self.global_avg,
78
+ max=self.max,
79
+ value=self.value)
80
+
81
+
82
+ class MetricLogger(object):
83
+ def __init__(self, delimiter="\t"):
84
+ self.meters = defaultdict(SmoothedValue)
85
+ self.delimiter = delimiter
86
+
87
+ def update(self, **kwargs):
88
+ for k, v in kwargs.items():
89
+ if v is None:
90
+ continue
91
+ if isinstance(v, torch.Tensor):
92
+ v = v.item()
93
+ assert isinstance(v, (float, int))
94
+ self.meters[k].update(v)
95
+
96
+ def __getattr__(self, attr):
97
+ if attr in self.meters:
98
+ return self.meters[attr]
99
+ if attr in self.__dict__:
100
+ return self.__dict__[attr]
101
+ raise AttributeError("'{}' object has no attribute '{}'".format(
102
+ type(self).__name__, attr))
103
+
104
+ def __str__(self):
105
+ loss_str = []
106
+ for name, meter in self.meters.items():
107
+ loss_str.append(
108
+ "{}: {}".format(name, str(meter))
109
+ )
110
+ return self.delimiter.join(loss_str)
111
+
112
+ def synchronize_between_processes(self):
113
+ for meter in self.meters.values():
114
+ meter.synchronize_between_processes()
115
+
116
+ def add_meter(self, name, meter):
117
+ self.meters[name] = meter
118
+
119
+ def log_every(self, iterable, print_freq, header=None):
120
+ i = 0
121
+ if not header:
122
+ header = ''
123
+ start_time = time.time()
124
+ end = time.time()
125
+ iter_time = SmoothedValue(fmt='{avg:.4f}')
126
+ data_time = SmoothedValue(fmt='{avg:.4f}')
127
+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
128
+ log_msg = [
129
+ header,
130
+ '[{0' + space_fmt + '}/{1}]',
131
+ 'eta: {eta}',
132
+ '{meters}',
133
+ 'time: {time}',
134
+ 'data: {data}'
135
+ ]
136
+ if torch.cuda.is_available():
137
+ log_msg.append('max mem: {memory:.0f}')
138
+ log_msg = self.delimiter.join(log_msg)
139
+ MB = 1024.0 * 1024.0
140
+ for obj in iterable:
141
+ data_time.update(time.time() - end)
142
+ yield obj
143
+ iter_time.update(time.time() - end)
144
+ if i % print_freq == 0 or i == len(iterable) - 1:
145
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
146
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
147
+ if torch.cuda.is_available():
148
+ print(log_msg.format(
149
+ i, len(iterable), eta=eta_string,
150
+ meters=str(self),
151
+ time=str(iter_time), data=str(data_time),
152
+ memory=torch.cuda.max_memory_allocated() / MB))
153
+ else:
154
+ print(log_msg.format(
155
+ i, len(iterable), eta=eta_string,
156
+ meters=str(self),
157
+ time=str(iter_time), data=str(data_time)))
158
+ i += 1
159
+ end = time.time()
160
+ total_time = time.time() - start_time
161
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
162
+ print('{} Total time: {} ({:.4f} s / it)'.format(
163
+ header, total_time_str, total_time / len(iterable)))
164
+
165
+
166
+ def setup_for_distributed(is_master):
167
+ """
168
+ This function disables printing when not in master process
169
+ """
170
+ builtin_print = builtins.print
171
+
172
+ def print(*args, **kwargs):
173
+ force = kwargs.pop('force', False)
174
+ force = force or (get_world_size() > 8)
175
+ if is_master or force:
176
+ now = datetime.datetime.now().time()
177
+ builtin_print('[{}] '.format(now), end='') # print with time stamp
178
+ builtin_print(*args, **kwargs)
179
+
180
+ builtins.print = print
181
+
182
+
183
+ def is_dist_avail_and_initialized():
184
+ if not dist.is_available():
185
+ return False
186
+ if not dist.is_initialized():
187
+ return False
188
+ return True
189
+
190
+
191
+ def get_world_size():
192
+ if not is_dist_avail_and_initialized():
193
+ return 1
194
+ return dist.get_world_size()
195
+
196
+
197
+ def get_rank():
198
+ if not is_dist_avail_and_initialized():
199
+ return 0
200
+ return dist.get_rank()
201
+
202
+
203
+ def is_main_process():
204
+ return get_rank() == 0
205
+
206
+
207
+ def save_on_master(*args, **kwargs):
208
+ if is_main_process():
209
+ torch.save(*args, **kwargs)
210
+
211
+
212
+ def init_distributed_mode(args):
213
+ if args.dist_on_itp:
214
+ args.rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
215
+ args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
216
+ args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
217
+ args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT'])
218
+ os.environ['LOCAL_RANK'] = str(args.gpu)
219
+ os.environ['RANK'] = str(args.rank)
220
+ os.environ['WORLD_SIZE'] = str(args.world_size)
221
+ # ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"]
222
+ elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
223
+ args.rank = int(os.environ["RANK"])
224
+ args.world_size = int(os.environ['WORLD_SIZE'])
225
+ args.gpu = int(os.environ['LOCAL_RANK'])
226
+ elif 'SLURM_PROCID' in os.environ:
227
+ args.rank = int(os.environ['SLURM_PROCID'])
228
+ args.gpu = args.rank % torch.cuda.device_count()
229
+ else:
230
+ print('Not using distributed mode')
231
+ setup_for_distributed(is_master=True) # hack
232
+ args.distributed = False
233
+ return
234
+
235
+ args.distributed = True
236
+
237
+ torch.cuda.set_device(args.gpu)
238
+ args.dist_backend = 'nccl'
239
+ print('| distributed init (rank {}): {}, gpu {}'.format(
240
+ args.rank, args.dist_url, args.gpu), flush=True)
241
+ torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
242
+ world_size=args.world_size, rank=args.rank)
243
+ torch.distributed.barrier()
244
+ setup_for_distributed(args.rank == 0)
245
+
246
+
247
+ class NativeScalerWithGradNormCount:
248
+ state_dict_key = "amp_scaler"
249
+
250
+ def __init__(self):
251
+ self._scaler = torch.cuda.amp.GradScaler()
252
+
253
+ def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
254
+ self._scaler.scale(loss).backward(create_graph=create_graph)
255
+ if update_grad:
256
+ if clip_grad is not None:
257
+ assert parameters is not None
258
+ self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
259
+ norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
260
+ else:
261
+ self._scaler.unscale_(optimizer)
262
+ norm = get_grad_norm_(parameters)
263
+ self._scaler.step(optimizer)
264
+ self._scaler.update()
265
+ else:
266
+ norm = None
267
+ return norm
268
+
269
+ def state_dict(self):
270
+ return self._scaler.state_dict()
271
+
272
+ def load_state_dict(self, state_dict):
273
+ self._scaler.load_state_dict(state_dict)
274
+
275
+
276
+ def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor:
277
+ if isinstance(parameters, torch.Tensor):
278
+ parameters = [parameters]
279
+ parameters = [p for p in parameters if p.grad is not None]
280
+ norm_type = float(norm_type)
281
+ if len(parameters) == 0:
282
+ return torch.tensor(0.)
283
+ device = parameters[0].grad.device
284
+ if norm_type == inf:
285
+ total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters)
286
+ else:
287
+ total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]),
288
+ norm_type)
289
+ return total_norm
290
+
291
+
292
+ def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, tag=None):
293
+ output_dir = Path(args.output_dir)
294
+ epoch_name = str(epoch)
295
+ if loss_scaler is not None:
296
+ if tag is None:
297
+ checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch_name)]
298
+ else:
299
+ checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % tag)]
300
+ for checkpoint_path in checkpoint_paths:
301
+ to_save = {
302
+ 'model': model_without_ddp.state_dict(),
303
+ 'optimizer': optimizer.state_dict(),
304
+ 'epoch': epoch,
305
+ 'scaler': loss_scaler.state_dict(),
306
+ 'args': args,
307
+ }
308
+
309
+ save_on_master(to_save, checkpoint_path)
310
+ else:
311
+ client_state = {'epoch': epoch}
312
+ if tag is None:
313
+ model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % epoch_name,
314
+ client_state=client_state)
315
+ else:
316
+ model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % tag,
317
+ client_state=client_state)
318
+
319
+
320
+ def save_model_target_encoder(args, epoch, model, model_target_encoder_without_ddp, optimizer, loss_scaler, tag=None):
321
+ output_dir = Path(args.output_dir)
322
+ epoch_name = str(epoch)
323
+ if loss_scaler is not None:
324
+ if tag is None:
325
+ checkpoint_paths = [output_dir / ('checkpoint-te-%s.pth' % epoch_name)]
326
+ else:
327
+ checkpoint_paths = [output_dir / ('checkpoint-te-%s.pth' % tag)]
328
+ for checkpoint_path in checkpoint_paths:
329
+ to_save = {
330
+ 'model': model_target_encoder_without_ddp.state_dict(),
331
+ 'optimizer': optimizer.state_dict(),
332
+ 'epoch': epoch,
333
+ 'scaler': loss_scaler.state_dict(),
334
+ 'args': args,
335
+ }
336
+
337
+ save_on_master(to_save, checkpoint_path)
338
+ else:
339
+ client_state = {'epoch': epoch}
340
+ if tag is None:
341
+ model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-te-%s" % epoch_name,
342
+ client_state=client_state)
343
+ else:
344
+ model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-te-%s" % tag,
345
+ client_state=client_state)
346
+
347
+
348
+ def load_model(args, model_without_ddp, optimizer, loss_scaler):
349
+ if args.resume:
350
+ if args.resume.startswith('https'):
351
+ checkpoint = torch.hub.load_state_dict_from_url(
352
+ args.resume, map_location='cpu', check_hash=True)
353
+ else:
354
+ checkpoint = torch.load(args.resume, map_location='cpu')
355
+ model_without_ddp.load_state_dict(checkpoint['model'])
356
+ print("Resume checkpoint %s" % args.resume)
357
+ if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
358
+ optimizer.load_state_dict(checkpoint['optimizer'])
359
+ args.start_epoch = checkpoint['epoch'] + 1
360
+ if 'scaler' in checkpoint:
361
+ loss_scaler.load_state_dict(checkpoint['scaler'])
362
+ print("With optim & sched!")
363
+
364
+
365
+ def load_model_target_encoder(args, model_target_encoder_without_ddp, optimizer, loss_scaler):
366
+ if args.resume:
367
+ if args.resume.startswith('https'):
368
+ checkpoint = torch.hub.load_state_dict_from_url(
369
+ args.resume, map_location='cpu', check_hash=True)
370
+ else:
371
+ checkpoint = torch.load(args.resume_target_encoder, map_location='cpu')
372
+ model_target_encoder_without_ddp.load_state_dict(checkpoint['model'])
373
+ print("Resume checkpoint %s" % args.resume_target_encoder)
374
+ if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval):
375
+ optimizer.load_state_dict(checkpoint['optimizer'])
376
+ args.start_epoch = checkpoint['epoch'] + 1
377
+ if 'scaler' in checkpoint:
378
+ loss_scaler.load_state_dict(checkpoint['scaler'])
379
+ print("With optim & sched!")
380
+
381
+
382
+ def all_reduce_mean(x):
383
+ world_size = get_world_size()
384
+ if world_size > 1:
385
+ x_reduce = torch.tensor(x).cuda()
386
+ dist.all_reduce(x_reduce)
387
+ x_reduce /= world_size
388
+ return x_reduce.item()
389
+ else:
390
+ return x
util/pos_embed.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Author: Gaojian Wang@ZJUICSR
3
+ # --------------------------------------------------------
4
+ # This source code is licensed under the Attribution-NonCommercial 4.0 International License.
5
+ # You can find the license in the LICENSE file in the root directory of this source tree.
6
+ # --------------------------------------------------------
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+
12
+ # --------------------------------------------------------
13
+ # 2D sine-cosine position embedding
14
+ # References:
15
+ # Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
16
+ # MoCo v3: https://github.com/facebookresearch/moco-v3
17
+ # --------------------------------------------------------
18
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
19
+ """
20
+ grid_size: int of the grid height and width
21
+ return:
22
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
23
+ """
24
+ grid_h = np.arange(grid_size, dtype=np.float32)
25
+ grid_w = np.arange(grid_size, dtype=np.float32)
26
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
27
+ grid = np.stack(grid, axis=0)
28
+
29
+ grid = grid.reshape([2, 1, grid_size, grid_size])
30
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
31
+ if cls_token:
32
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
33
+ return pos_embed
34
+
35
+
36
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
37
+ assert embed_dim % 2 == 0
38
+
39
+ # use half of dimensions to encode grid_h
40
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
41
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
42
+
43
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
44
+ return emb
45
+
46
+
47
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
48
+ """
49
+ embed_dim: output dimension for each position
50
+ pos: a list of positions to be encoded: size (M,)
51
+ out: (M, D)
52
+ """
53
+ assert embed_dim % 2 == 0
54
+ omega = np.arange(embed_dim // 2, dtype=np.float)
55
+ omega /= embed_dim / 2.
56
+ omega = 1. / 10000**omega # (D/2,)
57
+
58
+ pos = pos.reshape(-1) # (M,)
59
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
60
+
61
+ emb_sin = np.sin(out) # (M, D/2)
62
+ emb_cos = np.cos(out) # (M, D/2)
63
+
64
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
65
+ return emb
66
+
67
+
68
+ # --------------------------------------------------------
69
+ # Interpolate position embeddings for high-resolution
70
+ # References:
71
+ # DeiT: https://github.com/facebookresearch/deit
72
+ # --------------------------------------------------------
73
+ def interpolate_pos_embed(model, checkpoint_model):
74
+ if 'pos_embed' in checkpoint_model:
75
+ pos_embed_checkpoint = checkpoint_model['pos_embed']
76
+ embedding_size = pos_embed_checkpoint.shape[-1]
77
+ num_patches = model.patch_embed.num_patches
78
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches
79
+ # height (== width) for the checkpoint position embedding
80
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
81
+ # height (== width) for the new position embedding
82
+ new_size = int(num_patches ** 0.5)
83
+ # class_token and dist_token are kept unchanged
84
+ if orig_size != new_size:
85
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
86
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
87
+ # only the position tokens are interpolated
88
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
89
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
90
+ pos_tokens = torch.nn.functional.interpolate(
91
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
92
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
93
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
94
+ checkpoint_model['pos_embed'] = new_pos_embed
95
+
96
+
97
+ def interpolate_pos_embed_ema(model, checkpoint_model):
98
+ if checkpoint_model.pos_embed is not None:
99
+ pos_embed_checkpoint = checkpoint_model.pos_embed
100
+ embedding_size = pos_embed_checkpoint.shape[-1]
101
+ num_patches = model.patch_embed.num_patches
102
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches
103
+ # height (== width) for the checkpoint position embedding
104
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
105
+ # height (== width) for the new position embedding
106
+ new_size = int(num_patches ** 0.5)
107
+ # class_token and dist_token are kept unchanged
108
+ if orig_size != new_size:
109
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
110
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
111
+ # only the position tokens are interpolated
112
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
113
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
114
+ pos_tokens = torch.nn.functional.interpolate(
115
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
116
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
117
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
118
+ checkpoint_model.pos_embed = new_pos_embed