nnet3-latgen-faster-looped.cc
Go to the documentation of this file.
1 // nnet3bin/nnet3-latgen-faster-looped.cc
2 
3 // Copyright 2012-2016 Johns Hopkins University (author: Daniel Povey)
4 // 2014 Guoguo Chen
5 
6 // See ../../COPYING for clarification regarding multiple authors
7 //
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 //
12 // http://www.apache.org/licenses/LICENSE-2.0
13 //
14 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
16 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
17 // MERCHANTABLITY OR NON-INFRINGEMENT.
18 // See the Apache 2 License for the specific language governing permissions and
19 // limitations under the License.
20 
21 
22 #include "base/kaldi-common.h"
23 #include "util/common-utils.h"
24 #include "tree/context-dep.h"
25 #include "hmm/transition-model.h"
26 #include "fstext/fstext-lib.h"
29 #include "nnet3/nnet-utils.h"
30 #include "base/timer.h"
31 
32 
33 int main(int argc, char *argv[]) {
34  // note: making this program work with GPUs is as simple as initializing the
35  // device, but it probably won't make a huge difference in speed for typical
36  // setups.
37  try {
38  using namespace kaldi;
39  using namespace kaldi::nnet3;
40  typedef kaldi::int32 int32;
41  using fst::SymbolTable;
42  using fst::Fst;
43  using fst::StdArc;
44 
45  const char *usage =
46  "Generate lattices using nnet3 neural net model.\n"
47  "[this version uses the 'looped' computation, which may be slightly faster for\n"
48  "many architectures, but should not be used for backwards-recurrent architectures\n"
49  "such as BLSTMs.\n"
50  "Usage: nnet3-latgen-faster-looped [options] <nnet-in> <fst-in|fsts-rspecifier> <features-rspecifier>"
51  " <lattice-wspecifier> [ <words-wspecifier> [<alignments-wspecifier>] ]\n";
52  ParseOptions po(usage);
53  Timer timer;
54  bool allow_partial = false;
57 
58  std::string word_syms_filename;
59  std::string ivector_rspecifier,
60  online_ivector_rspecifier,
61  utt2spk_rspecifier;
62  int32 online_ivector_period = 0;
63  config.Register(&po);
64  decodable_opts.Register(&po);
65  po.Register("word-symbol-table", &word_syms_filename,
66  "Symbol table for words [for debug output]");
67  po.Register("allow-partial", &allow_partial,
68  "If true, produce output even if end state was not reached.");
69  po.Register("ivectors", &ivector_rspecifier, "Rspecifier for "
70  "iVectors as vectors (i.e. not estimated online); per utterance "
71  "by default, or per speaker if you provide the --utt2spk option.");
72  po.Register("online-ivectors", &online_ivector_rspecifier, "Rspecifier for "
73  "iVectors estimated online, as matrices. If you supply this,"
74  " you must set the --online-ivector-period option.");
75  po.Register("online-ivector-period", &online_ivector_period, "Number of frames "
76  "between iVectors in matrices supplied to the --online-ivectors "
77  "option");
78 
79  po.Read(argc, argv);
80 
81  if (po.NumArgs() < 4 || po.NumArgs() > 6) {
82  po.PrintUsage();
83  exit(1);
84  }
85 
86  std::string model_in_filename = po.GetArg(1),
87  fst_in_str = po.GetArg(2),
88  feature_rspecifier = po.GetArg(3),
89  lattice_wspecifier = po.GetArg(4),
90  words_wspecifier = po.GetOptArg(5),
91  alignment_wspecifier = po.GetOptArg(6);
92 
93  TransitionModel trans_model;
94  AmNnetSimple am_nnet;
95  {
96  bool binary;
97  Input ki(model_in_filename, &binary);
98  trans_model.Read(ki.Stream(), binary);
99  am_nnet.Read(ki.Stream(), binary);
100  SetBatchnormTestMode(true, &(am_nnet.GetNnet()));
101  SetDropoutTestMode(true, &(am_nnet.GetNnet()));
102  CollapseModel(CollapseModelConfig(), &(am_nnet.GetNnet()));
103  }
104 
105  bool determinize = config.determinize_lattice;
106  CompactLatticeWriter compact_lattice_writer;
107  LatticeWriter lattice_writer;
108  if (! (determinize ? compact_lattice_writer.Open(lattice_wspecifier)
109  : lattice_writer.Open(lattice_wspecifier)))
110  KALDI_ERR << "Could not open table for writing lattices: "
111  << lattice_wspecifier;
112 
113  RandomAccessBaseFloatMatrixReader online_ivector_reader(
114  online_ivector_rspecifier);
116  ivector_rspecifier, utt2spk_rspecifier);
117 
118  Int32VectorWriter words_writer(words_wspecifier);
119  Int32VectorWriter alignment_writer(alignment_wspecifier);
120 
121  fst::SymbolTable *word_syms = NULL;
122  if (word_syms_filename != "")
123  if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename)))
124  KALDI_ERR << "Could not read symbol table from file "
125  << word_syms_filename;
126 
127  double tot_like = 0.0;
128  kaldi::int64 frame_count = 0;
129  int num_success = 0, num_fail = 0;
130 
131  // this object contains precomputed stuff that is used by all decodable
132  // objects. It takes a pointer to am_nnet because if it has iVectors it has
133  // to modify the nnet to accept iVectors at intervals.
134  DecodableNnetSimpleLoopedInfo decodable_info(decodable_opts,
135  &am_nnet);
136 
137 
138  if (ClassifyRspecifier(fst_in_str, NULL, NULL) == kNoRspecifier) {
139  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
140 
141  // Input FST is just one FST, not a table of FSTs.
142  Fst<StdArc> *decode_fst = fst::ReadFstKaldiGeneric(fst_in_str);
143  timer.Reset();
144 
145  {
146  LatticeFasterDecoder decoder(*decode_fst, config);
147 
148  for (; !feature_reader.Done(); feature_reader.Next()) {
149  std::string utt = feature_reader.Key();
150  const Matrix<BaseFloat> &features (feature_reader.Value());
151  if (features.NumRows() == 0) {
152  KALDI_WARN << "Zero-length utterance: " << utt;
153  num_fail++;
154  continue;
155  }
156  const Matrix<BaseFloat> *online_ivectors = NULL;
157  const Vector<BaseFloat> *ivector = NULL;
158  if (!ivector_rspecifier.empty()) {
159  if (!ivector_reader.HasKey(utt)) {
160  KALDI_WARN << "No iVector available for utterance " << utt;
161  num_fail++;
162  continue;
163  } else {
164  ivector = &ivector_reader.Value(utt);
165  }
166  }
167  if (!online_ivector_rspecifier.empty()) {
168  if (!online_ivector_reader.HasKey(utt)) {
169  KALDI_WARN << "No online iVector available for utterance " << utt;
170  num_fail++;
171  continue;
172  } else {
173  online_ivectors = &online_ivector_reader.Value(utt);
174  }
175  }
176 
177 
178  DecodableAmNnetSimpleLooped nnet_decodable(
179  decodable_info, trans_model, features, ivector, online_ivectors,
180  online_ivector_period);
181 
182  double like;
184  decoder, nnet_decodable, trans_model, word_syms, utt,
185  decodable_opts.acoustic_scale, determinize, allow_partial,
186  &alignment_writer, &words_writer, &compact_lattice_writer,
187  &lattice_writer,
188  &like)) {
189  tot_like += like;
190  frame_count += nnet_decodable.NumFramesReady();
191  num_success++;
192  } else num_fail++;
193  }
194  }
195  delete decode_fst; // delete this only after decoder goes out of scope.
196  } else { // We have different FSTs for different utterances.
197  SequentialTableReader<fst::VectorFstHolder> fst_reader(fst_in_str);
198  RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
199  for (; !fst_reader.Done(); fst_reader.Next()) {
200  std::string utt = fst_reader.Key();
201  if (!feature_reader.HasKey(utt)) {
202  KALDI_WARN << "Not decoding utterance " << utt
203  << " because no features available.";
204  num_fail++;
205  continue;
206  }
207  const Matrix<BaseFloat> &features = feature_reader.Value(utt);
208  if (features.NumRows() == 0) {
209  KALDI_WARN << "Zero-length utterance: " << utt;
210  num_fail++;
211  continue;
212  }
213 
214  LatticeFasterDecoder decoder(fst_reader.Value(), config);
215 
216  const Matrix<BaseFloat> *online_ivectors = NULL;
217  const Vector<BaseFloat> *ivector = NULL;
218  if (!ivector_rspecifier.empty()) {
219  if (!ivector_reader.HasKey(utt)) {
220  KALDI_WARN << "No iVector available for utterance " << utt;
221  num_fail++;
222  continue;
223  } else {
224  ivector = &ivector_reader.Value(utt);
225  }
226  }
227  if (!online_ivector_rspecifier.empty()) {
228  if (!online_ivector_reader.HasKey(utt)) {
229  KALDI_WARN << "No online iVector available for utterance " << utt;
230  num_fail++;
231  continue;
232  } else {
233  online_ivectors = &online_ivector_reader.Value(utt);
234  }
235  }
236 
237  DecodableAmNnetSimpleLooped nnet_decodable(
238  decodable_info, trans_model, features, ivector, online_ivectors,
239  online_ivector_period);
240 
241  double like;
243  decoder, nnet_decodable, trans_model, word_syms, utt,
244  decodable_opts.acoustic_scale, determinize, allow_partial,
245  &alignment_writer, &words_writer, &compact_lattice_writer,
246  &lattice_writer, &like)) {
247  tot_like += like;
248  frame_count += nnet_decodable.NumFramesReady();
249  num_success++;
250  } else num_fail++;
251  }
252  }
253 
254  kaldi::int64 input_frame_count =
255  frame_count * decodable_opts.frame_subsampling_factor;
256 
257  double elapsed = timer.Elapsed();
258  KALDI_LOG << "Time taken "<< elapsed
259  << "s: real-time factor assuming 100 frames/sec is "
260  << (elapsed * 100.0 / input_frame_count);
261  KALDI_LOG << "Done " << num_success << " utterances, failed for "
262  << num_fail;
263  KALDI_LOG << "Overall log-likelihood per frame is "
264  << (tot_like / frame_count) << " over "
265  << frame_count <<" frames.";
266 
267  delete word_syms;
268  if (num_success != 0) return 0;
269  else return 1;
270  } catch(const std::exception &e) {
271  std::cerr << e.what();
272  return -1;
273  }
274 }
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
void CollapseModel(const CollapseModelConfig &config, Nnet *nnet)
This function modifies the neural net for efficiency, in a way that suitable to be done in test time...
Definition: nnet-utils.cc:2100
bool Open(const std::string &wspecifier)
Fst< StdArc > * ReadFstKaldiGeneric(std::string rxfilename, bool throw_on_err)
Definition: kaldi-fst-io.cc:45
void Reset()
Definition: timer.h:71
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
fst::StdArc StdArc
This class is for when you are reading something in random access, but it may actually be stored per-...
Definition: kaldi-table.h:432
virtual int32 NumFramesReady() const
The call NumFramesReady() will return the number of frames currently available for this decodable obj...
void SetBatchnormTestMode(bool test_mode, Nnet *nnet)
This function affects only components of type BatchNormComponent.
Definition: nnet-utils.cc:564
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
bool DecodeUtteranceLatticeFaster(LatticeFasterDecoderTpl< FST > &decoder, DecodableInterface &decodable, const TransitionModel &trans_model, const fst::SymbolTable *word_syms, std::string utt, double acoustic_scale, bool determinize, bool allow_partial, Int32VectorWriter *alignment_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, double *like_ptr)
This function DecodeUtteranceLatticeFaster is used in several decoders, and we have moved it here...
const Nnet & GetNnet() const
void Read(std::istream &is, bool binary)
void Register(const std::string &name, bool *ptr, const std::string &doc)
RspecifierType ClassifyRspecifier(const std::string &rspecifier, std::string *rxfilename, RspecifierOptions *opts)
Definition: kaldi-table.cc:225
This file contains some miscellaneous functions dealing with class Nnet.
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
void SetDropoutTestMode(bool test_mode, Nnet *nnet)
This function affects components of child-classes of RandomComponent.
Definition: nnet-utils.cc:573
std::istream & Stream()
Definition: kaldi-io.cc:826
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
const T & Value(const std::string &key)
void Read(std::istream &is, bool binary)
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Read(int argc, const char *const *argv)
Parses the command line options and fills the ParseOptions-registered variables.
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
bool HasKey(const std::string &key)
This is the "normal" lattice-generating decoder.
int NumArgs() const
Number of positional parameters (c.f. argc-1).
A class representing a vector.
Definition: kaldi-vector.h:406
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
const T & Value(const std::string &key)
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
When you instantiate class DecodableNnetSimpleLooped, you should give it a const reference to this cl...
std::string GetOptArg(int param) const
Config class for the CollapseModel function.
Definition: nnet-utils.h:240
int main(int argc, char *argv[])