-
Notifications
You must be signed in to change notification settings - Fork 28
/
train.lua
280 lines (229 loc) · 9.15 KB
/
train.lua
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
-- [SublimeLinter luacheck-globals:+lapp,nn,paths,xlua]
package.path = package.path .. ";./?/init.lua"
local deepwarp = require 'deepwarp'
local nn = require 'nn'
local optim = require 'optim'
local utils = require 'utils'
local xlua = require 'xlua'
local c = require 'trepl.colorize'
require 'cunn'
utils.dispImages = utils.dispImagesTGAN
utils.dispPlot = utils.dispPlotTGAN
local opts = lapp[[
-d,--data_path (default ./) Data path
-s,--snapshot_path (default ./snapshots) Snapshots path
-f,--snapshot_freq (default 50) Snapshots frequency
-t,--test_freq (default 20) Test frequency
-l,--learning_rate (default 1e-4) Learning rate
-b,--batch_size (default 128) Batch size
--beta1 (default 0.5) Adam: beta_1
--delta_vec (default 4) Dimensionality of delta vec
--palette_size (default 1) Number of colors in palette
--append_location Append location maps to the input
--use_anchors Use anchors
--use_all_attrs Use all binary attributes
--main_attr_weight (default 1.0) Weight of the main attribute
--transformer (default Transformer5)
--noblur_half_scale Disable blurring of half scale shifts
--gan_loss_weight (default 1.0) GAN loss weight
--attr_loss_weight (default 1.0) Attribure loss weight
--flow_tv (default 0) Strength of TV denoising for flow
--flow_l1 (default 0) Strength of L1 penalty for flow
--lcm_tv (default 0) Strength of TV denoising for LCM
--lcm_l1 (default 0) Strength of L1 penalty for LCM
--window_idx (default 10) Window index
--window_postfix (default '') Window postfix
]]
opts.blur_half_scale = not opts.noblur_half_scale
opts.noblur_half_scale = nil
print(opts)
local plot_data = {}
local function train(model, provider, criterion, optimizer)
model:training()
local input = {provider.buffers.images, provider.gpu_mu,
provider.buffers.deltas}
if opts.use_anchors then
table.insert(input, provider.buffers.anchor_maps)
end
local target = {provider.buffers.domains, provider.buffers.one_m_domains,
provider.buffers.all_labels}
local grad_divide_by = {2 * opts.batch_size, 2 * opts.batch_size,
opts.batch_size}
local losses = {}
for i = 1, #criterion.criterions do
losses[i] = {}
end
local epoch_done = false
local iter = 0
while not epoch_done do
local cur, total = provider:getProgress()
xlua.progress(cur, total)
epoch_done = provider:nextBatch(opts.batch_size)
local feval = function(x)
if x ~= model.flat_params then
model.flat_params:copy(x)
end
model.flat_grad_params:zero()
local output = model:forward(input)
local f = criterion:forward(output, target) / (2 * opts.batch_size)
local df_do = criterion:backward(output, target)
for i = 1, #df_do do
df_do[i]:div(grad_divide_by[i])
end
model:backward(input, df_do)
return f, model.flat_grad_params
end
optimizer.fun(feval, model.flat_params, optimizer.state)
for i = 1, #criterion.criterions do
losses[i][#losses[i] + 1] =
criterion.criterions[i].output / (2 * opts.batch_size)
end
iter = iter + 1
if iter % 10 == 0 then
utils.dispImages(model, provider, opts.window_idx + 10,
'Train' .. opts.window_postfix)
local plot_entry = {#plot_data}
for i = 1, #criterion.criterions do
table.insert(plot_entry, losses[i][#losses[i]])
end
table.insert(plot_data, plot_entry)
utils.dispPlot(plot_data, opts.window_idx + 20,
'Train' .. opts.window_postfix)
end
end
local _, total = provider:getProgress()
xlua.progress(total, total)
local mean_losses = {}
for i = 1, #criterion.criterions do
mean_losses[i] = torch.mean(torch.FloatTensor(losses[i]))
end
return mean_losses
end
local function test(model, provider, criterion)
model:evaluate()
local input = {provider.buffers.images, provider.gpu_mu,
provider.buffers.deltas}
if opts.use_anchors then
table.insert(input, provider.buffers.anchor_maps)
end
local target = {provider.buffers.domains, provider.buffers.one_m_domains,
provider.buffers.all_labels}
local losses = {}
for i = 1, #criterion.criterions do
losses[i] = {}
end
local epoch_done = false
while not epoch_done do
local cur, total = provider:getProgress()
xlua.progress(cur, total)
epoch_done = provider:nextBatch(opts.batch_size)
local output = model:forward(input)
criterion:forward(output, target)
for i = 1, #criterion.criterions do
losses[i][#losses[i] + 1] =
criterion.criterions[i].output / (2 * opts.batch_size)
end
end
local _, total = provider:getProgress()
xlua.progress(total, total)
local mean_losses = {}
for i = 1, #criterion.criterions do
mean_losses[i] = torch.mean(torch.FloatTensor(losses[i]))
end
return mean_losses
end
---------------------------------------------------------- Create training task
-- Handle attributes settings.
local num_attrs = 1
local attr_weights = nil
if opts.use_all_attrs then
num_attrs = 40
if opts.main_attr_weight > 1.0 then
attr_weights = torch.Tensor(num_attrs):fill(1.0)
attr_weights[32] = opts.main_attr_weight
attr_weights:div(attr_weights:sum())
end
end
-- Setup providers.
local train_data_path = paths.concat(opts.data_path, 'train.npz')
local test_data_path = paths.concat(opts.data_path, 'test.npz')
-- local train_data_path = paths.concat(opts.data_path, 'train_small.npz')
-- local test_data_path = paths.concat(opts.data_path, 'train_small.npz')
local train_provider = deepwarp.Provider(
train_data_path, nil, false, opts.use_all_attrs)
local test_provider = deepwarp.Provider(
test_data_path, train_provider.mu, false, opts.use_all_attrs)
-- Create models.
local transformer = deepwarp[opts.transformer](opts)
local d_encoder = deepwarp.base.createAEncoder()
local a_encoder = d_encoder:clone('weight', 'bias', 'gradWeight', 'gradBias')
local d_classifier = deepwarp.base.attachHead(d_encoder)
local a_classifier = deepwarp.base.attachHead(a_encoder, num_attrs)
local tgan = deepwarp.TGAN(transformer, d_classifier, a_classifier)
tgan:cuda()
tgan:flattenParams()
-- Setup training criteria.
local d_criterion = nn.BCECriterion()
d_criterion.sizeAverage = false
local g_criterion = nn.BCECriterion()
g_criterion.sizeAverage = false
local a_criterion = nn.BCECriterion(attr_weights)
a_criterion.sizeAverage = false
local train_criterion =
nn.ParallelCriterion():add(d_criterion, opts.gan_loss_weight)
:add(g_criterion, opts.gan_loss_weight)
:add(a_criterion, opts.attr_loss_weight)
train_criterion:cuda()
d_criterion = nn.BCECriterion()
d_criterion.sizeAverage = false
g_criterion = nn.BCECriterion()
g_criterion.sizeAverage = false
a_criterion = nn.BCECriterion(attr_weights)
a_criterion.sizeAverage = false
local test_criterion =
nn.ParallelCriterion():add(d_criterion, opts.gan_loss_weight)
:add(g_criterion, opts.gan_loss_weight)
:add(a_criterion, opts.attr_loss_weight)
test_criterion:cuda()
-- Setup optimizer.
local optimizer = {
fun = optim.adam,
state = {
learningRate = opts.learning_rate,
weightDecay = 0.0,
beta1 = opts.beta1
}
}
------------------------------------------------------------------ Run training
local snapshot_template = paths.concat(opts.snapshot_path, '%d.t7')
local start_iter = 1
local end_iter = 2400
tgan:saveParams(snapshot_template:format(start_iter - 1))
if opts.window_postfix ~= '' then
opts.window_postfix = ' (' .. opts.window_postfix .. ')'
end
for epoch = start_iter, end_iter do
print(c.blue '==>' .. ' online epoch # ' .. epoch .. ' [batch size = ' ..
opts.batch_size .. ']')
local tic = torch.tic()
local mean_losses = train(tgan, train_provider, train_criterion, optimizer)
print(('Mean train D loss: ' .. c.cyan '%.8f\n' ..
'Mean train G loss: ' .. c.cyan '%.8f\n' ..
'Mean train A loss: ' .. c.cyan '%.8f\n' ..
'Time: %.2f s'):format(
mean_losses[1], mean_losses[2], mean_losses[3], torch.toc(tic)))
utils.dispImages(tgan, train_provider, opts.window_idx + 10,
'Train' .. opts.window_postfix)
if epoch % opts.test_freq == 0 then
mean_losses = test(tgan, test_provider, test_criterion)
print(('Mean test D loss: ' .. c.cyan '%.8f\n' ..
'Mean test G loss: ' .. c.cyan '%.8f\n' ..
'Mean test A loss: ' .. c.cyan '%.8f'):format(
mean_losses[1], mean_losses[2], mean_losses[3]))
utils.dispImages(tgan, test_provider, opts.window_idx,
'Test' .. opts.window_postfix)
end
if epoch % opts.snapshot_freq == 0 then
tgan:saveParams(snapshot_template:format(epoch))
end
end