nnet-latgen-faster-parallel.cc
Go to the documentation of this file.
1 // nnet2bin/nnet-latgen-faster-parallel.cc
2 
3 // Copyright 2009-2013 Microsoft Corporation
4 // Johns Hopkins University (author: Daniel Povey)
5 // 2014 Guoguo Chen
6 
7 // See ../../COPYING for clarification regarding multiple authors
8 //
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 //
13 // http://www.apache.org/licenses/LICENSE-2.0
14 //
15 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
17 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
18 // MERCHANTABLITY OR NON-INFRINGEMENT.
19 // See the Apache 2 License for the specific language governing permissions and
20 // limitations under the License.
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/kaldi-fst-io.h"
29 #include "base/timer.h"
30 #include "util/kaldi-thread.h"
31 
32 
33 int main(int argc, char *argv[]) {
34  try {
35  using namespace kaldi;
36  using namespace kaldi::nnet2;
37  typedef kaldi::int32 int32;
38  using fst::SymbolTable;
39  using fst::Fst;
40  using fst::StdArc;
41 
42  const char *usage =
43  "Generate lattices using neural net model.\n"
44  "Usage: nnet-latgen-faster-parallel [options] <nnet-in> <fst-in|fsts-rspecifier> <features-rspecifier>"
45  " <lattice-wspecifier> [ <words-wspecifier> [<alignments-wspecifier>] ]\n";
46  ParseOptions po(usage);
47  Timer timer;
48  bool allow_partial = false;
49  BaseFloat acoustic_scale = 0.1;
51  TaskSequencerConfig sequencer_config; // has --num-threads option
52 
53  std::string word_syms_filename;
54  sequencer_config.Register(&po);
55  config.Register(&po);
56  po.Register("acoustic-scale", &acoustic_scale, "Scaling factor for acoustic likelihoods");
57  po.Register("word-symbol-table", &word_syms_filename, "Symbol table for words [for debug output]");
58  po.Register("allow-partial", &allow_partial, "If true, produce output even if end state was not reached.");
59 
60  po.Read(argc, argv);
61 
62  if (po.NumArgs() < 4 || po.NumArgs() > 6) {
63  po.PrintUsage();
64  exit(1);
65  }
66 
67  std::string model_in_filename = po.GetArg(1),
68  fst_in_str = po.GetArg(2),
69  feature_rspecifier = po.GetArg(3),
70  lattice_wspecifier = po.GetArg(4),
71  words_wspecifier = po.GetOptArg(5),
72  alignment_wspecifier = po.GetOptArg(6);
73 
74  TransitionModel trans_model;
75  AmNnet am_nnet;
76  {
77  bool binary;
78  Input ki(model_in_filename, &binary);
79  trans_model.Read(ki.Stream(), binary);
80  am_nnet.Read(ki.Stream(), binary);
81  }
82 
83  bool determinize = config.determinize_lattice;
84  CompactLatticeWriter compact_lattice_writer;
85  LatticeWriter lattice_writer;
86  if (! (determinize ? compact_lattice_writer.Open(lattice_wspecifier)
87  : lattice_writer.Open(lattice_wspecifier)))
88  KALDI_ERR << "Could not open table for writing lattices: "
89  << lattice_wspecifier;
90 
91  TaskSequencer<DecodeUtteranceLatticeFasterClass> sequencer(sequencer_config);
92 
93  Int32VectorWriter words_writer(words_wspecifier);
94 
95  Int32VectorWriter alignment_writer(alignment_wspecifier);
96 
97  fst::SymbolTable *word_syms = NULL;
98  if (word_syms_filename != "")
99  if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename)))
100  KALDI_ERR << "Could not read symbol table from file "
101  << word_syms_filename;
102 
103  // We support reading in a vector to describe each speaker, if the neural
104  // net requires this (i.e. it was trained with this).
105 
106  double tot_like = 0.0;
107  kaldi::int64 frame_count = 0;
108  int num_done = 0, num_err = 0;
109  Fst<StdArc> *decode_fst = NULL;
110  if (ClassifyRspecifier(fst_in_str, NULL, NULL) == kNoRspecifier) {
111  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
112 
113  decode_fst = fst::ReadFstKaldiGeneric(fst_in_str);
114  timer.Reset();
115 
116  {
117 
118  for (; !feature_reader.Done(); feature_reader.Next()) {
119  std::string utt = feature_reader.Key();
120  const Matrix<BaseFloat> &features (feature_reader.Value());
121  if (features.NumRows() == 0) {
122  KALDI_WARN << "Zero-length utterance: " << utt;
123  num_err++;
124  continue;
125  }
126  bool pad_input = true;
127  DecodableAmNnetParallel *nnet_decodable = new DecodableAmNnetParallel(
128  trans_model, am_nnet,
129  new CuMatrix<BaseFloat>(features),
130  pad_input, acoustic_scale);
131 
132  LatticeFasterDecoder *decoder = new LatticeFasterDecoder(*decode_fst,
133  config);
134 
137  decoder, nnet_decodable, // takes ownership of these two.
138  trans_model, word_syms, utt, acoustic_scale, determinize,
139  allow_partial, &alignment_writer, &words_writer,
140  &compact_lattice_writer, &lattice_writer,
141  &tot_like, &frame_count, &num_done, &num_err, NULL);
142 
143  sequencer.Run(task); // takes ownership of "task",
144  // and will delete it when done.
145  }
146  }
147  } else { // We have different FSTs for different utterances.
148  SequentialTableReader<fst::VectorFstHolder> fst_reader(fst_in_str);
149  RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
150  for (; !fst_reader.Done(); fst_reader.Next()) {
151  std::string utt = fst_reader.Key();
152  if (!feature_reader.HasKey(utt)) {
153  KALDI_WARN << "Not decoding utterance " << utt
154  << " because no features available.";
155  num_err++;
156  continue;
157  }
158  const Matrix<BaseFloat> &features = feature_reader.Value(utt);
159  if (features.NumRows() == 0) {
160  KALDI_WARN << "Zero-length utterance: " << utt;
161  num_err++;
162  continue;
163  }
164 
165  // This constructor of LatticeFasterDecoder takes ownership of the FST.
166  LatticeFasterDecoder *decoder =
167  new LatticeFasterDecoder(config, fst_reader.Value().Copy());
168 
169  bool pad_input = true;
170  DecodableAmNnetParallel *nnet_decodable = new DecodableAmNnetParallel(
171  trans_model, am_nnet,
172  new CuMatrix<BaseFloat>(features),
173  pad_input, acoustic_scale);
174 
177  decoder, nnet_decodable, // takes ownership of these two.
178  trans_model, word_syms, utt, acoustic_scale, determinize,
179  allow_partial, &alignment_writer, &words_writer,
180  &compact_lattice_writer, &lattice_writer,
181  &tot_like, &frame_count, &num_done, &num_err, NULL);
182 
183  sequencer.Run(task); // takes ownership of "task",
184  // and will delete it when done.
185  }
186  }
187  sequencer.Wait(); // Waits for all tasks to be done.
188  delete decode_fst;
189 
190  double elapsed = timer.Elapsed();
191  KALDI_LOG << "Time taken "<< elapsed
192  << "s: real-time factor per thread assuming 100 frames/sec is "
193  << (sequencer_config.num_threads * elapsed * 100.0 / frame_count);
194  KALDI_LOG << "Done " << num_done << " utterances, failed for "
195  << num_err;
196  KALDI_LOG << "Overall log-likelihood per frame is "
197  << (tot_like / frame_count) << " over " << frame_count
198  << " frames.";
199 
200  delete word_syms;
201  if (num_done != 0) return 0;
202  else return 1;
203  } catch(const std::exception &e) {
204  std::cerr << e.what();
205  return -1;
206  }
207 }
This version of DecodableAmNnet is intended for a version of the decoder that processes different utt...
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
bool Open(const std::string &wspecifier)
Fst< StdArc > * ReadFstKaldiGeneric(std::string rxfilename, bool throw_on_err)
Definition: kaldi-fst-io.cc:45
void Run(C *c)
This function takes ownership of the pointer "c", and will delete it in the same sequence as Run was ...
Definition: kaldi-thread.h:190
void Reset()
Definition: timer.h:71
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
fst::StdArc StdArc
void Read(std::istream &is, bool binary)
Definition: am-nnet.cc:39
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
This class represents a matrix that&#39;s stored on the GPU if we have one, and in memory if not...
Definition: matrix-common.h:71
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
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
std::istream & Stream()
Definition: kaldi-io.cc:826
float BaseFloat
Definition: kaldi-types.h:29
This class basically does the same job as the function DecodeUtteranceLatticeFaster, but in a way that allows us to build a multi-threaded command line program more easily.
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
int main(int argc, char *argv[])
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).
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
LatticeFasterDecoderTpl< fst::StdFst, decoder::StdToken > LatticeFasterDecoder
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
std::string GetOptArg(int param) const
void Register(OptionsItf *opts)
Definition: kaldi-thread.h:160