-
Notifications
You must be signed in to change notification settings - Fork 6
/
Losses.py
228 lines (162 loc) · 6.9 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
""" Module implementing various loss functions """
import torch as th
# =============================================================
# Interface for the losses
# =============================================================
class GANLoss:
""" Base class for all losses
@args:
dis: Discriminator used for calculating the loss
Note this must be a part of the GAN framework
"""
def __init__(self, dis):
self.dis = dis
def dis_loss(self, real_samps, fake_samps):
"""
calculate the discriminator loss using the following data
:param real_samps: batch of real samples
:param fake_samps: batch of generated (fake) samples
:return: loss => calculated loss Tensor
"""
raise NotImplementedError("dis_loss method has not been implemented")
def gen_loss(self, real_samps, fake_samps):
"""
calculate the generator loss
:param real_samps: batch of real samples
:param fake_samps: batch of generated (fake) samples
:return: loss => calculated loss Tensor
"""
raise NotImplementedError("gen_loss method has not been implemented")
# =============================================================
# Normal versions of the Losses:
# =============================================================
class StandardGAN(GANLoss):
def __init__(self, dis):
from torch.nn import BCEWithLogitsLoss
super().__init__(dis)
# define the criterion and activation used for object
self.criterion = BCEWithLogitsLoss()
def dis_loss(self, real_samps, fake_samps):
# small assertion:
assert real_samps.device == fake_samps.device, \
"Real and Fake samples are not on the same device"
# device for computations:
device = fake_samps.device
# predictions for real images and fake images separately :
r_preds = self.dis(real_samps)
f_preds = self.dis(fake_samps)
# calculate the real loss:
real_loss = self.criterion(
th.squeeze(r_preds),
th.ones(real_samps.shape[0]).to(device))
# calculate the fake loss:
fake_loss = self.criterion(
th.squeeze(f_preds),
th.zeros(fake_samps.shape[0]).to(device))
# return final losses
return (real_loss + fake_loss) / 2
def gen_loss(self, _, fake_samps):
preds, _, _ = self.dis(fake_samps)
return self.criterion(th.squeeze(preds),
th.ones(fake_samps.shape[0]).to(fake_samps.device))
class WGAN_GP(GANLoss):
def __init__(self, dis, drift=0.001, use_gp=False):
super().__init__(dis)
self.drift = drift
self.use_gp = use_gp
def __gradient_penalty(self, real_samps, fake_samps, reg_lambda=10):
"""
private helper for calculating the gradient penalty
:param real_samps: real samples
:param fake_samps: fake samples
:param reg_lambda: regularisation lambda
:return: tensor (gradient penalty)
"""
batch_size = real_samps.shape[0]
# generate random epsilon
epsilon = th.rand((batch_size, 1, 1, 1)).to(fake_samps.device)
# create the merge of both real and fake samples
merged = (epsilon * real_samps) + ((1 - epsilon) * fake_samps)
merged.requires_grad = True
# forward pass
op = self.dis(merged)
# perform backward pass from op to merged for obtaining the gradients
op.backward(gradient=th.ones_like(op), create_graph=True)
gradient = merged.grad # this is the gradient of the op wrt. merged
# calculate the penalty using these gradients
gradient = gradient.view(gradient.shape[0], -1)
penalty = reg_lambda * ((gradient.norm(p=2, dim=1) - 1) ** 2).mean()
# return the calculated penalty:
return penalty
def dis_loss(self, real_samps, fake_samps):
# define the (Wasserstein) loss
fake_out = self.dis(fake_samps)
real_out = self.dis(real_samps)
loss = (th.mean(fake_out) - th.mean(real_out)
+ (self.drift * th.mean(real_out ** 2)))
if self.use_gp:
# calculate the WGAN-GP (gradient penalty)
gp = self.__gradient_penalty(real_samps, fake_samps)
loss += gp
return loss
def gen_loss(self, _, fake_samps):
# calculate the WGAN loss for generator
loss = -th.mean(self.dis(fake_samps))
return loss
class LSGAN(GANLoss):
def __init__(self, dis):
super().__init__(dis)
def dis_loss(self, real_samps, fake_samps):
return 0.5 * (((th.mean(self.dis(real_samps)) - 1) ** 2)
+ (th.mean(self.dis(fake_samps))) ** 2)
def gen_loss(self, _, fake_samps):
return 0.5 * ((th.mean(self.dis(fake_samps)) - 1) ** 2)
class LSGAN_SIGMOID(GANLoss):
def __init__(self, dis):
super().__init__(dis)
def dis_loss(self, real_samps, fake_samps):
from torch.nn.functional import sigmoid
real_scores = th.mean(sigmoid(self.dis(real_samps)))
fake_scores = th.mean(sigmoid(self.dis(fake_samps)))
return 0.5 * (((real_scores - 1) ** 2) + (fake_scores ** 2))
def gen_loss(self, _, fake_samps):
from torch.nn.functional import sigmoid
scores = th.mean(sigmoid(self.dis(fake_samps)))
return 0.5 * ((scores - 1) ** 2)
class HingeGAN(GANLoss):
def __init__(self, dis):
super().__init__(dis)
def dis_loss(self, real_samps, fake_samps):
r_preds, r_mus, r_sigmas = self.dis(real_samps)
f_preds, f_mus, f_sigmas = self.dis(fake_samps)
loss = (th.mean(th.nn.ReLU()(1 - r_preds)) +
th.mean(th.nn.ReLU()(1 + f_preds)))
return loss
def gen_loss(self, _, fake_samps):
return -th.mean(self.dis(fake_samps))
class RelativisticAverageHingeGAN(GANLoss):
def __init__(self, dis):
super().__init__(dis)
def dis_loss(self, real_samps, fake_samps):
# Obtain predictions
r_preds = self.dis(real_samps)
f_preds = self.dis(fake_samps)
# difference between real and fake:
r_f_diff = r_preds - th.mean(f_preds)
# difference between fake and real samples
f_r_diff = f_preds - th.mean(r_preds)
# return the loss
loss = (th.mean(th.nn.ReLU()(1 - r_f_diff))
+ th.mean(th.nn.ReLU()(1 + f_r_diff)))
return loss
def gen_loss(self, real_samps, fake_samps):
# Obtain predictions
r_preds = self.dis(real_samps)
f_preds = self.dis(fake_samps)
# difference between real and fake:
r_f_diff = r_preds - th.mean(f_preds)
# difference between fake and real samples
f_r_diff = f_preds - th.mean(r_preds)
# return the loss
return (th.mean(th.nn.ReLU()(1 + r_f_diff))
+ th.mean(th.nn.ReLU()(1 - f_r_diff)))