nnet3-average.cc
Go to the documentation of this file.
1 // nnet3bin/nnet3-average.cc
2 
3 // Copyright 2015 Johns Hopkins University (author: Daniel Povey)
4 
5 // See ../../COPYING for clarification regarding multiple authors
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16 // MERCHANTABLITY OR NON-INFRINGEMENT.
17 // See the Apache 2 License for the specific language governing permissions and
18 // limitations under the License.
19 
20 #include "base/kaldi-common.h"
21 #include "util/common-utils.h"
22 #include "hmm/transition-model.h"
23 #include "nnet3/nnet-utils.h"
24 
25 
26 namespace kaldi {
27 
28 void GetWeights(const std::string &weights_str,
29  int32 num_inputs,
30  std::vector<BaseFloat> *weights) {
31  KALDI_ASSERT(num_inputs >= 1);
32  if (!weights_str.empty()) {
33  SplitStringToFloats(weights_str, ":", true, weights);
34  if (weights->size() != num_inputs) {
35  KALDI_ERR << "--weights option must be a colon-separated list "
36  << "with " << num_inputs << " elements, got: "
37  << weights_str;
38  }
39  } else {
40  for (int32 i = 0; i < num_inputs; i++)
41  weights->push_back(1.0 / num_inputs);
42  }
43  // normalize the weights to sum to one.
44  float weight_sum = 0.0;
45  for (int32 i = 0; i < num_inputs; i++)
46  weight_sum += (*weights)[i];
47  for (int32 i = 0; i < num_inputs; i++)
48  (*weights)[i] = (*weights)[i] / weight_sum;
49  if (fabs(weight_sum - 1.0) > 0.01) {
50  KALDI_WARN << "Normalizing weights to sum to one, sum was " << weight_sum;
51  }
52 }
53 
54 // This job is run in a spawned thread; it reads a subset of models with
55 // specified weights. Sets *success to 1 for success and 0 for failure. (We
56 // don't use bool because of the weird implementation of std::vector<bool>).
57 void ReadModels(std::vector<std::pair<std::string, BaseFloat> > models_and_weights,
58  nnet3::Nnet *output_nnet,
59  int32 *success) {
60  using namespace nnet3;
61  try {
62  int32 n = models_and_weights.size();
63  ReadKaldiObject(models_and_weights[0].first, output_nnet);
64  ScaleNnet(models_and_weights[0].second, output_nnet);
65  for (int32 i = 1; i < n; i++) {
66  Nnet nnet;
67  ReadKaldiObject(models_and_weights[i].first, &nnet);
68  AddNnet(nnet, models_and_weights[i].second, output_nnet);
69  }
70  *success = 1;
71  } catch (...) {
72  *success = 0;
73  }
74 }
75 
76 } // namespace kaldi
77 
78 
79 int main(int argc, char *argv[]) {
80  try {
81  using namespace kaldi;
82  using namespace kaldi::nnet3;
83  typedef kaldi::int32 int32;
84  typedef kaldi::int64 int64;
85 
86  const char *usage =
87  "This program averages the parameters over a number of 'raw' nnet3 neural nets.\n"
88  "\n"
89  "Usage: nnet3-average [options] <model1> <model2> ... <modelN> <model-out>\n"
90  "\n"
91  "e.g.:\n"
92  " nnet3-average 1.1.nnet 1.2.nnet 1.3.nnet 2.nnet\n";
93 
94  bool binary_write = true;
95  int32 num_threads = -1;
96 
97  ParseOptions po(usage);
98  po.Register("binary", &binary_write, "Write output in binary mode");
99  std::string weights_str;
100  po.Register("weights", &weights_str, "Colon-separated list of weights, one "
101  "for each input model. These will be normalized to sum to one.");
102  po.Register("num-threads", &num_threads, "Number of threads to read the "
103  "models (will be set automatically if not set.");
104 
105  po.Read(argc, argv);
106 
107  if (po.NumArgs() < 2) {
108  po.PrintUsage();
109  exit(1);
110  }
111 
112  std::string
113  first_nnet_rxfilename = po.GetArg(1),
114  nnet_wxfilename = po.GetArg(po.NumArgs());
115 
116  int32 num_inputs = po.NumArgs() - 1;
117 
118  if (num_threads <= 0) {
119  // Default logic for selecting the number of threads.
120  if (num_inputs > 10) num_threads = 3;
121  else if (num_inputs > 5) num_threads = 2;
122  else num_threads = 1;
123  }
124 
125  if (num_threads > 1 && num_threads * 2 > num_inputs) {
126  num_threads = num_inputs / 2;
127  }
128 
129  std::vector<BaseFloat> model_weights;
130  GetWeights(weights_str, num_inputs, &model_weights);
131 
132  std::vector<Nnet> nnets(num_threads);
133  std::vector<int32> return_statuses(num_threads);
134 
135  std::vector<std::thread*> threads(num_threads);
136 
137  for (int32 thread_id = 0; thread_id < num_threads; thread_id++) {
138  std::vector<std::pair<std::string, BaseFloat> > this_models_and_weights;
139  for (int32 j = 1 + thread_id; j < po.NumArgs(); j += num_threads) {
140  this_models_and_weights.push_back(std::pair<std::string, BaseFloat>(
141  po.GetArg(j), model_weights[j - 1]));
142  }
143  threads[thread_id] = new std::thread(ReadModels, this_models_and_weights,
144  &(nnets[thread_id]),
145  &(return_statuses[thread_id]));
146  }
147 
148  bool success = true;
149  for (int32 thread_id = 0; thread_id < num_threads; thread_id++) {
150  threads[thread_id]->join();
151  delete threads[thread_id];
152  if (!return_statuses[thread_id])
153  success = false;
154  if (success && thread_id > 0)
155  AddNnet(nnets[thread_id], 1.0, &(nnets[0]));
156  }
157 
158  if (!success) {
159  KALDI_ERR << "Error detected in a model-reading thread.";
160  }
161 
162  WriteKaldiObject(nnets[0], nnet_wxfilename, binary_write);
163 
164  KALDI_LOG << "Averaged parameters of " << num_inputs
165  << " neural nets, and wrote to " << nnet_wxfilename;
166  return 0; // it will throw an exception if there are any problems.
167  } catch(const std::exception &e) {
168  std::cerr << e.what() << '\n';
169  return -1;
170  }
171 }
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
void ScaleNnet(BaseFloat scale, Nnet *nnet)
Scales the nnet parameters and stats by this scale.
Definition: nnet-utils.cc:312
void GetWeights(const std::string &weights_str, int32 num_inputs, std::vector< BaseFloat > *weights)
bool SplitStringToFloats(const std::string &full, const char *delim, bool omit_empty_strings, std::vector< F > *out)
Definition: text-utils.cc:30
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
kaldi::int32 int32
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
This file contains some miscellaneous functions dealing with class Nnet.
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
int main(int argc, char *argv[])
struct rnnlm::@11::@12 n
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 ReadModels(std::vector< std::pair< std::string, BaseFloat > > models_and_weights, nnet3::Nnet *output_nnet, int32 *success)
int NumArgs() const
Number of positional parameters (c.f. argc-1).
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
void WriteKaldiObject(const C &c, const std::string &filename, bool binary)
Definition: kaldi-io.h:257
#define KALDI_LOG
Definition: kaldi-error.h:153
void AddNnet(const Nnet &src, BaseFloat alpha, Nnet *dest)
Does *dest += alpha * src (affects nnet parameters and stored stats).
Definition: nnet-utils.cc:349