decode-faster-mapped.cc
Go to the documentation of this file.
1 // bin/decode-faster-mapped.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 "tree/context-dep.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 {Compact}LatticeArc
31 
32 int main(int argc, char *argv[]) {
33  try {
34  using namespace kaldi;
35  typedef kaldi::int32 int32;
36  using fst::SymbolTable;
37  using fst::VectorFst;
38  using fst::Fst;
39  using fst::StdArc;
40 
41  const char *usage =
42  "Decode, reading log-likelihoods as matrices\n"
43  " (model is needed only for the integer mappings in its transition-model)\n"
44  "Usage: decode-faster-mapped [options] <model-in> <fst-in> "
45  "<loglikes-rspecifier> <words-wspecifier> [<alignments-wspecifier>]\n";
46  ParseOptions po(usage);
47  bool binary = true;
48  BaseFloat acoustic_scale = 0.1;
49  bool allow_partial = true;
50  std::string word_syms_filename;
51  FasterDecoderOptions decoder_opts;
52  decoder_opts.Register(&po, true); // true == include obscure settings.
53  po.Register("binary", &binary, "Write output in binary mode");
54  po.Register("acoustic-scale", &acoustic_scale, "Scaling factor for acoustic likelihoods");
55  po.Register("allow-partial", &allow_partial, "Produce output even when final state was not reached");
56  po.Register("word-symbol-table", &word_syms_filename, "Symbol table for words [for debug output]");
57 
58  po.Read(argc, argv);
59 
60  if (po.NumArgs() < 4 || po.NumArgs() > 5) {
61  po.PrintUsage();
62  exit(1);
63  }
64 
65  std::string model_in_filename = po.GetArg(1),
66  fst_in_filename = po.GetArg(2),
67  loglikes_rspecifier = po.GetArg(3),
68  words_wspecifier = po.GetArg(4),
69  alignment_wspecifier = po.GetOptArg(5);
70 
71  TransitionModel trans_model;
72  ReadKaldiObject(model_in_filename, &trans_model);
73 
74  Int32VectorWriter words_writer(words_wspecifier);
75 
76  Int32VectorWriter alignment_writer(alignment_wspecifier);
77 
78  fst::SymbolTable *word_syms = NULL;
79  if (word_syms_filename != "") {
80  word_syms = fst::SymbolTable::ReadText(word_syms_filename);
81  if (!word_syms)
82  KALDI_ERR << "Could not read symbol table from file "<<word_syms_filename;
83  }
84 
85  SequentialBaseFloatMatrixReader loglikes_reader(loglikes_rspecifier);
86 
87  // It's important that we initialize decode_fst after loglikes_reader, as it
88  // can prevent crashes on systems installed without enough virtual memory.
89  // It has to do with what happens on UNIX systems if you call fork() on a
90  // large process: the page-table entries are duplicated, which requires a
91  // lot of virtual memory.
92  Fst<StdArc> *decode_fst = fst::ReadFstKaldiGeneric(fst_in_filename);
93 
94  BaseFloat tot_like = 0.0;
95  kaldi::int64 frame_count = 0;
96  int num_success = 0, num_fail = 0;
97  FasterDecoder decoder(*decode_fst, decoder_opts);
98 
99  Timer timer;
100 
101  for (; !loglikes_reader.Done(); loglikes_reader.Next()) {
102  std::string key = loglikes_reader.Key();
103  const Matrix<BaseFloat> &loglikes (loglikes_reader.Value());
104 
105  if (loglikes.NumRows() == 0) {
106  KALDI_WARN << "Zero-length utterance: " << key;
107  num_fail++;
108  continue;
109  }
110 
111  DecodableMatrixScaledMapped decodable(trans_model, loglikes, acoustic_scale);
112  decoder.Decode(&decodable);
113 
114  VectorFst<LatticeArc> decoded; // linear FST.
115 
116  if ( (allow_partial || decoder.ReachedFinal())
117  && decoder.GetBestPath(&decoded) ) {
118  num_success++;
119  if (!decoder.ReachedFinal())
120  KALDI_WARN << "Decoder did not reach end-state, outputting partial traceback.";
121 
122  std::vector<int32> alignment;
123  std::vector<int32> words;
124  LatticeWeight weight;
125  frame_count += loglikes.NumRows();
126 
127  GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
128 
129  words_writer.Write(key, words);
130  if (alignment_writer.IsOpen())
131  alignment_writer.Write(key, alignment);
132  if (word_syms != NULL) {
133  std::cerr << key << ' ';
134  for (size_t i = 0; i < words.size(); i++) {
135  std::string s = word_syms->Find(words[i]);
136  if (s == "")
137  KALDI_ERR << "Word-id " << words[i] <<" not in symbol table.";
138  std::cerr << s << ' ';
139  }
140  std::cerr << '\n';
141  }
142  BaseFloat like = -weight.Value1() -weight.Value2();
143  tot_like += like;
144  KALDI_LOG << "Log-like per frame for utterance " << key << " is "
145  << (like / loglikes.NumRows()) << " over "
146  << loglikes.NumRows() << " frames.";
147 
148  } else {
149  num_fail++;
150  KALDI_WARN << "Did not successfully decode utterance " << key
151  << ", len = " << loglikes.NumRows();
152  }
153  }
154 
155  double elapsed = timer.Elapsed();
156  KALDI_LOG << "Time taken [excluding initialization] "<< elapsed
157  << "s: real-time factor assuming 100 frames/sec is "
158  << (elapsed*100.0/frame_count);
159  KALDI_LOG << "Done " << num_success << " utterances, failed for "
160  << num_fail;
161  KALDI_LOG << "Overall log-likelihood per frame is " << (tot_like/frame_count)
162  << " over " << frame_count << " frames.";
163 
164  delete word_syms;
165  delete decode_fst;
166  if (num_success != 0) return 0;
167  else return 1;
168  } catch(const std::exception &e) {
169  std::cerr << e.what();
170  return -1;
171  }
172 }
173 
174 
int32 words[kMaxOrder]
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
Fst< StdArc > * ReadFstKaldiGeneric(std::string rxfilename, bool throw_on_err)
Definition: kaldi-fst-io.cc:45
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
fst::StdArc StdArc
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)
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
int main(int argc, char *argv[])
bool GetBestPath(fst::MutableFst< LatticeArc > *fst_out, bool use_final_probs=true)
GetBestPath gets the decoding traceback.
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 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.
void Register(OptionsItf *opts, bool full)
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_LOG
Definition: kaldi-error.h:153
double Elapsed() const
Returns time in seconds.
Definition: timer.h:74
bool ReachedFinal() const
Returns true if a final state was active on the last frame.
std::string GetOptArg(int param) const