Blame view

src/nnet3/nnet-chain-training.cc 11.8 KB
8dcb6dfcb   Yannick Estève   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
  // nnet3/nnet-chain-training.cc
  
  // Copyright      2015    Johns Hopkins University (author: Daniel Povey)
  //                2016    Xiaohui Zhang
  
  // See ../../COPYING for clarification regarding multiple authors
  //
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //
  //  http://www.apache.org/licenses/LICENSE-2.0
  //
  // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  // MERCHANTABLITY OR NON-INFRINGEMENT.
  // See the Apache 2 License for the specific language governing permissions and
  // limitations under the License.
  
  #include "nnet3/nnet-chain-training.h"
  #include "nnet3/nnet-utils.h"
  
  namespace kaldi {
  namespace nnet3 {
  
  NnetChainTrainer::NnetChainTrainer(const NnetChainTrainingOptions &opts,
                                     const fst::StdVectorFst &den_fst,
                                     Nnet *nnet):
      opts_(opts),
      den_graph_(den_fst, nnet->OutputDim("output")),
      nnet_(nnet),
      compiler_(*nnet, opts_.nnet_config.optimize_config,
                opts_.nnet_config.compiler_config),
      num_minibatches_processed_(0),
      max_change_stats_(*nnet),
      srand_seed_(RandInt(0, 100000)) {
    if (opts.nnet_config.zero_component_stats)
      ZeroComponentStats(nnet);
    KALDI_ASSERT(opts.nnet_config.momentum >= 0.0 &&
                 opts.nnet_config.max_param_change >= 0.0 &&
                 opts.nnet_config.backstitch_training_interval > 0);
    delta_nnet_ = nnet_->Copy();
    ScaleNnet(0.0, delta_nnet_);
  
    if (opts.nnet_config.read_cache != "") {
      bool binary;
      try {
        Input ki(opts.nnet_config.read_cache, &binary);
        compiler_.ReadCache(ki.Stream(), binary);
        KALDI_LOG << "Read computation cache from " << opts.nnet_config.read_cache;
      } catch (...) {
        KALDI_WARN << "Could not open cached computation. "
                      "Probably this is the first training iteration.";
      }
    }
  }
  
  
  void NnetChainTrainer::Train(const NnetChainExample &chain_eg) {
    bool need_model_derivative = true;
    const NnetTrainerOptions &nnet_config = opts_.nnet_config;
    bool use_xent_regularization = (opts_.chain_config.xent_regularize != 0.0);
    ComputationRequest request;
    GetChainComputationRequest(*nnet_, chain_eg, need_model_derivative,
                               nnet_config.store_component_stats,
                               use_xent_regularization, need_model_derivative,
                               &request);
    std::shared_ptr<const NnetComputation> computation = compiler_.Compile(request);
  
    if (nnet_config.backstitch_training_scale > 0.0 && num_minibatches_processed_
        % nnet_config.backstitch_training_interval ==
        srand_seed_ % nnet_config.backstitch_training_interval) {
      // backstitch training is incompatible with momentum > 0
      KALDI_ASSERT(nnet_config.momentum == 0.0);
      FreezeNaturalGradient(true, delta_nnet_);
      bool is_backstitch_step1 = true;
      srand(srand_seed_ + num_minibatches_processed_);
      ResetGenerators(nnet_);
      TrainInternalBackstitch(chain_eg, *computation, is_backstitch_step1);
      FreezeNaturalGradient(false, delta_nnet_); // un-freeze natural gradient
      is_backstitch_step1 = false;
      srand(srand_seed_ + num_minibatches_processed_);
      ResetGenerators(nnet_);
      TrainInternalBackstitch(chain_eg, *computation, is_backstitch_step1);
    } else { // conventional training
      TrainInternal(chain_eg, *computation);
    }
    if (num_minibatches_processed_ == 0) {
      ConsolidateMemory(nnet_);
      ConsolidateMemory(delta_nnet_);
    }
    num_minibatches_processed_++;
  }
  
  void NnetChainTrainer::TrainInternal(const NnetChainExample &eg,
                                       const NnetComputation &computation) {
    const NnetTrainerOptions &nnet_config = opts_.nnet_config;
    // note: because we give the 1st arg (nnet_) as a pointer to the
    // constructor of 'computer', it will use that copy of the nnet to
    // store stats.
    NnetComputer computer(nnet_config.compute_config, computation,
                          nnet_, delta_nnet_);
  
    // give the inputs to the computer object.
    computer.AcceptInputs(*nnet_, eg.inputs);
    computer.Run();
  
    this->ProcessOutputs(false, eg, &computer);
    computer.Run();
  
    // If relevant, add in the part of the gradient that comes from
    // parameter-level L2 regularization.
    ApplyL2Regularization(*nnet_,
                          GetNumNvalues(eg.inputs, false) *
                          nnet_config.l2_regularize_factor,
                          delta_nnet_);
  
    // Updates the parameters of nnet
    bool success = UpdateNnetWithMaxChange(
        *delta_nnet_,
        nnet_config.max_param_change,
        1.0, 1.0 - nnet_config.momentum, nnet_,
        &max_change_stats_);
  
    // Scale down the batchnorm stats (keeps them fresh... this affects what
    // happens when we use the model with batchnorm test-mode set).
    ScaleBatchnormStats(nnet_config.batchnorm_stats_scale, nnet_);
  
    // The following will only do something if we have a LinearComponent
    // or AffineComponent with orthonormal-constraint set to a nonzero value.
    ConstrainOrthonormal(nnet_);
  
    // Scale delta_nnet
    if (success)
      ScaleNnet(nnet_config.momentum, delta_nnet_);
    else
      ScaleNnet(0.0, delta_nnet_);
  }
  
  void NnetChainTrainer::TrainInternalBackstitch(const NnetChainExample &eg,
                                                 const NnetComputation &computation,
                                                 bool is_backstitch_step1) {
    const NnetTrainerOptions &nnet_config = opts_.nnet_config;
    // note: because we give the 1st arg (nnet_) as a pointer to the
    // constructor of 'computer', it will use that copy of the nnet to
    // store stats.
    NnetComputer computer(nnet_config.compute_config, computation,
                          nnet_, delta_nnet_);
    // give the inputs to the computer object.
    computer.AcceptInputs(*nnet_, eg.inputs);
    computer.Run();
  
    bool is_backstitch_step2 = !is_backstitch_step1;
    this->ProcessOutputs(is_backstitch_step2, eg, &computer);
    computer.Run();
  
    BaseFloat max_change_scale, scale_adding;
    if (is_backstitch_step1) {
      // max-change is scaled by backstitch_training_scale;
      // delta_nnet is scaled by -backstitch_training_scale when added to nnet;
      max_change_scale = nnet_config.backstitch_training_scale;
      scale_adding = -nnet_config.backstitch_training_scale;
    } else {
      // max-change is scaled by 1 + backstitch_training_scale;
      // delta_nnet is scaled by 1 + backstitch_training_scale when added to nnet;
      max_change_scale = 1.0 + nnet_config.backstitch_training_scale;
      scale_adding = 1.0 + nnet_config.backstitch_training_scale;
      // If relevant, add in the part of the gradient that comes from L2
      // regularization.  It may not be optimally inefficient to do it on both
      // passes of the backstitch, like we do here, but it probably minimizes
      // any harmful interactions with the max-change.
      ApplyL2Regularization(*nnet_,
          1.0 / scale_adding * GetNumNvalues(eg.inputs, false) *
          nnet_config.l2_regularize_factor, delta_nnet_);
    }
  
    // Updates the parameters of nnet
    UpdateNnetWithMaxChange(
        *delta_nnet_, nnet_config.max_param_change,
        max_change_scale, scale_adding, nnet_,
        &max_change_stats_);
  
    if (is_backstitch_step1) {
      // The following will only do something if we have a LinearComponent or
      // AffineComponent with orthonormal-constraint set to a nonzero value. We
      // choose to do this only on the 1st backstitch step, for efficiency.
      ConstrainOrthonormal(nnet_);
    }
  
    if (!is_backstitch_step1) {
      // Scale down the batchnorm stats (keeps them fresh... this affects what
      // happens when we use the model with batchnorm test-mode set).  Do this
      // after backstitch step 2 so that the stats are scaled down before we start
      // the next minibatch.
      ScaleBatchnormStats(nnet_config.batchnorm_stats_scale, nnet_);
    }
  
    ScaleNnet(0.0, delta_nnet_);
  }
  
  void NnetChainTrainer::ProcessOutputs(bool is_backstitch_step2,
                                        const NnetChainExample &eg,
                                        NnetComputer *computer) {
    // normally the eg will have just one output named 'output', but
    // we don't assume this.
    // In backstitch training, the output-name with the "_backstitch" suffix is
    // the one computed after the first, backward step of backstitch.
    const std::string suffix = (is_backstitch_step2 ? "_backstitch" : "");
    std::vector<NnetChainSupervision>::const_iterator iter = eg.outputs.begin(),
        end = eg.outputs.end();
    for (; iter != end; ++iter) {
      const NnetChainSupervision &sup = *iter;
      int32 node_index = nnet_->GetNodeIndex(sup.name);
      if (node_index < 0 ||
          !nnet_->IsOutputNode(node_index))
        KALDI_ERR << "Network has no output named " << sup.name;
  
      const CuMatrixBase<BaseFloat> &nnet_output = computer->GetOutput(sup.name);
      CuMatrix<BaseFloat> nnet_output_deriv(nnet_output.NumRows(),
                                            nnet_output.NumCols(),
                                            kUndefined);
  
      bool use_xent = (opts_.chain_config.xent_regularize != 0.0);
      std::string xent_name = sup.name + "-xent";  // typically "output-xent".
      CuMatrix<BaseFloat> xent_deriv;
  
      BaseFloat tot_objf, tot_l2_term, tot_weight;
  
      ComputeChainObjfAndDeriv(opts_.chain_config, den_graph_,
                               sup.supervision, nnet_output,
                               &tot_objf, &tot_l2_term, &tot_weight,
                               &nnet_output_deriv,
                               (use_xent ? &xent_deriv : NULL));
  
      if (use_xent) {
        // this block computes the cross-entropy objective.
        const CuMatrixBase<BaseFloat> &xent_output = computer->GetOutput(
            xent_name);
        // at this point, xent_deriv is posteriors derived from the numerator
        // computation.  note, xent_objf has a factor of '.supervision.weight'
        BaseFloat xent_objf = TraceMatMat(xent_output, xent_deriv, kTrans);
        objf_info_[xent_name + suffix].UpdateStats(xent_name + suffix,
                                          opts_.nnet_config.print_interval,
                                          num_minibatches_processed_,
                                          tot_weight, xent_objf);
      }
  
      if (opts_.apply_deriv_weights && sup.deriv_weights.Dim() != 0) {
        CuVector<BaseFloat> cu_deriv_weights(sup.deriv_weights);
        nnet_output_deriv.MulRowsVec(cu_deriv_weights);
        if (use_xent)
          xent_deriv.MulRowsVec(cu_deriv_weights);
      }
  
      computer->AcceptInput(sup.name, &nnet_output_deriv);
  
      objf_info_[sup.name + suffix].UpdateStats(sup.name + suffix,
                                       opts_.nnet_config.print_interval,
                                       num_minibatches_processed_,
                                       tot_weight, tot_objf, tot_l2_term);
  
      if (use_xent) {
        xent_deriv.Scale(opts_.chain_config.xent_regularize);
        computer->AcceptInput(xent_name, &xent_deriv);
      }
    }
  }
  
  bool NnetChainTrainer::PrintTotalStats() const {
    unordered_map<std::string, ObjectiveFunctionInfo, StringHasher>::const_iterator
        iter = objf_info_.begin(),
        end = objf_info_.end();
    bool ans = false;
    for (; iter != end; ++iter) {
      const std::string &name = iter->first;
      const ObjectiveFunctionInfo &info = iter->second;
      ans = info.PrintTotalStats(name) || ans;
    }
    max_change_stats_.Print(*nnet_);
    return ans;
  }
  
  NnetChainTrainer::~NnetChainTrainer() {
    if (opts_.nnet_config.write_cache != "") {
      Output ko(opts_.nnet_config.write_cache, opts_.nnet_config.binary_write_cache);
      compiler_.WriteCache(ko.Stream(), opts_.nnet_config.binary_write_cache);
      KALDI_LOG << "Wrote computation cache to " << opts_.nnet_config.write_cache;
    }
    delete delta_nnet_;
  }
  
  
  } // namespace nnet3
  } // namespace kaldi