-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain_LOL.py
231 lines (179 loc) · 7.79 KB
/
train_LOL.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
import argparse
import itertools
import time
import datetime
import sys
from torchvision.utils import save_image
from torch.utils.data import DataLoader
from models_x import *
from datasets_LOL import *
import torch
parser = argparse.ArgumentParser()
parser.add_argument("--epoch", type=int, default=0, help="epoch to start training from, 0 starts from scratch, >0 starts from saved checkpoints")
parser.add_argument("--n_epochs", type=int, default=2000, help="total number of epochs of training")
parser.add_argument("--dataset_name", type=str, default="LOL", help="name of the dataset")
parser.add_argument("--input_color_space", type=str, default="sRGB", help="input color space: sRGB or XYZ")
parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
parser.add_argument("--lr", type=float, default=0.0001, help="adam: learning rate")
parser.add_argument("--b1", type=float, default=0.9, help="adam: decay of first order momentum of gradient")
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient")
parser.add_argument("--lambda_smooth", type=float, default=0.0001, help="smooth regularization")
parser.add_argument("--lambda_monotonicity", type=float, default=10.0, help="monotonicity regularization")
parser.add_argument("--n_cpu", type=int, default=1, help="number of cpu threads to use during batch generation")
parser.add_argument("--output_dir", type=str, default="LUTs/paired/LOL_400p_3LUT_sm_1e-4_mn_10", help="path to save model")
opt = parser.parse_args()
opt.output_dir = opt.output_dir + '_' + opt.input_color_space
print(opt)
os.makedirs("saved_models/%s" % opt.output_dir, exist_ok=True)
cuda = True if torch.cuda.is_available() else False
# Tensor type
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
# Loss functions
criterion_pixelwise = torch.nn.MSELoss()
# Initialize generator and discriminator
LUT0 = Generator3DLUT_identity()
LUT1 = Generator3DLUT_zero()
LUT2 = Generator3DLUT_zero()
classifier = Classifier()
TV3 = TV_3D()
trilinear_ = TrilinearInterpolation()
if cuda:
LUT0 = LUT0.cuda()
LUT1 = LUT1.cuda()
LUT2 = LUT2.cuda()
classifier = classifier.cuda()
criterion_pixelwise.cuda()
TV3.cuda()
TV3.weight_r = TV3.weight_r.type(Tensor)
TV3.weight_g = TV3.weight_g.type(Tensor)
TV3.weight_b = TV3.weight_b.type(Tensor)
if opt.epoch != 0:
# Load pretrained models
LUTs = torch.load("saved_models/%s/LUTs_%d.pth" % (opt.output_dir, opt.epoch))
LUT0.load_state_dict(LUTs["0"])
LUT1.load_state_dict(LUTs["1"])
LUT2.load_state_dict(LUTs["2"])
classifier.load_state_dict(torch.load("saved_models/%s/classifier_%d.pth" % (opt.output_dir, opt.epoch)))
else:
# Initialize weights
classifier.apply(weights_init_normal_classifier)
torch.nn.init.constant_(classifier.model[16].bias.data, 1.0)
# Optimizers
optimizer_G = torch.optim.Adam(itertools.chain(classifier.parameters(), LUT0.parameters(), LUT1.parameters(), LUT2.parameters()), lr=opt.lr, betas=(opt.b1, opt.b2))
if opt.input_color_space == 'sRGB':
dataloader = DataLoader(
ImageDataset_sRGB("./data/%s" % opt.dataset_name, mode = "train"),
batch_size=opt.batch_size,
shuffle=True,
num_workers=opt.n_cpu,
)
psnr_dataloader = DataLoader(
ImageDataset_sRGB("./data/%s" % opt.dataset_name, mode="test"),
batch_size=1,
shuffle=False,
num_workers=1,
)
def generator_train(img):
pred = classifier(img).squeeze()
if len(pred.shape) == 1:
pred = pred.unsqueeze(0)
gen_A0 = LUT0(img)
gen_A1 = LUT1(img)
gen_A2 = LUT2(img)
weights_norm = torch.mean(pred ** 2)
combine_A = img.new(img.size())
for b in range(img.size(0)):
combine_A[b,:,:,:] = pred[b,0] * gen_A0[b,:,:,:] + pred[b,1] * gen_A1[b,:,:,:] + pred[b,2] * gen_A2[b,:,:,:]
return combine_A, weights_norm
def generator_eval(img):
pred = classifier(img).squeeze()
LUT = pred[0] * LUT0.LUT + pred[1] * LUT1.LUT + pred[2] * LUT2.LUT
weights_norm = torch.mean(pred ** 2)
combine_A = img.new(img.size())
_, combine_A = trilinear_(LUT,img)
return combine_A, weights_norm
def calculate_psnr():
classifier.eval()
avg_psnr = 0
for i, batch in enumerate(psnr_dataloader):
real_A = Variable(batch["A_input"].type(Tensor))
real_B = Variable(batch["A_exptC"].type(Tensor))
fake_B, weights_norm = generator_eval(real_A)
fake_B = torch.round(fake_B*255)
real_B = torch.round(real_B*255)
mse = criterion_pixelwise(fake_B, real_B)
psnr = 10 * math.log10(255.0 * 255.0 / mse.item())
avg_psnr += psnr
return avg_psnr/ len(psnr_dataloader)
def visualize_result(epoch):
"""Saves a generated sample from the validation set"""
classifier.eval()
os.makedirs("images/%s/" % opt.output_dir +str(epoch), exist_ok=True)
for i, batch in enumerate(psnr_dataloader):
real_A = Variable(batch["A_input"].type(Tensor))
real_B = Variable(batch["A_exptC"].type(Tensor))
img_name = batch["input_name"]
fake_B, weights_norm = generator_eval(real_A)
img_sample = torch.cat((real_A.data, fake_B.data, real_B.data), -1)
fake_B = torch.round(fake_B*255)
real_B = torch.round(real_B*255)
mse = criterion_pixelwise(fake_B, real_B)
psnr = 10 * math.log10(255.0 * 255.0 / mse.item())
save_image(img_sample, "images/%s/%s/%s.jpg" % (opt.output_dir,epoch, img_name[0]+'_'+str(psnr)[:5]), nrow=3, normalize=False)
# ----------
# Training
# ----------
prev_time = time.time()
max_psnr = 0
max_epoch = 0
for epoch in range(opt.epoch, opt.n_epochs):
mse_avg = 0
psnr_avg = 0
classifier.train()
for i, batch in enumerate(dataloader):
# Model inputs
real_A = Variable(batch["A_input"].type(Tensor))
real_B = Variable(batch["A_exptC"].type(Tensor))
# ------------------
# Train Generators
# ------------------
optimizer_G.zero_grad()
fake_B, weights_norm = generator_train(real_A)
# Pixel-wise loss
mse = criterion_pixelwise(fake_B, real_B)
tv0, mn0 = TV3(LUT0)
tv1, mn1 = TV3(LUT1)
tv2, mn2 = TV3(LUT2)
tv_cons = tv0 + tv1 + tv2
mn_cons = mn0 + mn1 + mn2
loss = mse + opt.lambda_smooth * (weights_norm + tv_cons) + opt.lambda_monotonicity * mn_cons
psnr_avg += 10 * math.log10(1 / mse.item())
mse_avg += mse.item()
loss.backward()
optimizer_G.step()
# --------------
# Log Progress
# --------------
# Determine approximate time left
batches_done = epoch * len(dataloader) + i
batches_left = opt.n_epochs * len(dataloader) - batches_done
time_left = datetime.timedelta(seconds=batches_left * (time.time() - prev_time))
prev_time = time.time()
# Print log
sys.stdout.write(
"\r[Epoch %d/%d] [Batch %d/%d] [psnr: %f, tv: %f, wnorm: %f, mn: %f] ETA: %s"
% (epoch,opt.n_epochs,i,len(dataloader),psnr_avg / (i+1),tv_cons, weights_norm, mn_cons, time_left,
)
)
avg_psnr = calculate_psnr()
if avg_psnr > max_psnr:
max_psnr = avg_psnr
max_epoch = epoch
# Save model checkpoints
LUTs = {"0": LUT0.state_dict(),"1": LUT1.state_dict(),"2": LUT2.state_dict()}
torch.save(LUTs, "saved_models/%s/LUTs_%d.pth" % (opt.output_dir, epoch))
torch.save(classifier.state_dict(), "saved_models/%s/classifier_%d.pth" % (opt.output_dir, epoch))
file = open('saved_models/%s/result.txt' % opt.output_dir,'a')
file.write(" [PSNR: %f] [max PSNR: %f, epoch: %d]\n"% (avg_psnr, max_psnr, max_epoch))
file.close()
sys.stdout.write(" [PSNR: %f] [max PSNR: %f, epoch: %d]\n"% (avg_psnr, max_psnr, max_epoch))