-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnnet-combined-component.cc
More file actions
2332 lines (2062 loc) · 87.2 KB
/
Copy pathnnet-combined-component.cc
File metadata and controls
2332 lines (2062 loc) · 87.2 KB
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// nnet3/nnet-combined-component.cc
// Copyright 2015-2018 Johns Hopkins University (author: Daniel Povey)
// 2015 Daniel Galvez
// 2018 Hang Lyu
// 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 <iterator>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include "nnet3/nnet-combined-component.h"
#include "nnet3/nnet-parse.h"
#include "cudamatrix/cu-math.h"
namespace kaldi {
namespace nnet3 {
// Constructors for the convolution component
ConvolutionComponent::ConvolutionComponent():
UpdatableComponent(),
input_x_dim_(0), input_y_dim_(0), input_z_dim_(0),
filt_x_dim_(0), filt_y_dim_(0),
filt_x_step_(0), filt_y_step_(0),
input_vectorization_(kZyx) { }
ConvolutionComponent::ConvolutionComponent(
const ConvolutionComponent &component):
UpdatableComponent(component),
input_x_dim_(component.input_x_dim_),
input_y_dim_(component.input_y_dim_),
input_z_dim_(component.input_z_dim_),
filt_x_dim_(component.filt_x_dim_),
filt_y_dim_(component.filt_y_dim_),
filt_x_step_(component.filt_x_step_),
filt_y_step_(component.filt_y_step_),
input_vectorization_(component.input_vectorization_),
filter_params_(component.filter_params_),
bias_params_(component.bias_params_) { }
ConvolutionComponent::ConvolutionComponent(
const CuMatrixBase<BaseFloat> &filter_params,
const CuVectorBase<BaseFloat> &bias_params,
int32 input_x_dim, int32 input_y_dim, int32 input_z_dim,
int32 filt_x_dim, int32 filt_y_dim,
int32 filt_x_step, int32 filt_y_step,
TensorVectorizationType input_vectorization,
BaseFloat learning_rate):
input_x_dim_(input_x_dim),
input_y_dim_(input_y_dim),
input_z_dim_(input_z_dim),
filt_x_dim_(filt_x_dim),
filt_y_dim_(filt_y_dim),
filt_x_step_(filt_x_step),
filt_y_step_(filt_y_step),
input_vectorization_(input_vectorization),
filter_params_(filter_params),
bias_params_(bias_params){
KALDI_ASSERT(filter_params.NumRows() == bias_params.Dim() &&
bias_params.Dim() != 0);
KALDI_ASSERT(filter_params.NumCols() == filt_x_dim * filt_y_dim * input_z_dim);
SetUnderlyingLearningRate(learning_rate);
is_gradient_ = false;
}
// aquire input dim
int32 ConvolutionComponent::InputDim() const {
return input_x_dim_ * input_y_dim_ * input_z_dim_;
}
// aquire output dim
int32 ConvolutionComponent::OutputDim() const {
int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_);
int32 num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_);
int32 num_filters = filter_params_.NumRows();
return num_x_steps * num_y_steps * num_filters;
}
// initialize the component using hyperparameters
void ConvolutionComponent::Init(
int32 input_x_dim, int32 input_y_dim, int32 input_z_dim,
int32 filt_x_dim, int32 filt_y_dim,
int32 filt_x_step, int32 filt_y_step, int32 num_filters,
TensorVectorizationType input_vectorization,
BaseFloat param_stddev, BaseFloat bias_stddev) {
input_x_dim_ = input_x_dim;
input_y_dim_ = input_y_dim;
input_z_dim_ = input_z_dim;
filt_x_dim_ = filt_x_dim;
filt_y_dim_ = filt_y_dim;
filt_x_step_ = filt_x_step;
filt_y_step_ = filt_y_step;
input_vectorization_ = input_vectorization;
KALDI_ASSERT((input_x_dim_ - filt_x_dim_) % filt_x_step_ == 0);
KALDI_ASSERT((input_y_dim_ - filt_y_dim_) % filt_y_step_ == 0);
int32 filter_dim = filt_x_dim_ * filt_y_dim_ * input_z_dim_;
filter_params_.Resize(num_filters, filter_dim);
bias_params_.Resize(num_filters);
KALDI_ASSERT(param_stddev >= 0.0 && bias_stddev >= 0.0);
filter_params_.SetRandn();
filter_params_.Scale(param_stddev);
bias_params_.SetRandn();
bias_params_.Scale(bias_stddev);
}
// initialize the component using predefined matrix file
void ConvolutionComponent::Init(
int32 input_x_dim, int32 input_y_dim, int32 input_z_dim,
int32 filt_x_dim, int32 filt_y_dim,
int32 filt_x_step, int32 filt_y_step,
TensorVectorizationType input_vectorization,
std::string matrix_filename) {
input_x_dim_ = input_x_dim;
input_y_dim_ = input_y_dim;
input_z_dim_ = input_z_dim;
filt_x_dim_ = filt_x_dim;
filt_y_dim_ = filt_y_dim;
filt_x_step_ = filt_x_step;
filt_y_step_ = filt_y_step;
input_vectorization_ = input_vectorization;
CuMatrix<BaseFloat> mat;
ReadKaldiObject(matrix_filename, &mat);
int32 filter_dim = (filt_x_dim_ * filt_y_dim_ * input_z_dim_);
int32 num_filters = mat.NumRows();
KALDI_ASSERT(mat.NumCols() == (filter_dim + 1));
filter_params_.Resize(num_filters, filter_dim);
bias_params_.Resize(num_filters);
filter_params_.CopyFromMat(mat.Range(0, num_filters, 0, filter_dim));
bias_params_.CopyColFromMat(mat, filter_dim);
}
// display information about component
std::string ConvolutionComponent::Info() const {
std::ostringstream stream;
stream << UpdatableComponent::Info()
<< ", input-x-dim=" << input_x_dim_
<< ", input-y-dim=" << input_y_dim_
<< ", input-z-dim=" << input_z_dim_
<< ", filt-x-dim=" << filt_x_dim_
<< ", filt-y-dim=" << filt_y_dim_
<< ", filt-x-step=" << filt_x_step_
<< ", filt-y-step=" << filt_y_step_
<< ", input-vectorization=" << input_vectorization_
<< ", num-filters=" << filter_params_.NumRows();
PrintParameterStats(stream, "filter-params", filter_params_);
PrintParameterStats(stream, "bias-params", bias_params_, true);
return stream.str();
}
// initialize the component using configuration file
void ConvolutionComponent::InitFromConfig(ConfigLine *cfl) {
bool ok = true;
std::string matrix_filename;
int32 input_x_dim = -1, input_y_dim = -1, input_z_dim = -1,
filt_x_dim = -1, filt_y_dim = -1,
filt_x_step = -1, filt_y_step = -1,
num_filters = -1;
std::string input_vectorization_order = "zyx";
InitLearningRatesFromConfig(cfl);
ok = ok && cfl->GetValue("input-x-dim", &input_x_dim);
ok = ok && cfl->GetValue("input-y-dim", &input_y_dim);
ok = ok && cfl->GetValue("input-z-dim", &input_z_dim);
ok = ok && cfl->GetValue("filt-x-dim", &filt_x_dim);
ok = ok && cfl->GetValue("filt-y-dim", &filt_y_dim);
ok = ok && cfl->GetValue("filt-x-step", &filt_x_step);
ok = ok && cfl->GetValue("filt-y-step", &filt_y_step);
if (!ok)
KALDI_ERR << "Bad initializer " << cfl->WholeLine();
// optional argument
TensorVectorizationType input_vectorization;
cfl->GetValue("input-vectorization-order", &input_vectorization_order);
if (input_vectorization_order.compare("zyx") == 0) {
input_vectorization = kZyx;
} else if (input_vectorization_order.compare("yzx") == 0) {
input_vectorization = kYzx;
} else {
KALDI_ERR << "Unknown or unsupported input vectorization order "
<< input_vectorization_order
<< " accepted candidates are 'yzx' and 'zyx'";
}
if (cfl->GetValue("matrix", &matrix_filename)) {
// initialize from prefined parameter matrix
Init(input_x_dim, input_y_dim, input_z_dim,
filt_x_dim, filt_y_dim,
filt_x_step, filt_y_step,
input_vectorization,
matrix_filename);
} else {
ok = ok && cfl->GetValue("num-filters", &num_filters);
if (!ok)
KALDI_ERR << "Bad initializer " << cfl->WholeLine();
// initialize from configuration
int32 filter_input_dim = filt_x_dim * filt_y_dim * input_z_dim;
BaseFloat param_stddev = 1.0 / std::sqrt(filter_input_dim), bias_stddev = 1.0;
cfl->GetValue("param-stddev", ¶m_stddev);
cfl->GetValue("bias-stddev", &bias_stddev);
Init(input_x_dim, input_y_dim, input_z_dim,
filt_x_dim, filt_y_dim, filt_x_step, filt_y_step, num_filters,
input_vectorization, param_stddev, bias_stddev);
}
if (cfl->HasUnusedValues())
KALDI_ERR << "Could not process these elements in initializer: "
<< cfl->UnusedValues();
if (!ok)
KALDI_ERR << "Bad initializer " << cfl->WholeLine();
}
// Inline methods to convert from tensor index i.e., (x,y,z) index
// to index in yzx or zyx vectorized tensors
inline int32 YzxVectorIndex(int32 x, int32 y, int32 z,
int32 input_x_dim,
int32 input_y_dim,
int32 input_z_dim) {
KALDI_PARANOID_ASSERT(x < input_x_dim && y < input_y_dim && z < input_z_dim);
return (input_y_dim * input_z_dim) * x + (input_y_dim) * z + y;
}
inline int32 ZyxVectorIndex(int32 x, int32 y, int32 z,
int32 input_x_dim,
int32 input_y_dim,
int32 input_z_dim) {
KALDI_PARANOID_ASSERT(x < input_x_dim && y < input_y_dim && z < input_z_dim);
return (input_y_dim * input_z_dim) * x + (input_z_dim) * y + z;
}
// Method to convert from a matrix representing a minibatch of vectorized
// 3D tensors to patches for convolution, each patch corresponds to
// one dot product in the convolution
void ConvolutionComponent::InputToInputPatches(
const CuMatrixBase<BaseFloat>& in,
CuMatrix<BaseFloat> *patches) const{
int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_);
int32 num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_);
const int32 filt_x_step = filt_x_step_,
filt_y_step = filt_y_step_,
filt_x_dim = filt_x_dim_,
filt_y_dim = filt_y_dim_,
input_x_dim = input_x_dim_,
input_y_dim = input_y_dim_,
input_z_dim = input_z_dim_,
filter_dim = filter_params_.NumCols();
std::vector<int32> column_map(patches->NumCols());
int32 column_map_size = column_map.size();
for (int32 x_step = 0; x_step < num_x_steps; x_step++) {
for (int32 y_step = 0; y_step < num_y_steps; y_step++) {
int32 patch_number = x_step * num_y_steps + y_step;
int32 patch_start_index = patch_number * filter_dim;
for (int32 x = 0, index = patch_start_index; x < filt_x_dim; x++) {
for (int32 y = 0; y < filt_y_dim; y++) {
for (int32 z = 0; z < input_z_dim; z++, index++) {
KALDI_ASSERT(index < column_map_size);
if (input_vectorization_ == kZyx) {
column_map[index] = ZyxVectorIndex(x_step * filt_x_step + x,
y_step * filt_y_step + y, z,
input_x_dim, input_y_dim,
input_z_dim);
} else if (input_vectorization_ == kYzx) {
column_map[index] = YzxVectorIndex(x_step * filt_x_step + x,
y_step * filt_y_step + y, z,
input_x_dim, input_y_dim,
input_z_dim);
}
}
}
}
}
}
CuArray<int32> cu_cols(column_map);
patches->CopyCols(in, cu_cols);
}
// propagation function
// see function declaration in nnet-simple-component.h for details
void* ConvolutionComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
const int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_),
num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_),
num_filters = filter_params_.NumRows(),
num_frames = in.NumRows(),
filter_dim = filter_params_.NumCols();
KALDI_ASSERT((*out).NumRows() == num_frames &&
(*out).NumCols() == (num_filters * num_x_steps * num_y_steps));
CuMatrix<BaseFloat> patches(num_frames,
num_x_steps * num_y_steps * filter_dim,
kUndefined);
InputToInputPatches(in, &patches);
CuSubMatrix<BaseFloat>* filter_params_elem = new CuSubMatrix<BaseFloat>(
filter_params_, 0, filter_params_.NumRows(), 0, filter_params_.NumCols());
std::vector<CuSubMatrix<BaseFloat>* > tgt_batch, patch_batch,
filter_params_batch;
for (int32 x_step = 0; x_step < num_x_steps; x_step++) {
for (int32 y_step = 0; y_step < num_y_steps; y_step++) {
int32 patch_number = x_step * num_y_steps + y_step;
tgt_batch.push_back(new CuSubMatrix<BaseFloat>(
out->ColRange(patch_number * num_filters, num_filters)));
patch_batch.push_back(new CuSubMatrix<BaseFloat>(
patches.ColRange(patch_number * filter_dim, filter_dim)));
filter_params_batch.push_back(filter_params_elem);
tgt_batch[patch_number]->AddVecToRows(1.0, bias_params_, 1.0); // add bias
}
}
// apply all filters
AddMatMatBatched<BaseFloat>(1.0, tgt_batch, patch_batch,
kNoTrans, filter_params_batch,
kTrans, 1.0);
// release memory
delete filter_params_elem;
for (int32 p = 0; p < tgt_batch.size(); p++) {
delete tgt_batch[p];
delete patch_batch[p];
}
return NULL;
}
// scale the parameters
void ConvolutionComponent::Scale(BaseFloat scale) {
if (scale == 0.0) {
filter_params_.SetZero();
bias_params_.SetZero();
} else {
filter_params_.Scale(scale);
bias_params_.Scale(scale);
}
}
// add another convolution component
void ConvolutionComponent::Add(BaseFloat alpha, const Component &other_in) {
const ConvolutionComponent *other =
dynamic_cast<const ConvolutionComponent*>(&other_in);
KALDI_ASSERT(other != NULL);
filter_params_.AddMat(alpha, other->filter_params_);
bias_params_.AddVec(alpha, other->bias_params_);
}
/*
This function transforms a vector of lists into a list of vectors,
padded with -1.
@param[in] The input vector of lists. Let in.size() be D, and let
the longest list length (i.e. the max of in[i].size()) be L.
@param[out] The output list of vectors. The length of the list will
be L, each vector-dimension will be D (i.e. out[i].size() == D),
and if in[i] == j, then for some k we will have that
out[k][j] = i. The output vectors are padded with -1
where necessary if not all the input lists have the same side.
*/
void RearrangeIndexes(const std::vector<std::vector<int32> > &in,
std::vector<std::vector<int32> > *out) {
int32 D = in.size();
int32 L = 0;
for (int32 i = 0; i < D; i++)
if (in[i].size() > L)
L = in[i].size();
out->resize(L);
for (int32 i = 0; i < L; i++)
(*out)[i].resize(D, -1);
for (int32 i = 0; i < D; i++) {
for (int32 j = 0; j < in[i].size(); j++) {
(*out)[j][i] = in[i][j];
}
}
}
// Method to compute the input derivative matrix from the input derivatives
// for patches, where each patch corresponds to one dot product
// in the convolution
void ConvolutionComponent::InderivPatchesToInderiv(
const CuMatrix<BaseFloat>& in_deriv_patches,
CuMatrixBase<BaseFloat> *in_deriv) const {
const int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_),
num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_),
filt_x_step = filt_x_step_,
filt_y_step = filt_y_step_,
filt_x_dim = filt_x_dim_,
filt_y_dim = filt_y_dim_,
input_x_dim = input_x_dim_,
input_y_dim = input_y_dim_,
input_z_dim = input_z_dim_,
filter_dim = filter_params_.NumCols();
// Compute the reverse column_map from the matrix with input
// derivative patches to input derivative matrix
std::vector<std::vector<int32> > reverse_column_map(in_deriv->NumCols());
int32 rev_col_map_size = reverse_column_map.size();
for (int32 x_step = 0; x_step < num_x_steps; x_step++) {
for (int32 y_step = 0; y_step < num_y_steps; y_step++) {
int32 patch_number = x_step * num_y_steps + y_step;
int32 patch_start_index = patch_number * filter_dim;
for (int32 x = 0, index = patch_start_index; x < filt_x_dim; x++) {
for (int32 y = 0; y < filt_y_dim; y++) {
for (int32 z = 0; z < input_z_dim; z++, index++) {
int32 vector_index;
if (input_vectorization_ == kZyx) {
vector_index = ZyxVectorIndex(x_step * filt_x_step + x,
y_step * filt_y_step + y, z,
input_x_dim, input_y_dim,
input_z_dim);
} else {
KALDI_ASSERT(input_vectorization_ == kYzx);
vector_index = YzxVectorIndex(x_step * filt_x_step + x,
y_step * filt_y_step + y, z,
input_x_dim, input_y_dim,
input_z_dim);
}
KALDI_ASSERT(vector_index < rev_col_map_size);
reverse_column_map[vector_index].push_back(index);
}
}
}
}
}
std::vector<std::vector<int32> > rearranged_column_map;
RearrangeIndexes(reverse_column_map, &rearranged_column_map);
for (int32 p = 0; p < rearranged_column_map.size(); p++) {
CuArray<int32> cu_cols(rearranged_column_map[p]);
in_deriv->AddCols(in_deriv_patches, cu_cols);
}
}
// back propagation function
// see function declaration in nnet-simple-component.h for details
void ConvolutionComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &, // out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
void *memo,
Component *to_update_in,
CuMatrixBase<BaseFloat> *in_deriv) const {
ConvolutionComponent *to_update =
dynamic_cast<ConvolutionComponent*>(to_update_in);
const int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_),
num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_),
num_filters = filter_params_.NumRows(),
num_frames = out_deriv.NumRows(),
filter_dim = filter_params_.NumCols();
KALDI_ASSERT(out_deriv.NumRows() == num_frames &&
out_deriv.NumCols() ==
(num_filters * num_x_steps * num_y_steps));
// Compute inderiv patches
CuMatrix<BaseFloat> in_deriv_patches(num_frames,
num_x_steps * num_y_steps * filter_dim,
kSetZero);
std::vector<CuSubMatrix<BaseFloat>* > patch_deriv_batch, out_deriv_batch,
filter_params_batch;
CuSubMatrix<BaseFloat>* filter_params_elem = new CuSubMatrix<BaseFloat>(
filter_params_, 0, filter_params_.NumRows(), 0, filter_params_.NumCols());
for (int32 x_step = 0; x_step < num_x_steps; x_step++) {
for (int32 y_step = 0; y_step < num_y_steps; y_step++) {
int32 patch_number = x_step * num_y_steps + y_step;
patch_deriv_batch.push_back(new CuSubMatrix<BaseFloat>(
in_deriv_patches.ColRange(
patch_number * filter_dim, filter_dim)));
out_deriv_batch.push_back(new CuSubMatrix<BaseFloat>(out_deriv.ColRange(
patch_number * num_filters, num_filters)));
filter_params_batch.push_back(filter_params_elem);
}
}
AddMatMatBatched<BaseFloat>(1.0, patch_deriv_batch,
out_deriv_batch, kNoTrans,
filter_params_batch, kNoTrans, 0.0);
if (in_deriv) {
// combine the derivatives from the individual input deriv patches
// to compute input deriv matrix
InderivPatchesToInderiv(in_deriv_patches, in_deriv);
}
if (to_update != NULL) {
to_update->Update(debug_info, in_value, out_deriv, out_deriv_batch);
}
// release memory
delete filter_params_elem;
for (int32 p = 0; p < patch_deriv_batch.size(); p++) {
delete patch_deriv_batch[p];
delete out_deriv_batch[p];
}
}
// update parameters
// see function declaration in nnet-simple-component.h for details
void ConvolutionComponent::Update(const std::string &debug_info,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &out_deriv,
const std::vector<CuSubMatrix<BaseFloat> *>& out_deriv_batch) {
// useful dims
const int32 num_x_steps = (1 + (input_x_dim_ - filt_x_dim_) / filt_x_step_),
num_y_steps = (1 + (input_y_dim_ - filt_y_dim_) / filt_y_step_),
num_filters = filter_params_.NumRows(),
num_frames = out_deriv.NumRows(),
filter_dim = filter_params_.NumCols();
KALDI_ASSERT(out_deriv.NumRows() == num_frames &&
out_deriv.NumCols() ==
(num_filters * num_x_steps * num_y_steps));
CuMatrix<BaseFloat> filters_grad;
CuVector<BaseFloat> bias_grad;
CuMatrix<BaseFloat> input_patches(num_frames,
filter_dim * num_x_steps * num_y_steps,
kUndefined);
InputToInputPatches(in_value, &input_patches);
filters_grad.Resize(num_filters, filter_dim, kSetZero); // reset
bias_grad.Resize(num_filters, kSetZero); // reset
// create a single large matrix holding the smaller matrices
// from the vector container filters_grad_batch along the rows
CuMatrix<BaseFloat> filters_grad_blocks_batch(
num_x_steps * num_y_steps * filters_grad.NumRows(),
filters_grad.NumCols());
std::vector<CuSubMatrix<BaseFloat>* > filters_grad_batch, input_patch_batch;
for (int32 x_step = 0; x_step < num_x_steps; x_step++) {
for (int32 y_step = 0; y_step < num_y_steps; y_step++) {
int32 patch_number = x_step * num_y_steps + y_step;
filters_grad_batch.push_back(new CuSubMatrix<BaseFloat>(
filters_grad_blocks_batch.RowRange(
patch_number * filters_grad.NumRows(), filters_grad.NumRows())));
input_patch_batch.push_back(new CuSubMatrix<BaseFloat>(
input_patches.ColRange(patch_number * filter_dim, filter_dim)));
}
}
AddMatMatBatched<BaseFloat>(1.0, filters_grad_batch, out_deriv_batch, kTrans,
input_patch_batch, kNoTrans, 1.0);
// add the row blocks together to filters_grad
filters_grad.AddMatBlocks(1.0, filters_grad_blocks_batch);
// create a matrix holding the col blocks sum of out_deriv
CuMatrix<BaseFloat> out_deriv_col_blocks_sum(out_deriv.NumRows(),
num_filters);
// add the col blocks together to out_deriv_col_blocks_sum
out_deriv_col_blocks_sum.AddMatBlocks(1.0, out_deriv);
bias_grad.AddRowSumMat(1.0, out_deriv_col_blocks_sum, 1.0);
// release memory
for (int32 p = 0; p < input_patch_batch.size(); p++) {
delete filters_grad_batch[p];
delete input_patch_batch[p];
}
//
// update
//
filter_params_.AddMat(learning_rate_, filters_grad);
bias_params_.AddVec(learning_rate_, bias_grad);
}
void ConvolutionComponent::Read(std::istream &is, bool binary) {
ReadUpdatableCommon(is, binary); // Read opening tag and learning rate.
ExpectToken(is, binary, "<InputXDim>");
ReadBasicType(is, binary, &input_x_dim_);
ExpectToken(is, binary, "<InputYDim>");
ReadBasicType(is, binary, &input_y_dim_);
ExpectToken(is, binary, "<InputZDim>");
ReadBasicType(is, binary, &input_z_dim_);
ExpectToken(is, binary, "<FiltXDim>");
ReadBasicType(is, binary, &filt_x_dim_);
ExpectToken(is, binary, "<FiltYDim>");
ReadBasicType(is, binary, &filt_y_dim_);
ExpectToken(is, binary, "<FiltXStep>");
ReadBasicType(is, binary, &filt_x_step_);
ExpectToken(is, binary, "<FiltYStep>");
ReadBasicType(is, binary, &filt_y_step_);
ExpectToken(is, binary, "<InputVectorization>");
int32 input_vectorization;
ReadBasicType(is, binary, &input_vectorization);
input_vectorization_ = static_cast<TensorVectorizationType>(input_vectorization);
ExpectToken(is, binary, "<FilterParams>");
filter_params_.Read(is, binary);
ExpectToken(is, binary, "<BiasParams>");
bias_params_.Read(is, binary);
std::string tok;
ReadToken(is, binary, &tok);
if (tok == "<IsGradient>") {
ReadBasicType(is, binary, &is_gradient_);
ExpectToken(is, binary, "</ConvolutionComponent>");
} else {
is_gradient_ = false;
KALDI_ASSERT(tok == "</ConvolutionComponent>");
}
}
void ConvolutionComponent::Write(std::ostream &os, bool binary) const {
WriteUpdatableCommon(os, binary); // write opening tag and learning rate.
WriteToken(os, binary, "<InputXDim>");
WriteBasicType(os, binary, input_x_dim_);
WriteToken(os, binary, "<InputYDim>");
WriteBasicType(os, binary, input_y_dim_);
WriteToken(os, binary, "<InputZDim>");
WriteBasicType(os, binary, input_z_dim_);
WriteToken(os, binary, "<FiltXDim>");
WriteBasicType(os, binary, filt_x_dim_);
WriteToken(os, binary, "<FiltYDim>");
WriteBasicType(os, binary, filt_y_dim_);
WriteToken(os, binary, "<FiltXStep>");
WriteBasicType(os, binary, filt_x_step_);
WriteToken(os, binary, "<FiltYStep>");
WriteBasicType(os, binary, filt_y_step_);
WriteToken(os, binary, "<InputVectorization>");
WriteBasicType(os, binary, static_cast<int32>(input_vectorization_));
WriteToken(os, binary, "<FilterParams>");
filter_params_.Write(os, binary);
WriteToken(os, binary, "<BiasParams>");
bias_params_.Write(os, binary);
WriteToken(os, binary, "<IsGradient>");
WriteBasicType(os, binary, is_gradient_);
WriteToken(os, binary, "</ConvolutionComponent>");
}
BaseFloat ConvolutionComponent::DotProduct(const UpdatableComponent &other_in) const {
const ConvolutionComponent *other =
dynamic_cast<const ConvolutionComponent*>(&other_in);
return TraceMatMat(filter_params_, other->filter_params_, kTrans)
+ VecVec(bias_params_, other->bias_params_);
}
Component* ConvolutionComponent::Copy() const {
ConvolutionComponent *ans = new ConvolutionComponent(*this);
return ans;
}
void ConvolutionComponent::PerturbParams(BaseFloat stddev) {
CuMatrix<BaseFloat> temp_filter_params(filter_params_);
temp_filter_params.SetRandn();
filter_params_.AddMat(stddev, temp_filter_params);
CuVector<BaseFloat> temp_bias_params(bias_params_);
temp_bias_params.SetRandn();
bias_params_.AddVec(stddev, temp_bias_params);
}
void ConvolutionComponent::SetParams(const VectorBase<BaseFloat> &bias,
const MatrixBase<BaseFloat> &filter) {
bias_params_ = bias;
filter_params_ = filter;
KALDI_ASSERT(bias_params_.Dim() == filter_params_.NumRows());
}
int32 ConvolutionComponent::NumParameters() const {
return (filter_params_.NumCols() + 1) * filter_params_.NumRows();
}
void ConvolutionComponent::Vectorize(VectorBase<BaseFloat> *params) const {
KALDI_ASSERT(params->Dim() == this->NumParameters());
int32 num_filter_params = filter_params_.NumCols() * filter_params_.NumRows();
params->Range(0, num_filter_params).CopyRowsFromMat(filter_params_);
params->Range(num_filter_params, bias_params_.Dim()).CopyFromVec(bias_params_);
}
void ConvolutionComponent::UnVectorize(const VectorBase<BaseFloat> ¶ms) {
KALDI_ASSERT(params.Dim() == this->NumParameters());
int32 num_filter_params = filter_params_.NumCols() * filter_params_.NumRows();
filter_params_.CopyRowsFromVec(params.Range(0, num_filter_params));
bias_params_.CopyFromVec(params.Range(num_filter_params, bias_params_.Dim()));
}
// aquire input dim
int32 MaxpoolingComponent::InputDim() const {
return input_x_dim_ * input_y_dim_ * input_z_dim_;
}
MaxpoolingComponent::MaxpoolingComponent(
const MaxpoolingComponent &component):
input_x_dim_(component.input_x_dim_),
input_y_dim_(component.input_y_dim_),
input_z_dim_(component.input_z_dim_),
pool_x_size_(component.pool_x_size_),
pool_y_size_(component.pool_y_size_),
pool_z_size_(component.pool_z_size_),
pool_x_step_(component.pool_x_step_),
pool_y_step_(component.pool_y_step_),
pool_z_step_(component.pool_z_step_) { }
// aquire output dim
int32 MaxpoolingComponent::OutputDim() const {
int32 num_pools_x = 1 + (input_x_dim_ - pool_x_size_) / pool_x_step_;
int32 num_pools_y = 1 + (input_y_dim_ - pool_y_size_) / pool_y_step_;
int32 num_pools_z = 1 + (input_z_dim_ - pool_z_size_) / pool_z_step_;
return num_pools_x * num_pools_y * num_pools_z;
}
// check the component parameters
void MaxpoolingComponent::Check() const {
// sanity check of the max pooling parameters
KALDI_ASSERT(input_x_dim_ > 0);
KALDI_ASSERT(input_y_dim_ > 0);
KALDI_ASSERT(input_z_dim_ > 0);
KALDI_ASSERT(pool_x_size_ > 0);
KALDI_ASSERT(pool_y_size_ > 0);
KALDI_ASSERT(pool_z_size_ > 0);
KALDI_ASSERT(pool_x_step_ > 0);
KALDI_ASSERT(pool_y_step_ > 0);
KALDI_ASSERT(pool_z_step_ > 0);
KALDI_ASSERT(input_x_dim_ >= pool_x_size_);
KALDI_ASSERT(input_y_dim_ >= pool_y_size_);
KALDI_ASSERT(input_z_dim_ >= pool_z_size_);
KALDI_ASSERT(pool_x_size_ >= pool_x_step_);
KALDI_ASSERT(pool_y_size_ >= pool_y_step_);
KALDI_ASSERT(pool_z_size_ >= pool_z_step_);
KALDI_ASSERT((input_x_dim_ - pool_x_size_) % pool_x_step_ == 0);
KALDI_ASSERT((input_y_dim_ - pool_y_size_) % pool_y_step_ == 0);
KALDI_ASSERT((input_z_dim_ - pool_z_size_) % pool_z_step_ == 0);
}
// initialize the component using configuration file
void MaxpoolingComponent::InitFromConfig(ConfigLine *cfl) {
bool ok = true;
ok = ok && cfl->GetValue("input-x-dim", &input_x_dim_);
ok = ok && cfl->GetValue("input-y-dim", &input_y_dim_);
ok = ok && cfl->GetValue("input-z-dim", &input_z_dim_);
ok = ok && cfl->GetValue("pool-x-size", &pool_x_size_);
ok = ok && cfl->GetValue("pool-y-size", &pool_y_size_);
ok = ok && cfl->GetValue("pool-z-size", &pool_z_size_);
ok = ok && cfl->GetValue("pool-x-step", &pool_x_step_);
ok = ok && cfl->GetValue("pool-y-step", &pool_y_step_);
ok = ok && cfl->GetValue("pool-z-step", &pool_z_step_);
if (cfl->HasUnusedValues())
KALDI_ERR << "Could not process these elements in initializer: "
<< cfl->UnusedValues();
if (!ok)
KALDI_ERR << "Bad initializer " << cfl->WholeLine();
Check();
}
// Method to convert from a matrix representing a minibatch of vectorized
// 3D tensors to patches for 3d max pooling, each patch corresponds to
// the nodes having the same local coordinatenodes from each pool
void MaxpoolingComponent::InputToInputPatches(
const CuMatrixBase<BaseFloat>& in,
CuMatrix<BaseFloat> *patches) const{
int32 num_pools_x = 1 + (input_x_dim_ - pool_x_size_) / pool_x_step_;
int32 num_pools_y = 1 + (input_y_dim_ - pool_y_size_) / pool_y_step_;
int32 num_pools_z = 1 + (input_z_dim_ - pool_z_size_) / pool_z_step_;
std::vector<int32> column_map(patches->NumCols());
int32 column_map_size = column_map.size();
for (int32 x = 0, index =0; x < pool_x_size_; x++) {
for (int32 y = 0; y < pool_y_size_; y++) {
for (int32 z = 0; z < pool_z_size_; z++) {
// given the local node coordinate, group them from each pool
// to form a patch
for (int32 x_pool = 0; x_pool < num_pools_x; x_pool++) {
for (int32 y_pool = 0; y_pool < num_pools_y; y_pool++) {
for (int32 z_pool = 0; z_pool < num_pools_z; z_pool++, index++) {
KALDI_ASSERT(index < column_map_size);
column_map[index] = (x_pool * pool_x_step_ + x) * input_y_dim_ * input_z_dim_ +
(y_pool * pool_y_step_ + y) * input_z_dim_ +
(z_pool * pool_z_step_ + z);
}
}
}
}
}
}
CuArray<int32> cu_cols(column_map);
patches->CopyCols(in, cu_cols);
}
/*
This is the 3d max pooling propagate function.
It is assumed that each row of the input matrix
is a vectorized 3D-tensor of type zxy.
Similar to the propagate function of ConvolutionComponent,
the input matrix is first arranged into patches so that
pools (with / without overlapping) could be
processed in a parallelizable manner.
The output matrix is also a vectorized 3D-tensor of type zxy.
*/
void* MaxpoolingComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
int32 num_frames = in.NumRows();
int32 num_pools = OutputDim();
int32 pool_size = pool_x_size_ * pool_y_size_ * pool_z_size_;
CuMatrix<BaseFloat> patches(num_frames, num_pools * pool_size, kUndefined);
InputToInputPatches(in, &patches);
out->Set(-1e20); // reset a large negative value
for (int32 q = 0; q < pool_size; q++)
out->Max(patches.ColRange(q * num_pools, num_pools));
return NULL;
}
// Method to compute the input derivative matrix from the input derivatives
// for patches, where each patch corresponds to
// the nodes having the same local coordinatenodes from each pool
void MaxpoolingComponent::InderivPatchesToInderiv(
const CuMatrix<BaseFloat>& in_deriv_patches,
CuMatrixBase<BaseFloat> *in_deriv) const {
int32 num_pools_x = 1 + (input_x_dim_ - pool_x_size_) / pool_x_step_;
int32 num_pools_y = 1 + (input_y_dim_ - pool_y_size_) / pool_y_step_;
int32 num_pools_z = 1 + (input_z_dim_ - pool_z_size_) / pool_z_step_;
std::vector<std::vector<int32> > reverse_column_map(in_deriv->NumCols());
int32 rev_col_map_size = reverse_column_map.size();
for (int32 x = 0, index = 0; x < pool_x_size_; x++) {
for (int32 y = 0; y < pool_y_size_; y++) {
for (int32 z = 0; z < pool_z_size_; z++) {
for (int32 x_pool = 0; x_pool < num_pools_x; x_pool++) {
for (int32 y_pool = 0; y_pool < num_pools_y; y_pool++) {
for (int32 z_pool = 0; z_pool < num_pools_z; z_pool++, index++) {
int32 vector_index = (x_pool * pool_x_step_ + x) * input_y_dim_ * input_z_dim_ +
(y_pool * pool_y_step_ + y) * input_z_dim_ +
(z_pool * pool_z_step_ + z);
KALDI_ASSERT(vector_index < rev_col_map_size);
reverse_column_map[vector_index].push_back(index);
}
}
}
}
}
}
std::vector<std::vector<int32> > rearranged_column_map;
RearrangeIndexes(reverse_column_map, &rearranged_column_map);
for (int32 p = 0; p < rearranged_column_map.size(); p++) {
CuArray<int32> cu_cols(rearranged_column_map[p]);
in_deriv->AddCols(in_deriv_patches, cu_cols);
}
}
/*
3d max pooling backpropagate function
This function backpropagate the error from
out_deriv to in_deriv.
In order to select the node in each pool to
backpropagate the error, it has to compare
the output pool value stored in the out_value
matrix with each of its input pool member node
stroed in the in_value matrix.
*/
void MaxpoolingComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
void *memo,
Component *, // to_update,
CuMatrixBase<BaseFloat> *in_deriv) const {
if (!in_deriv)
return;
int32 num_frames = in_value.NumRows();
int32 num_pools = OutputDim();
int32 pool_size = pool_x_size_ * pool_y_size_ * pool_z_size_;
CuMatrix<BaseFloat> patches(num_frames, num_pools * pool_size, kUndefined);
InputToInputPatches(in_value, &patches);
for (int32 q = 0; q < pool_size; q++) {
// zero-out mask
CuMatrix<BaseFloat> mask;
out_value.EqualElementMask(patches.ColRange(q * num_pools, num_pools), &mask);
mask.MulElements(out_deriv);
patches.ColRange(q * num_pools, num_pools).CopyFromMat(mask);
}
// combine the derivatives from the individual input deriv patches
// to compute input deriv matrix
InderivPatchesToInderiv(patches, in_deriv);
}
void MaxpoolingComponent::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<MaxpoolingComponent>", "<InputXDim>");
ReadBasicType(is, binary, &input_x_dim_);
ExpectToken(is, binary, "<InputYDim>");
ReadBasicType(is, binary, &input_y_dim_);
ExpectToken(is, binary, "<InputZDim>");
ReadBasicType(is, binary, &input_z_dim_);
ExpectToken(is, binary, "<PoolXSize>");
ReadBasicType(is, binary, &pool_x_size_);
ExpectToken(is, binary, "<PoolYSize>");
ReadBasicType(is, binary, &pool_y_size_);
ExpectToken(is, binary, "<PoolZSize>");
ReadBasicType(is, binary, &pool_z_size_);
ExpectToken(is, binary, "<PoolXStep>");
ReadBasicType(is, binary, &pool_x_step_);
ExpectToken(is, binary, "<PoolYStep>");
ReadBasicType(is, binary, &pool_y_step_);
ExpectToken(is, binary, "<PoolZStep>");
ReadBasicType(is, binary, &pool_z_step_);
ExpectToken(is, binary, "</MaxpoolingComponent>");
Check();
}
void MaxpoolingComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<MaxpoolingComponent>");
WriteToken(os, binary, "<InputXDim>");
WriteBasicType(os, binary, input_x_dim_);
WriteToken(os, binary, "<InputYDim>");
WriteBasicType(os, binary, input_y_dim_);
WriteToken(os, binary, "<InputZDim>");
WriteBasicType(os, binary, input_z_dim_);
WriteToken(os, binary, "<PoolXSize>");
WriteBasicType(os, binary, pool_x_size_);
WriteToken(os, binary, "<PoolYSize>");
WriteBasicType(os, binary, pool_y_size_);
WriteToken(os, binary, "<PoolZSize>");
WriteBasicType(os, binary, pool_z_size_);
WriteToken(os, binary, "<PoolXStep>");
WriteBasicType(os, binary, pool_x_step_);
WriteToken(os, binary, "<PoolYStep>");
WriteBasicType(os, binary, pool_y_step_);
WriteToken(os, binary, "<PoolZStep>");
WriteBasicType(os, binary, pool_z_step_);
WriteToken(os, binary, "</MaxpoolingComponent>");
}
// display information about component
std::string MaxpoolingComponent::Info() const {
std::ostringstream stream;
stream << Type()
<< ", input-x-dim=" << input_x_dim_
<< ", input-y-dim=" << input_y_dim_
<< ", input-z-dim=" << input_z_dim_
<< ", pool-x-size=" << pool_x_size_
<< ", pool-y-size=" << pool_y_size_
<< ", pool-z-size=" << pool_z_size_
<< ", pool-x-step=" << pool_x_step_
<< ", pool-y-step=" << pool_y_step_
<< ", pool-z-step=" << pool_z_step_;
return stream.str();
}
int32 LstmNonlinearityComponent::InputDim() const {
int32 cell_dim = value_sum_.NumCols();
return cell_dim * 5 + (use_dropout_ ? 3 : 0);
}
int32 LstmNonlinearityComponent::OutputDim() const {
int32 cell_dim = value_sum_.NumCols();
return cell_dim * 2;
}
void LstmNonlinearityComponent::Read(std::istream &is, bool binary) {
ReadUpdatableCommon(is, binary); // Read opening tag and learning rate.
ExpectToken(is, binary, "<Params>");
params_.Read(is, binary);
ExpectToken(is, binary, "<ValueAvg>");
value_sum_.Read(is, binary);
ExpectToken(is, binary, "<DerivAvg>");
deriv_sum_.Read(is, binary);
ExpectToken(is, binary, "<SelfRepairConfig>");
self_repair_config_.Read(is, binary);
ExpectToken(is, binary, "<SelfRepairProb>");
self_repair_total_.Read(is, binary);
std::string tok;
ReadToken(is, binary, &tok);
if (tok == "<UseDropout>") {
ReadBasicType(is, binary, &use_dropout_);
ReadToken(is, binary, &tok);
} else {
use_dropout_ = false;
}
KALDI_ASSERT(tok == "<Count>");
ReadBasicType(is, binary, &count_);