-
Notifications
You must be signed in to change notification settings - Fork 7
/
losses.py
500 lines (399 loc) · 18.2 KB
/
losses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
import torch
from torch import nn
from torchvision.models.vgg import vgg16, vgg19
from modules import SimpleGray
class PixelwiseLoss(nn.Module):
"""
It is just a simple MSE loss
assuming input in range [-1, 1]
"""
def __init__(self, is_gray=False):
super(PixelwiseLoss, self).__init__()
if is_gray:
self.gray_layer = SimpleGray()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, out_images, target_images, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
if hasattr(self, 'gray_layer'):
out_images = self.gray_layer((out_images + 1.) / 2.)
target_images = self.gray_layer((target_images + 1.) / 2.)
return weight * self.criterion(out_images, target_images)
class PixelwiseGrayLoss(nn.Module):
"""
It is just a simple MSE loss
assuming input in range [-1, 1]
"""
def __init__(self, is_gray=False):
super(PixelwiseGrayLoss, self).__init__()
if is_gray:
self.gray_layer = SimpleGray()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, out_images, target_images, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
out_images = torch.mean(out_images,dim=1,keepdim= True)
target_images = torch.mean(target_images,dim=1,keepdim= True)
return weight * self.criterion(out_images, target_images)
class PerceptualLoss(nn.Module):
def __init__(self, model='vgg19_5_4', include_max_pool=False, norm=False, is_gray=False):
super(PerceptualLoss, self).__init__()
if model.startswith('vgg16'):
# vgg16: [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']
# 1 3 5 6 8 10 11 13 15 17 18 20 22 24 25 27 29 31
vgg = vgg16(pretrained=True)
if model.endswith('2_2'):
layer_idx, output_nc = 10, 128
elif model.endswith('5_3'):
layer_idx, output_nc = 31, 512
else:
raise NotImplementedError('Only support [2_2 and 5_3]')
elif model.startswith('vgg19'):
# vgg19: [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M']
# 1 3 5 6 8 10 11 13 15 17 19 20 22 24 26 28 29 31 33 35 37
vgg = vgg19(pretrained=True)
if model.endswith('2_2'):
layer_idx, output_nc = 10, 128
elif model.endswith('5_4'):
layer_idx, output_nc = 37, 512
else:
raise NotImplementedError('Only support [2_2 and 5_4]')
if not include_max_pool:
layer_idx -= 1
loss_network = nn.Sequential(*list(vgg.features)[:layer_idx]).eval()
for param in loss_network.parameters():
param.requires_grad = False
self.loss_network = loss_network
# input normalization
t_mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
t_mean -= 1. # if input in range [-1, 1]
t_std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
t_std *= 2. # if input in range [-1, 1]
self.register_buffer('mean', t_mean)
self.register_buffer('std', t_std)
# criterion
self.mse_loss = nn.MSELoss()
# domain-invariant perceptual loss from MUNIT paper
# seems not working... T^T
if norm:
self.norm_layer = nn.InstanceNorm2d(output_nc)
if is_gray:
self.gray_layer = SimpleGray()
if torch.cuda.is_available():
self.cuda()
def forward(self, out_images, target_images, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
# make it gray
if hasattr(self, 'gray_layer'):
out_images = self.gray_layer((out_images + 1.) / 2.).expand_as(out_images)
target_images = self.gray_layer((target_images + 1.) / 2.).expand_as(target_images)
# normalization
out_images = (out_images - self.mean) / self.std
target_images = (target_images - self.mean) / self.std
out_features = self.loss_network(out_images)
target_feature = self.loss_network(target_images)
if hasattr(self, 'norm_layer'):
return weight * self.mse_loss(self.norm_layer(out_features), self.norm_layer(target_feature))
else:
return weight * self.mse_loss(out_features, target_feature)
class PerceptualMultiplierLoss(nn.Module):
def __init__(self, model='vgg19_5_4', include_max_pool=False, norm=False, is_gray=False):
super(PerceptualMultiplierLoss, self).__init__()
# vgg19: [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M']
# 1 3 5 6 8 10 11 13 15 17 19 20 22 24 26 28 29 31 33 35 37
vgg = vgg19(pretrained=True)
layer_idx, output_nc = 19, 256
if not include_max_pool:
layer_idx -= 1
loss_network = nn.Sequential(*list(vgg.features)[:layer_idx]).eval()
for param in loss_network.parameters():
param.requires_grad = False
self.loss_network = loss_network
# input normalization
t_mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
t_mean -= 1. # if input in range [-1, 1]
t_std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
t_std *= 2. # if input in range [-1, 1]
self.register_buffer('mean', t_mean)
self.register_buffer('std', t_std)
# criterion
self.mse_loss = nn.MSELoss()
if norm:
self.norm_layer = nn.InstanceNorm2d(output_nc)
if is_gray:
self.gray_layer = SimpleGray()
if torch.cuda.is_available():
self.cuda()
def forward(self, out_images, target_images, multiplier, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
# make it gray
out_images = torch.mean(out_images,dim=1,keepdim= True).expand_as(out_images)
target_images = torch.mean(target_images,dim=1, keepdim= True).expand_as(target_images)
# normalization
out_images = (out_images - self.mean) / self.std
target_images = (target_images - self.mean) / self.std
out_features = self.loss_network(out_images)
target_feature = self.loss_network(target_images)
if hasattr(self, 'norm_layer'):
return weight * self.mse_loss(self.norm_layer(out_features), self.norm_layer(target_feature * multiplier.detach() ) )
else:
return weight * self.mse_loss(out_features, target_feature )
class GANLoss(nn.Module):
def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0):
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
if use_lsgan:
self.loss = nn.MSELoss()
else:
self.loss = nn.BCELoss()
if torch.cuda.is_available():
self.cuda()
def get_target_tensor(self, input, target_is_real):
if target_is_real:
target_tensor = self.real_label
else:
target_tensor = self.fake_label
return target_tensor.expand_as(input)
def __call__(self, input, target_is_real):
target_tensor = self.get_target_tensor(input, target_is_real)
return self.loss(input, target_tensor)
class CrossEntropyGANLoss(nn.Module):
def __init__(self):
super(CrossEntropyGANLoss, self).__init__()
self.loss = nn.CrossEntropyLoss()
if torch.cuda.is_available():
self.cuda()
def get_target_tensor(self, input, label):
label_tensor = torch.tensor(label, dtype=torch.long)
if torch.cuda.is_available():
label_tensor = label_tensor.cuda()
return label_tensor.expand(input.size()[:1] + input.size()[2:])
def __call__(self, input, label):
target = self.get_target_tensor(input, label)
return self.loss(input, target)
class TVLoss(nn.Module):
def __init__(self, tv_loss_weight=1):
super(TVLoss, self).__init__()
self.tv_loss_weight = tv_loss_weight
if torch.cuda.is_available():
self.cuda()
def forward(self, x):
batch_size = x.size()[0]
h_x = x.size()[2]
w_x = x.size()[3]
count_h = self.tensor_size(x[:, :, 1:, :])
count_w = self.tensor_size(x[:, :, :, 1:])
h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, :h_x - 1, :]), 2).sum()
w_tv = torch.pow((x[:, :, :, 1:] - x[:, :, :, :w_x - 1]), 2).sum()
return self.tv_loss_weight * 2 * (h_tv / count_h + w_tv / count_w) / batch_size
@staticmethod
def tensor_size(t):
return t.size()[1] * t.size()[2] * t.size()[3]
class EnTVLoss(nn.Module):
def __init__(self):
super(EnTVLoss, self).__init__()
self.eps = 1/255.
self.sigma = 6.0 * self.eps
if torch.cuda.is_available():
self.cuda()
def forward(self, x, y=None, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
if y is not None:
ref_gx, ref_gy = self.calc_gradxy(y)
wx = torch.exp(-ref_gx.pow_(2) / (2 * self.sigma ** 2))
wy = torch.exp(-ref_gy.pow_(2) / (2 * self.sigma ** 2))
else:
wx, wy = 1., 1.
tvx, tvy = self.calc_gradxy(x)
tvx = (torch.pow(tvx, 2) * wx).mean()
tvy = (torch.pow(tvy, 2) * wy).mean()
return weight * 2 * (tvx + tvy)
@staticmethod
def calc_gradxy(t):
gx = t[:, :, 1:, :] - t[:, :, :-1, :]
gy = t[:, :, :, 1:] - t[:, :, :, :-1]
return gx, gy
class EqTVLoss(nn.Module):
def __init__(self):
super(EqTVLoss, self).__init__()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, pred, trans, input_img, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
pred = (pred + 1.) / 2.
trans = (trans + 1.) / 2.
input_img = (input_img + 1.) / 2.
gxi, gyi = self.calc_gradxy(input_img)
gxj, gyj = self.calc_gradxy(pred*trans)
return weight * 2 * (self.criterion(gxj, gxi) + self.criterion(gyj, gyi))
@staticmethod
def calc_gradxy(t):
gx = t[:, :, 1:, :] - t[:, :, :-1, :]
gy = t[:, :, :, 1:] - t[:, :, :, :-1]
return gx, gy
class GrayLoss(nn.Module):
def __init__(self, weighted_average=False, abs_cos=False):
super(GrayLoss, self).__init__()
self.weighted_average = weighted_average
self.register_buffer('gray', torch.ones((3,)).view(1, 3, 1, 1))
self.zero = torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
self.cosine_sim = nn.CosineSimilarity()
self.abs_cos = abs_cos
if torch.cuda.is_available():
self.cuda()
def forward(self, x, weight=1.0):
if (weight == 0.) or (x.shape[1] < 2):
return self.zero
else:
# pixelwise consine similarity
cosine_sim = self.cosine_sim(x, self.gray)
# pixelwise cosine embedding loss
if self.abs_cos:
cos_embed_loss = 1 - cosine_sim.abs()
else:
cos_embed_loss = (1 - cosine_sim)/2
if self.weighted_average:
x_norm = torch.norm(x, 2, dim=1)
loss = (x_norm * cos_embed_loss).sum() / x_norm.sum()
else:
loss = cos_embed_loss.mean()
return weight * loss
class CenterLoss(nn.Module):
def __init__(self):
super(CenterLoss, self).__init__()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, x, weight=1.0):
if weight == 0. or (x.size(2) == 1 and x.size(3) == 1):
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
bs, cs = x.size(0), x.size(1)
assert cs == 3
x = x.view((bs, cs, -1))
assert x.size(2) > 1
xmean = x.mean(dim=-1, keepdim=True)
return weight * (x - xmean).pow(2).sum(dim=1).sqrt().mean()
class HazelineLoss(nn.Module):
def __init__(self, use_chromaticity=False, weighted_average=False, abs_cos=False, norm_input=False, mask=False):
super(HazelineLoss, self).__init__()
self.use_chromaticity = use_chromaticity
self.weighted_average = weighted_average
self.abs_cos = abs_cos
self.norm_input= norm_input
self.mask = mask
self.cosine_sim = nn.CosineSimilarity()
if torch.cuda.is_available():
self.cuda()
def forward(self, hazy_input, pred, airlight, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
hazy_input = (hazy_input + 1.) / 2.
pred = (pred + 1.) / 2.
mask = 1.
if self.norm_input:
airlight = torch.ones_like(airlight).cuda() if torch.cuda.is_available() else torch.ones_like(airlight)
if self.use_chromaticity:
hazy_input = hazy_input / hazy_input.sum(dim=1, keepdim=True).clamp(min=1e-8)
pred = pred / pred.sum(dim=1, keepdim=True).clamp(min=1e-8)
airlight = airlight / 3.
if self.mask:
mask *= ((hazy_input - airlight).norm(p=2, dim=1, keepdim=True) > 0.01).float()
else:
# by intensity
if self.mask:
mask *= ((hazy_input - airlight).norm(p=2, dim=1, keepdim=True) > 0.25).float()
# pixelwise cosine similarity, [-pi, pi]
cosine_sim = self.cosine_sim(hazy_input - airlight, pred - airlight)
if self.mask:
mask *= (cosine_sim.unsqueeze_(1) > 0.0).float()
# pixelwise cosine embedding loss
if self.abs_cos:
cos_embed_loss = 1 - cosine_sim.abs()
else:
cos_embed_loss = (1 - cosine_sim)/2
loss = (cos_embed_loss * mask).mean()
return weight * loss
class DistantLoss(nn.Module):
def __init__(self):
super(DistantLoss, self).__init__()
if torch.cuda.is_available():
self.cuda()
def forward(self, pred, airlight, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
pred = (pred + 1.) / 2.
janorm = torch.norm(pred - airlight, 2, dim=1)
loss = torch.exp(-janorm).mean()
return weight * loss
class DistantPreserveLoss(nn.Module):
def __init__(self):
super(DistantPreserveLoss, self).__init__()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, pred, pre_pred, airlight, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
pred = (pred + 1.) / 2.
pre_pred = (pre_pred + 1.) / 2.
norm_curr = torch.norm(pred - airlight, 2, dim=1)
norm_prev = torch.norm(pre_pred - airlight, 2, dim=1)
loss = self.criterion(norm_curr, norm_prev)
return weight * loss
class DistancePreserveLoss(nn.Module):
def __init__(self, use_chromaticity=False):
super(DistancePreserveLoss, self).__init__()
self.criterion = nn.MSELoss()
self.use_chromaticity = use_chromaticity
if torch.cuda.is_available():
self.cuda()
def forward(self, pred, pre_pred, airlight, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
pred = (pred + 1.) / 2.
pre_pred = (pre_pred + 1.) / 2.
if self.use_chromaticity:
pred = pred / pred.sum(dim=1, keepdim=True).clamp(min=1e-8)
pre_pred = pre_pred / pre_pred.sum(dim=1, keepdim=True).clamp(min=1e-8)
airlight = airlight / airlight.sum(dim=1, keepdim=True).clamp(min=1e-8)
norm_curr = torch.norm(pred - airlight, 2, dim=1)
norm_prev = torch.norm(pre_pred - airlight, 2, dim=1)
loss = self.criterion(norm_curr, norm_prev)
return weight * loss
class SaturationPreserveLoss(nn.Module):
def __init__(self):
super(SaturationPreserveLoss, self).__init__()
self.criterion = nn.MSELoss()
if torch.cuda.is_available():
self.cuda()
def forward(self, pred, pre_pred, weight=1.0):
if weight == 0.:
return torch.zeros(()).cuda() if torch.cuda.is_available() else torch.zeros(())
else:
pred = (pred + 1.) / 2.
pre_pred = (pre_pred + 1.) / 2.
pred_sat = 1. - pred.min(dim=1)[0] / pred.max(dim=1)[0].clamp(min=1e-8)
pre_pred_sat = 1. - pre_pred.min(dim=1)[0] / pre_pred.max(dim=1)[0].clamp(min=1e-8)
loss = self.criterion(pred_sat, pre_pred_sat)
return weight * loss