PATN.py
10.8 KB
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
import numpy as np
import torch
import os
from collections import OrderedDict
from torch.autograd import Variable
import itertools
import util.util as util
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
# losses
from losses.L1_plus_perceptualLoss import L1_plus_perceptualLoss
import sys
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn as nn
class TransferModel(BaseModel):
def name(self):
return 'TransferModel'
def initialize(self, opt):
BaseModel.initialize(self, opt)
nb = opt.batchSize
size = opt.fineSize
self.input_P1_set = self.Tensor(nb, opt.P_input_nc, size, size)
self.input_BP1_set = self.Tensor(nb, opt.BP_input_nc, size, size)
self.input_P2_set = self.Tensor(nb, opt.P_input_nc, size, size)
self.input_BP2_set = self.Tensor(nb, opt.BP_input_nc, size, size)
input_nc = [opt.P_input_nc, opt.BP_input_nc+opt.BP_input_nc]
self.netG = networks.define_G(input_nc, opt.P_input_nc,
opt.ngf, opt.which_model_netG, opt.norm, not opt.no_dropout, opt.init_type, self.gpu_ids,
n_downsampling=opt.G_n_downsampling)
if self.isTrain:
use_sigmoid = opt.no_lsgan
if opt.with_D_PB:
self.netD_PB = networks.define_D(opt.P_input_nc+opt.BP_input_nc, opt.ndf,
opt.which_model_netD,
opt.n_layers_D, opt.norm, use_sigmoid, opt.init_type, self.gpu_ids,
not opt.no_dropout_D,
n_downsampling = opt.D_n_downsampling)
if opt.with_D_PP:
self.netD_PP = networks.define_D(opt.P_input_nc+opt.P_input_nc, opt.ndf,
opt.which_model_netD,
opt.n_layers_D, opt.norm, use_sigmoid, opt.init_type, self.gpu_ids,
not opt.no_dropout_D,
n_downsampling = opt.D_n_downsampling)
if not self.isTrain or opt.continue_train:
which_epoch = opt.which_epoch
self.load_network(self.netG, 'netG', which_epoch)
if self.isTrain:
if opt.with_D_PB:
self.load_network(self.netD_PB, 'netD_PB', which_epoch)
if opt.with_D_PP:
self.load_network(self.netD_PP, 'netD_PP', which_epoch)
if self.isTrain:
self.old_lr = opt.lr
self.fake_PP_pool = ImagePool(opt.pool_size)
self.fake_PB_pool = ImagePool(opt.pool_size)
# define loss functions
self.criterionGAN = networks.GANLoss(use_lsgan=not opt.no_lsgan, tensor=self.Tensor)
if opt.L1_type == 'origin':
self.criterionL1 = torch.nn.L1Loss()
elif opt.L1_type == 'l1_plus_perL1':
self.criterionL1 = L1_plus_perceptualLoss(opt.lambda_A, opt.lambda_B, opt.perceptual_layers, self.gpu_ids, opt.percep_is_l1)
else:
raise Excption('Unsurportted type of L1!')
# initialize optimizers
self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
if opt.with_D_PB:
self.optimizer_D_PB = torch.optim.Adam(self.netD_PB.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
if opt.with_D_PP:
self.optimizer_D_PP = torch.optim.Adam(self.netD_PP.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
self.optimizers = []
self.schedulers = []
self.optimizers.append(self.optimizer_G)
if opt.with_D_PB:
self.optimizers.append(self.optimizer_D_PB)
if opt.with_D_PP:
self.optimizers.append(self.optimizer_D_PP)
for optimizer in self.optimizers:
self.schedulers.append(networks.get_scheduler(optimizer, opt))
print('---------- Networks initialized -------------')
networks.print_network(self.netG)
if self.isTrain:
if opt.with_D_PB:
networks.print_network(self.netD_PB)
if opt.with_D_PP:
networks.print_network(self.netD_PP)
print('-----------------------------------------------')
def set_input(self, input):
input_P1, input_BP1 = input['P1'], input['BP1']
input_P2, input_BP2 = input['P2'], input['BP2']
self.input_P1_set.resize_(input_P1.size()).copy_(input_P1)
self.input_BP1_set.resize_(input_BP1.size()).copy_(input_BP1)
self.input_P2_set.resize_(input_P2.size()).copy_(input_P2)
self.input_BP2_set.resize_(input_BP2.size()).copy_(input_BP2)
self.image_paths = input['P1_path'][0] + '___' + input['P2_path'][0]
def forward(self):
self.input_P1 = Variable(self.input_P1_set)
self.input_BP1 = Variable(self.input_BP1_set)
self.input_P2 = Variable(self.input_P2_set)
self.input_BP2 = Variable(self.input_BP2_set)
G_input = [self.input_P1,
torch.cat((self.input_BP1, self.input_BP2), 1)]
self.fake_p2 = self.netG(G_input)
def test(self):
self.input_P1 = Variable(self.input_P1_set)
self.input_BP1 = Variable(self.input_BP1_set)
self.input_P2 = Variable(self.input_P2_set)
self.input_BP2 = Variable(self.input_BP2_set)
G_input = [self.input_P1,
torch.cat((self.input_BP1, self.input_BP2), 1)]
self.fake_p2 = self.netG(G_input)
# get image paths
def get_image_paths(self):
return self.image_paths
def backward_G(self):
if self.opt.with_D_PB:
pred_fake_PB = self.netD_PB(torch.cat((self.fake_p2, self.input_BP2), 1))
self.loss_G_GAN_PB = self.criterionGAN(pred_fake_PB, True)
if self.opt.with_D_PP:
pred_fake_PP = self.netD_PP(torch.cat((self.fake_p2, self.input_P1), 1))
self.loss_G_GAN_PP = self.criterionGAN(pred_fake_PP, True)
# L1 loss
if self.opt.L1_type == 'l1_plus_perL1' :
losses = self.criterionL1(self.fake_p2, self.input_P2)
self.loss_G_L1 = losses[0]
self.loss_originL1 = losses[1].data
self.loss_perceptual = losses[2].data
else:
self.loss_G_L1 = self.criterionL1(self.fake_p2, self.input_P2) * self.opt.lambda_A
pair_L1loss = self.loss_G_L1
if self.opt.with_D_PB:
pair_GANloss = self.loss_G_GAN_PB * self.opt.lambda_GAN
if self.opt.with_D_PP:
pair_GANloss += self.loss_G_GAN_PP * self.opt.lambda_GAN
pair_GANloss = pair_GANloss / 2
else:
if self.opt.with_D_PP:
pair_GANloss = self.loss_G_GAN_PP * self.opt.lambda_GAN
if self.opt.with_D_PB or self.opt.with_D_PP:
pair_loss = pair_L1loss + pair_GANloss
else:
pair_loss = pair_L1loss
pair_loss.backward()
self.pair_L1loss = pair_L1loss.data
if self.opt.with_D_PB or self.opt.with_D_PP:
self.pair_GANloss = pair_GANloss.data
def backward_D_basic(self, netD, real, fake):
# Real
pred_real = netD(real)
loss_D_real = self.criterionGAN(pred_real, True) * self.opt.lambda_GAN
# Fake
pred_fake = netD(fake.detach())
loss_D_fake = self.criterionGAN(pred_fake, False) * self.opt.lambda_GAN
# Combined loss
loss_D = (loss_D_real + loss_D_fake) * 0.5
# backward
loss_D.backward()
return loss_D
# D: take(P, B) as input
def backward_D_PB(self):
real_PB = torch.cat((self.input_P2, self.input_BP2), 1)
# fake_PB = self.fake_PB_pool.query(torch.cat((self.fake_p2, self.input_BP2), 1))
fake_PB = self.fake_PB_pool.query( torch.cat((self.fake_p2, self.input_BP2), 1).data )
loss_D_PB = self.backward_D_basic(self.netD_PB, real_PB, fake_PB)
self.loss_D_PB = loss_D_PB.data
# D: take(P, P') as input
def backward_D_PP(self):
real_PP = torch.cat((self.input_P2, self.input_P1), 1)
# fake_PP = self.fake_PP_pool.query(torch.cat((self.fake_p2, self.input_P1), 1))
fake_PP = self.fake_PP_pool.query( torch.cat((self.fake_p2, self.input_P1), 1).data )
loss_D_PP = self.backward_D_basic(self.netD_PP, real_PP, fake_PP)
self.loss_D_PP = loss_D_PP.data
def optimize_parameters(self):
# forward
self.forward()
self.optimizer_G.zero_grad()
self.backward_G()
self.optimizer_G.step()
# D_P
if self.opt.with_D_PP:
for i in range(self.opt.DG_ratio):
self.optimizer_D_PP.zero_grad()
self.backward_D_PP()
self.optimizer_D_PP.step()
# D_BP
if self.opt.with_D_PB:
for i in range(self.opt.DG_ratio):
self.optimizer_D_PB.zero_grad()
self.backward_D_PB()
self.optimizer_D_PB.step()
def get_current_errors(self):
ret_errors = OrderedDict([ ('pair_L1loss', self.pair_L1loss)])
if self.opt.with_D_PP:
ret_errors['D_PP'] = self.loss_D_PP
if self.opt.with_D_PB:
ret_errors['D_PB'] = self.loss_D_PB
if self.opt.with_D_PB or self.opt.with_D_PP:
ret_errors['pair_GANloss'] = self.pair_GANloss
if self.opt.L1_type == 'l1_plus_perL1':
ret_errors['origin_L1'] = self.loss_originL1
ret_errors['perceptual'] = self.loss_perceptual
return ret_errors
def get_current_visuals(self):
height, width = self.input_P1.size(2), self.input_P1.size(3)
input_P1 = util.tensor2im(self.input_P1.data)
input_P2 = util.tensor2im(self.input_P2.data)
input_BP1 = util.draw_pose_from_map(self.input_BP1.data)[0]
input_BP2 = util.draw_pose_from_map(self.input_BP2.data)[0]
fake_p2 = util.tensor2im(self.fake_p2.data)
vis = np.zeros((height, width*5, 3)).astype(np.uint8) #h, w, c
vis[:, :width, :] = input_P1
vis[:, width:width*2, :] = input_BP1
vis[:, width*2:width*3, :] = input_P2
vis[:, width*3:width*4, :] = input_BP2
vis[:, width*4:, :] = fake_p2
ret_visuals = OrderedDict([('vis', vis)])
return ret_visuals
def save(self, label):
self.save_network(self.netG, 'netG', label, self.gpu_ids)
if self.opt.with_D_PB:
self.save_network(self.netD_PB, 'netD_PB', label, self.gpu_ids)
if self.opt.with_D_PP:
self.save_network(self.netD_PP, 'netD_PP', label, self.gpu_ids)