Blame view

src/nnet/nnet-frame-pooling-component.h 9.97 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
  // nnet/nnet-frame-pooling-component.h
  
  // Copyright 2014  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_FRAME_POOLING_COMPONENT_H_
  #define KALDI_NNET_NNET_FRAME_POOLING_COMPONENT_H_
  
  #include <string>
  #include <vector>
  #include <algorithm>
  #include <sstream>
  
  #include "nnet/nnet-component.h"
  #include "nnet/nnet-utils.h"
  #include "cudamatrix/cu-math.h"
  
  namespace kaldi {
  namespace nnet1 {
  
  /**
   * FramePoolingComponent :
   * The input/output matrices are split to frames of width 'feature_dim_'.
   * Here we do weighted pooling of frames along the temporal axis,
   * given a frame-offset of leftmost frame, the pool-size is defined
   * by weight-vector size.
   */
  class FramePoolingComponent : public UpdatableComponent {
   public:
    FramePoolingComponent(int32 dim_in, int32 dim_out):
      UpdatableComponent(dim_in, dim_out),
      feature_dim_(0),
      normalize_(false)
    { }
  
    ~FramePoolingComponent()
    { }
  
    Component* Copy() const { return new FramePoolingComponent(*this); }
    ComponentType GetType() const { return kFramePoolingComponent; }
  
    /**
     * Here the offsets are w.r.t. central frames, which has offset 0.
     * Note.: both the offsets and pool sizes can be negative.
     */
    void InitData(std::istream &is) {
      // temporary, for initialization,
      std::vector<int32> pool_size;
      std::vector<int32> central_offset;
      Vector<BaseFloat> pool_weight;
      float learn_rate_coef = 0.01;
      // parse config
      std::string token;
      while (is >> std::ws, !is.eof()) {
        ReadToken(is, false, &token);
        /**/ if (token == "<FeatureDim>") ReadBasicType(is, false, &feature_dim_);
        else if (token == "<CentralOffset>") ReadIntegerVector(is, false, &central_offset);
        else if (token == "<PoolSize>") ReadIntegerVector(is, false, &pool_size);
        else if (token == "<PoolWeight>") pool_weight.Read(is, false);
        else if (token == "<LearnRateCoef>") ReadBasicType(is, false, &learn_rate_coef);
        else if (token == "<Normalize>") ReadBasicType(is, false, &normalize_);
        else KALDI_ERR << "Unknown token " << token << ", a typo in config?"
                       << " (FeatureDim|CentralOffset <vec>|PoolSize <vec>|LearnRateCoef|Normalize)";
      }
      // check inputs:
      KALDI_ASSERT(feature_dim_ > 0);
      KALDI_ASSERT(central_offset.size() > 0);
      KALDI_ASSERT(central_offset.size() == pool_size.size());
      // initialize:
      int32 num_frames = InputDim() / feature_dim_;
      int32 central_frame = (num_frames -1) / 2;
      int32 num_pools = central_offset.size();
      offset_.resize(num_pools);
      weight_.resize(num_pools);
      for (int32 p = 0; p < num_pools; p++) {
        offset_[p] = central_frame + central_offset[p] + std::min(0, pool_size[p]+1);
        weight_[p].Resize(std::abs(pool_size[p]));
        weight_[p].Set(1.0/std::abs(pool_size[p]));
      }
      learn_rate_coef_ = learn_rate_coef;
      if (pool_weight.Dim() != 0) {
        KALDI_LOG << "Initializing from pool-weight vector";
        int32 num_weights = 0;
        for (int32 p = 0; p < num_pools; p++) {
          weight_[p].CopyFromVec(pool_weight.Range(num_weights, weight_[p].Dim()));
          num_weights += weight_[p].Dim();
        }
        KALDI_ASSERT(num_weights == pool_weight.Dim());
      }
      // check that offsets are within the splice we had,
      for (int32 p = 0; p < num_pools; p++) {
        KALDI_ASSERT(offset_[p] >= 0);
        KALDI_ASSERT(offset_[p] + weight_[p].Dim() <= num_frames);
      }
    }
  
    /**
     * Here the offsets are w.r.t. leftmost frame from splice, its offset is 0.
     * If we spliced +/- 15 frames, the central frames has index '15'.
     */
    void ReadData(std::istream &is, bool binary) {
      // get the input dimension before splicing
      ExpectToken(is, binary, "<FeatureDim>");
      ReadBasicType(is, binary, &feature_dim_);
      ExpectToken(is, binary, "<LearnRateCoef>");
      ReadBasicType(is, binary, &learn_rate_coef_);
      ExpectToken(is, binary, "<Normalize>");
      ReadBasicType(is, binary, &normalize_);
      // read the offsets w.r.t. central frame
      ExpectToken(is, binary, "<FrameOffset>");
      ReadIntegerVector(is, binary, &offset_);
      // read the frame-weights
      ExpectToken(is, binary, "<FrameWeight>");
      int32 num_pools = offset_.size();
      weight_.resize(num_pools);
      for (int32 p = 0; p < num_pools; p++) {
        weight_[p].Read(is, binary);
      }
      //
      // Sanity checks:
      //
      KALDI_ASSERT(input_dim_ % feature_dim_ == 0);
      KALDI_ASSERT(output_dim_ % feature_dim_ == 0);
      KALDI_ASSERT(output_dim_ / feature_dim_ == num_pools);
      KALDI_ASSERT(offset_.size() == weight_.size());
      // check the shifts don't exceed the splicing
      int32 total_frame = InputDim() / feature_dim_;
      for (int32 p = 0; p < num_pools; p++) {
        KALDI_ASSERT(offset_[p] >= 0);
        KALDI_ASSERT(offset_[p] + (weight_[p].Dim()-1) < total_frame);
      }
      //
    }
  
    void WriteData(std::ostream &os, bool binary) const {
      WriteToken(os, binary, "<FeatureDim>");
      WriteBasicType(os, binary, feature_dim_);
      WriteToken(os, binary, "<LearnRateCoef>");
      WriteBasicType(os, binary, learn_rate_coef_);
      WriteToken(os, binary, "<Normalize>");
      WriteBasicType(os, binary, normalize_);
      WriteToken(os, binary, "<FrameOffset>");
      WriteIntegerVector(os, binary, offset_);
      // write pooling weights of individual frames
      WriteToken(os, binary, "<FrameWeight>");
      int32 num_pools = offset_.size();
      for (int32 p = 0; p < num_pools; p++) {
        weight_[p].Write(os, binary);
      }
    }
  
    int32 NumParams() const {
      int32 ans = 0;
      for (int32 p = 0; p < weight_.size(); p++) {
        ans += weight_[p].Dim();
      }
      return ans;
    }
  
    void GetGradient(VectorBase<BaseFloat> *gradient) const {
      KALDI_ERR << "Unimplemented.";
    }
  
    void GetParams(VectorBase<BaseFloat>* params) const {
      KALDI_ASSERT(params->Dim() == NumParams());
      int32 offset = 0;
      for (int32 p = 0; p < weight_.size(); p++) {
        params->Range(offset, weight_[p].Dim()).CopyFromVec(weight_[p]);
        offset += weight_[p].Dim();
      }
      KALDI_ASSERT(offset == params->Dim());
    }
  
    void SetParams(const VectorBase<BaseFloat>& params) {
      KALDI_ERR << "Unimplemented.";
    }
  
    std::string Info() const {
      std::ostringstream oss;
      oss << "
    (offset,weights) : ";
      for (int32 p = 0; p < weight_.size(); p++) {
        oss << "(" << offset_[p] << "," << weight_[p] << "), ";
      }
      return oss.str();
    }
  
    std::string InfoGradient() const {
      std::ostringstream oss;
      oss << "
    lr-coef " << ToString(learn_rate_coef_);
      oss << "
    (offset,weights_grad) : ";
      for (int32 p = 0; p < weight_diff_.size(); p++) {
        oss << "(" << offset_[p] << ",";
        // pass the weight vector, remove '
  ' as last char
        oss << weight_diff_[p];
        oss.seekp(-1, std::ios_base::cur);
        oss << "), ";
      }
      return oss.str();
    }
  
    void PropagateFnc(const CuMatrixBase<BaseFloat> &in,
                      CuMatrixBase<BaseFloat> *out) {
      // check dims
      KALDI_ASSERT(in.NumCols() % feature_dim_ == 0);
      KALDI_ASSERT(out->NumCols() % feature_dim_ == 0);
      // useful dims
      int32 num_pools = offset_.size();
      // compute the output pools
      for (int32 p = 0; p < num_pools; p++) {
        CuSubMatrix<BaseFloat> tgt(out->ColRange(p*feature_dim_, feature_dim_));
        tgt.SetZero();  // reset
        for (int32 i = 0; i < weight_[p].Dim(); i++) {
          tgt.AddMat(weight_[p](i), in.ColRange((offset_[p]+i) * feature_dim_, feature_dim_));
        }
      }
    }
  
    void BackpropagateFnc(const CuMatrixBase<BaseFloat> &in,
                          const CuMatrixBase<BaseFloat> &out,
                          const CuMatrixBase<BaseFloat> &out_diff,
                          CuMatrixBase<BaseFloat> *in_diff) {
      KALDI_ERR << "Unimplemented.";
    }
  
  
    void Update(const CuMatrixBase<BaseFloat> &input,
                const CuMatrixBase<BaseFloat> &diff) {
      // useful dims
      int32 num_pools = offset_.size();
      // lazy init
      if (weight_diff_.size() != num_pools) weight_diff_.resize(num_pools);
      // get the derivatives
      for (int32 p = 0; p < num_pools; p++) {
        weight_diff_[p].Resize(weight_[p].Dim(), kSetZero);  // reset
        for (int32 i = 0; i < weight_[p].Dim(); i++) {
          // multiply matrices element-wise, and sum to get the derivative
          CuSubMatrix<BaseFloat> in_frame(
            input.ColRange((offset_[p]+i) * feature_dim_, feature_dim_)
          );
          CuSubMatrix<BaseFloat> diff_frame(
            diff.ColRange(p * feature_dim_, feature_dim_)
          );
          CuMatrix<BaseFloat> mul_elems(in_frame);
          mul_elems.MulElements(diff_frame);
          weight_diff_[p](i) = mul_elems.Sum();
        }
      }
      // update
      for (int32 p = 0; p < num_pools; p++) {
        weight_[p].AddVec(- learn_rate_coef_ * opts_.learn_rate, weight_diff_[p]);
      }
      // force to be positive, re-normalize the sum
      if (normalize_) {
        for (int32 p = 0; p < num_pools; p++) {
          weight_[p].ApplyFloor(0.0);
          weight_[p].Scale(1.0/weight_[p].Sum());
        }
      }
    }
  
   private:
    int32 feature_dim_;  // feature dimension before splicing
    std::vector<int32> offset_;  // vector of pooling offsets
    /// Vector of pooling weight vectors,
    std::vector<Vector<BaseFloat> > weight_;
    /// detivatives of weight vectors,
    std::vector<Vector<BaseFloat> > weight_diff_;
  
    bool normalize_;  // apply normalization after each update
  };
  
  }  // namespace nnet1
  }  // namespace kaldi
  
  #endif  // KALDI_NNET_NNET_FRAME_POOLING_COMPONENT_H_