-
Notifications
You must be signed in to change notification settings - Fork 92
/
train
executable file
·229 lines (179 loc) · 9.82 KB
/
train
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
#!/usr/bin/env python
import argparse
import os
import sys
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import torch.nn as nn
from torch.autograd import Variable
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from tensorboard_logger import configure, log_value
from models import Generator, Discriminator, FeatureExtractor
from utils import Visualizer
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='cifar100', help='cifar10 | cifar100 | folder')
parser.add_argument('--dataroot', type=str, default='./data', help='path to dataset')
parser.add_argument('--workers', type=int, default=2, help='number of data loading workers')
parser.add_argument('--batchSize', type=int, default=16, help='input batch size')
parser.add_argument('--imageSize', type=int, default=15, help='the low resolution image size')
parser.add_argument('--upSampling', type=int, default=2, help='low to high resolution scaling factor')
parser.add_argument('--nEpochs', type=int, default=100, help='number of epochs to train for')
parser.add_argument('--generatorLR', type=float, default=0.0001, help='learning rate for generator')
parser.add_argument('--discriminatorLR', type=float, default=0.0001, help='learning rate for discriminator')
parser.add_argument('--cuda', action='store_true', help='enables cuda')
parser.add_argument('--nGPU', type=int, default=1, help='number of GPUs to use')
parser.add_argument('--generatorWeights', type=str, default='', help="path to generator weights (to continue training)")
parser.add_argument('--discriminatorWeights', type=str, default='', help="path to discriminator weights (to continue training)")
parser.add_argument('--out', type=str, default='checkpoints', help='folder to output model checkpoints')
opt = parser.parse_args()
print(opt)
try:
os.makedirs(opt.out)
except OSError:
pass
if torch.cuda.is_available() and not opt.cuda:
print("WARNING: You have a CUDA device, so you should probably run with --cuda")
transform = transforms.Compose([transforms.RandomCrop(opt.imageSize*opt.upSampling),
transforms.ToTensor()])
normalize = transforms.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, 0.225])
scale = transforms.Compose([transforms.ToPILImage(),
transforms.Scale(opt.imageSize),
transforms.ToTensor(),
transforms.Normalize(mean = [0.485, 0.456, 0.406],
std = [0.229, 0.224, 0.225])
])
if opt.dataset == 'folder':
# folder dataset
dataset = datasets.ImageFolder(root=opt.dataroot, transform=transform)
elif opt.dataset == 'cifar10':
dataset = datasets.CIFAR10(root=opt.dataroot, train=True, download=True, transform=transform)
elif opt.dataset == 'cifar100':
dataset = datasets.CIFAR100(root=opt.dataroot, train=True, download=True, transform=transform)
assert dataset
dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batchSize,
shuffle=True, num_workers=int(opt.workers))
generator = Generator(16, opt.upSampling)
if opt.generatorWeights != '':
generator.load_state_dict(torch.load(opt.generatorWeights))
print generator
discriminator = Discriminator()
if opt.discriminatorWeights != '':
discriminator.load_state_dict(torch.load(opt.discriminatorWeights))
print discriminator
# For the content loss
feature_extractor = FeatureExtractor(torchvision.models.vgg19(pretrained=True))
print feature_extractor
content_criterion = nn.MSELoss()
adversarial_criterion = nn.BCELoss()
ones_const = Variable(torch.ones(opt.batchSize, 1))
# if gpu is to be used
if opt.cuda:
generator.cuda()
discriminator.cuda()
feature_extractor.cuda()
content_criterion.cuda()
adversarial_criterion.cuda()
ones_const = ones_const.cuda()
optim_generator = optim.Adam(generator.parameters(), lr=opt.generatorLR)
optim_discriminator = optim.Adam(discriminator.parameters(), lr=opt.discriminatorLR)
configure('logs/' + opt.dataset + '-' + str(opt.batchSize) + '-' + str(opt.generatorLR) + '-' + str(opt.discriminatorLR), flush_secs=5)
visualizer = Visualizer(image_size=opt.imageSize*opt.upSampling)
low_res = torch.FloatTensor(opt.batchSize, 3, opt.imageSize, opt.imageSize)
# Pre-train generator using raw MSE loss
print 'Generator pre-training'
for epoch in range(2):
mean_generator_content_loss = 0.0
for i, data in enumerate(dataloader):
# Generate data
high_res_real, _ = data
# Downsample images to low resolution
for j in range(opt.batchSize):
low_res[j] = scale(high_res_real[j])
high_res_real[j] = normalize(high_res_real[j])
# Generate real and fake inputs
if opt.cuda:
high_res_real = Variable(high_res_real.cuda())
high_res_fake = generator(Variable(low_res).cuda())
else:
high_res_real = Variable(high_res_real)
high_res_fake = generator(Variable(low_res))
######### Train generator #########
generator.zero_grad()
generator_content_loss = content_criterion(high_res_fake, high_res_real)
mean_generator_content_loss += generator_content_loss.data[0]
generator_content_loss.backward()
optim_generator.step()
######### Status and display #########
sys.stdout.write('\r[%d/%d][%d/%d] Generator_MSE_Loss: %.4f' % (epoch, 2, i, len(dataloader), generator_content_loss.data[0]))
visualizer.show(low_res, high_res_real.cpu().data, high_res_fake.cpu().data)
sys.stdout.write('\r[%d/%d][%d/%d] Generator_MSE_Loss: %.4f\n' % (epoch, 2, i, len(dataloader), mean_generator_content_loss/len(dataloader)))
log_value('generator_mse_loss', mean_generator_content_loss/len(dataloader), epoch)
# Do checkpointing
torch.save(generator.state_dict(), '%s/generator_pretrain.pth' % opt.out)
# SRGAN training
optim_generator = optim.Adam(generator.parameters(), lr=opt.generatorLR*0.1)
optim_discriminator = optim.Adam(discriminator.parameters(), lr=opt.discriminatorLR*0.1)
print 'SRGAN training'
for epoch in range(opt.nEpochs):
mean_generator_content_loss = 0.0
mean_generator_adversarial_loss = 0.0
mean_generator_total_loss = 0.0
mean_discriminator_loss = 0.0
for i, data in enumerate(dataloader):
# Generate data
high_res_real, _ = data
# Downsample images to low resolution
for j in range(opt.batchSize):
low_res[j] = scale(high_res_real[j])
high_res_real[j] = normalize(high_res_real[j])
# Generate real and fake inputs
if opt.cuda:
high_res_real = Variable(high_res_real.cuda())
high_res_fake = generator(Variable(low_res).cuda())
target_real = Variable(torch.rand(opt.batchSize,1)*0.5 + 0.7).cuda()
target_fake = Variable(torch.rand(opt.batchSize,1)*0.3).cuda()
else:
high_res_real = Variable(high_res_real)
high_res_fake = generator(Variable(low_res))
target_real = Variable(torch.rand(opt.batchSize,1)*0.5 + 0.7)
target_fake = Variable(torch.rand(opt.batchSize,1)*0.3)
######### Train discriminator #########
discriminator.zero_grad()
discriminator_loss = adversarial_criterion(discriminator(high_res_real), target_real) + \
adversarial_criterion(discriminator(Variable(high_res_fake.data)), target_fake)
mean_discriminator_loss += discriminator_loss.data[0]
discriminator_loss.backward()
optim_discriminator.step()
######### Train generator #########
generator.zero_grad()
real_features = Variable(feature_extractor(high_res_real).data)
fake_features = feature_extractor(high_res_fake)
generator_content_loss = content_criterion(high_res_fake, high_res_real) + 0.006*content_criterion(fake_features, real_features)
mean_generator_content_loss += generator_content_loss.data[0]
generator_adversarial_loss = adversarial_criterion(discriminator(high_res_fake), ones_const)
mean_generator_adversarial_loss += generator_adversarial_loss.data[0]
generator_total_loss = generator_content_loss + 1e-3*generator_adversarial_loss
mean_generator_total_loss += generator_total_loss.data[0]
generator_total_loss.backward()
optim_generator.step()
######### Status and display #########
sys.stdout.write('\r[%d/%d][%d/%d] Discriminator_Loss: %.4f Generator_Loss (Content/Advers/Total): %.4f/%.4f/%.4f' % (epoch, opt.nEpochs, i, len(dataloader),
discriminator_loss.data[0], generator_content_loss.data[0], generator_adversarial_loss.data[0], generator_total_loss.data[0]))
visualizer.show(low_res, high_res_real.cpu().data, high_res_fake.cpu().data)
sys.stdout.write('\r[%d/%d][%d/%d] Discriminator_Loss: %.4f Generator_Loss (Content/Advers/Total): %.4f/%.4f/%.4f\n' % (epoch, opt.nEpochs, i, len(dataloader),
mean_discriminator_loss/len(dataloader), mean_generator_content_loss/len(dataloader),
mean_generator_adversarial_loss/len(dataloader), mean_generator_total_loss/len(dataloader)))
log_value('generator_content_loss', mean_generator_content_loss/len(dataloader), epoch)
log_value('generator_adversarial_loss', mean_generator_adversarial_loss/len(dataloader), epoch)
log_value('generator_total_loss', mean_generator_total_loss/len(dataloader), epoch)
log_value('discriminator_loss', mean_discriminator_loss/len(dataloader), epoch)
# Do checkpointing
torch.save(generator.state_dict(), '%s/generator_final.pth' % opt.out)
torch.save(discriminator.state_dict(), '%s/discriminator_final.pth' % opt.out)
# Avoid closing
while True:
pass