This repository has been archived by the owner on May 31, 2024. It is now read-only.
forked from flashlight/wav2letter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.lua
283 lines (253 loc) · 7.76 KB
/
test.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
-- Copyright (c) 2017-present, Facebook, Inc.
-- All rights reserved.
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
require 'torch'
require 'nn'
local tnt = require 'torchnet'
local xlua = require 'xlua'
require 'wav2letter'
local serial = require 'wav2letter.runtime.serial'
local data = require 'wav2letter.runtime.data'
torch.setdefaulttensortype('torch.FloatTensor')
local function cmdtestoptions(cmd)
cmd:text()
cmd:text('SpeechRec (c) Ronan Collobert 2015')
cmd:text()
cmd:text('Arguments:')
cmd:argument('-model', 'the trained model!')
cmd:text()
cmd:text('Options:')
cmd:option('-datadir', string.format('%s/local/datasets/speech', os.getenv('HOME')), 'speech directory data')
cmd:option('-dictdir', string.format('%s/local/datasets/speech', os.getenv('HOME')), 'dictionary directory')
cmd:option('-maxloadtest', -1, 'max number of testing examples')
cmd:option('-show', false, 'show predictions')
cmd:option('-save', false, 'save network predictions')
cmd:option('-gpu', 1, 'gpu device')
cmd:option('-nolsm', false, 'remove lsm layer')
cmd:option('-addlsm', false, 'add lsm layer')
cmd:option('-progress', false, 'display testing progress per epoch')
cmd:option('-gfsai', false, 'override above paths to gfsai ones')
cmd:option('-test', '', 'space-separated list of test data')
cmd:text()
end
if #arg < 1 then
error(string.format([[
usage:
%s -model <options...>
]], arg[0]))
end
local reload = arg[1]
local opt = serial.parsecmdline{
closure = cmdtestoptions,
arg = arg,
default = serial.loadmodel(reload).config.opt
}
-- override paths?
if opt.gfsai then
opt.datadir = '/mnt/vol/gfsai-east/ai-group/datasets/speech'
opt.rundir = '/mnt/vol/gfsai-east/ai-group/users/' .. assert(os.getenv('USER'), 'unknown user') .. '/chronos'
end
if opt.gpu > 0 then
require 'cutorch'
require 'cunn'
require 'cudnn'
cutorch.setDevice(opt.gpu)
cutorch.manualSeedAll(opt.seed)
end
--dictionaries
local dict = data.newdict{
path = paths.concat(opt.dictdir, opt.dict)
}
local dict39phn
if opt.target == "phn" then
dict39phn = data.dictcollapsephones{dictionary=dict}
if opt.dict39 then
dict = dict39phn
end
end
if opt.dictsil then
data.dictadd{dictionary=dict, token='N', idx=assert(dict['|'])}
data.dictadd{dictionary=dict, token='L', idx=assert(dict['|'])}
end
if opt.ctc or opt.garbage then
data.dictadd{dictionary=dict, token="#"} -- blank
end
if opt.replabel > 0 then
for i=1,opt.replabel do
data.dictadd{dictionary=dict, token=string.format("%d", i)}
end
end
print(string.format('| number of classes (network) = %d', #dict))
--reloading network
print(string.format('| reloading model <%s>', reload))
local model = serial.loadmodel{filename=reload, arch=true}
local network = model.arch.network
local transitions = model.arch.transitions
local config = model.config
local kw = model.config.kw
local dw = model.config.dw
assert(kw and dw, 'kw and dw could not be found in model archive')
if opt.nolsm then
for i=network:size(),1,-1 do
if torch.typename(network:get(i)) == 'nn.LogSoftMax' then
print('! removing nn.LogSoftMax layer ' .. i)
network:remove(i)
end
end
end
assert(not (opt.addlsm and opt.nolsm))
if opt.addlsm then
if opt.gpu then
network:insert(nn.LogSoftMax():cuda(), network:size())
else
network:add(nn.LogSoftMax())
end
end
print(network)
-- make sure we do not apply aug on this
opt.aug = false
opt.shift = opt.shift or 0
local criterion
if opt.msc then
criterion = nn.MultiStateFullConnectCriterion(#dict/opt.nstate, opt.nstate)
else
criterion = (opt.ctc and nn.ConnectionistTemporalCriterion(#dict, nil)) or nn.Viterbi(#dict)
end
if not opt.ctc then
criterion.transitions:copy(transitions)
end
if opt.shift > 0 then
print(string.format("| using shift scheme (shift=%d dshift=%d)", opt.shift, opt.dshift))
network = nn.ShiftNet(network, opt.shift)
end
local iterators = {}
for _, name in ipairs(data.namelist(opt.test)) do
iterators[name] = data.newiterator{
nthread = opt.nthread,
closure =
function()
local data = require 'wav2letter.runtime.data'
return data.newdataset{
names = {name},
opt = opt,
dict = dict,
kw = kw,
dw = dw,
maxload = opt.maxloadtest,
words = 'wrd'
}
end
}
end
local function createProgress(iterator)
local N = iterator.execSingle
and iterator:execSingle('size')
or iterator:exec('size')
local n = 0
return function ()
n = n + 1
xlua.progress(n, N)
end
end
local utils = require 'wav2letter.utils'
local function tostring(tensor)
local str = {}
tensor:apply(
function(idx)
local letter = dict[idx]
assert(letter)
table.insert(str, letter)
end
)
return table.concat(str)
end
local words = {}
local wordsIdx = 0
local function string2wordtensor(str)
local t = {}
for word in str:gmatch('([^|]+)') do
if not words[word] then
words[word] = wordsIdx
wordsIdx = wordsIdx + 1
end
table.insert(t, words[word])
end
return torch.LongTensor(t)
end
local function test(name, network, iterator)
local fout
local encodedName = string.gsub(name, '/', '-')
if opt.save then
-- outputs
local path = paths.dirname(opt.model)
fout = tnt.IndexedDatasetWriter{
indexfilename = string.format("%s/output-%s.idx", path, encodedName),
datafilename = string.format("%s/output-%s.bin", path, encodedName),
type = 'table',
}
-- transitions
local f = torch.DiskFile(string.format("%s/transitions-%s.bin",
path, encodedName), "w")
f:binary()
f:writeObject(transitions:float())
f:close()
end
local engine = tnt.SGDEngine()
local edit = tnt.EditDistanceMeter()
local progress = opt.progress and createProgress(iterator)
local wer = tnt.EditDistanceMeter()
local iwer = tnt.EditDistanceMeter()
function engine.hooks.onStart(state)
edit:reset()
end
function engine.hooks.onForward(state)
collectgarbage()
local predictions = criterion:viterbi(state.network.output)
predictions = utils.uniq(predictions)
local targets = utils.uniq(state.sample.target)
iwer:reset()
local viterbi = tostring(predictions)
local viterbiTensor = string2wordtensor(viterbi)
local targetTensor = string2wordtensor(tostring(targets))
iwer:add(viterbiTensor, targetTensor)
wer:add(viterbiTensor, targetTensor)
if opt.show then
print(
string.format("<%s>\n<%s>",
tostring(predictions),
tostring(targets))
)
print(
string.format("[Sentence WER: %06.2f%%, dataset WER: %06.2f%%]",
iwer:value(), wer:value()))
end
if progress then
progress()
end
if opt.save then
fout:add{output=state.network.output,
spellings=targets,
words=state.sample.words,
predictions=tostring(predictions)}
end
edit:add(
predictions,
targets
)
end
engine:test{
network = network,
iterator = iterator
}
if opt.save then
fout:close()
end
return edit:value(), wer:value()
end
for name, iterator in pairs(iterators) do
local ler, wer = test(name, network, iterator)
print(string.format("| %s LER = %05.2f%%, WER = %05.2f%%",
name, ler, wer))
end