NinadJoshi382 commited on
Commit
c8b2644
·
verified ·
1 Parent(s): 65f59d1

Upload 3 files

Browse files
Files changed (3) hide show
  1. __init__.py +0 -0
  2. model.py +110 -0
  3. utils.py +853 -0
__init__.py ADDED
File without changes
model.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import clip
4
+ import copy
5
+ from torch.autograd import Function
6
+
7
+ from huggingface_hub import PyTorchModelHubMixin
8
+
9
+
10
+ from .utils import convert_weights_float
11
+
12
+
13
+ class ReverseLayerF(Function):
14
+
15
+ @staticmethod
16
+ def forward(ctx, x, alpha):
17
+ ctx.alpha = alpha
18
+
19
+ return x.view_as(x)
20
+
21
+ @staticmethod
22
+ def backward(ctx, grad_output):
23
+ output = grad_output.neg() * ctx.alpha
24
+
25
+ return output, None
26
+
27
+
28
+ ## taken from https://github.com/moein-shariatnia/OpenAI-CLIP/blob/master/modules.py
29
+ class ProjectionHead(nn.Module):
30
+ def __init__(
31
+ self,
32
+ embedding_dim,
33
+ projection_dim,
34
+ dropout=0
35
+ ):
36
+ super().__init__()
37
+ self.projection = nn.Linear(embedding_dim, projection_dim)
38
+ self.gelu = nn.GELU()
39
+ self.fc = nn.Linear(projection_dim, projection_dim)
40
+ self.dropout = nn.Dropout(dropout)
41
+ self.layer_norm = nn.LayerNorm(projection_dim)
42
+
43
+ def forward(self, x):
44
+ projected = self.projection(x)
45
+ x = self.gelu(projected)
46
+ x = self.fc(x)
47
+ x = self.dropout(x)
48
+ x = x + projected
49
+ x = self.layer_norm(x)
50
+ return x
51
+
52
+
53
+ def init_weights(m): # TODO: do we need init for layernorm?
54
+ if isinstance(m, nn.Linear):
55
+ torch.nn.init.xavier_uniform_(m.weight)
56
+ if m.bias is not None:
57
+ nn.init.normal_(m.bias, std=1e-6)
58
+
59
+
60
+ class CSD_CLIP(nn.Module, PyTorchModelHubMixin, repo_url="https://github.com/learn2phoenix/CSD", pipeline_tag="image-feature-extraction", license="mit"):
61
+ """backbone + projection head"""
62
+ def __init__(self, name='vit_large',content_proj_head='default'):
63
+ super(CSD_CLIP, self).__init__()
64
+ self.content_proj_head = content_proj_head
65
+ if name == 'vit_large':
66
+ clipmodel, _ = clip.load("ViT-L/14")
67
+ self.backbone = clipmodel.visual
68
+ self.embedding_dim = 1024
69
+ elif name == 'vit_base':
70
+ clipmodel, _ = clip.load("ViT-B/16")
71
+ self.backbone = clipmodel.visual
72
+ self.embedding_dim = 768
73
+ self.feat_dim = 512
74
+ else:
75
+ raise Exception('This model is not implemented')
76
+
77
+ convert_weights_float(self.backbone)
78
+ self.last_layer_style = copy.deepcopy(self.backbone.proj)
79
+ if content_proj_head == 'custom':
80
+ self.last_layer_content = ProjectionHead(self.embedding_dim,self.feat_dim)
81
+ self.last_layer_content.apply(init_weights)
82
+
83
+ else:
84
+ self.last_layer_content = copy.deepcopy(self.backbone.proj)
85
+
86
+ self.backbone.proj = None
87
+
88
+ @property
89
+ def dtype(self):
90
+ return self.backbone.conv1.weight.dtype
91
+
92
+ def forward(self, input_data, alpha=None):
93
+
94
+ feature = self.backbone(input_data)
95
+
96
+ if alpha is not None:
97
+ reverse_feature = ReverseLayerF.apply(feature, alpha)
98
+ else:
99
+ reverse_feature = feature
100
+
101
+ style_output = feature @ self.last_layer_style
102
+ style_output = nn.functional.normalize(style_output, dim=1, p=2)
103
+
104
+ # if alpha is not None:
105
+ if self.content_proj_head == 'custom':
106
+ content_output = self.last_layer_content(reverse_feature)
107
+ else:
108
+ content_output = reverse_feature @ self.last_layer_content
109
+ content_output = nn.functional.normalize(content_output, dim=1, p=2)
110
+ return feature, content_output, style_output
utils.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Misc functions.
16
+
17
+ Mostly copy-paste from torchvision references or other public repos like DETR:
18
+ https://github.com/facebookresearch/detr/blob/master/util/misc.py
19
+ """
20
+ import os
21
+ import sys
22
+ import time
23
+ import math
24
+ import random
25
+ import datetime
26
+ import subprocess
27
+ from collections import defaultdict, deque, OrderedDict
28
+
29
+ import numpy as np
30
+ import torch
31
+ from torch import nn
32
+ import torch.distributed as dist
33
+ import warnings
34
+ import argparse
35
+ from PIL import ImageFilter, ImageOps
36
+
37
+
38
+ class GaussianBlur(object):
39
+ """
40
+ Apply Gaussian Blur to the PIL image.
41
+ """
42
+
43
+ def __init__(self, p=0.5, radius_min=0.1, radius_max=2.):
44
+ self.prob = p
45
+ self.radius_min = radius_min
46
+ self.radius_max = radius_max
47
+
48
+ def __call__(self, img):
49
+ do_it = random.random() <= self.prob
50
+ if not do_it:
51
+ return img
52
+
53
+ return img.filter(
54
+ ImageFilter.GaussianBlur(
55
+ radius=random.uniform(self.radius_min, self.radius_max)
56
+ )
57
+ )
58
+
59
+
60
+ class Solarization(object):
61
+ """
62
+ Apply Solarization to the PIL image.
63
+ """
64
+
65
+ def __init__(self, p):
66
+ self.p = p
67
+
68
+ def __call__(self, img):
69
+ if random.random() < self.p:
70
+ return ImageOps.solarize(img)
71
+ else:
72
+ return img
73
+
74
+
75
+ def clip_gradients(model, clip):
76
+ norms = []
77
+ for name, p in model.named_parameters():
78
+ if p.grad is not None:
79
+ param_norm = p.grad.data.norm(2)
80
+ norms.append(param_norm.item())
81
+ clip_coef = clip / (param_norm + 1e-6)
82
+ if clip_coef < 1:
83
+ p.grad.data.mul_(clip_coef)
84
+ return norms
85
+
86
+
87
+ def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs):
88
+ """
89
+ Re-start from checkpoint
90
+ """
91
+ if not os.path.isfile(ckp_path):
92
+ return
93
+ print("Found checkpoint at {}".format(ckp_path))
94
+
95
+ # open checkpoint file
96
+ checkpoint = torch.load(ckp_path, map_location="cpu")
97
+
98
+ # key is what to look for in the checkpoint file
99
+ # value is the object to load
100
+ # example: {'state_dict': model}
101
+ for key, value in kwargs.items():
102
+ if key in checkpoint and value is not None:
103
+ try:
104
+ msg = value.load_state_dict(checkpoint[key], strict=False)
105
+ print("=> loaded '{}' from checkpoint '{}' with msg {}".format(key, ckp_path, msg))
106
+ except TypeError:
107
+ try:
108
+ msg = value.load_state_dict(checkpoint[key])
109
+ print("=> loaded '{}' from checkpoint: '{}'".format(key, ckp_path))
110
+ except ValueError:
111
+ print("=> failed to load '{}' from checkpoint: '{}'".format(key, ckp_path))
112
+ else:
113
+ print("=> key '{}' not found in checkpoint: '{}'".format(key, ckp_path))
114
+
115
+ # re load variable important for the run
116
+ if run_variables is not None:
117
+ for var_name in run_variables:
118
+ if var_name in checkpoint:
119
+ run_variables[var_name] = checkpoint[var_name]
120
+
121
+
122
+ def convert_state_dict(state_dict):
123
+ new_state_dict = OrderedDict()
124
+ for k, v in state_dict.items():
125
+ if k.startswith("module."):
126
+ k = k.replace("module.", "")
127
+ new_state_dict[k] = v
128
+ return new_state_dict
129
+
130
+
131
+ def cosine_scheduler(base_value, final_value, iters, warmup_iters, start_warmup_value=0):
132
+ warmup_schedule = np.array([])
133
+
134
+ if warmup_iters > 0:
135
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
136
+
137
+ post_warmup_iters = np.arange(iters - warmup_iters)
138
+ schedule = final_value + 0.5 * (base_value - final_value) * (
139
+ 1 + np.cos(np.pi * post_warmup_iters / len(post_warmup_iters)))
140
+
141
+ schedule = np.concatenate((warmup_schedule, schedule))
142
+ assert len(schedule) == iters
143
+ return schedule
144
+
145
+
146
+ def constant_with_warmup_scheduler(base_value, iters, warmup_iters=0, start_warmup_value=0):
147
+ warmup_schedule = np.array([])
148
+
149
+ if warmup_iters > 0:
150
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
151
+
152
+ num_iters = iters - warmup_iters
153
+ schedule = np.array([base_value] * num_iters)
154
+
155
+ schedule = np.concatenate((warmup_schedule, schedule))
156
+ assert len(schedule) == iters
157
+ return schedule
158
+
159
+
160
+ def bool_flag(s):
161
+ """
162
+ Parse boolean arguments from the command line.
163
+ """
164
+ FALSY_STRINGS = {"off", "false", "0"}
165
+ TRUTHY_STRINGS = {"on", "true", "1"}
166
+ if s.lower() in FALSY_STRINGS:
167
+ return False
168
+ elif s.lower() in TRUTHY_STRINGS:
169
+ return True
170
+ else:
171
+ raise argparse.ArgumentTypeError("invalid value for a boolean flag")
172
+
173
+
174
+ def fix_random_seeds(seed=31):
175
+ """
176
+ Fix random seeds.
177
+ """
178
+ torch.manual_seed(seed)
179
+ torch.cuda.manual_seed_all(seed)
180
+ np.random.seed(seed)
181
+
182
+
183
+ class SmoothedValue(object):
184
+ """Track a series of values and provide access to smoothed values over a
185
+ window or the global series average.
186
+ """
187
+
188
+ def __init__(self, window_size=20, fmt=None):
189
+ if fmt is None:
190
+ fmt = "{median:.6f} ({global_avg:.6f})"
191
+ self.deque = deque(maxlen=window_size)
192
+ self.total = 0.0
193
+ self.count = 0
194
+ self.fmt = fmt
195
+
196
+ def update(self, value, n=1):
197
+ self.deque.append(value)
198
+ self.count += n
199
+ self.total += value * n
200
+
201
+ def synchronize_between_processes(self):
202
+ """
203
+ Warning: does not synchronize the deque!
204
+ """
205
+ if not is_dist_avail_and_initialized():
206
+ return
207
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
208
+ dist.barrier()
209
+ dist.all_reduce(t)
210
+ t = t.tolist()
211
+ self.count = int(t[0])
212
+ self.total = t[1]
213
+
214
+ @property
215
+ def median(self):
216
+ d = torch.tensor(list(self.deque))
217
+ return d.median().item()
218
+
219
+ @property
220
+ def avg(self):
221
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
222
+ return d.mean().item()
223
+
224
+ @property
225
+ def global_avg(self):
226
+ return self.total / self.count
227
+
228
+ @property
229
+ def max(self):
230
+ return max(self.deque)
231
+
232
+ @property
233
+ def value(self):
234
+ return self.deque[-1]
235
+
236
+ def __str__(self):
237
+ return self.fmt.format(
238
+ median=self.median,
239
+ avg=self.avg,
240
+ global_avg=self.global_avg,
241
+ max=self.max,
242
+ value=self.value)
243
+
244
+
245
+ def reduce_dict(input_dict, average=True):
246
+ """
247
+ Args:
248
+ input_dict (dict): all the values will be reduced
249
+ average (bool): whether to do average or sum
250
+ Reduce the values in the dictionary from all processes so that all processes
251
+ have the averaged results. Returns a dict with the same fields as
252
+ input_dict, after reduction.
253
+ """
254
+ world_size = get_world_size()
255
+ if world_size < 2:
256
+ return input_dict
257
+ with torch.no_grad():
258
+ names = []
259
+ values = []
260
+ # sort the keys so that they are consistent across processes
261
+ for k in sorted(input_dict.keys()):
262
+ names.append(k)
263
+ values.append(input_dict[k])
264
+ values = torch.stack(values, dim=0)
265
+ dist.all_reduce(values)
266
+ if average:
267
+ values /= world_size
268
+ reduced_dict = {k: v for k, v in zip(names, values)}
269
+ return reduced_dict
270
+
271
+
272
+ class MetricLogger(object):
273
+ def __init__(self, delimiter="\t", max_len=100):
274
+ self.meters = defaultdict(SmoothedValue)
275
+ self.delimiter = delimiter
276
+ self.max_len = max_len
277
+
278
+ def update(self, **kwargs):
279
+ for k, v in kwargs.items():
280
+ if isinstance(v, torch.Tensor):
281
+ v = v.item()
282
+ assert isinstance(v, (float, int))
283
+ self.meters[k].update(v)
284
+
285
+ def __getattr__(self, attr):
286
+ if attr in self.meters:
287
+ return self.meters[attr]
288
+ if attr in self.__dict__:
289
+ return self.__dict__[attr]
290
+ raise AttributeError("'{}' object has no attribute '{}'".format(
291
+ type(self).__name__, attr))
292
+
293
+ def __str__(self):
294
+ loss_str = []
295
+ for name, meter in self.meters.items():
296
+ loss_str.append(
297
+ "{}: {}".format(name, str(meter))
298
+ )
299
+ return self.delimiter.join(loss_str)
300
+
301
+ def synchronize_between_processes(self):
302
+ for meter in self.meters.values():
303
+ meter.synchronize_between_processes()
304
+
305
+ def add_meter(self, name, meter):
306
+ self.meters[name] = meter
307
+
308
+ def log_every(self, iterable, print_freq, header=None):
309
+ i = 0
310
+ if not header:
311
+ header = ''
312
+ start_time = time.time()
313
+ end = time.time()
314
+ iter_time = SmoothedValue(fmt='{avg:.6f}')
315
+ data_time = SmoothedValue(fmt='{avg:.6f}')
316
+ space_fmt = ':' + str(len(str(self.max_len))) + 'd'
317
+ if torch.cuda.is_available():
318
+ log_msg = self.delimiter.join([
319
+ header,
320
+ '[{0' + space_fmt + '}/{1}]',
321
+ 'eta: {eta}',
322
+ '{meters}',
323
+ 'time: {time}',
324
+ 'data: {data}',
325
+ 'max mem: {memory:.0f}'
326
+ ])
327
+ else:
328
+ log_msg = self.delimiter.join([
329
+ header,
330
+ '[{0' + space_fmt + '}/{1}]',
331
+ 'eta: {eta}',
332
+ '{meters}',
333
+ 'time: {time}',
334
+ 'data: {data}'
335
+ ])
336
+ MB = 1024.0 * 1024.0
337
+ for obj in iterable:
338
+ data_time.update(time.time() - end)
339
+ yield obj
340
+ iter_time.update(time.time() - end)
341
+ if i % print_freq == 0 or i == self.max_len - 1:
342
+ eta_seconds = iter_time.global_avg * (self.max_len - i)
343
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
344
+ if torch.cuda.is_available():
345
+ print(log_msg.format(
346
+ i, self.max_len,
347
+ eta=eta_string,
348
+ meters=str(self),
349
+ time=str(iter_time), data=str(data_time),
350
+ memory=torch.cuda.max_memory_allocated() / MB))
351
+ else:
352
+ print(log_msg.format(
353
+ i, self.max_len,
354
+ eta=eta_string,
355
+ meters=str(self),
356
+ time=str(iter_time), data=str(data_time)))
357
+ i += 1
358
+ end = time.time()
359
+ total_time = time.time() - start_time
360
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
361
+ print('{} Total time: {} ({:.6f} s / it)'.format(
362
+ header, total_time_str, total_time / self.max_len))
363
+
364
+
365
+ def get_sha():
366
+ cwd = os.path.dirname(os.path.abspath(__file__))
367
+
368
+ def _run(command):
369
+ return subprocess.check_output(command, cwd=cwd).decode('ascii').strip()
370
+
371
+ sha = 'N/A'
372
+ diff = "clean"
373
+ branch = 'N/A'
374
+ try:
375
+ sha = _run(['git', 'rev-parse', 'HEAD'])
376
+ subprocess.check_output(['git', 'diff'], cwd=cwd)
377
+ diff = _run(['git', 'diff-index', 'HEAD'])
378
+ diff = "has uncommited changes" if diff else "clean"
379
+ branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
380
+ except Exception:
381
+ pass
382
+ message = f"sha: {sha}, status: {diff}, branch: {branch}"
383
+ return message
384
+
385
+
386
+ def is_dist_avail_and_initialized():
387
+ if not dist.is_available():
388
+ return False
389
+ if not dist.is_initialized():
390
+ return False
391
+ return True
392
+
393
+
394
+ def get_world_size():
395
+ if not is_dist_avail_and_initialized():
396
+ return 1
397
+ return dist.get_world_size()
398
+
399
+
400
+ def get_rank():
401
+ if not is_dist_avail_and_initialized():
402
+ return 0
403
+ return dist.get_rank()
404
+
405
+
406
+ def is_main_process():
407
+ return get_rank() == 0
408
+
409
+
410
+ def save_on_master(*args, **kwargs):
411
+ if is_main_process():
412
+ torch.save(*args, **kwargs)
413
+
414
+
415
+ def setup_for_distributed(is_master):
416
+ """
417
+ This function disables printing when not in master process
418
+ """
419
+ import builtins as __builtin__
420
+ builtin_print = __builtin__.print
421
+
422
+ def print(*args, **kwargs):
423
+ force = kwargs.pop('force', False)
424
+ if is_master or force:
425
+ builtin_print(*args, **kwargs)
426
+
427
+ __builtin__.print = print
428
+
429
+
430
+ def init_distributed_mode(args):
431
+ # launched with torch.distributed.launch
432
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
433
+ args.rank = int(os.environ["RANK"])
434
+ args.world_size = int(os.environ['WORLD_SIZE'])
435
+ args.gpu = int(os.environ['LOCAL_RANK'])
436
+ # launched with submitit on a slurm cluster
437
+ elif 'SLURM_PROCID' in os.environ:
438
+ args.rank = int(os.environ['SLURM_PROCID'])
439
+ args.gpu = args.rank % torch.cuda.device_count()
440
+ # launched naively with `python main_dino.py`
441
+ # we manually add MASTER_ADDR and MASTER_PORT to env variables
442
+ elif torch.cuda.is_available():
443
+ print('Will run the code on one GPU.')
444
+ args.rank, args.gpu, args.world_size = 0, 0, 1
445
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
446
+ os.environ['MASTER_PORT'] = '29500'
447
+ else:
448
+ print('Does not support training without GPU.')
449
+ sys.exit(1)
450
+
451
+ if torch.cuda.device_count() > 0:
452
+ args.distributed = True
453
+ else:
454
+ args.distributed = False
455
+
456
+ dist.init_process_group(
457
+ backend="nccl",
458
+ init_method=args.dist_url,
459
+ world_size=args.world_size,
460
+ rank=args.rank,
461
+ )
462
+
463
+ torch.cuda.set_device(args.gpu)
464
+ print('| distributed init (rank {}): {}'.format(
465
+ args.rank, args.dist_url), flush=True)
466
+ dist.barrier()
467
+ setup_for_distributed(args.rank == 0)
468
+
469
+
470
+ def accuracy(output, target, topk=(1,)):
471
+ """Computes the accuracy over the k top predictions for the specified values of k"""
472
+ maxk = max(topk)
473
+ batch_size = target.size(0)
474
+ _, pred = output.topk(maxk, 1, True, True)
475
+ pred = pred.t()
476
+ correct = pred.eq(target.reshape(1, -1).expand_as(pred))
477
+ return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
478
+
479
+
480
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
481
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
482
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
483
+ def norm_cdf(x):
484
+ # Computes standard normal cumulative distribution function
485
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
486
+
487
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
488
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
489
+ "The distribution of values may be incorrect.",
490
+ stacklevel=2)
491
+
492
+ with torch.no_grad():
493
+ # Values are generated by using a truncated uniform distribution and
494
+ # then using the inverse CDF for the normal distribution.
495
+ # Get upper and lower cdf values
496
+ l = norm_cdf((a - mean) / std)
497
+ u = norm_cdf((b - mean) / std)
498
+
499
+ # Uniformly fill tensor with values from [l, u], then translate to
500
+ # [2l-1, 2u-1].
501
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
502
+
503
+ # Use inverse cdf transform for normal distribution to get truncated
504
+ # standard normal
505
+ tensor.erfinv_()
506
+
507
+ # Transform to proper mean, std
508
+ tensor.mul_(std * math.sqrt(2.))
509
+ tensor.add_(mean)
510
+
511
+ # Clamp to ensure it's in the proper range
512
+ tensor.clamp_(min=a, max=b)
513
+ return tensor
514
+
515
+
516
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
517
+ # type: (Tensor, float, float, float, float) -> Tensor
518
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
519
+
520
+
521
+ class LARS(torch.optim.Optimizer):
522
+ """
523
+ Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py
524
+ """
525
+
526
+ def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001,
527
+ weight_decay_filter=None, lars_adaptation_filter=None):
528
+ defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum,
529
+ eta=eta, weight_decay_filter=weight_decay_filter,
530
+ lars_adaptation_filter=lars_adaptation_filter)
531
+ super().__init__(params, defaults)
532
+
533
+ @torch.no_grad()
534
+ def step(self):
535
+ for g in self.param_groups:
536
+ for p in g['params']:
537
+ dp = p.grad
538
+
539
+ if dp is None:
540
+ continue
541
+
542
+ if p.ndim != 1:
543
+ dp = dp.add(p, alpha=g['weight_decay'])
544
+
545
+ if p.ndim != 1:
546
+ param_norm = torch.norm(p)
547
+ update_norm = torch.norm(dp)
548
+ one = torch.ones_like(param_norm)
549
+ q = torch.where(param_norm > 0.,
550
+ torch.where(update_norm > 0,
551
+ (g['eta'] * param_norm / update_norm), one), one)
552
+ dp = dp.mul(q)
553
+
554
+ param_state = self.state[p]
555
+ if 'mu' not in param_state:
556
+ param_state['mu'] = torch.zeros_like(p)
557
+ mu = param_state['mu']
558
+ mu.mul_(g['momentum']).add_(dp)
559
+
560
+ p.add_(mu, alpha=-g['lr'])
561
+
562
+
563
+ class MultiCropWrapper(nn.Module):
564
+ """
565
+ Perform forward pass separately on each resolution input.
566
+ The inputs corresponding to a single resolution are clubbed and single
567
+ forward is run on the same resolution inputs. Hence we do several
568
+ forward passes = number of different resolutions used. We then
569
+ concatenate all the output features and run the head forward on these
570
+ concatenated features.
571
+ """
572
+
573
+ def __init__(self, backbone, head):
574
+ super(MultiCropWrapper, self).__init__()
575
+ # disable layers dedicated to ImageNet labels classification
576
+ backbone.fc, backbone.head = nn.Identity(), nn.Identity()
577
+ self.backbone = backbone
578
+ self.head = head
579
+
580
+ def forward(self, x):
581
+ # convert to list
582
+ if not isinstance(x, list):
583
+ x = [x]
584
+ idx_crops = torch.cumsum(torch.unique_consecutive(
585
+ torch.tensor([inp.shape[-1] for inp in x]),
586
+ return_counts=True,
587
+ )[1], 0)
588
+ start_idx, output = 0, torch.empty(0).to(x[0].device)
589
+ for end_idx in idx_crops:
590
+ _out = self.backbone(torch.cat(x[start_idx: end_idx]))
591
+ # The output is a tuple with XCiT model. See:
592
+ # https://github.com/facebookresearch/xcit/blob/master/xcit.py#L404-L405
593
+ if isinstance(_out, tuple):
594
+ _out = _out[0]
595
+ # accumulate outputs
596
+ output = torch.cat((output, _out))
597
+ start_idx = end_idx
598
+ # Run the head forward on the concatenated features.
599
+ return self.head(output)
600
+
601
+
602
+ def get_params_groups(model):
603
+ regularized = []
604
+ not_regularized = []
605
+ for name, param in model.named_parameters():
606
+ if not param.requires_grad:
607
+ continue
608
+ # we do not regularize biases nor Norm parameters
609
+ if name.endswith(".bias") or len(param.shape) == 1:
610
+ not_regularized.append(param)
611
+ else:
612
+ regularized.append(param)
613
+ return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}]
614
+
615
+
616
+ def cancel_gradients_last_layer(epoch, model, freeze_last_layer):
617
+ if epoch >= freeze_last_layer:
618
+ return
619
+ for n, p in model.named_parameters():
620
+ if "last_layer" in n:
621
+ p.grad = None
622
+
623
+
624
+ def has_batchnorms(model):
625
+ bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)
626
+ for name, module in model.named_modules():
627
+ if isinstance(module, bn_types):
628
+ return True
629
+ return False
630
+
631
+
632
+ #####
633
+ def convert_weights_float(model: nn.Module):
634
+ """Convert applicable model parameters to fp32"""
635
+
636
+ def _convert_weights_to_fp32(l):
637
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
638
+ l.weight.data = l.weight.data.float()
639
+ if l.bias is not None:
640
+ l.bias.data = l.bias.data.float()
641
+
642
+ if isinstance(l, nn.MultiheadAttention):
643
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
644
+ tensor = getattr(l, attr)
645
+ if tensor is not None:
646
+ tensor.data = tensor.data.float()
647
+
648
+ for name in ["text_projection", "proj"]:
649
+ if hasattr(l, name):
650
+ attr = getattr(l, name)
651
+ if attr is not None:
652
+ attr.data = attr.data.float()
653
+
654
+ model.apply(_convert_weights_to_fp32)
655
+
656
+
657
+ def split_reshape(x, bs, combination=None):
658
+ n = len(x) // bs
659
+ assert n in [2, 3], "The num augs should be 2 or 3 in number"
660
+ f = torch.split(x, [bs] * n, dim=0)
661
+ if combination is None:
662
+ x_reshape = torch.cat([f[i].unsqueeze(1) for i in range(n)], dim=1)
663
+ else:
664
+ x_reshape = torch.cat([f[i].unsqueeze(1) for i in combination], dim=1)
665
+
666
+ # if repeatcase:
667
+ # x_reshape = torch.cat([f1.unsqueeze(1), f1.unsqueeze(1)], dim=1)
668
+ return x_reshape
669
+
670
+
671
+ class AverageMeter(object):
672
+ """Computes and stores the average and current value"""
673
+
674
+ def __init__(self, name, fmt=":f"):
675
+ self.name = name
676
+ self.fmt = fmt
677
+ self.reset()
678
+
679
+ def reset(self):
680
+ self.val = 0
681
+ self.avg = 0
682
+ self.sum = 0
683
+ self.count = 0
684
+
685
+ def update(self, val, n=1):
686
+ self.val = val
687
+ self.sum += val * n
688
+ self.count += n
689
+ self.avg = self.sum / self.count
690
+
691
+ def __str__(self):
692
+ fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
693
+ return fmtstr.format(**self.__dict__)
694
+
695
+
696
+ class ProgressMeter(object):
697
+ def __init__(self, num_batches, meters, prefix=""):
698
+ self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
699
+ self.meters = meters
700
+ self.prefix = prefix
701
+
702
+ def display(self, batch):
703
+ entries = [self.prefix + self.batch_fmtstr.format(batch)]
704
+ entries += [str(meter) for meter in self.meters]
705
+ print("\t".join(entries))
706
+
707
+ def _get_batch_fmtstr(self, num_batches):
708
+ num_digits = len(str(num_batches // 1))
709
+ fmt = "{:" + str(num_digits) + "d}"
710
+ return "[" + fmt + "/" + fmt.format(num_batches) + "]"
711
+
712
+
713
+ @torch.no_grad()
714
+ def extract_features(model, data_loader, use_cuda=True, use_fp16=False, eval_embed='head'):
715
+ metric_logger = MetricLogger(delimiter=" ")
716
+ features = None
717
+ # count = 0
718
+ for samples, *_, index in metric_logger.log_every(data_loader, 100):
719
+ # print(f'At the index {index}')
720
+ samples = samples.cuda(non_blocking=True)
721
+ index = index.cuda(non_blocking=True)
722
+ if use_fp16:
723
+ with torch.cuda.amp.autocast():
724
+ bb_feats, cont_feats, style_feats = model(samples)
725
+
726
+ if eval_embed == 'backbone':
727
+ feats = bb_feats.clone()
728
+ else:
729
+ feats = style_feats.clone()
730
+
731
+ else:
732
+ bb_feats, cont_feats, style_feats = model(samples)
733
+ if eval_embed == 'backbone':
734
+ feats = bb_feats.clone()
735
+ else:
736
+ feats = style_feats.clone()
737
+ # init storage feature matrix
738
+ if dist.get_rank() == 0 and features is None:
739
+ features = torch.zeros(len(data_loader.dataset), feats.shape[-1], dtype=feats.dtype)
740
+ if use_cuda:
741
+ features = features.cuda(non_blocking=True)
742
+ print(f"Storing features into tensor of shape {features.shape}")
743
+
744
+ # get indexes from all processes
745
+ y_all = torch.empty(dist.get_world_size(), index.size(0), dtype=index.dtype, device=index.device)
746
+ y_l = list(y_all.unbind(0))
747
+ y_all_reduce = torch.distributed.all_gather(y_l, index, async_op=True)
748
+ y_all_reduce.wait()
749
+ index_all = torch.cat(y_l)
750
+
751
+ # share features between processes
752
+ feats_all = torch.empty(
753
+ dist.get_world_size(),
754
+ feats.size(0),
755
+ feats.size(1),
756
+ dtype=feats.dtype,
757
+ device=feats.device,
758
+ )
759
+ output_l = list(feats_all.unbind(0))
760
+ output_all_reduce = torch.distributed.all_gather(output_l, feats, async_op=True)
761
+ output_all_reduce.wait()
762
+
763
+ # update storage feature matrix
764
+ if dist.get_rank() == 0:
765
+ if use_cuda:
766
+ features.index_copy_(0, index_all, torch.cat(output_l))
767
+ else:
768
+ features.index_copy_(0, index_all.cpu(), torch.cat(output_l).cpu())
769
+ return features
770
+
771
+
772
+ # Copy from https://github.com/learn2phoenix/dynamicDistances/blob/main/metrics/metrics.py
773
+ class Metrics(object):
774
+ def __init__(self):
775
+ self.data = None
776
+
777
+ @staticmethod
778
+ def get_recall(preds, gts, topk=5):
779
+ preds = preds[:, :topk]
780
+ preds -= gts[:, None]
781
+ found = np.where(np.amin(np.absolute(preds), axis=1) == 0)[0]
782
+ return found.shape[0] / gts.shape[0]
783
+
784
+ @staticmethod
785
+ def get_mrr(preds, gts, topk=5):
786
+ preds = preds[:, :topk]
787
+ preds -= gts[:, None]
788
+ rows, cols = np.where(preds == 0)
789
+ _, unique_rows = np.unique(rows, return_index=True)
790
+ valid_cols = cols[unique_rows]
791
+ valid_cols += 1
792
+ return np.mean(1 / valid_cols)
793
+
794
+ @staticmethod
795
+ def get_map(preds, gts, topk=5):
796
+ preds = preds[:, :topk]
797
+ preds -= gts[:, None]
798
+ rows, cols = np.where(preds == 0)
799
+ _, unique_rows = np.unique(rows, return_index=True)
800
+ row_cols = np.split(cols, unique_rows)[1:]
801
+ row_cols = [np.hstack([x[0], np.diff(x), topk - x[-1]]) for x in row_cols]
802
+ row_cols = [np.pad(x, (0, topk + 1 - x.shape[0]), 'constant', constant_values=(0, 0)) for x in row_cols]
803
+ precision = np.asarray([np.repeat(np.arange(topk + 1), x) / np.arange(1, topk + 1) for x in row_cols])
804
+ return np.sum(np.mean(precision, axis=1)) / preds.shape[0]
805
+
806
+ @staticmethod
807
+ def get_recall_bin(preds, topk=5):
808
+ # preds is a binary matrix of size Q x K
809
+ preds = preds[:, :topk]
810
+ found = np.where(np.amax(preds, axis=1) == True)[0]
811
+ return found.shape[0] / preds.shape[0]
812
+
813
+ @staticmethod
814
+ def get_mrr_bin(preds, topk=5):
815
+ # preds is a binary matrix of size Q x K
816
+ preds = preds[:, :topk]
817
+ rows, cols = np.where(preds)
818
+ _, unique_rows = np.unique(rows, return_index=True)
819
+ valid_cols = cols[unique_rows]
820
+ valid_cols += 1
821
+ return np.mean(1 / valid_cols)
822
+
823
+ @staticmethod
824
+ def get_map_bin(preds, topk=5):
825
+ # preds is a binary matrix of size Q x K
826
+ preds = preds[:, :topk]
827
+ rows, cols = np.where(preds)
828
+ _, unique_rows = np.unique(rows, return_index=True)
829
+ row_cols = np.split(cols, unique_rows)[1:]
830
+ row_cols = [np.hstack([x[0], np.diff(x), topk - x[-1]]) for x in row_cols]
831
+ row_cols = [np.pad(x, (0, topk + 1 - x.shape[0]), 'constant', constant_values=(0, 0)) for x in row_cols]
832
+ precision = np.asarray([np.repeat(np.arange(topk + 1), x) / np.arange(1, topk + 1) for x in row_cols])
833
+ return np.sum(np.mean(precision, axis=1)) / preds.shape[0]
834
+
835
+
836
+ class GatherLayer(torch.autograd.Function):
837
+ """Gather tensors from all process, supporting backward propagation.
838
+ """
839
+
840
+ @staticmethod
841
+ def forward(ctx, input):
842
+ ctx.save_for_backward(input)
843
+ output = [torch.zeros_like(input) \
844
+ for _ in range(dist.get_world_size())]
845
+ dist.all_gather(output, input)
846
+ return tuple(output)
847
+
848
+ @staticmethod
849
+ def backward(ctx, *grads):
850
+ input, = ctx.saved_tensors
851
+ grad_out = torch.zeros_like(input)
852
+ grad_out[:] = grads[dist.get_rank()]
853
+ return grad_out