-
Notifications
You must be signed in to change notification settings - Fork 0
/
loss.py
273 lines (213 loc) · 8.99 KB
/
loss.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
import numpy as np
import torch
import torch.nn as nn
class GANLoss:
""" Base class for all losses
"""
def __init__(self, dis):
self.dis = dis
def dis_loss(self, real_samps, fake_samps):
raise NotImplementedError("dis_loss method has not been implemented")
def gen_loss(self, real_samps, fake_samps):
raise NotImplementedError("gen_loss method has not been implemented")
class ConditionalGANLoss:
""" Base class for all conditional losses """
def __init__(self, dis,gen):
self.dis = dis
self.gen = gen
def loss(self,input,real_samps,if_l1=True):
raise NotImplementedError("loss method has not been implemented")
class LSGAN(ConditionalGANLoss):
def __init__(self,dis,gen):
from torch.nn import MSELoss
from torch.nn import L1Loss
super().__init__(dis,gen)
self.criterion=MSELoss()
self.criterion_pix=L1Loss()
def loss(self,input,real_samps,if_l1=True,l1_lambda=10.):
assert real_samps.device == real_samps.device, \
"Real and Fake samples are not on the same device"
if type(input)==list:
dis_input=input[-1]
else:
dis_input=input
fake_samps = self.gen(input)
device = real_samps.device
r_preds = self.dis(real_samps, dis_input)
f_preds = self.dis(fake_samps.detach(), dis_input)
real_loss = self.criterion(
r_preds,
torch.ones(r_preds.size()).to(device)
)
fake_loss = self.criterion(
f_preds,
torch.zeros(f_preds.size()).to(device)
)
dis_loss=real_loss+fake_loss
preds=self.dis(fake_samps,dis_input)
gen_loss=self.criterion(
preds,
torch.ones(f_preds.size()).to(fake_samps.device)
)
if if_l1:
gen_loss+=l1_lambda*self.criterion_pix(fake_samps,real_samps)
return dis_loss,gen_loss
class StandardGAN(ConditionalGANLoss):
def __init__(self, dis,gen):
from torch.nn import BCEWithLogitsLoss
super().__init__(dis,gen)
# define the criterion and activation used for object
self.criterion = BCEWithLogitsLoss()
def loss(self,input,real_samps):
# small assertion:
fake_samps=self.gen(input)
assert real_samps.device == fake_samps.device, \
"Real and Fake samples are not on the same device"
if type(input)==list:
input=input[-1]
# device for computations:
device = fake_samps.device
# predictions for real images and fake images separately :
r_preds = self.dis(real_samps, input)
f_preds = self.dis(fake_samps.detach(), input)
real_loss = self.criterion(
r_preds,
torch.ones(r_preds.size()).to(device)
)
fake_loss = self.criterion(
f_preds,
torch.zeros(f_preds.size()).to(device)
)
dis_loss = real_loss + fake_loss
preds = self.dis(fake_samps, input)
gen_loss = self.criterion(
preds,
torch.ones(f_preds.size()).to(fake_samps.device)
)
return dis_loss, gen_loss
class HingeGAN(ConditionalGANLoss):
def __init__(self, dis,gen):
from torch.nn import L1Loss
super().__init__(dis,gen)
self.criterion_l1=L1Loss()
def loss(self,input,real_samps,if_l1=True,l1_lambda=10.):
if type(input)==list:
dis_input=input[-1]
else:
dis_input=input
fake_samps=self.gen(input)
r_preds = self.dis(real_samps, dis_input)
f_preds = self.dis(fake_samps.detach(), dis_input)
dis_loss = (torch.mean(nn.ReLU()(1 - r_preds)) +
torch.mean(nn.ReLU()(1 + f_preds)))
preds = self.dis(fake_samps,dis_input)
gen_loss = -torch.mean(preds)
if if_l1:
gen_loss+=l1_lambda*self.criterion_pix(fake_samps,real_samps)
return dis_loss,gen_loss
class RelativisticAverageHingeGAN(ConditionalGANLoss):
def __init__(self, dis,gen):
from torch.nn import L1Loss
super().__init__(dis,gen)
self.criterion_pix=L1Loss()
def loss(self,input,real_samps,if_l1=True,l1_lambda=10.):
if type(input)==list:
dis_input=input[-1]
else:
dis_input=input
fake_samps = self.gen(input)
r_preds = self.dis(real_samps, dis_input)
f_preds = self.dis(fake_samps.detach(), dis_input)
# difference between real and fake:
r_f_diff = r_preds - torch.mean(f_preds)
# difference between fake and real samples
f_r_diff = f_preds - torch.mean(r_preds)
# return the loss
dis_loss = (torch.mean(nn.ReLU()(1 - r_f_diff))
+ torch.mean(nn.ReLU()(1 + f_r_diff)))
# Obtain predictions
# r_preds = self.dis(real_samps, input)
f_preds = self.dis(fake_samps, dis_input)
# difference between real and fake:
r_f_diff = r_preds - torch.mean(f_preds)
# difference between fake and real samples
# f_r_diff = f_preds - torch.mean(r_preds)
# return the loss
gen_loss = (torch.mean(nn.ReLU()(1 + r_f_diff))
+ torch.mean(nn.ReLU()(1 - f_r_diff)))
if if_l1:
gen_loss+=l1_lambda*self.criterion_pix(fake_samps,real_samps)
return dis_loss,gen_loss
class LogisticGAN(ConditionalGANLoss):
def __init__(self, dis,gen):
from torch.nn import L1Loss
super().__init__(dis,gen)
self.criterion_pix=L1Loss()
# gradient penalty
def R1Penalty(self, real_img, input):
# TODO: use_loss_scaling, for fp16
apply_loss_scaling = lambda x: x * torch.exp(x * torch.Tensor([np.float32(np.log(2.0))]).to(real_img.device))
undo_loss_scaling = lambda x: x * torch.exp(-x * torch.Tensor([np.float32(np.log(2.0))]).to(real_img.device))
real_img = torch.autograd.Variable(real_img, requires_grad=True)
real_logit = self.dis(real_img,input)
# real_logit = apply_loss_scaling(torch.sum(real_logit))
real_grads = torch.autograd.grad(outputs=real_logit, inputs=real_img,
grad_outputs=torch.ones(real_logit.size()).to(real_img.device),
create_graph=True, retain_graph=True)[0].view(real_img.size(0), -1)
# real_grads = undo_loss_scaling(real_grads)
r1_penalty = torch.sum(torch.mul(real_grads, real_grads))
return r1_penalty
def loss(self,input,real_samps,if_l1=True,l1_lambda=10.,r1_gamma=10.0):
if type(input)==list:
dis_input=input[-1]
else:
dis_input=input
fake_samps=self.gen(input)
r_preds = self.dis(real_samps, dis_input)
f_preds = self.dis(fake_samps.detach(), dis_input)
dis_loss = torch.mean(nn.Softplus()(f_preds)) + torch.mean(nn.Softplus()(-r_preds))
if r1_gamma != 0.0:
r1_penalty = self.R1Penalty(real_samps.detach(),dis_input) * (r1_gamma * 0.5)
dis_loss += r1_penalty
f_preds = self.dis(fake_samps, dis_input)
gen_loss=torch.mean(nn.Softplus()(-f_preds))
if if_l1:
gen_loss+=l1_lambda*self.criterion_pix(fake_samps,real_samps)
return dis_loss,gen_loss
class WassersteinLoss(ConditionalGANLoss):
def __init__(self,dis,gen):
from torch.nn import L1Loss
super(WassersteinLoss, self).__init__(dis,gen)
self.criterion_pix=L1Loss()
def gradient_penalty(self, y,real_img):
weight = torch.ones(y.size()).to(real_img.device)
dydx = torch.autograd.grad(outputs=y,
inputs=real_img,
grad_outputs=weight,
retain_graph=True,
create_graph=True,
only_inputs=True)[0]
dydx = dydx.view(dydx.size(0), -1)
# 将dy/dx转换为batch,n
dydx_l2norm = torch.sqrt(torch.sum(dydx ** 2, dim=1))
return torch.mean((dydx_l2norm - 1) ** 2)
def loss(self,input,real_samps,if_l1=True,l1_lambda=10.,gp_alpha=10.):
if type(input)==list:
dis_input=input[-1]
else:
dis_input=input
fake_samps=self.gen(input)
r_preds = self.dis(real_samps, dis_input)
f_preds = self.dis(fake_samps.detach(), dis_input)
real_loss = -torch.mean(r_preds)
fake_loss = torch.mean(f_preds)
alpha = torch.rand(real_samps.size(0), 1, 1, 1).to(real_samps.device)
x_hat = (alpha * real_samps.detach() + (1 - alpha) * fake_samps.detach()).requires_grad_(True)
g_preds = self.dis(x_hat, dis_input)
loss_gp = self.gradient_penalty(g_preds, x_hat)
dis_loss=real_loss+fake_loss+gp_alpha*loss_gp
f_preds=self.dis(fake_samps,dis_input)
gen_loss=-torch.mean(f_preds)
if if_l1:
gen_loss+=l1_lambda*self.criterion_pix(fake_samps,real_samps)
return dis_loss,gen_loss