forked from aiwizzard/dino-vit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
236 lines (197 loc) · 7.05 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import ImageFilter, ImageOps, Image
class RandomGaussianBlur:
r"""RandomGaussianBlur class
Apply Gaussian Blur to the PIL image
"""
def __init__(self, prob=0.5, min_radius=0.1, max_radius=2.0) -> None:
self.prob = prob
self.min_radius = min_radius
self.max_radius = max_radius
def __call__(self, img) -> Image:
if torch.rand(1) < self.prob:
return img.filter(
ImageFilter.GaussianBlur(
radius=random.uniform(self.min_radius, self.max_radius)
)
)
return img
class Solarization:
r"""Solarization Class
Apply solarization to the PIL image.
Solarization is the effect of tone reversal.
"""
def __init__(self, prob) -> None:
self.prob = prob
def __call__(self, img: Image) -> Image:
if torch.rand(1) < self.prob:
return ImageOps.solarize(img)
return img
class ImageAugmentation:
r"""ImageAugmentation Class
Apply various transformations to the PIL Image
"""
def __init__(self, global_crop_scales, local_crop_scales, n_local_crops) -> None:
self.n_local_crops = n_local_crops
flip_and_jitter = transforms.Compose(
[
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomApply(
[
transforms.ColorJitter(
brightness=0.8, contrast=0.4, saturation=0.2, hue=0.1
)
]
),
]
)
normalize = transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
]
)
self.global_transform1 = transforms.Compose(
[
transforms.RandomResizedCrop(
224,
scale=global_crop_scales,
interpolation=transforms.InterpolationMode.BICUBIC,
),
flip_and_jitter,
RandomGaussianBlur(prob=1.0), # not random
normalize,
]
)
self.global_transform2 = transforms.Compose(
[
transforms.RandomResizedCrop(
224,
scale=global_crop_scales,
interpolation=transforms.InterpolationMode.BICUBIC,
),
flip_and_jitter,
RandomGaussianBlur(0.1),
Solarization(0.2),
normalize,
]
)
self.local_transform = transforms.Compose(
[
transforms.RandomResizedCrop(
96,
scale=local_crop_scales,
interpolation=transforms.InterpolationMode.BICUBIC,
),
flip_and_jitter,
RandomGaussianBlur(prob=0.5),
normalize,
]
)
def __call__(self, img):
crops = []
crops.append(self.global_transform1(img))
crops.append(self.global_transform2(img))
for _ in range(self.n_local_crops):
crops.append(self.local_transform(img))
return crops
class ProjectionHead(nn.Module):
r"""ProjectionHead Class
This consist of 3 layer multi perceptron followed by l2 weight
normalization and a weight normalized fully connected layer.
"""
def __init__(self, in_dim, out_dim, hidden_dim=2048, bottleneck_dim=256):
super(ProjectionHead, self).__init__()
self.mlp = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.Linear(hidden_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, bottleneck_dim),
)
self.last_layer = nn.utils.weight_norm(
nn.Linear(bottleneck_dim, out_dim, bias=False)
)
self.last_layer.weight_g.data.fill_(1)
self.last_layer.weight_g.requires_grad = False
def forward(self, x):
x = self.mlp(x)
x = nn.functional.normalize(x)
x = self.last_layer(x)
return x
class MultiCropWrapper(nn.Module):
def __init__(self, backbone, head) -> None:
super(MultiCropWrapper, self).__init__()
backbone.head = nn.Identity() # disable the original head
self.backbone = backbone
self.head = head
def forward(self, x):
# get the counts of the same resolution images
_, counts = torch.unique_consecutive(
torch.tensor([inp.shape[-1] for inp in x]), return_counts=True
)
n_crops = len(x)
idx_crops = torch.cumsum(counts, 0)
start_idx = 0
output = torch.empty(0).to(x[0].device)
for end_idx in idx_crops:
_out = self.backbone(torch.cat(x[start_idx:end_idx]))
output = torch.cat((output, _out))
start_idx = end_idx
out = self.head(output)
return out.chunk(n_crops)
class DINOLoss(nn.Module):
r"""DINOLoss Class
Compute the loss.
"""
def __init__(self, out_dim, teacher_temp, student_temp, center_momentum) -> None:
super(DINOLoss, self).__init__()
self.teacher_temp = teacher_temp
self.student_temp = student_temp
self.center_momentum = center_momentum
self.register_buffer("center", torch.zeros(1, out_dim))
def forward(self, student_output, teacher_output):
student_out = [
F.log_softmax(s / self.student_temp, dim=-1) for s in student_output
]
teacher_out = [
F.softmax((t - self.center) / self.teacher_temp, dim=-1).detach()
for t in teacher_output
]
total_loss = 0
n_loss_terms = 0
for t_idx, t in enumerate(teacher_out):
for s_idx, s in enumerate(student_out):
# Skip for the same image
if t_idx == s_idx:
continue
loss = torch.sum(-t * s, dim=-1)
total_loss += loss.mean()
n_loss_terms += 1
total_loss /= n_loss_terms
self.update_center(teacher_output)
return total_loss
@torch.no_grad()
def update_center(self, teacher_output):
r"""Update center for teacher output
Exponential moving average as described in the paper
"""
batch_center = torch.cat(teacher_output).mean(dim=0, keepdim=True)
self.center = (
self.center * self.center_momentum
+ (1 - self.center_momentum) * batch_center
)
def clip_gradients(model, clip):
r"""Clip gradients.
This function will normalize the gradients.
Thus avoid gradient Explotion
"""
for param in model.parameters():
if param.grad is not None:
param_norm = param.grad.data.norm(2)
clip_coef = clip / (param_norm + 1e-6)
if clip_coef < 1:
param.grad.data.mul_(clip_coef)