-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvolution.cc
More file actions
1671 lines (1513 loc) · 69.6 KB
/
convolution.cc
File metadata and controls
1671 lines (1513 loc) · 69.6 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/convolution.cc
// Copyright 2017 Johns Hopkins University (author: Daniel Povey)
// 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 <iomanip>
#include "nnet3/convolution.h"
#include "nnet3/nnet-parse.h"
#include "nnet3/nnet-compile-utils.h"
namespace kaldi {
namespace nnet3 {
namespace time_height_convolution {
/**
This function, used in ConvolutionComputation::ComputeDerived(),
reverses a mapping that may not be unique. 'columns' is a column
mapping where each member is either -1 (meaning, copy a zero), or
a number between 0 and input_dim - 1.
Its output, 'backward_columns', is the reverse mapping, but it's a vector of
vectors instead of just a vector because the mapping may have been
many-to-one. Each element of 'backward_columns' will be of dimension
input_dim. For each columns[i] = j such that j != -1,
for some k we will have (*backward_columns)[k][j] = i.
*/
static void ReverseColumnMapping(
const std::vector<int32> &columns,
int32 input_dim,
std::vector<std::vector<int32> > *backward_columns) {
int32 columns_dim = columns.size();
std::vector<std::vector<int32> > temp(input_dim);
for (int32 i = 0; i < columns_dim; i++) {
int32 j = columns[i];
KALDI_ASSERT(j >= -1 && j < input_dim);
if (j != -1)
temp[j].push_back(i);
}
// 'max_overlap' is the largest number of times that some j >= 0 appears in
// 'columns'.
int32 max_overlap = 0;
for (int32 j = 0; j < input_dim; j++)
max_overlap = std::max(max_overlap,
static_cast<int32>(temp[j].size()));
backward_columns->resize(max_overlap);
for (int32 k = 0; k < max_overlap; k++) {
(*backward_columns)[k].clear();
(*backward_columns)[k].resize(input_dim, -1);
}
for (int32 j = 0; j < input_dim; j++) {
for (int32 k = 0; k < static_cast<int32>(temp[j].size()); k++) {
int32 i = temp[j][k];
(*backward_columns)[k][j] = i;
}
}
}
// returns true if 'vec' is of the form
// [ n, n+1, n+2, .... ].
static bool VectorIsContiguous(const std::vector<int32> &vec) {
KALDI_ASSERT(!vec.empty());
int32 s = vec.size();
for (int32 i = 0; i + 1 < s; i++)
if (vec[i+1] != vec[i] + 1)
return false;
return true;
}
std::string ConvolutionModel::Info() const {
std::ostringstream os;
os << "num-filters-in=" << num_filters_in
<< ", num-filters-out=" << num_filters_out
<< ", height-in=" << height_in
<< ", height-out=" << height_out
<< ", height-subsample-out=" << height_subsample_out
<< ", {time,height}-offsets=[";
for (size_t i = 0; i < offsets.size(); i++) {
if (i > 0) os << ' ';
os << offsets[i].time_offset << ',' << offsets[i].height_offset;
}
os << "], required-time-offsets=[";
for (std::set<int32>::const_iterator iter = required_time_offsets.begin();
iter != required_time_offsets.end(); ++iter) {
if (iter != required_time_offsets.begin()) os << ',';
os << *iter;
}
os << "], input-dim=" << InputDim() << ", output-dim=" << OutputDim();
return os.str();
}
void ConvolutionModel::ComputeDerived() {
{ // compute all_time_offsets
all_time_offsets.clear();
for (std::vector<Offset>::const_iterator iter = offsets.begin();
iter != offsets.end(); ++iter)
all_time_offsets.insert(iter->time_offset);
}
{ // compute time_offsets_modulus
time_offsets_modulus = 0;
std::set<int32>::iterator iter = all_time_offsets.begin();
int32 cur_offset = *iter;
for (++iter; iter != all_time_offsets.end(); ++iter) {
int32 this_offset = *iter;
time_offsets_modulus = Gcd(time_offsets_modulus,
this_offset - cur_offset);
cur_offset = this_offset;
}
}
}
bool ConvolutionModel::Check(bool check_heights_used,
bool allow_height_padding) const {
if (num_filters_in <= 0 || num_filters_out <= 0 ||
height_in <= 0 || height_out <= 0 ||
height_subsample_out <= 0 || offsets.empty() ||
required_time_offsets.empty()) {
KALDI_WARN << "Convolution model fails basic check.";
return false;
}
ConvolutionModel temp(*this);
temp.ComputeDerived();
if (!(temp == *this)) {
KALDI_WARN << "Derived variables are incorrect.";
return false;
}
// check that required_time_offsets is included in all_time_offsets.
for (std::set<int32>::iterator iter = required_time_offsets.begin();
iter != required_time_offsets.end(); ++iter) {
if (all_time_offsets.count(*iter) == 0) {
KALDI_WARN << "Required time offsets not a subset of all_time_offsets.";
return false;
}
}
KALDI_ASSERT(IsSortedAndUniq(offsets));
std::vector<bool> h_in_used(height_in, false);
std::vector<bool> offsets_used(offsets.size(), false);
// check that in cases where we only have the minimum
// required input (from required_time_offsets), each
// height in the output is potentially nonzero.
for (int32 h_out = 0; h_out < height_out * height_subsample_out;
h_out += height_subsample_out) {
bool some_input_available = false;
for (size_t i = 0; i < offsets.size(); i++) {
const Offset &offset = offsets[i];
int32 h_in = h_out + offset.height_offset;
if (h_in >= 0 && h_in < height_in) {
offsets_used[i] = true;
h_in_used[h_in] = true;
if (required_time_offsets.count(offset.time_offset) != 0)
some_input_available = true;
} else {
if (!allow_height_padding) {
KALDI_WARN << "height padding not allowed but is required.";
return false;
}
}
}
if (!some_input_available) {
// none of the
// input pixels for this output pixel were available (at least in the case
// where we only have the 'required' inputs on the time dimension).
std::ostringstream os;
Write(os, false);
KALDI_WARN << "for the " << (h_out / height_out) << "'th output height, "
"no input is available, if only required time-indexes "
"are available.";
// We could later change this part of the validation code to accept
// such models, if there is a legitimate use-case.
return false;
}
}
if (check_heights_used) {
for (int32 h = 0; h < height_in; h++) {
if (!h_in_used[h]) {
KALDI_WARN << "The input at the " << h << "'th height is never used.";
return false;
}
}
}
for (size_t i = 0; i < offsets_used.size(); i++) {
if (!offsets_used[i]) {
KALDI_WARN << "(time,height) offset (" << offsets[i].time_offset
<< "," << offsets[i].height_offset
<< ") of this computation is never used.";
return false;
}
}
return true;
}
bool ConvolutionModel::operator == (const ConvolutionModel &other) const {
return num_filters_in == other.num_filters_in &&
num_filters_out == other.num_filters_out &&
height_in == other.height_in &&
height_out == other.height_out &&
height_subsample_out == other.height_subsample_out &&
offsets == other.offsets &&
required_time_offsets == other.required_time_offsets &&
all_time_offsets == other.all_time_offsets &&
time_offsets_modulus == other.time_offsets_modulus;
}
void ConvolutionModel::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<ConvolutionModel>");
WriteToken(os, binary, "<NumFiltersIn>");
WriteBasicType(os, binary, num_filters_in);
WriteToken(os, binary, "<NumFiltersOut>");
WriteBasicType(os, binary, num_filters_out);
WriteToken(os, binary, "<HeightIn>");
WriteBasicType(os, binary, height_in);
WriteToken(os, binary, "<HeightOut>");
WriteBasicType(os, binary, height_out);
WriteToken(os, binary, "<HeightSubsampleOut>");
WriteBasicType(os, binary, height_subsample_out);
WriteToken(os, binary, "<Offsets>");
std::vector<std::pair<int32, int32> > pairs(offsets.size());
for (size_t i = 0; i < offsets.size(); i++) {
pairs[i].first = offsets[i].time_offset;
pairs[i].second = offsets[i].height_offset;
}
WriteIntegerPairVector(os, binary, pairs);
std::vector<int32> required_time_offsets_list(required_time_offsets.begin(),
required_time_offsets.end());
WriteToken(os, binary, "<RequiredTimeOffsets>");
WriteIntegerVector(os, binary, required_time_offsets_list);
WriteToken(os, binary, "</ConvolutionModel>");
}
void ConvolutionModel::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<ConvolutionModel>", "<NumFiltersIn>");
ReadBasicType(is, binary, &num_filters_in);
ExpectToken(is, binary, "<NumFiltersOut>");
ReadBasicType(is, binary, &num_filters_out);
ExpectToken(is, binary, "<HeightIn>");
ReadBasicType(is, binary, &height_in);
ExpectToken(is, binary, "<HeightOut>");
ReadBasicType(is, binary, &height_out);
ExpectToken(is, binary, "<HeightSubsampleOut>");
ReadBasicType(is, binary, &height_subsample_out);
ExpectToken(is, binary, "<Offsets>");
std::vector<std::pair<int32, int32> > pairs;
ReadIntegerPairVector(is, binary, &pairs);
offsets.resize(pairs.size());
for (size_t i = 0; i < offsets.size(); i++) {
offsets[i].time_offset = pairs[i].first;
offsets[i].height_offset = pairs[i].second;
}
std::vector<int32> required_time_offsets_list;
ExpectToken(is, binary, "<RequiredTimeOffsets>");
ReadIntegerVector(is, binary, &required_time_offsets_list);
required_time_offsets.clear();
required_time_offsets.insert(required_time_offsets_list.begin(),
required_time_offsets_list.end());
ExpectToken(is, binary, "</ConvolutionModel>");
ComputeDerived();
KALDI_ASSERT(Check(false, true));
}
void ConvolutionComputation::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<ConvComputation>");
WriteToken(os, binary, "<NumFiltersInOut>");
WriteBasicType(os, binary, num_filters_in);
WriteBasicType(os, binary, num_filters_out);
WriteToken(os, binary, "<HeightInOut>");
WriteBasicType(os, binary, height_in);
WriteBasicType(os, binary, height_out);
WriteToken(os, binary, "<NumTInOut>");
WriteBasicType(os, binary, num_t_in);
WriteBasicType(os, binary, num_t_out);
WriteToken(os, binary, "<NumImages>");
WriteBasicType(os, binary, num_images);
WriteToken(os, binary, "<TempRowsCols>");
WriteBasicType(os, binary, temp_rows);
WriteBasicType(os, binary, temp_cols);
int32 num_steps = steps.size();
WriteToken(os, binary, "<NumSteps>");
WriteBasicType(os, binary, num_steps);
for (int32 s = 0; s < num_steps; s++) {
const ConvolutionStep &step = steps[s];
WriteToken(os, binary, "<TimeShift>");
WriteBasicType(os, binary, step.input_time_shift);
WriteToken(os, binary, "<ParamsStartCol>");
WriteBasicType(os, binary, step.params_start_col);
WriteToken(os, binary, "<HeightMap>");
WriteIntegerVector(os, binary, step.height_map);
}
WriteToken(os, binary, "</ConvComputation>");
}
void ConvolutionComputation::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<ConvComputation>", "<NumFiltersInOut>");
ReadBasicType(is, binary, &num_filters_in);
ReadBasicType(is, binary, &num_filters_out);
ExpectToken(is, binary, "<HeightInOut>");
ReadBasicType(is, binary, &height_in);
ReadBasicType(is, binary, &height_out);
ExpectToken(is, binary, "<NumTInOut>");
ReadBasicType(is, binary, &num_t_in);
ReadBasicType(is, binary, &num_t_out);
ExpectToken(is, binary, "<NumImages>");
ReadBasicType(is, binary, &num_images);
ExpectToken(is, binary, "<TempRowsCols>");
ReadBasicType(is, binary, &temp_rows);
ReadBasicType(is, binary, &temp_cols);
int32 num_steps;
ExpectToken(is, binary, "<NumSteps>");
ReadBasicType(is, binary, &num_steps);
steps.resize(num_steps);
for (int32 s = 0; s < num_steps; s++) {
ConvolutionStep &step = steps[s];
ExpectToken(is, binary, "<TimeShift>");
ReadBasicType(is, binary, &step.input_time_shift);
ExpectToken(is, binary, "<ParamsStartCol>");
ReadBasicType(is, binary, &step.params_start_col);
ExpectToken(is, binary, "<HeightMap>");
ReadIntegerVector(is, binary, &step.height_map);
}
ExpectToken(is, binary, "</ConvComputation>");
ComputeDerived();
Check();
}
void ConvolutionComputation::Check() const {
KALDI_ASSERT(num_filters_in > 0 && num_filters_out > 0 &&
height_in > 0 && height_out > 0);
KALDI_ASSERT(num_t_in >= num_t_out &&
num_t_out > 0 && num_images > 0);
KALDI_ASSERT((temp_rows == 0 && temp_cols == 0) ||
(temp_rows <= num_t_out * num_images &&
temp_cols > 0));
KALDI_ASSERT(temp_rows % num_images == 0);
bool temp_mat_required = false;
int32 num_steps = steps.size();
int32 num_extra_input_times = num_t_in - num_t_out,
input_cols = num_filters_in * height_in,
smallest_time_shift = 1000,
largest_time_shift = 0;
// check 'steps'
for (int32 s = 0; s < num_steps; s++) {
const ConvolutionStep &step = steps[s];
KALDI_ASSERT(step.input_time_shift >= 0 &&
step.input_time_shift <= num_extra_input_times);
if (step.input_time_shift < smallest_time_shift)
smallest_time_shift = step.input_time_shift;
if (step.input_time_shift > largest_time_shift)
largest_time_shift = step.input_time_shift;
KALDI_ASSERT(step.params_start_col >= 0 &&
step.params_start_col % num_filters_in == 0);
if (s != 0) {
KALDI_ASSERT(step.input_time_shift != steps[s-1].input_time_shift);
}
std::vector<int32> columns;
step.columns.CopyToVec(&columns);
KALDI_ASSERT(step.first_column == columns[0]);
KALDI_ASSERT(step.columns.Dim() == step.height_map.size() * num_filters_in);
bool all_negative = true;
int32 temp_height = step.height_map.size();
bool contiguous = true;
for (int32 i = 0; i < temp_height; i++) {
int32 h = step.height_map[i];
KALDI_ASSERT(h >= -1 && h < height_in);
if (i > 0 && step.height_map[i-1] != h-1)
contiguous = false;
if (h == -1) {
contiguous = false;
for (int32 f = 0; f < num_filters_in; f++) {
KALDI_ASSERT(columns[i * num_filters_in + f] == -1);
}
} else {
all_negative = false;
for (int32 f = 0; f < num_filters_in; f++) {
KALDI_ASSERT(columns[i * num_filters_in + f] ==
h * num_filters_in + f);
}
}
}
KALDI_ASSERT(contiguous == step.columns_are_contiguous);
if (!contiguous || columns.size() != input_cols) {
// we would need the temporary matrix. Make sure the
// temporary matrix is big enough.
temp_mat_required = true;
KALDI_ASSERT(columns.size() <= temp_cols);
}
KALDI_ASSERT(!all_negative);
std::vector<int32> columns_reconstructed(columns.size(), -1);
// reconstruct 'columns' from backward_columns as a way to
// check that backward_columns is correct.
// they are reverse-direction maps, but we may need
// step.backward_columns.size() > 1 because of elements
// in the input that are duplicated in the temp matrix.
for (size_t k = 0; k < step.backward_columns.size(); k++) {
std::vector<int32> backward_columns;
step.backward_columns[k].CopyToVec(&backward_columns);
KALDI_ASSERT(int32(backward_columns.size()) ==
num_filters_in * height_in);
for (int32 l = 0; l < num_filters_in * height_in; l++) {
int32 c = backward_columns[l];
KALDI_ASSERT(c < int32(columns.size()));
if (c != -1) {
KALDI_ASSERT(columns_reconstructed[c] == -1);
columns_reconstructed[c] = l;
}
}
}
KALDI_ASSERT(columns_reconstructed == columns);
}
// check that all rows of the input were used.
KALDI_ASSERT(smallest_time_shift == 0 &&
largest_time_shift == num_extra_input_times);
// check that the temp matrix is only allocated if it is required.
KALDI_ASSERT((temp_cols != 0) == temp_mat_required);
}
// Internal function called inside ConvolveForward.
// Note: the number of time steps covered may be different
// from that implied by cc.num_t_in and cc.num_t_out
// if the matrices are very large and we've broken the
// computation up into pieces to save memoiry.
static void ConvolveForwardInternal(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> &input,
const CuMatrixBase<BaseFloat> ¶ms,
CuMatrixBase<BaseFloat> *temp_mat,
CuMatrixBase<BaseFloat> *output) {
KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols());
// num_t_out supersedes cc.num_t_out (they'll only be different in
// cases where we are doing the computation in pieces to save memory).
int32 input_rows = input.NumRows(),
output_rows = output->NumRows();
KALDI_ASSERT(output_rows <= input_rows &&
input_rows % cc.num_images == 0 &&
output_rows % cc.num_images == 0);
int32 num_steps = cc.steps.size();
for (int32 s = 0; s < num_steps; s++) {
const ConvolutionComputation::ConvolutionStep &step = cc.steps[s];
int32 input_row_start = step.input_time_shift * cc.num_images;
// note: 'input_part' will normally be almost all of 'input', perhaps
// minus one or two time steps at the start or end.
CuSubMatrix<BaseFloat> input_part(input,
input_row_start, output_rows,
0, input.NumCols());
int32 temp_num_cols = step.columns.Dim(),
param_cols = temp_num_cols / cc.height_out;
CuSubMatrix<BaseFloat> params_part(params,
0, params.NumRows(),
step.params_start_col,
param_cols);
CuSubMatrix<BaseFloat> output_reshaped(
output->Data(), output_rows * cc.height_out,
cc.num_filters_out, cc.num_filters_out);
if (!step.columns_are_contiguous ||
temp_num_cols != input.NumCols()) {
// In most cases we will take this branch, where we have to copy the input
// to a temporary matrix. (however, different steps may require different
// num-cols of the temporary matrix, so we create sub-parts of 'temp_mat'.
// We create the sub-matrix 'temp_mat_part' in a lower-level way, using
// pointers, because we need to ensure that its num-cols and the stride
// are the same (this is necessary so that we can do reshaping in
// ConvolutionReshapedMultiply()).
CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(),
temp_mat->NumRows(),
temp_num_cols, temp_num_cols);
if (!step.columns_are_contiguous) {
// we're doing a column mapping.
temp_mat_part.CopyCols(input_part, step.columns);
} else {
// we're just taking a sub-matrix of the input matrix, but we still need
// to make a copy because we need the stride == num-cols (so that the
// reshaping will work).
temp_mat_part.CopyFromMat(input_part.ColRange(step.first_column,
step.columns.Dim()));
}
CuSubMatrix<BaseFloat> temp_mat_part_reshaped(
temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out,
temp_num_cols / cc.height_out, temp_num_cols / cc.height_out);
output_reshaped.AddMatMat(1.0, temp_mat_part_reshaped, kNoTrans,
params_part, kTrans, 1.0);
} else {
CuSubMatrix<BaseFloat> input_reshaped(
input_part.Data(), input_part.NumRows() * cc.height_out,
input_part.NumCols() / cc.height_out,
input_part.NumCols() / cc.height_out);
output_reshaped.AddMatMat(1.0, input_reshaped, kNoTrans,
params_part, kTrans, 1.0);
}
}
}
void ConvolveForward(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> &input,
const CuMatrixBase<BaseFloat> ¶ms,
CuMatrixBase<BaseFloat> *output) {
KALDI_ASSERT(input.NumCols() == input.Stride() &&
output->NumCols() == output->Stride());
KALDI_ASSERT(params.NumRows() == cc.num_filters_out);
KALDI_ASSERT(output->NumRows() == cc.num_t_out * cc.num_images &&
output->NumCols() == cc.height_out * cc.num_filters_out);
// the input might need to be reshaped but we can check its total size.
KALDI_ASSERT(input.NumRows() * input.NumCols() == cc.num_images *
cc.num_t_in * cc.height_in * cc.num_filters_in);
int32 input_rows = input.NumRows(),
required_input_rows = cc.num_images * cc.num_t_in;
// this if-statement handles reshaping the input and recursing if there
// is subsampling.
if (input_rows != required_input_rows) {
if (input_rows % required_input_rows != 0)
KALDI_ERR << "Input matrix has wrong size."; // error in calling code.
// nr is a multiple of required_nr. Reshape the matrix.
// we already checked that its Stride() == NumCols();
int32 num_cols = input.NumCols(),
multiple = input_rows / required_input_rows,
new_num_cols = num_cols * multiple,
new_stride = new_num_cols;
CuSubMatrix<BaseFloat> input_reshaped(
input.Data(), required_input_rows, new_num_cols, new_stride);
ConvolveForward(cc, input_reshaped, params, output);
return;
}
CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols,
kUndefined, kStrideEqualNumCols);
// this if-statement handles breaking up the arguments
// and the computation into row-ranges if the temporary
// matrix would have been excessively large, and we've decided
// to give it fewer rows than the output (this saves
// memory). normally we won't take this if-statement
// so ignore it if you're trying to understand the framework.
if (cc.temp_rows != 0 && cc.temp_rows != input_rows) {
KALDI_ASSERT(cc.temp_rows % cc.num_images == 0);
int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images;
int32 num_extra_in = cc.num_t_in - cc.num_t_out;
for (int32 t_start = 0; t_start < cc.num_t_out;
t_start += num_time_steps_per_chunk) {
int32 num_t_left = cc.num_t_out - t_start,
this_num_t_out = std::min<int32>(num_t_left,
num_time_steps_per_chunk),
this_num_t_in = this_num_t_out + num_extra_in;
CuSubMatrix<BaseFloat> input_part(input, t_start * cc.num_images,
this_num_t_in * cc.num_images,
0, input.NumCols());
CuSubMatrix<BaseFloat> output_part(*output, t_start * cc.num_images,
this_num_t_out * cc.num_images,
0, output->NumCols());
CuSubMatrix<BaseFloat> temp_part(temp_mat, 0,
this_num_t_out * cc.num_images,
0, temp_mat.NumCols());
ConvolveForwardInternal(cc, input_part, params,
&temp_part, &output_part);
}
return;
}
ConvolveForwardInternal(cc, input, params, &temp_mat, output);
}
// Internal function called inside ConvolveBackwardData.
// Note: the number of time steps covered may be different
// from that implied by cc.num_t_in and cc.num_t_out
// if the matrices are very large and we've broken the
// computation up into pieces to save memory.
// We require that temp_mat should not contain inf's
// or nan's on entry.
static void ConvolveBackwardDataInternal(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> ¶ms,
const CuMatrixBase<BaseFloat> &output_deriv,
CuMatrixBase<BaseFloat> *temp_mat,
CuMatrixBase<BaseFloat> *input_deriv) {
KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols());
// num_t_out supersedes cc.num_t_out (they'll only be different in
// cases where we are doing the computation in pieces to save memory).
int32 input_rows = input_deriv->NumRows(),
output_rows = output_deriv.NumRows();
KALDI_ASSERT(output_rows <= input_rows &&
input_rows % cc.num_images == 0 &&
output_rows % cc.num_images == 0);
int32 num_steps = cc.steps.size();
for (int32 s = 0; s < num_steps; s++) {
const ConvolutionComputation::ConvolutionStep &step = cc.steps[s];
int32 input_row_start = step.input_time_shift * cc.num_images;
CuSubMatrix<BaseFloat> input_deriv_part(*input_deriv,
input_row_start, output_rows,
0, input_deriv->NumCols());
int32 temp_num_cols = step.columns.Dim(),
param_cols = temp_num_cols / cc.height_out;
CuSubMatrix<BaseFloat> params_part(params,
0, params.NumRows(),
step.params_start_col,
param_cols);
CuSubMatrix<BaseFloat> output_deriv_reshaped(
output_deriv.Data(), output_rows * cc.height_out,
cc.num_filters_out, cc.num_filters_out);
if (!step.columns_are_contiguous ||
temp_num_cols != input_deriv->NumCols()) {
// In most cases we will take this branch, where we have to propagate the
// input-derivative via a temporary matrix. (however, different steps may
// require different num-cols of the temporary matrix, so we create
// sub-parts of 'temp_mat'.
// We create the sub-matrix 'temp_mat_part' in a lower-level way, using
// pointers, because we need to ensure that its num-cols and the stride
// are the same (this is necessary so that we can do reshaping in
// ConvolutionReshapedMultiply()).
CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(),
temp_mat->NumRows(),
temp_num_cols, temp_num_cols),
temp_mat_part_reshaped(
temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out,
temp_num_cols / cc.height_out, temp_num_cols / cc.height_out);
temp_mat_part_reshaped.AddMatMat(1.0, output_deriv_reshaped, kNoTrans,
params_part, kNoTrans, 0.0);
if (!step.columns_are_contiguous) {
for (size_t i = 0; i < step.backward_columns.size(); i++) {
input_deriv_part.AddCols(temp_mat_part, step.backward_columns[i]);
}
} else {
// we're just taking a sub-matrix of the input matrix, but we still need
// to make a copy because we need the stride == num-cols (so that the
// reshaping will work).
int32 num_cols = step.columns.Dim();
input_deriv_part.ColRange(step.first_column,
num_cols).AddMat(1.0, temp_mat_part);
}
} else {
CuSubMatrix<BaseFloat> input_deriv_reshaped(
input_deriv_part.Data(), input_deriv_part.NumRows() * cc.height_out,
input_deriv_part.NumCols() / cc.height_out,
input_deriv_part.NumCols() / cc.height_out);
input_deriv_reshaped.AddMatMat(1.0, output_deriv_reshaped, kNoTrans,
params_part, kNoTrans, 1.0);
}
}
}
void ConvolveBackwardData(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> ¶ms,
const CuMatrixBase<BaseFloat> &output_deriv,
CuMatrixBase<BaseFloat> *input_deriv) {
KALDI_ASSERT(input_deriv->NumCols() == input_deriv->Stride() &&
output_deriv.NumCols() == output_deriv.Stride());
KALDI_ASSERT(params.NumRows() == cc.num_filters_out);
KALDI_ASSERT(output_deriv.NumRows() == cc.num_t_out * cc.num_images &&
output_deriv.NumCols() == cc.height_out * cc.num_filters_out);
// the input might need to be reshaped but we can check its total size.
KALDI_ASSERT(input_deriv->NumRows() * input_deriv->NumCols() ==
cc.num_images * cc.num_t_in * cc.height_in * cc.num_filters_in);
int32 input_rows = input_deriv->NumRows(),
required_input_rows = cc.num_images * cc.num_t_in;
// this if-statement handles reshaping the input and recursing if there
// is subsampling.
if (input_rows != required_input_rows) {
if (input_rows % required_input_rows != 0)
KALDI_ERR << "Input matrix has wrong size."; // error in calling code.
// nr is a multiple of required_nr. Reshape the matrix.
// we already checked that its Stride() == NumCols();
int32 num_cols = input_deriv->NumCols(),
multiple = input_rows / required_input_rows,
new_num_cols = num_cols * multiple,
new_stride = new_num_cols;
CuSubMatrix<BaseFloat> input_deriv_reshaped(
input_deriv->Data(), required_input_rows,
new_num_cols, new_stride);
ConvolveBackwardData(cc, params, output_deriv, &input_deriv_reshaped);
return;
}
CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols,
kSetZero, kStrideEqualNumCols);
// this if-statement handles breaking up the arguments
// and the computation into row-ranges if the temporary
// matrix would have been excessively large, and we've decided
// to give it fewer rows than the output (this saves
// memory). normally we won't take this if-statement
// so ignore it if you're trying to understand the framework.
if (cc.temp_rows != 0 && cc.temp_rows != input_rows) {
KALDI_ASSERT(cc.temp_rows % cc.num_images == 0);
int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images;
int32 num_extra_in = cc.num_t_in - cc.num_t_out;
for (int32 t_start = 0; t_start < cc.num_t_out;
t_start += num_time_steps_per_chunk) {
int32 num_t_left = cc.num_t_out - t_start,
this_num_t_out = std::min<int32>(num_t_left,
num_time_steps_per_chunk),
this_num_t_in = this_num_t_out + num_extra_in;
CuSubMatrix<BaseFloat> input_deriv_part(
*input_deriv, t_start * cc.num_images,
this_num_t_in * cc.num_images,
0, input_deriv->NumCols());
CuSubMatrix<BaseFloat> output_deriv_part(
output_deriv, t_start * cc.num_images,
this_num_t_out * cc.num_images,
0, output_deriv.NumCols());
CuSubMatrix<BaseFloat> temp_part(
temp_mat, 0, this_num_t_out * cc.num_images,
0, temp_mat.NumCols());
ConvolveBackwardDataInternal(cc, params, output_deriv_part,
&temp_part, &input_deriv_part);
}
return;
}
ConvolveBackwardDataInternal(cc, params, output_deriv,
&temp_mat, input_deriv);
}
// Internal function called inside ConvolveBackwardParams.
// Note: the number of time steps covered may be different
// from that implied by cc.num_t_in and cc.num_t_out
// if the matrices are very large and we've broken the
// computation up into pieces to save memoiry.
static void ConvolveBackwardParamsInternal(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> &input,
const CuMatrixBase<BaseFloat> &output_deriv,
BaseFloat alpha,
CuMatrixBase<BaseFloat> *temp_mat,
CuMatrixBase<BaseFloat> *params_deriv) {
KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols());
// num_t_out supersedes cc.num_t_out (they'll only be different in
// cases where we are doing the computation in pieces to save memory).
int32 input_rows = input.NumRows(),
output_rows = output_deriv.NumRows();
KALDI_ASSERT(output_rows <= input_rows &&
input_rows % cc.num_images == 0 &&
output_rows % cc.num_images == 0);
int32 num_steps = cc.steps.size();
for (int32 s = 0; s < num_steps; s++) {
const ConvolutionComputation::ConvolutionStep &step = cc.steps[s];
int32 input_row_start = step.input_time_shift * cc.num_images;
// note: 'input_part' will normally be almost all of 'input', perhaps
// minus one or two time steps at the start or end.
CuSubMatrix<BaseFloat> input_part(input,
input_row_start, output_rows,
0, input.NumCols());
int32 temp_num_cols = step.columns.Dim(),
param_cols = temp_num_cols / cc.height_out;
CuSubMatrix<BaseFloat> params_deriv_part(*params_deriv,
0, params_deriv->NumRows(),
step.params_start_col,
param_cols);
CuSubMatrix<BaseFloat> output_deriv_reshaped(
output_deriv.Data(), output_rows * cc.height_out,
cc.num_filters_out, cc.num_filters_out);
if (!step.columns_are_contiguous ||
temp_num_cols != input.NumCols()) {
// In most cases we will take this branch, where we have to copy the input
// to a temporary matrix. (however, different steps may require different
// num-cols of the temporary matrix, so we create sub-parts of 'temp_mat'.
// We create the sub-matrix 'temp_mat_part' in a lower-level way, using
// pointers, because we need to ensure that its num-cols and the stride
// are the same (this is necessary so that we can do reshaping in
// ConvolutionReshapedMultiply()).
CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(),
temp_mat->NumRows(),
temp_num_cols, temp_num_cols);
if (!step.columns_are_contiguous) {
// we're doing a column mapping.
temp_mat_part.CopyCols(input_part, step.columns);
} else {
// we're just taking a sub-matrix of the input matrix, but we still need
// to make a copy because we need the stride == num-cols (so that the
// reshaping will work).
temp_mat_part.CopyFromMat(input_part.ColRange(step.first_column,
step.columns.Dim()));
}
CuSubMatrix<BaseFloat> temp_mat_part_reshaped(
temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out,
temp_num_cols / cc.height_out, temp_num_cols / cc.height_out);
params_deriv_part.AddMatMat(alpha, output_deriv_reshaped, kTrans,
temp_mat_part_reshaped, kNoTrans, 1.0);
} else {
CuSubMatrix<BaseFloat> input_reshaped(
input_part.Data(), input_part.NumRows() * cc.height_out,
input_part.NumCols() / cc.height_out,
input_part.NumCols() / cc.height_out);
params_deriv_part.AddMatMat(alpha, output_deriv_reshaped, kTrans,
input_reshaped, kNoTrans, 1.0);
}
}
}
void ConvolveBackwardParams(
const ConvolutionComputation &cc,
const CuMatrixBase<BaseFloat> &input,
const CuMatrixBase<BaseFloat> &output_deriv,
BaseFloat alpha,
CuMatrixBase<BaseFloat> *params_deriv) {
KALDI_ASSERT(input.NumCols() == input.Stride() &&
output_deriv.NumCols() == output_deriv.Stride());
KALDI_ASSERT(params_deriv->NumRows() == cc.num_filters_out);
KALDI_ASSERT(output_deriv.NumRows() == cc.num_t_out * cc.num_images &&
output_deriv.NumCols() == cc.height_out * cc.num_filters_out);
// the input might need to be reshaped but we can check its total size.
KALDI_ASSERT(input.NumRows() * input.NumCols() == cc.num_images *
cc.num_t_in * cc.height_in * cc.num_filters_in);
int32 input_rows = input.NumRows(),
required_input_rows = cc.num_images * cc.num_t_in;
// this if-statement handles reshaping the input and recursing if there
// is subsampling.
if (input_rows != required_input_rows) {
if (input_rows % required_input_rows != 0)
KALDI_ERR << "Input matrix has wrong size."; // error in calling code.
// nr is a multiple of required_nr. Reshape the matrix.
// we already checked that its Stride() == NumCols();
int32 num_cols = input.NumCols(),
multiple = input_rows / required_input_rows,
new_num_cols = num_cols * multiple,
new_stride = new_num_cols;
CuSubMatrix<BaseFloat> input_reshaped(
input.Data(), required_input_rows, new_num_cols, new_stride);
ConvolveBackwardParams(cc, input_reshaped, output_deriv, alpha,
params_deriv);
return;
}
CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols,
kUndefined, kStrideEqualNumCols);
// this if-statement handles breaking up the arguments
// and the computation into row-ranges if the temporary
// matrix would have been excessively large, and we've decided
// to give it fewer rows than the output (this saves
// memory). normally we won't take this if-statement
// so ignore it if you're trying to understand the framework.
if (cc.temp_rows != 0 && cc.temp_rows != input_rows) {
KALDI_ASSERT(cc.temp_rows % cc.num_images == 0);
int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images;
int32 num_extra_in = cc.num_t_in - cc.num_t_out;
for (int32 t_start = 0; t_start < cc.num_t_out;
t_start += num_time_steps_per_chunk) {
int32 num_t_left = cc.num_t_out - t_start,
this_num_t_out = std::min<int32>(num_t_left,
num_time_steps_per_chunk),
this_num_t_in = this_num_t_out + num_extra_in;
CuSubMatrix<BaseFloat> input_part(
input, t_start * cc.num_images,
this_num_t_in * cc.num_images,
0, input.NumCols());
CuSubMatrix<BaseFloat> output_deriv_part(
output_deriv, t_start * cc.num_images,
this_num_t_out * cc.num_images,
0, output_deriv.NumCols());
CuSubMatrix<BaseFloat> temp_part(temp_mat,
0, this_num_t_out * cc.num_images,
0, temp_mat.NumCols());
ConvolveBackwardParamsInternal(cc, input_part, output_deriv_part,
alpha, &temp_part, params_deriv);
}
return;
}
ConvolveBackwardParamsInternal(cc, input, output_deriv,
alpha, &temp_mat, params_deriv);
}
void PadModelHeight(const ConvolutionModel &model,
ConvolutionModel *model_padded) {
*model_padded = model;
KALDI_ASSERT(!model.offsets.empty());
int32 min_height_offset = model.offsets[0].height_offset,
max_height_offset = model.offsets[0].height_offset,
num_offsets = model.offsets.size();
for (int32 i = 1; i < num_offsets; i++) {
min_height_offset = std::min<int32>(min_height_offset,
model.offsets[i].height_offset);
max_height_offset = std::max<int32>(max_height_offset,
model.offsets[i].height_offset);
}
int32 max_output_height = model.height_subsample_out * (model.height_out - 1),
max_required_input = max_height_offset + max_output_height,
min_required_input = min_height_offset + 0;
int32 bottom_padding = -min_required_input,
top_padding = max_required_input - (model.height_in - 1);
if (bottom_padding < 0)
bottom_padding = 0;
if (top_padding < 0)
top_padding = 0;
model_padded->height_in += bottom_padding + top_padding;
for (int32 i = 0; i < num_offsets; i++)
model_padded->offsets[i].height_offset += bottom_padding;
// The reason why we say 'allow_height_padding = false' below is obvious--
// we've 'manually' padded by changing the model, so this modified model
// should not require height padding. The reason we set 'check_heights_used'
// is a little more non-obvious. The very lowest and hightest heights
// should always be used, but there may, in unusual models, be other heights
// that are not used. We found this in random testing.
KALDI_ASSERT(model_padded->Check(false, false));
}
/** This function sets 'temp_rows' and 'temp_cols' in 'computation'.
*/
static void ComputeTempMatrixSize(const ConvolutionComputationOptions &opts,
ConvolutionComputation *computation) {
int32 temp_rows = 0, temp_cols = 0;
for (size_t i = 0; i < computation->steps.size(); i++) {
const ConvolutionComputation::ConvolutionStep &step = computation->steps[i];
int32 height_map_size = step.height_map.size(),
this_num_cols = height_map_size * computation->num_filters_in;
bool columns_are_contiguous =
(step.height_map[0] != -1 && VectorIsContiguous(step.height_map));
bool need_temp_matrix = true;
if (columns_are_contiguous && step.height_map[0] == 0 &&
this_num_cols == computation->num_filters_in * computation->height_in) {
// the only situation in which we wouldn't need the temporary matrix
// for this step, is where the columns are all of the input matrix.
need_temp_matrix = false;
}
if (need_temp_matrix && this_num_cols > temp_cols)
temp_cols = this_num_cols;
}
if (temp_cols > 0) {
// work out how many rows the temporary matrix should have, taking
// into account the specified memory limit.
temp_rows = computation->num_t_out * computation->num_images;
BaseFloat num_megabytes = (4 * (temp_rows / 1000.0) * (temp_cols / 1000.0)),
megabyte_limit = opts.max_memory_mb;
// C++ rounds down; here, we want to round up so we add one.
int32 ratio = 1.0 + num_megabytes / megabyte_limit;
// divide the number of time steps into 'ratio' pieces that are as equal as
// possible; round up when dividing, to make sure that new_temp_rows * ratio
// >= temp_rows so that we don't have a small leftover piece.
int32 new_num_t_out = (computation->num_t_out + ratio - 1) / ratio;
temp_rows = new_num_t_out * computation->num_images;
BaseFloat new_num_megabytes = (4 * (temp_rows / 1000.0) * (temp_cols / 1000.0));
// make sure we're within the memory limit.
if (new_num_megabytes > 1.01 * megabyte_limit) {
KALDI_WARN << "Memory consumed in convolution is more than requested "
<< "(maybe very long time sequence?)";
}
}
computation->temp_rows = temp_rows;
computation->temp_cols = temp_cols;
}