Blame view

src/nnet/nnet-loss.cc 14.9 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
  // nnet/nnet-loss.cc
  
  // Copyright 2011-2015  Brno University of Technology (author: Karel Vesely)
  
  // 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 <sstream>
  #include <iterator>
  #include <algorithm>
  #include <iomanip>
  
  #include "nnet/nnet-loss.h"
  #include "nnet/nnet-utils.h"
  #include "cudamatrix/cu-math.h"
  #include "hmm/posterior.h"
  
  namespace kaldi {
  namespace nnet1 {
  
  
  /* Xent */
  
  /**
   * Helper function of Xent::Eval,
   * calculates number of matching elemente in 'hyp', 'ref' weighted by 'weights'.
   */
  template <typename T>
  inline void CountCorrectFramesWeighted(const CuArray<T> &hyp,
                                         const CuArray<T> &ref,
                                         const CuVectorBase<BaseFloat> &weights,
                                         Vector<double> *correct) {
    KALDI_ASSERT(hyp.Dim() == ref.Dim());
    KALDI_ASSERT(hyp.Dim() == weights.Dim());
    int32 dim = hyp.Dim();
    // Get GPU data to host,
    std::vector<T> hyp_h(dim), ref_h(dim);
    hyp.CopyToVec(&hyp_h);
    ref.CopyToVec(&ref_h);
    Vector<BaseFloat> w(dim);
    weights.CopyToVec(&w);
    // Accumulate weighted counts of correct frames,
    for (int32 i = 0; i < dim; i++) {
      KALDI_ASSERT(ref_h[i] < correct->Dim());
      (*correct)(ref_h[i]) += w(i) * (hyp_h[i] == ref_h[i] ? 1.0 : 0.0);
    }
  }
  
  
  void Xent::Eval(const VectorBase<BaseFloat> &frame_weights,
                  const CuMatrixBase<BaseFloat> &net_out,
                  const CuMatrixBase<BaseFloat> &targets,
                  CuMatrix<BaseFloat> *diff) {
    // check inputs,
    KALDI_ASSERT(net_out.NumCols() == targets.NumCols());
    KALDI_ASSERT(net_out.NumRows() == targets.NumRows());
    KALDI_ASSERT(net_out.NumRows() == frame_weights.Dim());
  
    KALDI_ASSERT(KALDI_ISFINITE(frame_weights.Sum()));
    KALDI_ASSERT(KALDI_ISFINITE(net_out.Sum()));
    KALDI_ASSERT(KALDI_ISFINITE(targets.Sum()));
  
    // buffer initialization,
    int32 num_classes = targets.NumCols();
    if (frames_.Dim() == 0) {
      frames_.Resize(num_classes);
      xentropy_.Resize(num_classes);
      entropy_.Resize(num_classes);
      correct_.Resize(num_classes);
    }
  
    // get frame_weights to GPU,
    frame_weights_ = frame_weights;
  
    // There may be frames for which the sum of targets is zero.
    // This happens in multi-lingual training when the frame
    // has target class in the softmax of another language.
    // We 'switch-off' such frames by masking the 'frame_weights_',
    target_sum_.Resize(targets.NumRows());
    target_sum_.AddColSumMat(1.0, targets, 0.0);
    frame_weights_.MulElements(target_sum_);
  
    // compute derivative wrt. activations of last layer of neurons,
    *diff = net_out;
    diff->AddMat(-1.0, targets);
    diff->MulRowsVec(frame_weights_);  // weighting,
  
    // count frames per class,
    frames_aux_ = targets;
    frames_aux_.MulRowsVec(frame_weights_);
    frames_.AddRowSumMat(1.0, CuMatrix<double>(frames_aux_));
  
    // evaluate the frame-level classification,
    net_out.FindRowMaxId(&max_id_out_);  // find max in nn-output
    targets.FindRowMaxId(&max_id_tgt_);  // find max in targets
    CountCorrectFramesWeighted(max_id_out_, max_id_tgt_,
                               frame_weights_, &correct_);
  
    // calculate cross_entropy (in GPU),
    xentropy_aux_ = net_out;  // y
    xentropy_aux_.Add(1e-20);  // avoid log(0)
    xentropy_aux_.ApplyLog();  // log(y)
    xentropy_aux_.MulElements(targets);  // t*log(y)
    xentropy_aux_.MulRowsVec(frame_weights_);  // w*t*log(y)
    xentropy_.AddRowSumMat(-1.0, CuMatrix<double>(xentropy_aux_));
  
    // caluculate entropy (in GPU),
    entropy_aux_ = targets;  // t
    entropy_aux_.Add(1e-20);  // avoid log(0)
    entropy_aux_.ApplyLog();  // log(t)
    entropy_aux_.MulElements(targets);  // t*log(t)
    entropy_aux_.MulRowsVec(frame_weights_);  // w*t*log(t)
    entropy_.AddRowSumMat(-1.0, CuMatrix<double>(entropy_aux_));
  
    // progressive loss reporting
    if (opts_.loss_report_frames > 0) {
      frames_progress_ += frame_weights_.Sum();
      xentropy_progress_ += -xentropy_aux_.Sum();
      entropy_progress_ += -entropy_aux_.Sum();
  
      KALDI_ASSERT(KALDI_ISFINITE(xentropy_progress_));
      KALDI_ASSERT(KALDI_ISFINITE(entropy_progress_));
  
      if (frames_progress_ > opts_.loss_report_frames) {
        // loss value,
        double progress_value =
          (xentropy_progress_ - entropy_progress_) / frames_progress_;
  
        // time-related info (fps is weighted),
        double time_now = timer_.Elapsed();
        double fps = frames_progress_ / (time_now - elapsed_seconds_);
        double elapsed_hours = time_now / 3600;
        elapsed_seconds_ = time_now; // store,
  
        // print,
        KALDI_LOG << "ProgressLoss[last "
                  << static_cast<int>(frames_progress_/100/3600) << "h of "
                  << static_cast<int>(frames_.Sum()/100/3600) << "h]: "
                  << progress_value << " (Xent)"
                  << ", fps=" << fps
                  << std::setprecision(3)
                  << ", elapsed " << elapsed_hours << "h";
        // store,
        loss_vec_.push_back(progress_value);
        // reset,
        frames_progress_ = 0;
        xentropy_progress_ = 0.0;
        entropy_progress_ = 0.0;
      }
    }
  }
  
  
  void Xent::Eval(const VectorBase<BaseFloat> &frame_weights,
                  const CuMatrixBase<BaseFloat> &net_out,
                  const Posterior &post,
                  CuMatrix<BaseFloat> *diff) {
    int32 num_frames = net_out.NumRows(),
      num_pdf = net_out.NumCols();
    KALDI_ASSERT(num_frames == post.size());
  
    // convert posterior to matrix,
    PosteriorToMatrix(post, num_pdf, &tgt_mat_);
  
    // call the other eval function,
    Eval(frame_weights, net_out, tgt_mat_, diff);
  }
  
  
  std::string Xent::Report() {
    double loss_value =
      (xentropy_.Sum() - entropy_.Sum()) / frames_.Sum();
    std::ostringstream oss;
    oss << "AvgLoss: " << loss_value << " (Xent), "
        << "[AvgXent: " << xentropy_.Sum() / frames_.Sum()
        << ", AvgTargetEnt: " << entropy_.Sum() / frames_.Sum()
        << "]" << std::endl;
  
    oss << "progress: [";
    std::copy(loss_vec_.begin(), loss_vec_.end(),
              std::ostream_iterator<float>(oss, " "));
    oss << "]" << std::endl;
  
    double frame_accuracy = 100.0 * correct_.Sum() / frames_.Sum();
    oss << "FRAME_ACCURACY >> " << frame_accuracy << "% <<" << std::endl;
  
    return oss.str();
  }
  
  
  std::string Xent::ReportPerClass() {
    std::ostringstream oss;
    oss << "PER-CLASS PERFORMANCE:" << std::endl;
    oss << "@@@ Frames per-class:" << frames_;
    // get inverted counts,
    CuVector<double> inv_frames(frames_);
    inv_frames.Add(0.5);  // avoid 0-frames,
    inv_frames.ApplyPow(-1.0);
    // loss, kl = xentropy-entropy,
    CuVector<double> loss(xentropy_);
    loss.AddVec(-1.0, entropy_);
    loss.MulElements(inv_frames);
    oss << "@@@ Loss per-class:" << loss;
    // frame accuracy (assuming targets are binary),
    CuVector<double> frm_accu(correct_);
    frm_accu.MulElements(inv_frames);
    frm_accu.Scale(100.0);
    oss << "@@@ Frame-accuracy per-class:" << frm_accu;
    //
    return oss.str();
  }
  
  
  /* Mse */
  
  void Mse::Eval(const VectorBase<BaseFloat> &frame_weights,
                 const CuMatrixBase<BaseFloat>& net_out,
                 const CuMatrixBase<BaseFloat>& target,
                 CuMatrix<BaseFloat>* diff) {
    // check inputs,
    KALDI_ASSERT(net_out.NumCols() == target.NumCols());
    KALDI_ASSERT(net_out.NumRows() == target.NumRows());
    KALDI_ASSERT(net_out.NumRows() == frame_weights.Dim());
  
    KALDI_ASSERT(KALDI_ISFINITE(frame_weights.Sum()));
    KALDI_ASSERT(KALDI_ISFINITE(net_out.Sum()));
    KALDI_ASSERT(KALDI_ISFINITE(target.Sum()));
  
    int32 num_frames = frame_weights.Sum();
    KALDI_ASSERT(num_frames >= 0.0);
  
    // get frame_weights to GPU,
    frame_weights_ = frame_weights;
  
    // compute derivative w.r.t. neural nerwork outputs
    *diff = net_out;  // y
    diff->AddMat(-1.0, target);  // (y - t)
    diff->MulRowsVec(frame_weights_);  // weighting,
  
    // Compute MeanSquareError loss of mini-batch
    diff_pow_2_ = *diff;
    diff_pow_2_.MulElements(diff_pow_2_);  // (y - t)^2
    diff_pow_2_.MulRowsVec(frame_weights_);  // w*(y - t)^2
    double mean_square_error = 0.5 * diff_pow_2_.Sum();  // sum the matrix,
  
    KALDI_ASSERT(KALDI_ISFINITE(mean_square_error));
  
    // accumulate
    loss_ += mean_square_error;
    frames_ += num_frames;
  
    // progressive loss reporting
    if (opts_.loss_report_frames > 0) {
      frames_progress_ += num_frames;
      loss_progress_ += mean_square_error;
      if (frames_progress_ > opts_.loss_report_frames) {
        KALDI_LOG << "ProgressLoss[last "
                  << static_cast<int>(frames_progress_/100/3600) << "h of "
                  << static_cast<int>(frames_/100/3600) << "h]: "
                  << loss_progress_/frames_progress_ << " (Mse)";
        // store
        loss_vec_.push_back(loss_progress_/frames_progress_);
        // reset
        frames_progress_ = 0;
        loss_progress_ = 0.0;
      }
    }
  }
  
  
  void Mse::Eval(const VectorBase<BaseFloat> &frame_weights,
                 const CuMatrixBase<BaseFloat>& net_out,
                 const Posterior& post,
                 CuMatrix<BaseFloat>* diff) {
    int32 num_frames = net_out.NumRows(),
      num_nn_outputs = net_out.NumCols();
    KALDI_ASSERT(num_frames == post.size());
  
    // convert posterior to matrix,
    PosteriorToMatrix(post, num_nn_outputs, &tgt_mat_);
  
    // call the other eval function,
    Eval(frame_weights, net_out, tgt_mat_, diff);
  }
  
  
  std::string Mse::Report() {
    // compute root mean square,
    int32 num_tgt = diff_pow_2_.NumCols();
    BaseFloat root_mean_square = sqrt(loss_/frames_/num_tgt);
    // build the message,
    std::ostringstream oss;
    oss << "AvgLoss: " << loss_/frames_ << " (Mse), "
        << "[RMS " << root_mean_square << ", frames "
        << frames_ << "]" << std::endl;
    oss << "progress: [";
    std::copy(loss_vec_.begin(), loss_vec_.end(),
              std::ostream_iterator<float>(oss, " "));
    oss << "]" << std::endl;
    return oss.str();
  }
  
  
  /* MultiTaskLoss */
  
  void MultiTaskLoss::InitFromString(const std::string& s) {
    std::vector<std::string> v;
    SplitStringToVector(s, ",:" /* delimiter */, false, &v);
  
    KALDI_ASSERT((v.size()-1) % 3 == 0);  // triplets,
    KALDI_ASSERT(v[0] == "multitask");  // header,
  
    // parse the definition of multitask loss,
    std::vector<std::string>::iterator it(v.begin()+1);  // skip header,
    for ( ; it != v.end(); ++it) {
      // type,
      if (*it == "xent") {
        loss_vec_.push_back(new Xent(opts_));
      } else if (*it == "mse") {
        loss_vec_.push_back(new Mse(opts_));
      } else {
        KALDI_ERR << "Unknown objective function code : " << *it;
      }
      ++it;
      // dim,
      int32 dim;
      if (!ConvertStringToInteger(*it, &dim)) {
        KALDI_ERR << "Cannot convert 'dim' " << *it << " to integer!";
      }
      loss_dim_.push_back(dim);
      ++it;
      // weight,
      BaseFloat weight;
      if (!ConvertStringToReal(*it, &weight)) {
        KALDI_ERR << "Cannot convert 'weight' " << *it << " to integer!";
      }
      KALDI_ASSERT(weight >= 0.0);
      loss_weights_.push_back(weight);
    }
  
    // build vector with starting-point offsets,
    loss_dim_offset_.resize(loss_dim_.size()+1, 0);  // 1st zero stays,
    for (int32 i = 1; i <= loss_dim_.size(); i++) {
      loss_dim_offset_[i] = loss_dim_offset_[i-1] + loss_dim_[i-1];
    }
  
    // sanity check,
    KALDI_ASSERT(loss_vec_.size() > 0);
    KALDI_ASSERT(loss_vec_.size() == loss_dim_.size());
    KALDI_ASSERT(loss_vec_.size() == loss_weights_.size());
  }
  
  void MultiTaskLoss::Eval(const VectorBase<BaseFloat> &frame_weights,
              const CuMatrixBase<BaseFloat>& net_out,
              const Posterior& post,
              CuMatrix<BaseFloat>* diff) {
    int32 num_frames = net_out.NumRows(),
      num_output = net_out.NumCols();
    KALDI_ASSERT(num_frames == post.size());
    KALDI_ASSERT(num_output == loss_dim_offset_.back());  // sum of loss-dims,
  
    // convert posterior to matrix,
    PosteriorToMatrix(post, num_output, &tgt_mat_);
  
    // allocate diff matrix,
    diff->Resize(num_frames, num_output);
  
    /// One vector of frame_weights per loss-function,
    /// The original frame weights are multiplied with
    /// a mask of `defined targets' according to the 'Posterior'.
    std::vector<Vector<BaseFloat> > frmwei_have_tgt;
    for (int32 l = 0; l < loss_vec_.size(); l++) {
      // copy original weights,
      frmwei_have_tgt.push_back(Vector<BaseFloat>(frame_weights));
      // We need to mask-out the frames for which the 'posterior' is not defined (= is empty):
      int32 loss_beg = loss_dim_offset_[l];   // first column of loss target,
      int32 loss_end = loss_dim_offset_[l+1]; // (last+1) column of loss target,
      for (int32 f = 0; f < num_frames; f++) {
        bool tgt_defined = false;
        for (int32 p = 0; p < post[f].size(); p++) {
          if (post[f][p].first >= loss_beg && post[f][p].first < loss_end) {
            tgt_defined = true;
            break;
          }
        }
        if (!tgt_defined) {
          frmwei_have_tgt[l](f) = 0.0; // set zero_weight for the frame with no targets!
        }
      }
    }
  
    // call the vector of loss functions,
    CuMatrix<BaseFloat> diff_aux;
    for (int32 l = 0; l < loss_vec_.size(); l++) {
      loss_vec_[l]->Eval(frmwei_have_tgt[l],
        net_out.ColRange(loss_dim_offset_[l], loss_dim_[l]),
        tgt_mat_.ColRange(loss_dim_offset_[l], loss_dim_[l]),
        &diff_aux);
      // Scale the gradients,
      diff_aux.Scale(loss_weights_[l]);
      // Copy to diff,
      diff->ColRange(loss_dim_offset_[l], loss_dim_[l]).CopyFromMat(diff_aux);
    }
  }
  
  std::string MultiTaskLoss::Report() {
    // calculate overall loss (weighted),
    BaseFloat overall_loss = AvgLoss();
    // copy the loss-values into a vector,
    std::vector<BaseFloat> loss_values;
    for (int32 i = 0; i < loss_vec_.size(); i++) {
      loss_values.push_back(loss_vec_[i]->AvgLoss());
    }
  
    // build the message,
    std::ostringstream oss;
    oss << "MultiTaskLoss, with " << loss_vec_.size()
        << " parallel loss functions." << std::endl;
    // individual loss reports first,
    for (int32 i = 0; i < loss_vec_.size(); i++) {
      oss << "Loss " << i+1 << ", " << loss_vec_[i]->Report() << std::endl;
    }
  
    // overall loss is last,
    oss << "Loss (OVERALL), "
        << "AvgLoss: " << overall_loss << " (MultiTaskLoss), "
        << "weights " << loss_weights_ << ", "
        << "values " << loss_values << std::endl;
  
    return oss.str();
  }
  
  BaseFloat MultiTaskLoss::AvgLoss() {
    BaseFloat ans(0.0);
    for (int32 i = 0; i < loss_vec_.size(); i++) {
      BaseFloat val = loss_weights_[i] * loss_vec_[i]->AvgLoss();
      if (!KALDI_ISFINITE(val)) {
        KALDI_WARN << "Loss " << i+1 << ", has bad objective function value '"
                   << val << "', using 0.0 instead.";
        val = 0.0;
      }
      ans += val;
    }
    return ans;
  }
  
  }  // namespace nnet1
  }  // namespace kaldi