sgmm2-latgen-faster-parallel.cc
Go to the documentation of this file.
1 // sgmm2bin/sgmm2-latgen-faster-parallel.cc
2 
3 // Copyright 2009-2013 Saarland University; 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 <string>
23 using std::string;
24 
25 #include "base/kaldi-common.h"
26 #include "util/common-utils.h"
27 #include "sgmm2/am-sgmm2.h"
28 #include "hmm/transition-model.h"
29 #include "fstext/fstext-lib.h"
32 #include "util/kaldi-thread.h"
33 #include "base/timer.h"
34 
35 namespace kaldi {
36 
37 // the reference arguments at the beginning are not const as the style guide
38 // requires, but are best viewed as inputs.
39 void ProcessUtterance(const AmSgmm2 &am_sgmm,
40  const TransitionModel &trans_model,
41  double log_prune,
42  double acoustic_scale,
43  const Matrix<BaseFloat> &features,
46  const fst::SymbolTable *word_syms,
47  const std::string &utt,
48  bool determinize,
49  bool allow_partial,
50  Int32VectorWriter *alignments_writer,
51  Int32VectorWriter *words_writer,
52  CompactLatticeWriter *compact_lattice_writer,
53  LatticeWriter *lattice_writer,
54  LatticeFasterDecoder *decoder, // Takes ownership of this.
55  double *like_sum,
56  int64 *frame_sum,
57  int32 *num_done,
58  int32 *num_err,
60  using fst::Fst;
61  using std::vector;
62 
63  Sgmm2PerSpkDerivedVars *spk_vars = new Sgmm2PerSpkDerivedVars; // decodable
64  // will take ownership.
65  if (spkvecs_reader.IsOpen()) {
66  if (spkvecs_reader.HasKey(utt)) {
67  spk_vars->SetSpeakerVector(spkvecs_reader.Value(utt));
68  am_sgmm.ComputePerSpkDerivedVars(spk_vars);
69  } else {
70  KALDI_WARN << "Cannot find speaker vector for " << utt << ", not decoding this utterance";
71  delete spk_vars;
72  (*num_err)++;
73  return;
74  }
75  }
76  if (!gselect_reader.HasKey(utt) ||
77  gselect_reader.Value(utt).size() != features.NumRows()) {
78  KALDI_WARN << "No Gaussian-selection info available for utterance "
79  << utt << " (or wrong size)";
80  }
81 
82  // decodable will take ownership.
83  vector<vector<int32> > *gselect = new std::vector<vector<int32> >(
84  gselect_reader.Value(utt));
85 
86  Matrix<BaseFloat> *new_feats = new Matrix<BaseFloat>(features); // decodable
87  // will take ownership of this.
88 
89  // This takes ownership of new_feats, gselect, and spk_vars
90  DecodableAmSgmm2Scaled *sgmm_decodable = new DecodableAmSgmm2Scaled(
91  am_sgmm, trans_model, new_feats, gselect,
92  spk_vars, log_prune, acoustic_scale);
93 
94  // takes ownership of decoder and sgmm_decodable.
97  decoder, sgmm_decodable, trans_model, word_syms, utt, acoustic_scale,
98  determinize, allow_partial, alignments_writer, words_writer,
99  compact_lattice_writer, lattice_writer, like_sum, frame_sum, num_done,
100  num_err, NULL);
101 
102  sequencer->Run(task); // takes ownership.
103 }
104 
105 } // end namespace kaldi
106 
107 int main(int argc, char *argv[]) {
108  try {
109  using namespace kaldi;
110  typedef kaldi::int32 int32;
111  using fst::SymbolTable;
112  using fst::Fst;
113  using fst::VectorFst;
114  using fst::StdArc;
115 
116  const char *usage =
117  "Decode features using SGMM-based model. This version accepts the --num-threads\n"
118  "option but otherwise behaves identically to sgmm2-latgen-faster\n"
119  "Usage: sgmm2-latgen-faster-parallel [options] <model-in> (<fst-in>|<fsts-rspecifier>) "
120  "<features-rspecifier> <lattices-wspecifier> [<words-wspecifier> [<alignments-wspecifier>] ]\n";
121  ParseOptions po(usage);
122  BaseFloat acoustic_scale = 0.1;
123  bool allow_partial = false;
124  BaseFloat log_prune = 5.0;
125  string word_syms_filename, gselect_rspecifier, spkvecs_rspecifier,
126  utt2spk_rspecifier;
127 
128  LatticeFasterDecoderConfig decoder_opts;
129  TaskSequencerConfig sequencer_config; // has --num-threads option
130  decoder_opts.Register(&po);
131  sequencer_config.Register(&po);
132 
133  po.Register("acoustic-scale", &acoustic_scale,
134  "Scaling factor for acoustic likelihoods");
135  po.Register("log-prune", &log_prune,
136  "Pruning beam used to reduce number of exp() evaluations.");
137  po.Register("word-symbol-table", &word_syms_filename,
138  "Symbol table for words [for debug output]");
139  po.Register("allow-partial", &allow_partial,
140  "Produce output even when final state was not reached");
141  po.Register("gselect", &gselect_rspecifier,
142  "rspecifier for precomputed per-frame Gaussian indices.");
143  po.Register("spk-vecs", &spkvecs_rspecifier,
144  "rspecifier for speaker vectors");
145  po.Register("utt2spk", &utt2spk_rspecifier,
146  "rspecifier for utterance to speaker map");
147  po.Read(argc, argv);
148 
149  if (po.NumArgs() < 4 || po.NumArgs() > 6) {
150  po.PrintUsage();
151  exit(1);
152  }
153 
154  if (gselect_rspecifier == "")
155  KALDI_ERR << "--gselect option is required.";
156 
157  std::string model_in_filename = po.GetArg(1),
158  fst_in_str = po.GetArg(2),
159  feature_rspecifier = po.GetArg(3),
160  lattice_wspecifier = po.GetArg(4),
161  words_wspecifier = po.GetOptArg(5),
162  alignment_wspecifier = po.GetOptArg(6);
163 
164  double tot_like = 0.0;
165  kaldi::int64 frame_count = 0;
166  int num_done = 0, num_err = 0;
167  Timer timer;
168  Fst<StdArc> *decode_fst = NULL;
169  fst::SymbolTable *word_syms = NULL;
170 
172  sequencer_config);
173  TransitionModel trans_model;
174  kaldi::AmSgmm2 am_sgmm;
175  {
176  bool binary;
177  Input ki(model_in_filename, &binary);
178  trans_model.Read(ki.Stream(), binary);
179  am_sgmm.Read(ki.Stream(), binary);
180  }
181 
182  CompactLatticeWriter compact_lattice_writer;
183  LatticeWriter lattice_writer;
184 
185  bool determinize = decoder_opts.determinize_lattice;
186  if (! (determinize ? compact_lattice_writer.Open(lattice_wspecifier)
187  : lattice_writer.Open(lattice_wspecifier)))
188  KALDI_ERR << "Could not open table for writing lattices: "
189  << lattice_wspecifier;
190 
191  Int32VectorWriter words_writer(words_wspecifier);
192  Int32VectorWriter alignment_writer(alignment_wspecifier);
193 
194  if (word_syms_filename != "")
195  if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename)))
196  KALDI_ERR << "Could not read symbol table from file "
197  << word_syms_filename;
198 
199  RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier);
200  RandomAccessBaseFloatVectorReaderMapped spkvecs_reader(spkvecs_rspecifier,
201  utt2spk_rspecifier);
202 
203  if (ClassifyRspecifier(fst_in_str, NULL, NULL) == kNoRspecifier) { // a single FST.
204  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
205  // It's important that we initialize decode_fst after feature_reader, as it
206  // can prevent crashes on systems installed without enough virtual memory.
207  // It has to do with what happens on UNIX systems if you call fork() on a
208  // large process: the page-table entries are duplicated, which requires a
209  // lot of virtual memory.
210  decode_fst = fst::ReadFstKaldiGeneric(fst_in_str);
211  timer.Reset(); // exclude graph loading time.
212 
213  {
214  for (; !feature_reader.Done(); feature_reader.Next()) {
215  string utt = feature_reader.Key();
216  const Matrix<BaseFloat> &features(feature_reader.Value());
217  if (features.NumRows() == 0) {
218  KALDI_WARN << "Zero-length utterance: " << utt;
219  num_err++;
220  continue;
221  }
222 
223  // ProcessUtterance will take ownership of this.
225  *decode_fst, decoder_opts);
226 
227  ProcessUtterance(am_sgmm, trans_model, log_prune, acoustic_scale,
228  features, gselect_reader, spkvecs_reader, word_syms,
229  utt, determinize, allow_partial,
230  &alignment_writer, &words_writer, &compact_lattice_writer,
231  &lattice_writer, decoder, &tot_like, &frame_count,
232  &num_done, &num_err, &sequencer);
233  }
234  }
235  } else { // We have different FSTs for different utterances.
236  SequentialTableReader<fst::VectorFstHolder> fst_reader(fst_in_str);
237  RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
238  for (; !fst_reader.Done(); fst_reader.Next()) {
239  std::string utt = fst_reader.Key();
240  if (!feature_reader.HasKey(utt)) {
241  KALDI_WARN << "Not decoding utterance " << utt
242  << " because no features available.";
243  num_err++;
244  continue;
245  }
246  const Matrix<BaseFloat> &features = feature_reader.Value(utt);
247  if (features.NumRows() == 0) {
248  KALDI_WARN << "Zero-length utterance: " << utt;
249  num_err++;
250  continue;
251  }
252  VectorFst<StdArc> *fst = fst_reader.Value().Copy(); // Note: this does
253  // a shallow copy because OpenFst is "smart" about these things and
254  // does reference counting. The constructor of LatticeFasterDecoder
255  // takes ownership of this FST (note: LatticeFasterDecoder has 2
256  // constructors, one of which takes ownership and one of which does not).
257  LatticeFasterDecoder *decoder = new LatticeFasterDecoder(decoder_opts,
258  fst);
259 
260  // ProcessUtterance takes ownership of "decoder".
261  ProcessUtterance(am_sgmm, trans_model, log_prune, acoustic_scale,
262  features, gselect_reader, spkvecs_reader, word_syms,
263  utt, determinize, allow_partial,
264  &alignment_writer, &words_writer, &compact_lattice_writer,
265  &lattice_writer, decoder, &tot_like, &frame_count,
266  &num_done, &num_err, &sequencer);
267  }
268  }
269  sequencer.Wait(); // Wait till all tasks are done.
270 
271  delete decode_fst;
272  delete word_syms;
273 
274  double elapsed = timer.Elapsed();
275  KALDI_LOG << "Decoded with " << sequencer_config.num_threads << " threads.";
276  KALDI_LOG << "Time taken [excluding initialization] "<< elapsed
277  << "s: real-time factor per thread assuming 100 frames/sec is "
278  << (sequencer_config.num_threads * elapsed * 100.0 / frame_count);
279  KALDI_LOG << "Done " << num_done << " utterances, failed for "
280  << num_err;
281  KALDI_LOG << "Overall log-likelihood per frame = " << (tot_like/frame_count)
282  << " over " << frame_count << " frames.";
283 
284  return (num_done != 0 ? 0 : 1);
285  } catch(const std::exception &e) {
286  std::cerr << e.what();
287  return -1;
288  }
289 }
290 
291 
void ProcessUtterance(const AmSgmm2 &am_sgmm, const TransitionModel &trans_model, double log_prune, double acoustic_scale, const Matrix< BaseFloat > &features, RandomAccessInt32VectorVectorReader &gselect_reader, RandomAccessBaseFloatVectorReaderMapped &spkvecs_reader, const fst::SymbolTable *word_syms, const std::string &utt, bool determinize, bool allow_partial, Int32VectorWriter *alignments_writer, Int32VectorWriter *words_writer, CompactLatticeWriter *compact_lattice_writer, LatticeWriter *lattice_writer, LatticeFasterDecoder *decoder, double *like_sum, int64 *frame_sum, int32 *num_done, int32 *num_err, TaskSequencer< DecodeUtteranceLatticeFasterClass > *sequencer)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
Class for definition of the subspace Gmm acoustic model.
Definition: am-sgmm2.h:231
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
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
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
void Read(std::istream &is, bool binary)
Definition: am-sgmm2.cc:89
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
void ComputePerSpkDerivedVars(Sgmm2PerSpkDerivedVars *vars) const
Computes the per-speaker derived vars; assumes vars->v_s is already set up.
Definition: am-sgmm2.cc:1369
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
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
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
#define KALDI_WARN
Definition: kaldi-error.h:150
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
const T & Value(const std::string &key)
void SetSpeakerVector(const Vector< BaseFloat > &v_s_in)
Definition: am-sgmm2.h:180
#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
int main(int argc, char *argv[])
void Register(OptionsItf *opts)
Definition: kaldi-thread.h:160