-
Notifications
You must be signed in to change notification settings - Fork 24
/
algorithms.py
474 lines (419 loc) · 16.2 KB
/
algorithms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import tensorflow as tf
from tensorflow import keras
from models import ContrastiveModel, MomentumContrastiveModel
class SimCLR(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
temperature,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
self.temperature = temperature
def contrastive_loss(self, projections_1, projections_2):
# InfoNCE loss (information noise-contrastive estimation)
# NT-Xent loss (normalized temperature-scaled cross entropy)
# cosine similarity: the dot product of the l2-normalized feature vectors
projections_1 = tf.math.l2_normalize(projections_1, axis=1)
projections_2 = tf.math.l2_normalize(projections_2, axis=1)
similarities = (
tf.matmul(projections_1, projections_2, transpose_b=True) / self.temperature
)
# the temperature-scaled similarities are used as logits for cross-entropy
batch_size = tf.shape(projections_1)[0]
contrastive_labels = tf.range(batch_size)
loss = keras.losses.sparse_categorical_crossentropy(
tf.concat([contrastive_labels, contrastive_labels], axis=0),
tf.concat([similarities, tf.transpose(similarities)], axis=0),
from_logits=True,
)
return loss
class NNCLR(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
temperature,
queue_size,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
self.temperature = temperature
feature_dimensions = encoder.output_shape[1]
self.feature_queue = tf.Variable(
tf.math.l2_normalize(
tf.random.normal(shape=(queue_size, feature_dimensions)), axis=1
),
trainable=False,
)
def nearest_neighbour(self, projections):
# highest cosine similarity == lowest L2 distance, for L2 normalized features
support_similarities = tf.matmul(
projections, self.feature_queue, transpose_b=True
)
# hard nearest-neighbours
nn_projections = tf.gather(
self.feature_queue, tf.argmax(support_similarities, axis=1), axis=0
)
# straight-through gradient estimation
# paper used stop gradient, however it helps performance at this scale
return projections + tf.stop_gradient(nn_projections - projections)
def contrastive_loss(self, projections_1, projections_2):
# similar to the SimCLR loss, however we take the nearest neighbours of a set
# of projections from a feature queue
projections_1 = tf.math.l2_normalize(projections_1, axis=1)
projections_2 = tf.math.l2_normalize(projections_2, axis=1)
similarities_1_2 = (
tf.matmul(
self.nearest_neighbour(projections_1), projections_2, transpose_b=True
)
/ self.temperature
)
similarities_2_1 = (
tf.matmul(
self.nearest_neighbour(projections_2), projections_1, transpose_b=True
)
/ self.temperature
)
batch_size = tf.shape(projections_1)[0]
contrastive_labels = tf.range(batch_size)
loss = keras.losses.sparse_categorical_crossentropy(
tf.concat([contrastive_labels, contrastive_labels], axis=0),
tf.concat([similarities_1_2, similarities_2_1], axis=0),
from_logits=True,
)
# feature queue update
self.feature_queue.assign(
tf.concat([projections_1, self.feature_queue[:-batch_size]], axis=0)
)
return loss
class DCCLR(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
temperature,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
self.temperature = temperature
def contrastive_loss(self, projections_1, projections_2):
# a modified InfoNCE loss, which should provide better performance at
# lower batch sizes
# cosine similarity: the dot product of the l2-normalized feature vectors
projections_1 = tf.math.l2_normalize(projections_1, axis=1)
projections_2 = tf.math.l2_normalize(projections_2, axis=1)
similarities = (
tf.matmul(projections_1, projections_2, transpose_b=True) / self.temperature
)
# the similarities of the positives (the main diagonal) are masked and
# are not included in the softmax normalization
batch_size = tf.shape(projections_1)[0]
decoupling_mask = 1.0 - tf.eye(batch_size)
decoupled_similarities = decoupling_mask * tf.exp(similarities)
loss = tf.reduce_mean(
-tf.linalg.diag_part(similarities)
+ tf.math.log(
tf.reduce_sum(decoupled_similarities, axis=0)
+ tf.reduce_sum(decoupled_similarities, axis=1)
)
)
# the sum along the two axes should be put in separate log-sum-exp
# expressions according to the paper, this however achieves slightly
# higher performance at this scale
return loss
class BarlowTwins(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
redundancy_reduction_weight,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
# weighting coefficient between the two loss components
self.redundancy_reduction_weight = redundancy_reduction_weight
# its value differs from the paper, because the loss implementation has been
# changed to be invariant to the encoder output dimensions (feature dim)
def contrastive_loss(self, projections_1, projections_2):
projections_1 = (
projections_1 - tf.reduce_mean(projections_1, axis=0)
) / tf.math.reduce_std(projections_1, axis=0)
projections_2 = (
projections_2 - tf.reduce_mean(projections_2, axis=0)
) / tf.math.reduce_std(projections_2, axis=0)
# the cross correlation of image representations should be the identity matrix
batch_size = tf.shape(projections_1, out_type=tf.float32)[0]
feature_dim = tf.shape(projections_1, out_type=tf.float32)[1]
cross_correlation = (
tf.matmul(projections_1, projections_2, transpose_a=True) / batch_size
)
target_cross_correlation = tf.eye(feature_dim)
squared_errors = (target_cross_correlation - cross_correlation) ** 2
# invariance loss = average diagonal error
# redundancy reduction loss = average off-diagonal error
invariance_loss = (
tf.reduce_sum(squared_errors * tf.eye(feature_dim)) / feature_dim
)
redundancy_reduction_loss = tf.reduce_sum(
squared_errors * (1 - tf.eye(feature_dim))
) / (feature_dim * (feature_dim - 1))
return (
invariance_loss
+ self.redundancy_reduction_weight * redundancy_reduction_loss
)
class HSICTwins(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
redundancy_reduction_weight,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
# weighting coefficient between the two loss components
self.redundancy_reduction_weight = redundancy_reduction_weight
# its value differs from the paper, because the loss implementation has been
# changed to be invariant to the encoder output dimensions (feature dim)
def contrastive_loss(self, projections_1, projections_2):
# a modified BarlowTwins loss, derived from Hilbert-Schmidt Independence
# Criterion maximization, the only difference is the target cross correlation
projections_1 = (
projections_1 - tf.reduce_mean(projections_1, axis=0)
) / tf.math.reduce_std(projections_1, axis=0)
projections_2 = (
projections_2 - tf.reduce_mean(projections_2, axis=0)
) / tf.math.reduce_std(projections_2, axis=0)
# the cross correlation of image representations should be 1 along the diagonal
# and -1 everywhere else
batch_size = tf.shape(projections_1, out_type=tf.float32)[0]
feature_dim = tf.shape(projections_1, out_type=tf.float32)[1]
cross_correlation = (
tf.matmul(projections_1, projections_2, transpose_a=True) / batch_size
)
target_cross_correlation = 2.0 * tf.eye(feature_dim) - 1.0
squared_errors = (target_cross_correlation - cross_correlation) ** 2
# invariance loss = average diagonal error
# redundancy reduction loss = average off-diagonal error
invariance_loss = (
tf.reduce_sum(squared_errors * tf.eye(feature_dim)) / feature_dim
)
redundancy_reduction_loss = tf.reduce_sum(
squared_errors * (1 - tf.eye(feature_dim))
) / (feature_dim * (feature_dim - 1))
return (
invariance_loss
+ self.redundancy_reduction_weight * redundancy_reduction_loss
)
class TWIST(ContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
)
def contrastive_loss(self, projections_1, projections_2):
# a probabilistic, hyperparameter- and negative-free loss
# batch normalization before softmax operation
projections_1 = (
projections_1 - tf.reduce_mean(projections_1, axis=0)
) / tf.math.reduce_std(projections_1, axis=0)
projections_2 = (
projections_2 - tf.reduce_mean(projections_2, axis=0)
) / tf.math.reduce_std(projections_2, axis=0)
probabilities_1 = keras.activations.softmax(projections_1)
probabilities_2 = keras.activations.softmax(projections_2)
mean_probabilities_1 = tf.reduce_mean(probabilities_1, axis=0)
mean_probabilities_2 = tf.reduce_mean(probabilities_2, axis=0)
# cross-entropy(1,2): KL-div(1,2) (consistency) + entropy(1) (sharpness)
# -cross-entropy(mean1,mean1): -entropy(mean1) (diversity)
loss = keras.losses.categorical_crossentropy(
tf.concat([probabilities_1, probabilities_2], axis=0),
tf.concat([probabilities_2, probabilities_1], axis=0),
) - keras.losses.categorical_crossentropy(
tf.concat([mean_probabilities_1, mean_probabilities_2], axis=0),
tf.concat([mean_probabilities_1, mean_probabilities_2], axis=0),
)
return loss
class MoCo(MomentumContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
momentum_coeff,
temperature,
queue_size,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
momentum_coeff,
)
self.temperature = temperature
feature_dimensions = encoder.output_shape[1]
self.feature_queue = tf.Variable(
tf.math.l2_normalize(
tf.random.normal(shape=(queue_size, feature_dimensions)), axis=1
),
trainable=False,
)
def contrastive_loss(
self,
projections_1,
projections_2,
m_projections_1,
m_projections_2,
):
# similar to the SimCLR loss, however it uses the momentum networks'
# representations of the differently augmented views as targets
projections_1 = tf.math.l2_normalize(projections_1, axis=1)
projections_2 = tf.math.l2_normalize(projections_2, axis=1)
m_projections_1 = tf.math.l2_normalize(m_projections_1, axis=1)
m_projections_2 = tf.math.l2_normalize(m_projections_2, axis=1)
similarities_1_2 = (
tf.matmul(
projections_1,
tf.concat((m_projections_2, self.feature_queue), axis=0),
transpose_b=True,
)
/ self.temperature
)
similarities_2_1 = (
tf.matmul(
projections_2,
tf.concat((m_projections_1, self.feature_queue), axis=0),
transpose_b=True,
)
/ self.temperature
)
batch_size = tf.shape(projections_1)[0]
contrastive_labels = tf.range(batch_size)
loss = keras.losses.sparse_categorical_crossentropy(
tf.concat([contrastive_labels, contrastive_labels], axis=0),
tf.concat([similarities_1_2, similarities_2_1], axis=0),
from_logits=True,
)
# feature queue update
self.feature_queue.assign(
tf.concat(
[
m_projections_1,
m_projections_2,
self.feature_queue[: -(2 * batch_size)],
],
axis=0,
)
)
return loss
class DINO(MomentumContrastiveModel):
def __init__(
self,
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
momentum_coeff,
temperature,
sharpening,
):
super().__init__(
contrastive_augmenter,
classification_augmenter,
encoder,
projection_head,
linear_probe,
momentum_coeff,
)
self.temperature = temperature
self.sharpening = sharpening
def contrastive_loss(
self,
projections_1,
projections_2,
m_projections_1,
m_projections_2,
):
# this loss does not use any negatives, needs centering + sharpening + momentum
# to avoid collapse
# l2-normalization is part of the projection head in the original implementation
projections_1 = tf.math.l2_normalize(projections_1, axis=1)
projections_2 = tf.math.l2_normalize(projections_2, axis=1)
m_projections_1 = tf.math.l2_normalize(m_projections_1, axis=1)
m_projections_2 = tf.math.l2_normalize(m_projections_2, axis=1)
center = tf.reduce_mean(
tf.concat([m_projections_1, m_projections_2], axis=0), axis=0, keepdims=True
)
target_probabilities_1 = keras.activations.softmax(
(m_projections_1 - center) / (self.sharpening * self.temperature)
)
target_probabilities_2 = keras.activations.softmax(
(m_projections_2 - center) / (self.sharpening * self.temperature)
)
pred_probabilities_1 = keras.activations.softmax(
projections_1 / self.temperature
)
pred_probabilities_2 = keras.activations.softmax(
projections_2 / self.temperature
)
loss = keras.losses.categorical_crossentropy(
tf.concat([target_probabilities_1, target_probabilities_2], axis=0),
tf.concat([pred_probabilities_2, pred_probabilities_1], axis=0),
)
return loss