tensorflow-rnnlm.cc
12.2 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// tensorflow-rnnlm.cc
// Copyright (C) 2017 Intellisist, Inc. (Author: Hainan Xu)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <utility>
#include <fstream>
#include "tfrnnlm/tensorflow-rnnlm.h"
#include "util/stl-utils.h"
#include "util/text-utils.h"
// Tensorflow includes were moved after tfrnnlm/tensorflow-rnnlm.h include to
// avoid macro redefinitions. See also the note in tfrnnlm/tensorflow-rnnlm.h.
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
namespace kaldi {
using std::ifstream;
using tf_rnnlm::KaldiTfRnnlmWrapper;
using tf_rnnlm::TfRnnlmDeterministicFst;
using tensorflow::Status;
// read a unigram count file of the OOSs and generate extra OOS costs for words
void SetUnkPenalties(const string &filename,
const fst::SymbolTable& fst_word_symbols,
std::vector<float> *out) {
if (filename == "")
return;
out->resize(fst_word_symbols.NumSymbols(), 0); // default is 0
ifstream ifile(filename.c_str());
string word;
float count, total_count = 0;
while (ifile >> word >> count) {
int id = fst_word_symbols.Find(word);
KALDI_ASSERT(id != -1); // fst::kNoSymbol
(*out)[id] = count;
total_count += count;
}
for (int i = 0; i < out->size(); i++) {
if ((*out)[i] != 0) {
(*out)[i] = log ((*out)[i] / total_count);
}
}
}
// Read tensorflow checkpoint files
void KaldiTfRnnlmWrapper::ReadTfModel(const std::string &tf_model_path,
int32 num_threads) {
string graph_path = tf_model_path + ".meta";
tensorflow::SessionOptions session_options;
session_options.config.set_intra_op_parallelism_threads(num_threads);
session_options.config.set_inter_op_parallelism_threads(num_threads);
Status status = tensorflow::NewSession(session_options,
&session_);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
tensorflow::MetaGraphDef graph_def;
status = tensorflow::ReadBinaryProto(tensorflow::Env::Default(), graph_path,
&graph_def);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
// Add the graph to the session
status = session_->Create(graph_def.graph_def());
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
Tensor checkpointPathTensor(tensorflow::DT_STRING, tensorflow::TensorShape());
checkpointPathTensor.scalar<std::string>()() = tf_model_path;
status = session_->Run(
{{graph_def.saver_def().filename_tensor_name(), checkpointPathTensor} },
{},
{graph_def.saver_def().restore_op_name()},
nullptr);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
}
KaldiTfRnnlmWrapper::KaldiTfRnnlmWrapper(
const KaldiTfRnnlmWrapperOpts &opts,
const std::string &rnn_wordlist,
const std::string &word_symbol_table_rxfilename,
const std::string &unk_prob_file,
const std::string &tf_model_path): opts_(opts) {
ReadTfModel(tf_model_path, opts.num_threads);
fst::SymbolTable *fst_word_symbols = NULL;
if (!(fst_word_symbols =
fst::SymbolTable::ReadText(word_symbol_table_rxfilename))) {
KALDI_ERR << "Could not read symbol table from file "
<< word_symbol_table_rxfilename;
}
fst_label_to_word_.resize(fst_word_symbols->NumSymbols());
for (int32 i = 0; i < fst_label_to_word_.size(); ++i) {
fst_label_to_word_[i] = fst_word_symbols->Find(i);
if (fst_label_to_word_[i] == "") {
KALDI_ERR << "Could not find word for integer " << i << " in the word "
<< "symbol table, mismatched symbol table or you have discoutinuous "
<< "integers in your symbol table?";
}
}
// first put all -1's; will check later
fst_label_to_rnn_label_.resize(fst_word_symbols->NumSymbols(), -1);
num_total_words = fst_word_symbols->NumSymbols();
// read rnn wordlist and then generate ngram-label-to-rnn-label map
oos_ = -1;
{ // input.
ifstream ifile(rnn_wordlist.c_str());
string word;
int id = -1;
eos_ = 0;
while (ifile >> word) {
id++;
rnn_label_to_word_.push_back(word); // vector[i] = word
int fst_label = fst_word_symbols->Find(word);
if (fst_label == -1) { // fst::kNoSymbol
if (id == eos_)
continue;
KALDI_ASSERT(word == opts_.unk_symbol && oos_ == -1);
oos_ = id;
continue;
}
KALDI_ASSERT(fst_label >= 0);
fst_label_to_rnn_label_[fst_label] = id;
}
}
if (fst_label_to_word_.size() > rnn_label_to_word_.size()) {
KALDI_ASSERT(oos_ != -1);
}
num_rnn_words = rnn_label_to_word_.size();
// we must have an oos symbol in the wordlist
if (oos_ == -1)
return;
for (int i = 0; i < fst_label_to_rnn_label_.size(); i++) {
if (fst_label_to_rnn_label_[i] == -1) {
fst_label_to_rnn_label_[i] = oos_;
}
}
AcquireInitialTensors();
SetUnkPenalties(unk_prob_file, *fst_word_symbols, &unk_costs_);
delete fst_word_symbols;
}
void KaldiTfRnnlmWrapper::AcquireInitialTensors() {
Status status;
// get the initial context; this is basically the all-0 tensor
{
std::vector<Tensor> state;
status = session_->Run(std::vector<std::pair<string, Tensor> >(),
{"Train/Model/test_initial_state"}, {}, &state);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
initial_context_ = state[0];
}
// get the initial pre-final-affine layer
{
std::vector<Tensor> state;
Tensor bosword(tensorflow::DT_INT32, {1, 1});
bosword.scalar<int32>()() = eos_; // eos_ is more like a sentence boundary
std::vector<std::pair<string, Tensor> > inputs = {
{"Train/Model/test_word_in", bosword},
{"Train/Model/test_state_in", initial_context_},
};
status = session_->Run(inputs, {"Train/Model/test_cell_out"}, {}, &state);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
initial_cell_ = state[0];
}
}
BaseFloat KaldiTfRnnlmWrapper::GetLogProb(int32 word,
int32 fst_word,
const Tensor &context_in,
const Tensor &cell_in,
Tensor *context_out,
Tensor *new_cell) {
std::vector<std::pair<string, Tensor> > inputs;
Tensor thisword(tensorflow::DT_INT32, {1, 1});
thisword.scalar<int32>()() = word;
std::vector<Tensor> outputs;
if (context_out != NULL) {
inputs = {
{"Train/Model/test_word_in", thisword},
{"Train/Model/test_word_out", thisword},
{"Train/Model/test_state_in", context_in},
{"Train/Model/test_cell_in", cell_in},
};
// The session will initialize the outputs
// Run the session, evaluating our "c" operation from the graph
Status status = session_->Run(inputs,
{"Train/Model/test_out",
"Train/Model/test_state_out",
"Train/Model/test_cell_out"}, {}, &outputs);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
*context_out = outputs[1];
*new_cell = outputs[2];
} else {
inputs = {
{"Train/Model/test_word_out", thisword},
{"Train/Model/test_cell_in", cell_in},
};
// Run the session, evaluating our "c" operation from the graph
Status status = session_->Run(inputs,
{"Train/Model/test_out"}, {}, &outputs);
if (!status.ok()) {
KALDI_ERR << status.ToString();
}
}
float ans;
if (word != oos_) {
ans = outputs[0].scalar<float>()();
} else {
if (unk_costs_.size() == 0) {
ans = outputs[0].scalar<float>()() - log(num_total_words - num_rnn_words);
} else {
ans = outputs[0].scalar<float>()() + unk_costs_[fst_word];
}
}
return ans;
}
const Tensor& KaldiTfRnnlmWrapper::GetInitialContext() const {
return initial_context_;
}
const Tensor& KaldiTfRnnlmWrapper::GetInitialCell() const {
return initial_cell_;
}
int KaldiTfRnnlmWrapper::FstLabelToRnnLabel(int i) const {
KALDI_ASSERT(i >= 0 && i < fst_label_to_rnn_label_.size());
return fst_label_to_rnn_label_[i];
}
TfRnnlmDeterministicFst::TfRnnlmDeterministicFst(int32 max_ngram_order,
KaldiTfRnnlmWrapper *rnnlm) {
KALDI_ASSERT(rnnlm != NULL);
max_ngram_order_ = max_ngram_order;
rnnlm_ = rnnlm;
std::vector<Label> bos;
const Tensor& initial_context = rnnlm_->GetInitialContext();
const Tensor& initial_cell = rnnlm_->GetInitialCell();
state_to_wseq_.push_back(bos);
state_to_context_.push_back(new Tensor(initial_context));
state_to_cell_.push_back(new Tensor(initial_cell));
wseq_to_state_[bos] = 0;
start_state_ = 0;
}
TfRnnlmDeterministicFst::~TfRnnlmDeterministicFst() {
for (int i = 0; i < state_to_context_.size(); i++) {
delete state_to_context_[i];
}
for (int i = 0; i < state_to_cell_.size(); i++) {
delete state_to_cell_[i];
}
}
void TfRnnlmDeterministicFst::Clear() {
// similar to the destructor but we retain the 0-th entries in each map
// which corresponds to the <bos> state
for (int i = 1; i < state_to_context_.size(); i++) {
delete state_to_context_[i];
}
for (int i = 1; i < state_to_cell_.size(); i++) {
delete state_to_cell_[i];
}
state_to_context_.resize(1);
state_to_cell_.resize(1);
state_to_wseq_.resize(1);
wseq_to_state_.clear();
wseq_to_state_[state_to_wseq_[0]] = 0;
}
fst::StdArc::Weight TfRnnlmDeterministicFst::Final(StateId s) {
// At this point, we should have created the state.
KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
std::vector<Label> wseq = state_to_wseq_[s];
BaseFloat logprob = rnnlm_->GetLogProb(rnnlm_->GetEos(),
-1, // only need type; this param will not be used
*state_to_context_[s],
*state_to_cell_[s], NULL, NULL);
return Weight(-logprob);
}
bool TfRnnlmDeterministicFst::GetArc(StateId s, Label ilabel,
fst::StdArc *oarc) {
KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
std::vector<Label> wseq = state_to_wseq_[s];
Tensor *new_context = new Tensor();
Tensor *new_cell = new Tensor();
// look-up the rnn label from the FST label
int32 rnn_word = rnnlm_->FstLabelToRnnLabel(ilabel);
BaseFloat logprob = rnnlm_->GetLogProb(rnn_word,
ilabel,
*state_to_context_[s],
*state_to_cell_[s],
new_context,
new_cell);
wseq.push_back(rnn_word);
if (max_ngram_order_ > 0) {
while (wseq.size() >= max_ngram_order_) {
// History state has at most <max_ngram_order_> - 1 words in the state.
wseq.erase(wseq.begin(), wseq.begin() + 1);
}
}
std::pair<const std::vector<Label>, StateId> wseq_state_pair(
wseq, static_cast<Label>(state_to_wseq_.size()));
// Attemps to insert the current <lseq_state_pair>. If the pair already exists
// then it returns false.
typedef MapType::iterator IterType;
std::pair<IterType, bool> result = wseq_to_state_.insert(wseq_state_pair);
// If the pair was just inserted, then also add it to <state_to_wseq_> and
// <state_to_context_>.
if (result.second == true) {
state_to_wseq_.push_back(wseq);
state_to_context_.push_back(new_context);
state_to_cell_.push_back(new_cell);
} else {
delete new_context;
delete new_cell;
}
// Creates the arc.
oarc->ilabel = ilabel;
oarc->olabel = ilabel;
oarc->nextstate = result.first->second;
oarc->weight = Weight(-logprob);
return true;
}
} // namespace kaldi