This repository has been archived by the owner on Aug 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathstyled_cnn.lua
288 lines (220 loc) · 7.41 KB
/
styled_cnn.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
281
282
283
284
285
286
287
288
require('nn')
require('nngraph')
require('loadcaffe')
require('xlua')
require('image')
require('optim')
require('cunn')
require('cudnn')
require('./lib/tvloss')
require('./lib/contentloss')
require('./lib/gramloss')
require('./lib/mrfloss')
require('./lib/masked_gramloss')
require('./lib/amplayer')
require('./lib/randlayer')
local cleanupModel = require('./lib/cleanup_model')
local caffeImage = require('./lib/caffe_image')
local g = {}
g.styleImage = './images/picasso.png'
g.trainImages_Path = './scene/'
g.trainImages_Number = 16657
-----------------------------------------------------------------------------------------
-- helper functions
string.startsWith = function(self, str)
return self:find('^' .. str) ~= nil
end
function loadVGG()
local proto = './cnn/vgg19/VGG_ILSVRC_19_layers_deploy.prototxt'
local caffeModel = './cnn/vgg19/VGG_ILSVRC_19_layers.caffemodel'
local fullModel = loadcaffe.load(proto, caffeModel, 'nn')
local cnn = nn.Sequential()
for i = 1, #fullModel do
local name = fullModel:get(i).name
if ( name:startsWith('relu') or name:startsWith('conv') or name:startsWith('pool') ) then
cnn:add( fullModel:get(i) )
else
break
end
end
fullModel = nil
collectgarbage()
return cnn
end
function loadTrainData()
local randSeq = torch.randperm(g.trainImages_Number)
local trainSplit = math.floor(g.trainImages_Number * 0.85)
g.trainSet = {}
g.trainSet.data = {}
g.trainSet.index = 1
for i = 1, trainSplit do
g.trainSet.data[i] = g.trainImages_Path .. '/' .. randSeq[i] .. '.png'
end
g.testSet = {}
g.testSet.data = {}
g.testSet.index = 1
for i = trainSplit + 1, g.trainImages_Number do
g.testSet.data[i] = g.trainImages_Path .. '/' .. randSeq[i] .. '.png'
end
end
function loadBatch(set, batch_size)
local batch = {}
batch.x = torch.Tensor(batch_size, 3, 256, 256)
for i = 1, batch_size do
local sampleIndex = i + set.index
sampleIndex = sampleIndex % #set.data + 1
local rgb = image.loadPNG( set.data[sampleIndex], 3)
batch.x[i]:copy( caffeImage.img2caffe(rgb) )
end
set.index = (set.index + batch_size) % #set.data + 1
return batch
end
-----------------------------------------------------------------------------------------
-- worker functions
function buildLossNet ()
local gramLoss = {'relu1_2', 'relu2_2', 'relu3_2', 'relu4_1'}
local contentLoss = {'relu4_2'}
local styleCaffeImage = caffeImage.img2caffe( image.loadPNG(g.styleImage, 3) )
local modifier = {}
local cindex = -1
local net = nn.Sequential()
net:add(nn.TVLoss(0.001))
local gram_index = 1
local content_index = 1
for i = 1, #g.vgg do
if ( gram_index > #gramLoss and content_index > #contentLoss) then
break
end
local name = g.vgg:get(i).name
net:add(g.vgg:get(i))
if ( name == gramLoss[ gram_index ] ) then
local target = net:forward( styleCaffeImage )
local layer = nn.GramLoss(0.01, target, false)
net:add(layer)
table.insert(modifier, layer)
gram_index = gram_index + 1
end
if ( name == contentLoss[content_index] ) then
local layer = nn.ContentLoss(1.0, nil, nil)
net:add(layer)
table.insert(modifier, layer)
cindex = #modifier
content_index = content_index + 1
end
end
local lossNet = {}
lossNet.net = net
lossNet.modifier = modifier
lossNet.cindex = cindex
return lossNet
end
function buildStyledNet()
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(3, 32, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(32))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(32))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(64))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 1, 1))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 3, 3, 3, 1, 1, 1, 1))
model:add(nn.Tanh())
model:add(nn.MulConstant(128))
return model
end
function doTrain()
g.lossNet.net:cuda()
g.styledNet:cuda()
g.zeroLoss = g.zeroLoss:cuda()
g.styledNet:training()
g.lossNet.net:evaluate()
local batchSize = 4
local oneEpoch = math.floor( #g.trainSet.data / batchSize )
g.trainSet.index = 1
local batch = nil
local dyhat = torch.zeros(batchSize, 3, 256, 256):cuda()
local parameters,gradParameters = g.styledNet:getParameters()
local feval = function(x)
-- get new parameters
if x ~= parameters then
parameters:copy(x)
end
-- reset gradients
gradParameters:zero()
local loss = 0
local yhat = g.styledNet:forward( batch.x )
for i = 1, batchSize do
g.lossNet.net:forward( batch.x[i] )
local contentTarget = g.lossNet.modifier[g.lossNet.cindex].output
g.lossNet.modifier[g.lossNet.cindex]:setTarget(contentTarget)
g.lossNet.net:forward(yhat[i])
local dy = g.lossNet.net:backward(yhat[i], g.zeroLoss)
dyhat[i]:copy(dy)
for _, mod in ipairs(g.lossNet.modifier) do
loss = loss + mod.loss
end
end
g.styledNet:backward(batch.x, dyhat)
return loss/batchSize, gradParameters
end
local minValue = -1
for j = 1, oneEpoch do
batch = loadBatch(g.trainSet, batchSize)
batch.x = batch.x:cuda()
local _, err = optim.adam(feval, parameters, g.optimState)
print(">>>>>>>>> err = " .. err[1]);
if ( j % 100 == 0) then
torch.save('./model/style_' .. err[1] .. '.t7', g.styledNet)
end
collectgarbage();
end
end
function doTest()
end
function doForward()
local net = torch.load( arg[1] )
local img = image.loadPNG( arg[2] , 3)
local img = caffeImage.img2caffe(img)
local x = torch.Tensor(1, img:size(1), img:size(2), img:size(3))
x[1]:copy(img)
x = x:cuda()
local outImg = net:forward(x)
outImg = outImg:float()
outImg = caffeImage.caffe2img(outImg[1])
image.savePNG('./output.png', outImg)
end
-----------------------------------------------------------------------------------------
function main()
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(1979)
if ( #arg == 2) then
doForward()
return
end
-- build net
g.vgg = loadVGG()
g.lossNet = buildLossNet()
local tempImage = torch.rand(3, 256, 256)
local tempOutput = g.lossNet.net:forward(tempImage)
g.zeroLoss = torch.zeros( tempOutput:size())
g.styledNet = buildStyledNet()
g.optimState = {
learningRate = 0.0005,
}
-- load data
loadTrainData()
-- trainging()
for i = 1, 4 do
doTrain()
doTest()
end
end
main()