gmm-decode-faster-regtree-mllr.cc
Go to the documentation of this file.
1 // gmmbin/gmm-decode-faster-regtree-mllr.cc
2 
3 // Copyright 2009-2013 Microsoft Corporation; Saarland University;
4 // 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 #include <string>
22 #include <vector>
23 
24 #include "base/kaldi-common.h"
25 #include "util/common-utils.h"
26 #include "gmm/am-diag-gmm.h"
27 #include "hmm/transition-model.h"
30 #include "fstext/fstext-lib.h"
31 #include "decoder/faster-decoder.h"
33 #include "base/timer.h"
34 #include "lat/kaldi-lattice.h" // for {Compact}LatticeArc
35 
36 using fst::SymbolTable;
37 using fst::VectorFst;
38 using fst::StdArc;
39 using kaldi::BaseFloat;
40 using std::string;
41 using std::vector;
43 using kaldi::LatticeArc;
44 
45 struct DecodeInfo {
46  public:
49  BaseFloat scale, bool allow_partial,
50  const kaldi::Int32VectorWriter &wwriter,
51  const kaldi::Int32VectorWriter &awriter, fst::SymbolTable *wsyms)
52  : acoustic_model(am), trans_model(tm), decoder(decoder),
53  acoustic_scale(scale), allow_partial(allow_partial), words_writer(wwriter),
54  alignment_writer(awriter), word_syms(wsyms) {}
55 
60  bool allow_partial;
63  fst::SymbolTable *word_syms;
64 
65  private:
67 };
68 
70  kaldi::DecodableInterface *decodable,
71  DecodeInfo *info,
72  const string &uttid,
73  int32 num_frames,
74  BaseFloat *total_like) {
75  decoder->Decode(decodable);
76  KALDI_LOG << "Length of file is " << num_frames;;
77 
78  VectorFst<LatticeArc> decoded; // linear FST.
79  if ( (info->allow_partial || decoder->ReachedFinal())
80  && decoder->GetBestPath(&decoded) ) {
81  if (!decoder->ReachedFinal())
82  KALDI_WARN << "Decoder did not reach end-state, outputting partial "
83  "traceback.";
84 
85  vector<kaldi::int32> alignment, words;
86  LatticeWeight weight;
87  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
88 
89  info->words_writer.Write(uttid, words);
90  if (info->alignment_writer.IsOpen())
91  info->alignment_writer.Write(uttid, alignment);
92  if (info->word_syms != NULL) {
93  std::ostringstream ss;
94  ss << uttid << ' ';
95  for (size_t i = 0; i < words.size(); i++) {
96  string s = info->word_syms->Find(words[i]);
97  if (s == "")
98  KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
99  ss << s << ' ';
100  }
101  ss << '\n';
102  KALDI_LOG << ss.str();
103  }
104 
105  BaseFloat like = -weight.Value1() -weight.Value2();
106  KALDI_LOG << "Log-like per frame = " << (like/num_frames);
107  (*total_like) += like;
108  return true;
109  } else {
110  KALDI_WARN << "Did not successfully decode utterance, length = "
111  << num_frames;
112  return false;
113  }
114 }
115 
116 int main(int argc, char *argv[]) {
117  try {
118  using namespace kaldi;
119  typedef kaldi::int32 int32;
120 
121  const char *usage = "Decode features using GMM-based model.\n"
122  "Usage: gmm-decode-faster-regtree-mllr [options] model-in fst-in "
123  "regtree-in features-rspecifier transforms-rspecifier "
124  "words-wspecifier [alignments-wspecifier]\n";
125  ParseOptions po(usage);
126  bool binary = true;
127  bool allow_partial = true;
129 
130  std::string word_syms_filename, utt2spk_rspecifier;
131  FasterDecoderOptions decoder_opts;
132  decoder_opts.Register(&po, true); // true == include obscure settings.
133  po.Register("utt2spk", &utt2spk_rspecifier, "rspecifier for utterance to "
134  "speaker map");
135  po.Register("binary", &binary, "Write output in binary mode");
136  po.Register("acoustic-scale", &acoustic_scale,
137  "Scaling factor for acoustic likelihoods");
138  po.Register("word-symbol-table", &word_syms_filename,
139  "Symbol table for words [for debug output]");
140  po.Register("allow-partial", &allow_partial,
141  "Produce output even when final state was not reached");
142  po.Read(argc, argv);
143 
144  if (po.NumArgs() < 6 || po.NumArgs() > 7) {
145  po.PrintUsage();
146  exit(1);
147  }
148 
149  std::string model_in_filename = po.GetArg(1),
150  fst_in_filename = po.GetArg(2),
151  regtree_filename = po.GetArg(3),
152  feature_rspecifier = po.GetArg(4),
153  xforms_rspecifier = po.GetArg(5),
154  words_wspecifier = po.GetArg(6),
155  alignment_wspecifier = po.GetOptArg(7);
156 
158  AmDiagGmm am_gmm;
159  {
160  bool binary_read;
161  Input ki(model_in_filename, &binary_read);
162  trans_model.Read(ki.Stream(), binary_read);
163  am_gmm.Read(ki.Stream(), binary_read);
164  }
165 
166  VectorFst<StdArc> *decode_fst = fst::ReadFstKaldi(fst_in_filename);
167 
168  RegressionTree regtree;
169  {
170  bool binary_read;
171  Input in(regtree_filename, &binary_read);
172  regtree.Read(in.Stream(), binary_read, am_gmm);
173  }
174 
175  RandomAccessRegtreeMllrDiagGmmReaderMapped mllr_reader(xforms_rspecifier,
176  utt2spk_rspecifier);
177 
178  Int32VectorWriter words_writer(words_wspecifier);
179 
180  Int32VectorWriter alignment_writer(alignment_wspecifier);
181 
182  fst::SymbolTable *word_syms = NULL;
183  if (word_syms_filename != "") {
184  word_syms = fst::SymbolTable::ReadText(word_syms_filename);
185  if (!word_syms) {
186  KALDI_ERR << "Could not read symbol table from file "
187  << word_syms_filename;
188  }
189  }
190 
191  BaseFloat tot_like = 0.0;
192  kaldi::int64 frame_count = 0;
193  int num_success = 0, num_fail = 0;
194  FasterDecoder decoder(*decode_fst, decoder_opts);
195 
196  Timer timer;
197 
198  DecodeInfo decode_info(am_gmm, trans_model, &decoder, acoustic_scale,
199  allow_partial, words_writer, alignment_writer,
200  word_syms);
201 
202  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
203  for (; !feature_reader.Done(); feature_reader.Next()) {
204  string utt = feature_reader.Key();
205 
206  Matrix<BaseFloat> features(feature_reader.Value());
207  feature_reader.FreeCurrent();
208  if (features.NumRows() == 0) {
209  KALDI_WARN << "Zero-length utterance: " << utt;
210  num_fail++;
211  continue;
212  }
213 
214  if (!mllr_reader.HasKey(utt)) { // Decode without MLLR if none found
215  KALDI_WARN << "No MLLR transform for key " << utt <<
216  ", decoding without MLLR.";
217  kaldi::DecodableAmDiagGmmScaled gmm_decodable(am_gmm, trans_model,
218  features,
219  acoustic_scale);
220  if (DecodeUtterance(&decoder, &gmm_decodable, &decode_info,
221  utt, features.NumRows(), &tot_like)) {
222  frame_count += gmm_decodable.NumFramesReady();
223  num_success++;
224  } else {
225  num_fail++;
226  }
227  continue;
228  }
229 
230  // If found, load the transforms for the current utterance.
231  const RegtreeMllrDiagGmm &mllr = mllr_reader.Value(utt);
232  kaldi::DecodableAmDiagGmmRegtreeMllr gmm_decodable(am_gmm, trans_model,
233  features, mllr,
234  regtree,
235  acoustic_scale);
236  if (DecodeUtterance(&decoder, &gmm_decodable, &decode_info,
237  utt, features.NumRows(), &tot_like)) {
238  frame_count += gmm_decodable.NumFramesReady();
239  num_success++;
240  } else {
241  num_fail++;
242  }
243  } // end looping over all utterances
244 
245  double elapsed = timer.Elapsed();
246  KALDI_LOG << "Time taken [excluding initialization] " << elapsed
247  << "s: real-time factor assuming 100 frames/sec is "
248  << (elapsed * 100.0 / frame_count);
249  KALDI_LOG << "Done " << num_success << " utterances, failed for "
250  << num_fail;
251  KALDI_LOG << "Overall log-likelihood per frame is "
252  << (tot_like / frame_count) << " over " << frame_count
253  << " frames.";
254 
255  delete decode_fst;
256  if (num_success != 0)
257  return 0;
258  else
259  return 1;
260  }
261  catch(const std::exception &e) {
262  std::cerr << e.what();
263  return -1;
264  }
265 }
266 
267 
int32 words[kMaxOrder]
void Read(std::istream &in, bool binary, const AmDiagGmm &am)
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
fst::ArcTpl< LatticeWeight > LatticeArc
Definition: kaldi-lattice.h:40
An MLLR mean transformation is an affine transformation of Gaussian means.
DecodableInterface provides a link between the (acoustic-modeling and feature-processing) code and th...
Definition: decodable-itf.h:82
const kaldi::Int32VectorWriter & alignment_writer
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
bool DecodeUtterance(kaldi::FasterDecoder *decoder, kaldi::DecodableInterface *decodable, DecodeInfo *info, const string &uttid, int32 num_frames, BaseFloat *total_like)
const kaldi::TransitionModel & trans_model
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
DecodeInfo(const kaldi::AmDiagGmm &am, const kaldi::TransitionModel &tm, kaldi::FasterDecoder *decoder, BaseFloat scale, bool allow_partial, const kaldi::Int32VectorWriter &wwriter, const kaldi::Int32VectorWriter &awriter, fst::SymbolTable *wsyms)
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.
KALDI_DISALLOW_COPY_AND_ASSIGN(DecodeInfo)
void Write(const std::string &key, const T &value) const
void Register(const std::string &name, bool *ptr, const std::string &doc)
fst::LatticeWeightTpl< BaseFloat > LatticeWeight
Definition: kaldi-lattice.h:32
bool GetBestPath(fst::MutableFst< LatticeArc > *fst_out, bool use_final_probs=true)
GetBestPath gets the decoding traceback.
std::istream & Stream()
Definition: kaldi-io.cc:826
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
A regression tree is a clustering of Gaussian densities in an acoustic model, such that the group of ...
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
void Register(OptionsItf *opts, bool full)
bool HasKey(const std::string &key)
virtual int32 NumFramesReady() const
The call NumFramesReady() will return the number of frames currently available for this decodable obj...
fst::SymbolTable * word_syms
kaldi::FasterDecoder * decoder
const kaldi::AmDiagGmm & acoustic_model
int NumArgs() const
Number of positional parameters (c.f. argc-1).
void ReadFstKaldi(std::istream &is, bool binary, VectorFst< Arc > *fst)
virtual int32 NumFramesReady() const
The call NumFramesReady() will return the number of frames currently available for this decodable obj...
LatticeWeightTpl< BaseFloat > LatticeWeight
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
void Read(std::istream &in_stream, bool binary)
Definition: am-diag-gmm.cc:147
int main(int argc, char *argv[])
bool ReachedFinal() const
Returns true if a final state was active on the last frame.
const kaldi::Int32VectorWriter & words_writer
std::string GetOptArg(int param) const