-
Notifications
You must be signed in to change notification settings - Fork 3
/
model_parallel_cnn_fasttext.lua
306 lines (279 loc) · 9.39 KB
/
model_parallel_cnn_fasttext.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
dofile('optim-rmsprop-single.lua')
embedding = nn.LookupTableMaskZero(mapWordIdx2Vector:size()[1], opt.embeddingDim)
embedding.weight:sub(2,-1):copy(mapWordIdx2Vector)
cnn = nn.Sequential()
if cudnnok then
conv = cudnn.TemporalConvolution(opt.wordHiddenDim, opt.numFilters, opt.contConvWidth)
elseif fbok then
conv = nn.TemporalConvolutionFB(opt.wordHiddenDim, opt.numFilters, opt.contConvWidth)
else
conv = nn.TemporalConvolution(opt.wordHiddenDim, opt.numFilters, opt.contConvWidth)
end
cnn:add(conv)
if opt.useACN then
cnn:add(nn.AddConstantNeg(-20000))
end
cnn:add(nn.Max(2))
if opt.lastReLU then
cnn:add(nn.ReLU())
else
cnn:add(nn.Tanh())
end
fasttext = nn.Sequential()
fasttext:add(nn.Mean(2))
fasttext:add(nn.ReLU())
parallel = nn.ConcatTable()
parallel:add(cnn)
parallel:add(fasttext)
model = nn.Sequential()
model:add(embedding)
model:add(parallel)
model:add(nn.JoinTable(2))
model:add(nn.Linear(opt.numFilters + opt.embeddingDim, opt.hiddenDim))
model:add(nn.ReLU())
if opt.dropout > 0 then
model:add(nn.Dropout(opt.dropout))
end
model:add(nn.Linear(opt.hiddenDim, opt.numLabels))
model:add(nn.LogSoftMax())
if opt.twoCriterion then
prob_idx = nn.ConcatTable()
prob_idx:add(nn.Identity())
prob_idx:add(nn.ArgMax(2,opt.numLabels, false))
model:add(prob_idx)
nll = nn.ClassNLLCriterion()
abs = nn.AbsCriterion()
criterion = nn.ParallelCriterion(true):add(nll, opt.criterionWeight):add(abs)
else
criterion = nn.ClassNLLCriterion()
end
if opt.type == 'cuda' then
model:cuda()
criterion:cuda()
end
if model then
parameters,gradParameters = model:getParameters()
print("Model Size: ", parameters:size()[1])
parametersClone = parameters:clone()
end
print(model)
print(criterion)
if opt.optimization == 'CG' then
optimState = {
maxIter = opt.maxIter
}
optimMethod = optim.cg
elseif opt.optimization == 'LBFGS' then
optimState = {
learningRate = opt.learningRate,
maxIter = opt.maxIter,
nCorrection = 10
}
optimMethod = optim.lbfgs
elseif opt.optimization == 'sgd' then
optimState = {
lr = opt.learningRate,
lrd = opt.weightDecay,
mom = opt.momentum,
}
optimMethod = optim.msgd
elseif opt.optimization == 'SGD' then
optimState = {
learningRate = opt.learningRate,
learningRateDecay = opt.learningRateDecay,
momentum = opt.momentum,
learningRateDecay = 0,
dampening = 0,
nesterov = opt.nesterov
}
optimMethod = optim.sgd
elseif opt.optimization == 'RMSPROP' then
optimState = {
decay = opt.decayRMSProp,
lr = opt.lrRMSProp,
momentum = opt.momentumRMSProp,
epsilon = opt.epsilonRMSProp
}
optimMethod = optim.rmspropsingle
else
error('unknown optimization method')
end
function saveModel(s)
torch.save(opt.outputprefix .. string.format("_%010.2f_model", s), parameters)
end
function loadModel(m)
parameters:copy(torch.load(m))
end
function cleanMemForRuntime()
parametersClone = nil
gradParameters = nil
model:get(1).gradWeight = nil
model:get(3).gradWeight = nil
model:get(3).gradBias = nil
model:get(6).gradWeight = nil
model:get(6).gradBias = nil
model:get(9).gradWeight = nil
model:get(9).gradBias = nil
model:get(11).gradWeight = nil
model:get(11).gradBias = nil
collectgarbage()
collectgarbage()
end
function train()
epoch = epoch or 1
if optimState.evalCounter then
optimState.evalCounter = optimState.evalCounter + 1
end
-- optimState.learningRate = opt.learningRate
local time = sys.clock()
model:training()
local batches = trainDataTensor:size()[1]/opt.batchSize
local bs = opt.batchSize
shuffle = torch.randperm(batches)
for t = 1,batches,1 do
local begin = (shuffle[t] - 1)*bs + 1
local input = trainDataTensor:narrow(1, begin , bs)
local target = trainDataTensor_y:narrow(1, begin , bs)
local input_lstm_fwd = trainDataTensor_lstm_fwd:narrow(1, begin , bs)
local input_lstm_bwd = trainDataTensor_lstm_bwd:narrow(1, begin , bs)
local feval = function(x)
if x ~= parameters then
parameters:copy(x)
end
gradParameters:zero()
local f = 0
if true then
local output = model:forward(input)
f = criterion:forward(output, target)
local df_do = criterion:backward(output, target)
model:backward(input, df_do)
end
--cutorch.synchronize()
if opt.L1reg ~= 0 then
local norm, sign = torch.norm, torch.sign
f = f + opt.L1reg * norm(parameters,1)
gradParameters:add( sign(parameters):mul(opt.L1reg) )
end
if opt.L2reg ~= 0 then
-- local norm, sign = torch.norm, torch.sign
-- f = f + opt.L2reg * norm(parameters,2)^2/2
parametersClone:copy(parameters)
gradParameters:add( parametersClone:mul(opt.L2reg) )
end
-- gradParameters:clamp(-opt.gradClip, opt.gradClip)
return f,gradParameters
end
if optimMethod == optim.asgd then
_,_,average = optimMethod(feval, parameters, optimState)
else
-- a,b = model:parameters()
-- print('a ' .. a[1][1][1]);
optimMethod(feval, parameters, optimState)
-- print(' ' .. a[1][1][1]);
end
end
time = sys.clock() - time
print("\n==> time for 1 epoch = " .. (time) .. ' seconds')
end
function test(inputDataTensor, inputDataTensor_lstm_fwd, inputDataTensor_lstm_bwd, inputTarget, state)
local time = sys.clock()
model:evaluate()
local bs = opt.batchSizeTest
local batches = inputDataTensor:size()[1]/bs
local correct = 0
local correct2 = 0
local correct3 = 0
local curr = -1
for t = 1,batches,1 do
curr = t
local begin = (t - 1)*bs + 1
local input = inputDataTensor:narrow(1, begin , bs)
local pred
if true then
pred = model:forward(input)
end
local prob, pos
if opt.twoCriterion then
prob, pos = torch.max(pred[1], 2)
else
prob, pos = torch.max(pred, 2)
end
for m = 1,bs do
for k,v in ipairs(inputTarget[begin+m-1]) do
if pos[m][1] == v then
correct = correct + 1
break
end
end
for k,v in ipairs(inputTarget[begin+m-1]) do
if torch.abs(pos[m][1] - v) < 2 then
correct2 = correct2 + 1
break
end
end
for k,v in ipairs(inputTarget[begin+m-1]) do
if torch.abs(pos[m][1] - v) < 3 then
correct3 = correct3 + 1
break
end
end
end
end
local rest_size = inputDataTensor:size()[1] - curr * bs
if rest_size > 0 then
local input
local input_lstm_fwd
local input_lstm_bwd
if opt.type == 'cuda' then
input = torch.CudaTensor(bs, inputDataTensor:size(2)):zero()
else
input = torch.FloatTensor(bs, inputDataTensor:size(2)):zero()
end
input:narrow(1,1,rest_size):copy(inputDataTensor:narrow(1, curr*bs + 1, rest_size))
local pred
if true then
pred = model:forward(input)
end
local prob, pos
if opt.twoCriterion then
prob, pos = torch.max(pred[1], 2)
else
prob, pos = torch.max(pred, 2)
end
for m = 1,rest_size do
for k,v in ipairs(inputTarget[curr*bs+m]) do
if pos[m][1] == v then
correct = correct + 1
break
end
end
for k,v in ipairs(inputTarget[curr*bs+m]) do
if torch.abs(pos[m][1] - v) < 2 then
correct2 = correct2 + 1
break
end
end
for k,v in ipairs(inputTarget[curr*bs+m]) do
if torch.abs(pos[m][1] - v) < 3 then
correct3 = correct3 + 1
break
end
end
end
end
state.bestAccuracy = state.bestAccuracy or 0
state.bestEpoch = state.bestEpoch or 0
state.bestAccuracy2 = state.bestAccuracy2 or 0
state.bestEpoch2 = state.bestEpoch2 or 0
state.bestAccuracy3 = state.bestAccuracy3 or 0
state.bestEpoch3 = state.bestEpoch3 or 0
local currAccuracy = correct/(inputDataTensor:size()[1])
local currAccuracy2 = correct2/(inputDataTensor:size()[1])
local currAccuracy3 = correct3/(inputDataTensor:size()[1])
if currAccuracy > state.bestAccuracy then state.bestAccuracy = currAccuracy; state.bestEpoch = epoch end
if currAccuracy2 > state.bestAccuracy2 then state.bestAccuracy2 = currAccuracy2; state.bestEpoch2 = epoch end
if currAccuracy3 > state.bestAccuracy3 then state.bestAccuracy3 = currAccuracy3; state.bestEpoch3 = epoch end
print(string.format("Epoch %s Accuracy: %s, best Accuracy: %s on epoch %s at time %s", epoch, currAccuracy, state.bestAccuracy, state.bestEpoch, sys.toc() ))
print(string.format("Epoch %s Accuracy2: %s, best Accuracy: %s on epoch %s at time %s", epoch, currAccuracy2, state.bestAccuracy2, state.bestEpoch2, sys.toc() ))
print(string.format("Epoch %s Accuracy3: %s, best Accuracy: %s on epoch %s at time %s", epoch, currAccuracy3, state.bestAccuracy3, state.bestEpoch3, sys.toc() ))
end