sgmm2-acc-stats-gpost.cc
Go to the documentation of this file.
1 // sgmm2bin/sgmm2-acc-stats-gpost.cc
2 
3 // Copyright 2009-2012 Saarland University Microsoft Corporation
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 
22 #include "base/kaldi-common.h"
23 #include "util/common-utils.h"
24 #include "sgmm2/am-sgmm2.h"
25 #include "hmm/transition-model.h"
27 
28 
29 int main(int argc, char *argv[]) {
30  using namespace kaldi;
31  try {
32  const char *usage =
33  "Accumulate stats for SGMM training, given Gaussian-level posteriors\n"
34  "Usage: sgmm2-acc-stats-gpost [options] <model-in> <feature-rspecifier> "
35  "<gpost-rspecifier> <stats-out>\n"
36  "e.g.: sgmm2-acc-stats-gpost 1.mdl 1.ali scp:train.scp ark, s, cs:- 1.acc\n";
37 
38  ParseOptions po(usage);
39  bool binary = true;
40  std::string spkvecs_rspecifier, utt2spk_rspecifier;
41  std::string update_flags_str = "vMNwcSt";
42  BaseFloat rand_prune = 1.0e-05;
43 
44  po.Register("binary", &binary, "Write output in binary mode");
45  po.Register("spk-vecs", &spkvecs_rspecifier, "Speaker vectors (rspecifier)");
46  po.Register("utt2spk", &utt2spk_rspecifier,
47  "rspecifier for utterance to speaker map");
48  po.Register("rand-prune", &rand_prune, "Pruning threshold for posteriors");
49  po.Register("update-flags", &update_flags_str, "Which SGMM parameters to update: subset of vMNwcS.");
50  po.Read(argc, argv);
51 
52  kaldi::SgmmUpdateFlagsType acc_flags = StringToSgmmUpdateFlags(update_flags_str);
53 
54  if (po.NumArgs() != 4) {
55  po.PrintUsage();
56  exit(1);
57  }
58 
59  std::string model_filename = po.GetArg(1),
60  feature_rspecifier = po.GetArg(2),
61  gpost_rspecifier = po.GetArg(3),
62  accs_wxfilename = po.GetArg(4);
63 
64  using namespace kaldi;
65  typedef kaldi::int32 int32;
66 
67  // Initialize the readers before the model, as this can avoid
68  // crashes on systems with low virtual memory.
69  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
70  RandomAccessSgmm2GauPostReader gpost_reader(gpost_rspecifier);
71  RandomAccessBaseFloatVectorReaderMapped spkvecs_reader(spkvecs_rspecifier,
72  utt2spk_rspecifier);
73  RandomAccessTokenReader utt2spk_map(utt2spk_rspecifier);
74 
75  AmSgmm2 am_sgmm;
76  TransitionModel trans_model;
77  {
78  bool binary;
79  Input ki(model_filename, &binary);
80  trans_model.Read(ki.Stream(), binary);
81  am_sgmm.Read(ki.Stream(), binary);
82  }
83 
84  Vector<double> transition_accs;
85  trans_model.InitStats(&transition_accs);
86  MleAmSgmm2Accs sgmm_accs(rand_prune);
87  sgmm_accs.ResizeAccumulators(am_sgmm, acc_flags, (spkvecs_rspecifier != ""));
88 
89  double tot_t = 0.0;
90  kaldi::Sgmm2PerFrameDerivedVars per_frame_vars;
91 
92  int32 num_done = 0, num_err = 0;
93  std::string cur_spk;
94  Sgmm2PerSpkDerivedVars spk_vars;
95 
96  for (; !feature_reader.Done(); feature_reader.Next()) {
97  std::string utt = feature_reader.Key();
98  std::string spk = utt;
99 
100  if (!utt2spk_rspecifier.empty()) {
101  if (!utt2spk_map.HasKey(utt)) {
102  KALDI_WARN << "utt2spk map does not have value for " << utt
103  << ", ignoring this utterance.";
104  continue;
105  } else { spk = utt2spk_map.Value(utt); }
106  }
107 
108  if (spk != cur_spk && cur_spk != "")
109  sgmm_accs.CommitStatsForSpk(am_sgmm, spk_vars);
110 
111  if (spk != cur_spk || spk_vars.Empty()) {
112  spk_vars.Clear();
113  if (spkvecs_reader.IsOpen()) {
114  if (spkvecs_reader.HasKey(utt)) {
115  spk_vars.SetSpeakerVector(spkvecs_reader.Value(utt));
116  am_sgmm.ComputePerSpkDerivedVars(&spk_vars);
117  } else {
118  KALDI_WARN << "Cannot find speaker vector for " << utt;
119  num_err++;
120  continue;
121  }
122  } // else spk_vars is "empty"
123  }
124 
125  cur_spk = spk;
126 
127  const Matrix<BaseFloat> &mat = feature_reader.Value();
128  if (!gpost_reader.HasKey(utt) ||
129  gpost_reader.Value(utt).size() != mat.NumRows()) {
130  KALDI_WARN << "No Gaussian-posterior information for utterance "
131  << utt << " (or wrong size).";
132  num_err++;
133  continue;
134  }
135  const Sgmm2GauPost &gpost = gpost_reader.Value(utt);
136 
137  num_done++;
138  BaseFloat tot_weight = 0.0;
139 
140  for (size_t i = 0; i < gpost.size(); i++) {
141  const std::vector<int32> &gselect = gpost[i].gselect;
142  am_sgmm.ComputePerFrameVars(mat.Row(i), gselect, spk_vars,
143  &per_frame_vars);
144 
145  for (size_t j = 0; j < gpost[i].tids.size(); j++) {
146  int32 tid = gpost[i].tids[j], // transition identifier.
147  pdf_id = trans_model.TransitionIdToPdf(tid);
148 
149  BaseFloat weight = gpost[i].posteriors[j].Sum();
150  trans_model.Accumulate(weight, tid, &transition_accs);
151  sgmm_accs.AccumulateFromPosteriors(am_sgmm, per_frame_vars,
152  gpost[i].posteriors[j],
153  pdf_id, &spk_vars);
154  tot_weight += weight;
155  }
156  }
157 
158  tot_t += tot_weight;
159  if (num_done % 50 == 0)
160  KALDI_LOG << "Processed " << num_done << " utterances";
161  }
162  sgmm_accs.CommitStatsForSpk(am_sgmm, spk_vars); // for last speaker
163 
164  KALDI_LOG << "Overall number of frames is " << tot_t;
165  KALDI_LOG << "Done " << num_done << " files, "
166  << num_err << " with errors.";
167 
168  {
169  Output ko(accs_wxfilename, binary);
170  transition_accs.Write(ko.Stream(), binary);
171  sgmm_accs.Write(ko.Stream(), binary);
172  }
173  KALDI_LOG << "Written accs.";
174  return (num_done != 0 ? 0 : 1);
175  } catch(const std::exception &e) {
176  std::cerr << e.what();
177  return -1;
178  }
179 }
180 
181 
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
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
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 Write(std::ostream &Out, bool binary) const
Writes to C++ stream (option to write in binary).
void Read(std::istream &is, bool binary)
Definition: am-sgmm2.cc:89
kaldi::int32 int32
SgmmUpdateFlagsType StringToSgmmUpdateFlags(std::string str)
Definition: model-common.cc:64
int32 TransitionIdToPdf(int32 trans_id) const
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)
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
void CommitStatsForSpk(const AmSgmm2 &model, const Sgmm2PerSpkDerivedVars &spk_vars)
Accumulates global stats for the current speaker (if applicable).
std::istream & Stream()
Definition: kaldi-io.cc:826
float BaseFloat
Definition: kaldi-types.h:29
void InitStats(Vector< double > *stats) const
uint16 SgmmUpdateFlagsType
Bitwise OR of the above flags.
Definition: model-common.h:59
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
std::ostream & Stream()
Definition: kaldi-io.cc:701
const SubVector< Real > Row(MatrixIndexT i) const
Return specific row of matrix [const].
Definition: kaldi-matrix.h:188
const T & Value(const std::string &key)
void Read(std::istream &is, bool binary)
void Accumulate(BaseFloat prob, int32 trans_id, Vector< double > *stats) const
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.
void ComputePerFrameVars(const VectorBase< BaseFloat > &data, const std::vector< int32 > &gselect, const Sgmm2PerSpkDerivedVars &spk_vars, Sgmm2PerFrameDerivedVars *per_frame_vars) const
This needs to be called with each new frame of data, prior to accumulation or likelihood evaluation: ...
Definition: am-sgmm2.cc:442
#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.
indexed by time.
Definition: am-sgmm2.h:568
bool HasKey(const std::string &key)
BaseFloat AccumulateFromPosteriors(const AmSgmm2 &model, const Sgmm2PerFrameDerivedVars &frame_vars, const Matrix< BaseFloat > &posteriors, int32 pdf_index, Sgmm2PerSpkDerivedVars *spk_vars)
Returns count accumulated (may differ from posteriors.Sum() due to weight pruning).
void Write(std::ostream &out_stream, bool binary) const
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
int main(int argc, char *argv[])
const T & Value(const std::string &key)
void SetSpeakerVector(const Vector< BaseFloat > &v_s_in)
Definition: am-sgmm2.h:180
Class for the accumulators associated with the phonetic-subspace model parameters.
#define KALDI_LOG
Definition: kaldi-error.h:153
Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf...
Definition: am-sgmm2.h:142
void ResizeAccumulators(const AmSgmm2 &model, SgmmUpdateFlagsType flags, bool have_spk_vecs)
Resizes the accumulators to the correct sizes given the model.