sgmm2-est-fmllr.cc
Go to the documentation of this file.
1 // sgmm2bin/sgmm2-est-fmllr.cc
2 
3 // Copyright 2009-2012 Saarland University Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
4 // 2014 Guoguo Chen
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 using std::string;
23 #include <vector>
24 using std::vector;
25 
26 #include "base/kaldi-common.h"
27 #include "util/common-utils.h"
28 #include "sgmm2/am-sgmm2.h"
29 #include "sgmm2/fmllr-sgmm2.h"
30 #include "hmm/transition-model.h"
31 #include "hmm/posterior.h"
32 
33 namespace kaldi {
34 
36  const Matrix<BaseFloat> &transformed_feats, // if already fMLLR
37  const std::vector<std::vector<int32> > &gselect,
38  const Posterior &post,
39  const TransitionModel &trans_model,
40  const AmSgmm2 &am_sgmm,
41  BaseFloat logdet,
42  Sgmm2PerSpkDerivedVars *spk_vars,
43  FmllrSgmm2Accs *spk_stats) {
44  kaldi::Sgmm2PerFrameDerivedVars per_frame_vars;
45 
46  Posterior pdf_post;
47  ConvertPosteriorToPdfs(trans_model, post, &pdf_post);
48  for (size_t t = 0; t < post.size(); t++) {
49  // per-frame vars only used for computing posteriors... use the
50  // transformed feats for this, if available.
51  am_sgmm.ComputePerFrameVars(transformed_feats.Row(t), gselect[t],
52  *spk_vars, &per_frame_vars);
53 
54 
55  for (size_t j = 0; j < pdf_post[t].size(); j++) {
56  int32 pdf_id = pdf_post[t][j].first;
57  Matrix<BaseFloat> posteriors;
58  am_sgmm.ComponentPosteriors(per_frame_vars, pdf_id,
59  spk_vars, &posteriors);
60  posteriors.Scale(pdf_post[t][j].second);
61  spk_stats->AccumulateFromPosteriors(am_sgmm, *spk_vars, feats.Row(t),
62  gselect[t], posteriors, pdf_id);
63  }
64  }
65 }
66 
67 } // end namespace kaldi
68 
69 int main(int argc, char *argv[]) {
70  try {
71  typedef kaldi::int32 int32;
72  using namespace kaldi;
73  const char *usage =
74  "Estimate FMLLR transform for SGMMs, either per utterance or for the "
75  "supplied set of speakers (with spk2utt option).\n"
76  "Reads state-level posteriors. Writes to a table of matrices.\n"
77  "--gselect option is mandatory.\n"
78  "Usage: sgmm2-est-fmllr [options] <model-in> <feature-rspecifier> "
79  "<post-rspecifier> <mats-wspecifier>\n";
80 
81  ParseOptions po(usage);
82  string spk2utt_rspecifier, spkvecs_rspecifier, fmllr_rspecifier,
83  gselect_rspecifier;
84  BaseFloat min_count = 100;
85  Sgmm2FmllrConfig fmllr_opts;
86 
87  po.Register("spk2utt", &spk2utt_rspecifier,
88  "File to read speaker to utterance-list map from.");
89  po.Register("spkvec-min-count", &min_count,
90  "Minimum count needed to estimate speaker vectors");
91  po.Register("spk-vecs", &spkvecs_rspecifier,
92  "Speaker vectors to use during aligment (rspecifier)");
93  po.Register("input-fmllr", &fmllr_rspecifier,
94  "Initial FMLLR transform per speaker (rspecifier)");
95  po.Register("gselect", &gselect_rspecifier,
96  "Precomputed Gaussian indices (rspecifier)");
97  fmllr_opts.Register(&po);
98 
99  po.Read(argc, argv);
100 
101  if (po.NumArgs() != 4) {
102  po.PrintUsage();
103  exit(1);
104  }
105 
106  string model_rxfilename = po.GetArg(1),
107  feature_rspecifier = po.GetArg(2),
108  post_rspecifier = po.GetArg(3),
109  fmllr_wspecifier = po.GetArg(4);
110 
111  TransitionModel trans_model;
112  AmSgmm2 am_sgmm;
113  Sgmm2FmllrGlobalParams fmllr_globals;
114  {
115  bool binary;
116  Input ki(model_rxfilename, &binary);
117  trans_model.Read(ki.Stream(), binary);
118  am_sgmm.Read(ki.Stream(), binary);
119  fmllr_globals.Read(ki.Stream(), binary);
120  }
121  if (gselect_rspecifier == "")
122  KALDI_ERR << "--gselect option is required.";
123 
124  RandomAccessPosteriorReader post_reader(post_rspecifier);
125  RandomAccessBaseFloatVectorReader spkvecs_reader(spkvecs_rspecifier);
126  RandomAccessInt32VectorVectorReader gselect_reader(gselect_rspecifier);
127  RandomAccessBaseFloatMatrixReader fmllr_reader(fmllr_rspecifier);
128 
129  BaseFloatMatrixWriter fmllr_writer(fmllr_wspecifier);
130 
131  int32 dim = am_sgmm.FeatureDim();
132  FmllrSgmm2Accs spk_stats;
133  spk_stats.Init(dim, am_sgmm.NumGauss());
134  Matrix<BaseFloat> fmllr_xform(dim, dim + 1);
135  BaseFloat logdet = 0.0;
136  double tot_impr = 0.0, tot_t = 0.0;
137  int32 num_done = 0, num_err = 0;
138  std::vector<std::vector<int32> > empty_gselect;
139 
140  if (!spk2utt_rspecifier.empty()) { // per-speaker adaptation
141  SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
142  RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier);
143 
144  for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
145  spk_stats.SetZero();
146  string spk = spk2utt_reader.Key();
147  const vector<string> &uttlist = spk2utt_reader.Value();
148 
149  Sgmm2PerSpkDerivedVars spk_vars;
150  if (spkvecs_reader.IsOpen()) {
151  if (spkvecs_reader.HasKey(spk)) {
152  spk_vars.SetSpeakerVector(spkvecs_reader.Value(spk));
153  am_sgmm.ComputePerSpkDerivedVars(&spk_vars);
154  } else {
155  KALDI_WARN << "Cannot find speaker vector for " << spk;
156  num_err++;
157  continue;
158  }
159  } // else spk_vars is "empty"
160 
161  if (fmllr_reader.IsOpen()) {
162  if (fmllr_reader.HasKey(spk)) {
163  fmllr_xform.CopyFromMat(fmllr_reader.Value(spk));
164  logdet = fmllr_xform.Range(0, dim, 0, dim).LogDet();
165  } else {
166  KALDI_WARN << "Cannot find FMLLR transform for " << spk;
167  fmllr_xform.SetUnit();
168  logdet = 0.0;
169  }
170  } else {
171  fmllr_xform.SetUnit();
172  logdet = 0.0;
173  }
174 
175  for (size_t i = 0; i < uttlist.size(); i++) {
176  std::string utt = uttlist[i];
177  if (!feature_reader.HasKey(utt)) {
178  KALDI_WARN << "Did not find features for utterance " << utt;
179  num_err++;
180  continue;
181  }
182  const Matrix<BaseFloat> &feats = feature_reader.Value(utt);
183  if (!post_reader.HasKey(utt) ||
184  post_reader.Value(utt).size() != feats.NumRows()) {
185  KALDI_WARN << "Did not find posteriors for utterance " << utt
186  << " (or wrong size).";
187  num_err++;
188  continue;
189  }
190  const Posterior &post = post_reader.Value(utt);
191  if (!gselect_reader.HasKey(utt) ||
192  gselect_reader.Value(utt).size() != feats.NumRows()) {
193  KALDI_WARN << "Did not find gselect info for utterance " << utt
194  << " (or wrong size).";
195  num_err++;
196  continue;
197  }
198  const std::vector<std::vector<int32> > &gselect =
199  gselect_reader.Value(utt);
200 
201  Matrix<BaseFloat> transformed_feats(feats);
202  for (int32 r = 0; r < transformed_feats.NumRows(); r++) {
203  SubVector<BaseFloat> row(transformed_feats, r);
204  ApplyAffineTransform(fmllr_xform, &row);
205  }
206  AccumulateForUtterance(feats, transformed_feats, gselect,
207  post, trans_model, am_sgmm,
208  logdet, &spk_vars, &spk_stats);
209  num_done++;
210  } // end looping over all utterances of the current speaker
211 
212  BaseFloat impr, spk_frame_count;
213  // Compute the FMLLR transform and write it out.
214  spk_stats.Update(am_sgmm, fmllr_globals, fmllr_opts, &fmllr_xform,
215  &spk_frame_count, &impr);
216  fmllr_writer.Write(spk, fmllr_xform);
217  tot_impr += impr;
218  tot_t += spk_frame_count;
219  } // end looping over speakers
220  } else { // per-utterance adaptation
221  SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
222  for (; !feature_reader.Done(); feature_reader.Next()) {
223  string utt = feature_reader.Key();
224  const Matrix<BaseFloat> &feats = feature_reader.Value();
225 
226  if (!post_reader.HasKey(utt) ||
227  post_reader.Value(utt).size() != feats.NumRows()) {
228  KALDI_WARN << "Did not find posteriors for utterance " << utt
229  << " (or wrong size).";
230  num_err++;
231  continue;
232  }
233  const Posterior &post = post_reader.Value(utt);
234  if (!gselect_reader.HasKey(utt) ||
235  gselect_reader.Value(utt).size() != feats.NumRows()) {
236  KALDI_WARN << "Did not find gselect info for utterance " << utt
237  << " (or wrong size).";
238  num_err++;
239  continue;
240  }
241  const std::vector<std::vector<int32> > &gselect =
242  gselect_reader.Value(utt);
243 
244  if (fmllr_reader.IsOpen()) {
245  if (fmllr_reader.HasKey(utt)) {
246  fmllr_xform.CopyFromMat(fmllr_reader.Value(utt));
247  logdet = fmllr_xform.Range(0, dim, 0, dim).LogDet();
248  } else {
249  KALDI_WARN << "Cannot find FMLLR transform for " << utt;
250  fmllr_xform.SetUnit();
251  logdet = 0.0;
252  }
253  } else {
254  fmllr_xform.SetUnit();
255  logdet = 0.0;
256  }
257 
258  Matrix<BaseFloat> transformed_feats(feats);
259  for (int32 r = 0; r < transformed_feats.NumRows(); r++) {
260  SubVector<BaseFloat> row(transformed_feats, r);
261  ApplyAffineTransform(fmllr_xform, &row);
262  }
263 
264  Sgmm2PerSpkDerivedVars spk_vars;
265  if (spkvecs_reader.IsOpen()) {
266  if (spkvecs_reader.HasKey(utt)) {
267  spk_vars.SetSpeakerVector(spkvecs_reader.Value(utt));
268  am_sgmm.ComputePerSpkDerivedVars(&spk_vars);
269  } else {
270  KALDI_WARN << "Cannot find speaker vector for " << utt;
271  num_err++;
272  continue;
273  }
274  } // else spk_vars is "empty"
275 
276  spk_stats.SetZero();
277 
278  AccumulateForUtterance(feats, transformed_feats, gselect,
279  post, trans_model, am_sgmm,
280  logdet, &spk_vars, &spk_stats);
281  num_done++;
282 
283  BaseFloat impr, spk_frame_count;
284  // Compute the FMLLR transform and write it out.
285  spk_stats.Update(am_sgmm, fmllr_globals, fmllr_opts, &fmllr_xform,
286  &spk_frame_count, &impr);
287  fmllr_writer.Write(utt, fmllr_xform);
288  tot_impr += impr;
289  tot_t += spk_frame_count;
290  }
291  }
292 
293  KALDI_LOG << "Done " << num_done << " files, " << num_err << " with errors.";
294  KALDI_LOG << "Overall auxf impr per frame is " << (tot_impr / tot_t)
295  << " per frame, over " << tot_t << " frames.";
296  return (num_done != 0 ? 0 : 1);
297  } catch(const std::exception &e) {
298  std::cerr << e.what();
299  return -1;
300  }
301 }
302 
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
Class for computing the accumulators needed for the maximum-likelihood estimate of FMLLR transforms f...
Definition: fmllr-sgmm2.h:122
BaseFloat ComponentPosteriors(const Sgmm2PerFrameDerivedVars &per_frame_vars, int32 j2, Sgmm2PerSpkDerivedVars *spk_vars, Matrix< BaseFloat > *post) const
Similar to LogLikelihood() function above, but also computes the posterior probabilities for the pre-...
Definition: am-sgmm2.cc:574
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
void Read(std::istream &is, bool binary)
Definition: am-sgmm2.cc:89
void AccumulateForUtterance(const Matrix< BaseFloat > &feats, const GaussPost &gpost, const TransitionModel &trans_model, const AmDiagGmm &am_gmm, FmllrDiagGmmAccs *spk_stats)
void AccumulateFromPosteriors(const AmSgmm2 &sgmm, const Sgmm2PerSpkDerivedVars &spk, const VectorBase< BaseFloat > &data, const std::vector< int32 > &gauss_select, const Matrix< BaseFloat > &posteriors, int32 state_index)
Definition: fmllr-sgmm2.cc:171
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 CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void Register(OptionsItf *opts)
Definition: fmllr-sgmm2.h:69
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 SetUnit()
Sets to zero, except ones along diagonal [for non-square matrices too].
void Write(const std::string &key, const T &value) const
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
bool Update(const AmSgmm2 &model, const Sgmm2FmllrGlobalParams &fmllr_globals, const Sgmm2FmllrConfig &opts, Matrix< BaseFloat > *out_xform, BaseFloat *frame_count, BaseFloat *auxf_improv) const
Computes the FMLLR transform from the accumulated stats, using the pre-transforms in fmllr_globals...
Definition: fmllr-sgmm2.cc:356
int32 FeatureDim() const
Definition: am-sgmm2.h:363
std::istream & Stream()
Definition: kaldi-io.cc:826
float BaseFloat
Definition: kaldi-types.h:29
std::vector< std::vector< std::pair< int32, BaseFloat > > > Posterior
Posterior is a typedef for storing acoustic-state (actually, transition-id) posteriors over an uttera...
Definition: posterior.h:42
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
void Read(std::istream &in_stream, bool binary)
Definition: fmllr-sgmm2.cc:122
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 Scale(Real alpha)
Multiply each element with a scalar value.
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
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.
bool HasKey(const std::string &key)
int main(int argc, char *argv[])
Configuration variables needed in the estimation of FMLLR for SGMMs.
Definition: fmllr-sgmm2.h:40
int32 NumGauss() const
Definition: am-sgmm2.h:360
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
SubMatrix< Real > Range(const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Return a sub-part of matrix.
Definition: kaldi-matrix.h:202
void SetSpeakerVector(const Vector< BaseFloat > &v_s_in)
Definition: am-sgmm2.h:180
Global adaptation parameters.
Definition: fmllr-sgmm2.h:91
void ApplyAffineTransform(const MatrixBase< BaseFloat > &xform, VectorBase< BaseFloat > *vec)
Applies the affine transform &#39;xform&#39; to the vector &#39;vec&#39; and overwrites the contents of &#39;vec&#39;...
void ConvertPosteriorToPdfs(const TransitionModel &tmodel, const Posterior &post_in, Posterior *post_out)
Converts a posterior over transition-ids to be a posterior over pdf-ids.
Definition: posterior.cc:322
#define KALDI_LOG
Definition: kaldi-error.h:153
void Init(int32 dim, int32 num_gaussians)
Definition: fmllr-sgmm2.cc:146
Holds the per-frame precomputed quantities x(t), x_{i}(t), z_{i}(t), and n_{i}(t) (cf...
Definition: am-sgmm2.h:142
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501