Blame view

src/nnet/nnet-multibasis-component.h 15.1 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
  // nnet/nnet-multibasis-component.h
  
  // Copyright 2016  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.
  
  
  #ifndef KALDI_NNET_NNET_MULTIBASIS_COMPONENT_H_
  #define KALDI_NNET_NNET_MULTIBASIS_COMPONENT_H_
  
  #include <sstream>
  #include <vector>
  #include <string>
  
  #include "nnet/nnet-component.h"
  #include "nnet/nnet-affine-transform.h"
  
  namespace kaldi {
  namespace nnet1 {
  
  class MultiBasisComponent : public UpdatableComponent {
   public:
    MultiBasisComponent(int32 dim_in, int32 dim_out) :
      UpdatableComponent(dim_in, dim_out),
      selector_lr_coef_(1.0),
      threshold_(0.1)
    { }
  
    ~MultiBasisComponent()
    { }
  
    Component* Copy() const { return new MultiBasisComponent(*this); }
    ComponentType GetType() const { return kMultiBasisComponent; }
  
    void InitData(std::istream &is) {
      // define options,
      std::string selector_proto;
      std::string selector_filename;
      std::string basis_proto;
      std::string basis_filename;
      std::vector<std::string> basis_filename_vector;
  
      // parse config
      std::string token;
      while (is >> std::ws, !is.eof()) {
        ReadToken(is, false, &token);
        /**/ if (token == "<SelectorProto>") ReadToken(is, false, &selector_proto);
        else if (token == "<SelectorFilename>") ReadToken(is, false, &selector_filename);
        else if (token == "<SelectorLearnRateCoef>") ReadBasicType(is, false, &selector_lr_coef_);
        else if (token == "<BasisProto>") ReadToken(is, false, &basis_proto);
        else if (token == "<BasisFilename>") ReadToken(is, false, &basis_filename);
        else if (token == "<BasisFilenameVector>") {
          while(is >> std::ws, !is.eof()) {
            std::string file_or_end;
            ReadToken(is, false, &file_or_end);
            if (file_or_end == "</BasisFilenameVector>") break;
            basis_filename_vector.push_back(file_or_end);
          }
        } else KALDI_ERR << "Unknown token " << token << ", typo in config?"
                 << " (SelectorProto|SelectorFilename|BasisProto|BasisFilename|BasisFilenameVector)";
      }
  
      //// INITIALIZE
  
      // selector,
      if (selector_proto != "") {
        KALDI_LOG << "Initializing 'selector' from : " << selector_proto;
        selector_.Init(selector_proto);
      }
      if (selector_filename != "") {
        KALDI_LOG << "Reading 'selector' from : " << selector_filename;
        selector_.Read(selector_filename);
      }
  
      // as many empty basis as outputs of the selector,
      nnet_basis_.resize(selector_.OutputDim());
      // fill the basis,
      if (basis_proto != "") {
        // Initialized from prototype,
        KALDI_LOG << "Initializing 'basis' from : " << basis_proto;
        for (int32 i = 0; i < nnet_basis_.size(); i++) {
          nnet_basis_[i].Init(basis_proto);
        }
      } else if (basis_filename != "") {
        // Load 1 initial basis repeateadly,
        KALDI_LOG << "Reading 'basis' from : " << basis_filename;
        for (int32 i = 0; i < nnet_basis_.size(); i++) {
          nnet_basis_[i].Read(basis_filename);
        }
      } else if (basis_filename_vector.size() > 0) {
        // Read a list of basis functions,
        if (basis_filename_vector.size() != nnet_basis_.size()) {
          KALDI_ERR << "We need " << nnet_basis_.size() << " filenames. "
                    << "We got " << basis_filename_vector.size();
        }
        for (int32 i = 0; i < nnet_basis_.size(); i++) {
          KALDI_LOG << "Reading 'basis' from : "
                    << basis_filename_vector[i];
          nnet_basis_[i].Read(basis_filename_vector[i]);
        }
      } else {
        // Initialize basis by square identity matrix,
        int32 basis_input_dim = InputDim() - selector_.InputDim();
        KALDI_LOG << "Initializing 'basis' to Identity <AffineTransform> "
                  << OutputDim() << "x" << basis_input_dim;
        KALDI_ASSERT(OutputDim() == basis_input_dim);  // has to be square!
        Matrix<BaseFloat> m(OutputDim(), basis_input_dim);
        m.SetUnit();
        // wrap identity into AffineTransform,
        // (bias is vector of zeros),
        AffineTransform identity_comp(basis_input_dim, OutputDim());
        identity_comp.SetLinearity(CuMatrix<BaseFloat>(m));
        //
        for (int32 i = 0; i < nnet_basis_.size(); i++) {
          nnet_basis_[i].AppendComponent(identity_comp);
        }
      }
  
      // check,
      KALDI_ASSERT(InputDim() == selector_.InputDim() + nnet_basis_[0].InputDim());
      KALDI_ASSERT(OutputDim() == nnet_basis_[0].OutputDim());
    }
  
    void ReadData(std::istream &is, bool binary) {
      // Read all the '<Tokens>' in arbitrary order,
      bool end_loop = false;
      while (!end_loop && '<' == Peek(is, binary)) {
        std::string token;
        int first_char = PeekToken(is, binary);
        switch (first_char) {
          case 'S': ReadToken(is, false, &token);
            /**/ if (token == "<SelectorLearnRateCoef>") ReadBasicType(is, binary, &selector_lr_coef_);
            else if (token == "<Selector>") selector_.Read(is, binary);
            else KALDI_ERR << "Unknown token: " << token;
            break;
          case 'N': ExpectToken(is, binary, "<NumBasis>");
            int32 num_basis;
            ReadBasicType(is, binary, &num_basis);
            nnet_basis_.resize(num_basis);
            for (int32 i = 0; i < num_basis; i++) {
              int32 dummy;
              ExpectToken(is, binary, "<Basis>");
              ReadBasicType(is, binary, &dummy);
              nnet_basis_[i].Read(is, binary);
            }
            break;
          case '!':
            ExpectToken(is, binary, "<!EndOfComponent>");
            end_loop=true;
            break;
          default:
            ReadToken(is, false, &token);
            KALDI_ERR << "Unknown token: " << token;
        }
      }
  
      // check,
      KALDI_ASSERT(nnet_basis_.size() == selector_.OutputDim());
      KALDI_ASSERT(InputDim() == selector_.InputDim() + nnet_basis_[0].InputDim());
      KALDI_ASSERT(OutputDim() == nnet_basis_[0].OutputDim());
    }
  
    void WriteData(std::ostream &os, bool binary) const {
      int32 num_basis = nnet_basis_.size();
      WriteToken(os, binary, "<SelectorLearnRateCoef>");
      WriteBasicType(os, binary, selector_lr_coef_);
      if (!binary) os << "
  
  ";
      WriteToken(os, binary, "<Selector>");
      if (!binary) os << "
  ";
      selector_.Write(os, binary);
      if (!binary) os << "
  ";
      WriteToken(os, binary, "<NumBasis>");
      WriteBasicType(os, binary, num_basis);
      if (!binary) os << "
  ";
      for (int32 i = 0; i < num_basis; i++) {
        WriteToken(os, binary, "<Basis>");
        WriteBasicType(os, binary, i+1);
        if (!binary) os << "
  ";
        nnet_basis_.at(i).Write(os, binary);
      }
    }
  
    Nnet& GetBasis(int32 id) { return nnet_basis_.at(id); }
    const Nnet& GetBasis(int32 id) const { return nnet_basis_.at(id); }
  
    int32 NumParams() const {
      int32 num_params_sum = selector_.NumParams();
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        num_params_sum += nnet_basis_[i].NumParams();
      }
      return num_params_sum;
    }
  
    void GetGradient(VectorBase<BaseFloat> *gradient) const {
      KALDI_ERR << "TODO, not yet implemented!";
    }
  
    void GetParams(VectorBase<BaseFloat> *params) const {
      int32 offset = 0;
      Vector<BaseFloat> params_tmp;
      // selector,
      selector_.GetParams(&params_tmp);
      params->Range(offset, params_tmp.Dim()).CopyFromVec(params_tmp);
      offset += params_tmp.Dim();
      // basis,
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        nnet_basis_[i].GetParams(&params_tmp);
        params->Range(offset, params_tmp.Dim()).CopyFromVec(params_tmp);
        offset += params_tmp.Dim();
      }
      KALDI_ASSERT(offset == NumParams());
    }
  
    void SetParams(const VectorBase<BaseFloat> &params) {
      int32 offset = 0;
      // selector,
      selector_.SetParams(params.Range(offset, selector_.NumParams()));
      offset += selector_.NumParams();
      // basis,
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        nnet_basis_[i].SetParams(params.Range(offset, nnet_basis_[i].NumParams()));
        offset += nnet_basis_[i].NumParams();
      }
      KALDI_ASSERT(offset == NumParams());
    }
  
    std::string Info() const {
      std::ostringstream os;
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        os << "basis_network #" << i+1 << " {
  "
           << nnet_basis_[i].Info()
           << "}
  ";
      }
      os << "
  selector {
  "
         << selector_.Info()
         << "}";
      return os.str();
    }
  
    std::string InfoGradient() const {
      std::ostringstream os;
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        if (posterior_sum_(i) > threshold_) {
          os << "basis_gradient #" << i+1 << " {
  "
             << nnet_basis_[i].InfoGradient(false)
             << "}
  ";
        }
      }
      os << "selector_gradient {
  "
         << selector_.InfoGradient(false)
         << "}";
      return os.str();
    }
  
    std::string InfoPropagate() const {
      std::ostringstream os;
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        if (posterior_sum_(i) > threshold_) {
          os << "basis_propagate #" << i+1 << " {
  "
             << nnet_basis_[i].InfoPropagate(false)
             << "}
  ";
        }
      }
      os << "selector_propagate {
  "
         << selector_.InfoPropagate(false)
         << "}
  ";
      return os.str();
    }
  
    std::string InfoBackPropagate() const {
      std::ostringstream os;
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        if (posterior_sum_(i) > threshold_) {
          os << "basis_backpropagate #" << i+1 << "{
  "
             << nnet_basis_[i].InfoBackPropagate(false)
             << "}
  ";
        }
      }
      os << "selector_backpropagate {
  "
         << selector_.InfoBackPropagate(false)
         << "}
  ";
      return os.str();
    }
  
    void PropagateFnc(const CuMatrixBase<BaseFloat> &in,
                      CuMatrixBase<BaseFloat> *out) {
      // dimensions,
      int32 num_basis = nnet_basis_.size();
  
      // make sure we have all the buffers,
      if (basis_out_.size() != num_basis) {
        basis_out_.resize(num_basis);
      }
  
      // split the input,
      const CuSubMatrix<BaseFloat> in_basis(
          in.ColRange(0, nnet_basis_[0].InputDim())
      );
      const CuSubMatrix<BaseFloat> in_selector(
          in.ColRange(nnet_basis_[0].InputDim(), selector_.InputDim())
      );
  
      // get the 'selector_' posteriors,
      selector_.Propagate(in_selector, &posterior_);
      KALDI_ASSERT(posterior_.Row(0).Min() >= 0.0);
      KALDI_ASSERT(posterior_.Row(0).Max() <= 1.0);
      KALDI_ASSERT(ApproxEqual(posterior_.Row(0).Sum(), 1.0));
      posterior_.Transpose();  // trans,
  
      // sum 'selector_' posteriors over time,
      CuVector<BaseFloat> posterior_sum(num_basis);
      posterior_sum.AddColSumMat(1.0, posterior_, 0.0);
      posterior_sum_ = Vector<BaseFloat>(posterior_sum);
  
      // combine the 'basis' outputs,
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        if (posterior_sum_(i) > threshold_) {
          // use only basis with occupancy >0.1,
          nnet_basis_[i].Propagate(in_basis, &basis_out_[i]);
          out->AddDiagVecMat(1.0, posterior_.Row(i), basis_out_[i], kNoTrans);
        }
      }
    }
  
    void BackpropagateFnc(const CuMatrixBase<BaseFloat> &in,
                          const CuMatrixBase<BaseFloat> &out,
                          const CuMatrixBase<BaseFloat> &out_diff,
                          CuMatrixBase<BaseFloat> *in_diff) {
      // dimensions,
      int32 num_basis = nnet_basis_.size(),
            num_frames = in.NumRows();
  
      // split the in_diff,
      CuSubMatrix<BaseFloat> in_diff_basis(
          in_diff->ColRange(0, nnet_basis_[0].InputDim())
      );
      CuSubMatrix<BaseFloat> in_diff_selector(
          in_diff->ColRange(nnet_basis_[0].InputDim(), selector_.InputDim())
      );
  
      // backprop through 'selector',
      CuMatrix<BaseFloat> selector_out_diff(num_basis, num_frames);
      for (int32 i = 0; i < num_basis; i++) {
        if (posterior_sum_(i) > threshold_) {
          selector_out_diff.Row(i).AddDiagMatMat(1.0, out_diff, kNoTrans, basis_out_[i], kTrans, 0.0);
        }
      }
      selector_out_diff.Transpose();
      selector_out_diff.Scale(selector_lr_coef_);
      CuMatrix<BaseFloat> in_diff_selector_tmp;
      selector_.Backpropagate(selector_out_diff, &in_diff_selector_tmp);
      in_diff_selector.CopyFromMat(in_diff_selector_tmp);
  
      // backprop through 'basis',
      CuMatrix<BaseFloat> out_diff_scaled(num_frames, OutputDim()),
                          in_diff_basis_tmp;
      for (int32 i = 0; i < num_basis; i++) {
        // use only basis with occupancy >0.1,
        if (posterior_sum_(i) > threshold_) {
          out_diff_scaled.AddDiagVecMat(1.0, posterior_.Row(i), out_diff, kNoTrans, 0.0);
          nnet_basis_[i].Backpropagate(out_diff_scaled, &in_diff_basis_tmp);
          in_diff_basis.AddMat(1.0, in_diff_basis_tmp);
        }
      }
    }
  
    void Update(const CuMatrixBase<BaseFloat> &input,
                const CuMatrixBase<BaseFloat> &diff) {
      { }  // do nothing
    }
  
    /**
     * Overriding the default,
     * which was UpdatableComponent::SetTrainOptions(...)
     */
    void SetTrainOptions(const NnetTrainOptions &opts) {
      selector_.SetTrainOptions(opts);
      for (int32 i=0; i<nnet_basis_.size(); i++) {
        nnet_basis_[i].SetTrainOptions(opts);
      }
    }
  
    /**
     * Overriding the default,
     * which was UpdatableComponent::SetLearnRateCoef(...)
     */
    void SetLearnRateCoef(BaseFloat val) {
      // loop over nnets,
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        // loop over components,
        for (int32 j = 0; j < nnet_basis_[i].NumComponents(); j++) {
          if (nnet_basis_[i].GetComponent(j).IsUpdatable()) {
            UpdatableComponent& comp =
              dynamic_cast<UpdatableComponent&>(nnet_basis_[i].GetComponent(j));
            // set the value,
            comp.SetLearnRateCoef(val);
          }
        }
      }
    }
  
    /**
     * Overriding the default,
     * which was UpdatableComponent::SetBiasLearnRateCoef(...)
     */
    void SetBiasLearnRateCoef(BaseFloat val) {
      // loop over nnets,
      for (int32 i = 0; i < nnet_basis_.size(); i++) {
        // loop over components,
        for (int32 j = 0; j < nnet_basis_[i].NumComponents(); j++) {
          if (nnet_basis_[i].GetComponent(j).IsUpdatable()) {
            UpdatableComponent& comp =
              dynamic_cast<UpdatableComponent&>(nnet_basis_[i].GetComponent(j));
            // set the value,
            comp.SetBiasLearnRateCoef(val);
          }
        }
      }
    }
  
   private:
    /// The vector of 'basis' networks (output of basis is combined
    /// according to the posterior_ from the selector_)
    std::vector<Nnet> nnet_basis_;
    std::vector<CuMatrix<BaseFloat> > basis_out_;
  
    /// Selector network,
    Nnet selector_;
    BaseFloat selector_lr_coef_;
  
    /// The output of 'selector_',
    CuMatrix<BaseFloat> posterior_;
    Vector<BaseFloat> posterior_sum_;
  
    /// Threshold, applied to posterior_sum_, disables the unused basis,
    BaseFloat threshold_;
  
  };
  
  }  // namespace nnet1
  }  // namespace kaldi
  
  #endif  // KALDI_NNET_NNET_MULTIBASIS_COMPONENT_H_