forked from OpenNMT/OpenNMT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.lua
208 lines (164 loc) · 6.05 KB
/
translate.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
require('onmt.init')
local cmd = torch.CmdLine()
cmd:text("")
cmd:text("**onmt.translate.lua**")
cmd:text("")
cmd:option('-config', '', [[Read options from this file]])
cmd:text("")
cmd:text("**Data options**")
cmd:text("")
cmd:option('-model', '', [[Path to model .t7 file]])
cmd:option('-src', '', [[Source sequence to decode (one line per sequence)]])
cmd:option('-tgt', '', [[True target sequence (optional)]])
cmd:option('-output', 'pred.txt', [[Path to output the predictions (each line will be the decoded sequence]])
-- beam search options
cmd:text("")
cmd:text("**Beam Search options**")
cmd:text("")
cmd:option('-beam_size', 5,[[Beam size]])
cmd:option('-batch_size', 30, [[Batch size]])
cmd:option('-max_sent_length', 250, [[Maximum sentence length. If any sequences in srcfile are longer than this then it will error out]])
cmd:option('-replace_unk', false, [[Replace the generated UNK tokens with the source token that
had the highest attention weight. If phrase_table is provided,
it will lookup the identified source token and give the corresponding
target token. If it is not provided (or the identified source token
does not exist in the table) then it will copy the source token]])
cmd:option('-phrase_table', '', [[Path to source-target dictionary to replace UNK
tokens. See README.md for the format this file should be in]])
cmd:option('-n_best', 1, [[If > 1, it will also output an n_best list of decoded sentences]])
cmd:text("")
cmd:text("**Other options**")
cmd:text("")
cmd:option('-gpuid', -1, [[ID of the GPU to use (-1 = use CPU, 0 = let cuda choose between available GPUs)]])
cmd:option('-fallback_to_cpu', false, [[If = true, fallback to CPU if no GPU available]])
cmd:option('-time', false, [[Measure batch translation time]])
local function reportScore(name, scoreTotal, wordsTotal)
print(string.format(name .. " AVG SCORE: %.4f, " .. name .. " PPL: %.4f",
scoreTotal / wordsTotal,
math.exp(-scoreTotal/wordsTotal)))
end
local function main()
local opt = cmd:parse(arg)
local requiredOptions = {
"model",
"src"
}
onmt.utils.Opt.init(opt, requiredOptions)
local srcReader = onmt.utils.FileReader.new(opt.src)
local srcBatch = {}
local srcWordsBatch = {}
local srcFeaturesBatch = {}
local tgtReader
local tgtBatch
local tgtWordsBatch
local tgtFeaturesBatch
local withGoldScore = opt.tgt:len() > 0
if withGoldScore then
tgtReader = onmt.utils.FileReader.new(opt.tgt)
tgtBatch = {}
tgtWordsBatch = {}
tgtFeaturesBatch = {}
end
onmt.translate.Translator.init(opt)
local outFile = io.open(opt.output, 'w')
local sentId = 1
local batchId = 1
local predScoreTotal = 0
local predWordsTotal = 0
local goldScoreTotal = 0
local goldWordsTotal = 0
local timer
if opt.time then
timer = torch.Timer()
timer:stop()
timer:reset()
end
while true do
local srcTokens = srcReader:next()
local tgtTokens
if withGoldScore then
tgtTokens = tgtReader:next()
end
if srcTokens ~= nil then
local srcWords, srcFeats = onmt.utils.Features.extract(srcTokens)
table.insert(srcBatch, srcTokens)
table.insert(srcWordsBatch, srcWords)
if #srcFeats > 0 then
table.insert(srcFeaturesBatch, srcFeats)
end
if withGoldScore then
local tgtWords, tgtFeats = onmt.utils.Features.extract(tgtTokens)
table.insert(tgtBatch, tgtTokens)
table.insert(tgtWordsBatch, tgtWords)
if #tgtFeats > 0 then
table.insert(tgtFeaturesBatch, tgtFeats)
end
end
elseif #srcBatch == 0 then
break
end
if srcTokens == nil or #srcBatch == opt.batch_size then
if opt.time then
timer:resume()
end
local predBatch, info = onmt.translate.Translator.translate(srcWordsBatch, srcFeaturesBatch,
tgtWordsBatch, tgtFeaturesBatch)
if opt.time then
timer:stop()
end
for b = 1, #predBatch do
local srcSent = table.concat(srcBatch[b], " ")
local predSent = table.concat(predBatch[b], " ")
outFile:write(predSent .. '\n')
print('SENT ' .. sentId .. ': ' .. srcSent)
print('PRED ' .. sentId .. ': ' .. predSent)
print(string.format("PRED SCORE: %.4f", info[b].score))
predScoreTotal = predScoreTotal + info[b].score
predWordsTotal = predWordsTotal + #predBatch[b]
if withGoldScore then
local tgtSent = table.concat(tgtBatch[b], " ")
print('GOLD ' .. sentId .. ': ' .. tgtSent)
print(string.format("GOLD SCORE: %.4f", info[b].goldScore))
goldScoreTotal = goldScoreTotal + info[b].goldScore
goldWordsTotal = goldWordsTotal + #tgtBatch[b]
end
if opt.n_best > 1 then
print('\nBEST HYP:')
for n = 1, #info[b].nBest do
local nBest = table.concat(info[b].nBest[n].tokens, " ")
print(string.format("[%.4f] %s", info[b].nBest[n].score, nBest))
end
end
print('')
sentId = sentId + 1
end
if srcTokens == nil then
break
end
batchId = batchId + 1
srcBatch = {}
srcWordsBatch = {}
srcFeaturesBatch = {}
if withGoldScore then
tgtBatch = {}
tgtWordsBatch = {}
tgtFeaturesBatch = {}
end
collectgarbage()
end
end
if opt.time then
local time = timer:time()
local sentenceCount = sentId-1
io.stderr:write("Average sentence translation time (in seconds):\n")
io.stderr:write("avg real\t" .. time.real / sentenceCount .. "\n")
io.stderr:write("avg user\t" .. time.user / sentenceCount .. "\n")
io.stderr:write("avg sys\t" .. time.sys / sentenceCount .. "\n")
end
reportScore('PRED', predScoreTotal, predWordsTotal)
if withGoldScore then
reportScore('GOLD', goldScoreTotal, goldWordsTotal)
end
outFile:close()
end
main()