gmm-decode-faster.cc
Go to the documentation of this file.
1 // gmmbin/gmm-decode-faster.cc
2 
3 // Copyright 2009-2011 Microsoft Corporation
4 // 2013 Johns Hopkins University (author: Daniel Povey)
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 "gmm/am-diag-gmm.h"
25 #include "hmm/transition-model.h"
26 #include "fstext/fstext-lib.h"
27 #include "decoder/faster-decoder.h"
29 #include "base/timer.h"
30 #include "lat/kaldi-lattice.h" // for CompactLatticeArc
31 
32 namespace kaldi {
33 
34 fst::Fst<fst::StdArc> *ReadNetwork(std::string filename) {
35  // read decoding network FST
36  Input ki(filename); // use ki.Stream() instead of is.
37  if (!ki.Stream().good()) KALDI_ERR << "Could not open decoding-graph FST "
38  << filename;
39  fst::FstHeader hdr;
40  if (!hdr.Read(ki.Stream(), "<unknown>")) {
41  KALDI_ERR << "Reading FST: error reading FST header.";
42  }
43  if (hdr.ArcType() != fst::StdArc::Type()) {
44  KALDI_ERR << "FST with arc type " << hdr.ArcType() << " not supported.";
45  }
46  fst::FstReadOptions ropts("<unspecified>", &hdr);
47 
48  fst::Fst<fst::StdArc> *decode_fst = NULL;
49 
50  if (hdr.FstType() == "vector") {
51  decode_fst = fst::VectorFst<fst::StdArc>::Read(ki.Stream(), ropts);
52  } else if (hdr.FstType() == "const") {
53  decode_fst = fst::ConstFst<fst::StdArc>::Read(ki.Stream(), ropts);
54  } else {
55  KALDI_ERR << "Reading FST: unsupported FST type: " << hdr.FstType();
56  }
57  if (decode_fst == NULL) { // fst code will warn.
58  KALDI_ERR << "Error reading FST (after reading header).";
59  return NULL;
60  } else {
61  return decode_fst;
62  }
63 }
64 
65 }
66 
67 int main(int argc, char *argv[]) {
68  try {
69  using namespace kaldi;
70  typedef kaldi::int32 int32;
71 
72  const char *usage =
73  "Decode features using GMM-based model.\n"
74  "Usage: gmm-decode-faster [options] model-in fst-in features-rspecifier words-wspecifier [alignments-wspecifier [lattice-wspecifier]]\n"
75  "Note: lattices, if output, will just be linear sequences; use gmm-latgen-faster\n"
76  " if you want \"real\" lattices.\n";
77  ParseOptions po(usage);
78  bool allow_partial = true;
79  BaseFloat acoustic_scale = 0.1;
80 
81  std::string word_syms_filename;
82  FasterDecoderOptions decoder_opts;
83  decoder_opts.Register(&po, true); // true == include obscure settings.
84  po.Register("acoustic-scale", &acoustic_scale,
85  "Scaling factor for acoustic likelihoods");
86  po.Register("word-symbol-table", &word_syms_filename,
87  "Symbol table for words [for debug output]");
88  po.Register("allow-partial", &allow_partial,
89  "Produce output even when final state was not reached");
90  po.Read(argc, argv);
91 
92  if (po.NumArgs() < 4 || po.NumArgs() > 6) {
93  po.PrintUsage();
94  exit(1);
95  }
96 
97  std::string model_rxfilename = po.GetArg(1),
98  fst_rxfilename = po.GetArg(2),
99  feature_rspecifier = po.GetArg(3),
100  words_wspecifier = po.GetArg(4),
101  alignment_wspecifier = po.GetOptArg(5),
102  lattice_wspecifier = po.GetOptArg(6);
103 
104  TransitionModel trans_model;
105  AmDiagGmm am_gmm;
106  {
107  bool binary;
108  Input ki(model_rxfilename, &binary);
109  trans_model.Read(ki.Stream(), binary);
110  am_gmm.Read(ki.Stream(), binary);
111  }
112 
113  Int32VectorWriter words_writer(words_wspecifier);
114 
115  Int32VectorWriter alignment_writer(alignment_wspecifier);
116 
117  CompactLatticeWriter clat_writer(lattice_wspecifier);
118 
119  fst::SymbolTable *word_syms = NULL;
120  if (word_syms_filename != "")
121  if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename)))
122  KALDI_ERR << "Could not read symbol table from file "
123  << word_syms_filename;
124 
125  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
126 
127  // It's important that we initialize decode_fst after feature_reader, as it
128  // can prevent crashes on systems installed without enough virtual memory.
129  // It has to do with what happens on UNIX systems if you call fork() on a
130  // large process: the page-table entries are duplicated, which requires a
131  // lot of virtual memory.
132  fst::Fst<fst::StdArc> *decode_fst = ReadNetwork(fst_rxfilename);
133 
134  BaseFloat tot_like = 0.0;
135  kaldi::int64 frame_count = 0;
136  int num_success = 0, num_fail = 0;
137  FasterDecoder decoder(*decode_fst, decoder_opts);
138 
139  Timer timer;
140 
141  for (; !feature_reader.Done(); feature_reader.Next()) {
142  std::string key = feature_reader.Key();
143  Matrix<BaseFloat> features (feature_reader.Value());
144  feature_reader.FreeCurrent();
145  if (features.NumRows() == 0) {
146  KALDI_WARN << "Zero-length utterance: " << key;
147  num_fail++;
148  continue;
149  }
150 
151  DecodableAmDiagGmmScaled gmm_decodable(am_gmm, trans_model, features,
152  acoustic_scale);
153  decoder.Decode(&gmm_decodable);
154 
155  fst::VectorFst<LatticeArc> decoded; // linear FST.
156 
157  if ( (allow_partial || decoder.ReachedFinal())
158  && decoder.GetBestPath(&decoded) ) {
159  if (!decoder.ReachedFinal())
160  KALDI_WARN << "Decoder did not reach end-state, "
161  << "outputting partial traceback since --allow-partial=true";
162  num_success++;
163  std::vector<int32> alignment;
164  std::vector<int32> words;
165  LatticeWeight weight;
166  frame_count += features.NumRows();
167 
168  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
169 
170  words_writer.Write(key, words);
171  if (alignment_writer.IsOpen())
172  alignment_writer.Write(key, alignment);
173 
174  if (lattice_wspecifier != "") {
175  // We'll write the lattice without acoustic scaling.
176  if (acoustic_scale != 0.0)
177  fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale),
178  &decoded);
179  fst::VectorFst<CompactLatticeArc> clat;
180  ConvertLattice(decoded, &clat, true);
181  clat_writer.Write(key, clat);
182  }
183 
184  if (word_syms != NULL) {
185  std::cerr << key << ' ';
186  for (size_t i = 0; i < words.size(); i++) {
187  std::string s = word_syms->Find(words[i]);
188  if (s == "")
189  KALDI_ERR << "Word-id " << words[i] <<" not in symbol table.";
190  std::cerr << s << ' ';
191  }
192  std::cerr << '\n';
193  }
194  BaseFloat like = -weight.Value1() -weight.Value2();
195  tot_like += like;
196  KALDI_LOG << "Log-like per frame for utterance " << key << " is "
197  << (like / features.NumRows()) << " over "
198  << features.NumRows() << " frames.";
199  KALDI_VLOG(2) << "Cost for utterance " << key << " is "
200  << weight.Value1() << " + " << weight.Value2();
201  } else {
202  num_fail++;
203  KALDI_WARN << "Did not successfully decode utterance " << key
204  << ", len = " << features.NumRows();
205  }
206  }
207 
208  double elapsed = timer.Elapsed();
209  KALDI_LOG << "Time taken [excluding initialization] "<< elapsed
210  << "s: real-time factor assuming 100 frames/sec is "
211  << (elapsed*100.0/frame_count);
212  KALDI_LOG << "Done " << num_success << " utterances, failed for "
213  << num_fail;
214  KALDI_LOG << "Overall log-likelihood per frame is " << (tot_like/frame_count) << " over "
215  << frame_count<<" frames.";
216 
217  delete word_syms;
218  delete decode_fst;
219  return (num_success != 0 ? 0 : 1);
220  } catch(const std::exception &e) {
221  std::cerr << e.what();
222  return -1;
223  }
224 }
225 
226 
int32 words[kMaxOrder]
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
fst::Fst< fst::StdArc > * ReadNetwork(std::string filename)
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
void Decode(DecodableInterface *decodable)
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 GetLinearSymbolSequence(const Fst< Arc > &fst, std::vector< I > *isymbols_out, std::vector< I > *osymbols_out, typename Arc::Weight *tot_weight_out)
GetLinearSymbolSequence gets the symbol sequence from a linear FST.
void Write(const std::string &key, const T &value) const
void Register(const std::string &name, bool *ptr, const std::string &doc)
bool GetBestPath(fst::MutableFst< LatticeArc > *fst_out, bool use_final_probs=true)
GetBestPath gets the decoding traceback.
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
float BaseFloat
Definition: kaldi-types.h:29
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
void Read(std::istream &is, bool binary)
void ConvertLattice(const ExpandedFst< ArcTpl< Weight > > &ifst, MutableFst< ArcTpl< CompactLatticeWeightTpl< Weight, Int > > > *ofst, bool invert)
Convert lattice from a normal FST to a CompactLattice FST.
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.
int main(int argc, char *argv[])
#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.
void Register(OptionsItf *opts, bool full)
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
void Read(std::istream &in_stream, bool binary)
Definition: am-diag-gmm.cc:147
bool ReachedFinal() const
Returns true if a final state was active on the last frame.
std::string GetOptArg(int param) const