forked from kaldi-asr/kaldi
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnnet-simple-component.cc
More file actions
5350 lines (4770 loc) · 209 KB
/
nnet-simple-component.cc
File metadata and controls
5350 lines (4770 loc) · 209 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-simple-component.cc
// Copyright 2015 Johns Hopkins University (author: Daniel Povey)
// 2015 Guoguo Chen
// 2015 Daniel Galvez
// 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-simple-component.h"
#include "nnet3/nnet-parse.h"
#include "cudamatrix/cu-math.h"
namespace kaldi {
namespace nnet3 {
void PnormComponent::Init(int32 input_dim, int32 output_dim) {
input_dim_ = input_dim;
output_dim_ = output_dim;
KALDI_ASSERT(input_dim_ > 0 && output_dim_ > 0 &&
input_dim_ % output_dim_ == 0);
}
void PnormComponent::InitFromConfig(ConfigLine *cfl) {
int32 input_dim = 0;
int32 output_dim = 0;
bool ok = cfl->GetValue("output-dim", &output_dim) &&
cfl->GetValue("input-dim", &input_dim);
if (!ok || cfl->HasUnusedValues() || output_dim <= 0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
Init(input_dim, output_dim);
}
void PnormComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
BaseFloat p = 2.0;
out->GroupPnorm(in, p);
}
void PnormComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update,
CuMatrixBase<BaseFloat> *in_deriv) const {
if (!in_deriv)
return;
BaseFloat p = 2.0;
in_deriv->DiffGroupPnorm(in_value, out_value, out_deriv, p);
}
void PnormComponent::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<PnormComponent>", "<InputDim>");
ReadBasicType(is, binary, &input_dim_);
ExpectToken(is, binary, "<OutputDim>");
ReadBasicType(is, binary, &output_dim_);
ExpectToken(is, binary, "</PnormComponent>");
}
void PnormComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<PnormComponent>");
WriteToken(os, binary, "<InputDim>");
WriteBasicType(os, binary, input_dim_);
WriteToken(os, binary, "<OutputDim>");
WriteBasicType(os, binary, output_dim_);
WriteToken(os, binary, "</PnormComponent>");
}
void DropoutComponent::Init(int32 dim, BaseFloat dropout_proportion, bool dropout_per_frame) {
dropout_proportion_ = dropout_proportion;
dropout_per_frame_ = dropout_per_frame;
dim_ = dim;
}
void DropoutComponent::InitFromConfig(ConfigLine *cfl) {
int32 dim = 0;
BaseFloat dropout_proportion = 0.0;
bool dropout_per_frame = false;
bool ok = cfl->GetValue("dim", &dim) &&
cfl->GetValue("dropout-proportion", &dropout_proportion);
bool ok2 = cfl->GetValue("dropout-per-frame", &dropout_per_frame);
if (!ok || cfl->HasUnusedValues() || dim <= 0 ||
dropout_proportion < 0.0 || dropout_proportion > 1.0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
if( ! ok2 )
{
dropout_per_frame = false;
Init(dim, dropout_proportion, dropout_per_frame);
} else {
Init(dim, dropout_proportion, dropout_per_frame);
}
}
std::string DropoutComponent::Info() const {
std::ostringstream stream;
stream << Type() << ", dim=" << dim_
<< ", dropout-proportion=" << dropout_proportion_
<< ", dropout-per-frame=" << dropout_per_frame_;
return stream.str();
}
void DropoutComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
KALDI_ASSERT(out->NumRows() == in.NumRows() && out->NumCols() == in.NumCols()
&& in.NumCols() == dim_);
BaseFloat dropout = dropout_proportion_;
KALDI_ASSERT(dropout >= 0.0 && dropout <= 1.0);
if(dropout_per_frame_)
{
// This const_cast is only safe assuming you don't attempt
// to use multi-threaded code with the GPU.
const_cast<CuRand<BaseFloat>&>(random_generator_).RandUniform(out);
out->Add(-dropout); // now, a proportion "dropout" will be <0.0
out->ApplyHeaviside(); // apply the function (x>0?1:0). Now, a proportion "dropout" will
// be zero and (1 - dropout) will be 1.0.
out->MulElements(in);
} else {
// This const_cast is only safe assuming you don't attempt
// to use multi-threaded code with the GPU.
const_cast<CuRand<BaseFloat>&>(random_generator_).RandUniform(out);
out->Add(-dropout); // now, a proportion "dropout" will be <0.0
out->ApplyHeavisideByRow(); // apply the function (x>0?1:0). Now, a proportion "dropout" will
// be zero and (1 - dropout) will be 1.0 by row.
out->MulElements(in);
}
}
void DropoutComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update,
CuMatrixBase<BaseFloat> *in_deriv) const {
KALDI_ASSERT(in_value.NumRows() == out_value.NumRows() &&
in_value.NumCols() == out_value.NumCols());
KALDI_ASSERT(in_value.NumRows() == out_deriv.NumRows() &&
in_value.NumCols() == out_deriv.NumCols());
in_deriv->SetMatMatDivMat(out_deriv, out_value, in_value);
}
void DropoutComponent::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<DropoutComponent>", "<Dim>");
ReadBasicType(is, binary, &dim_);
ExpectToken(is, binary, "<DropoutProportion>");
ReadBasicType(is, binary, &dropout_proportion_);
ExpectToken(is, binary, "<DropoutPerFrame>");
ReadBasicType(is, binary, &dropout_per_frame_);
ExpectToken(is, binary, "</DropoutComponent>");
}
void DropoutComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<DropoutComponent>");
WriteToken(os, binary, "<Dim>");
WriteBasicType(os, binary, dim_);
WriteToken(os, binary, "<DropoutProportion>");
WriteBasicType(os, binary, dropout_proportion_);
WriteToken(os, binary, "<DropoutPerFrame>");
WriteBasicType(os, binary, dropout_per_frame_);
WriteToken(os, binary, "</DropoutComponent>");
}
void SumReduceComponent::Init(int32 input_dim, int32 output_dim) {
input_dim_ = input_dim;
output_dim_ = output_dim;
KALDI_ASSERT(input_dim_ > 0 && output_dim_ > 0 &&
input_dim_ % output_dim_ == 0);
}
void SumReduceComponent::InitFromConfig(ConfigLine *cfl) {
int32 input_dim = 0;
int32 output_dim = 0;
bool ok = cfl->GetValue("output-dim", &output_dim) &&
cfl->GetValue("input-dim", &input_dim);
if (!ok || cfl->HasUnusedValues() || output_dim <= 0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
Init(input_dim, output_dim);
}
void SumReduceComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
KALDI_ASSERT(out->NumRows() == in.NumRows() && in.NumCols() == input_dim_
&& out->NumCols() == output_dim_);
int32 num_blocks = input_dim_ / output_dim_;
for (int32 i = 0; i < num_blocks; i++) {
CuSubMatrix<BaseFloat> in_block(in, 0, in.NumRows(),
i * output_dim_, output_dim_);
if (i == 0)
out->CopyFromMat(in_block);
else
out->AddMat(1.0, in_block);
}
}
void SumReduceComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &, // in_value
const CuMatrixBase<BaseFloat> &, // out_value
const CuMatrixBase<BaseFloat> &out_deriv,
Component *, // to_update
CuMatrixBase<BaseFloat> *in_deriv) const {
if (!in_deriv) return;
KALDI_ASSERT(out_deriv.NumRows() == in_deriv->NumRows() &&
in_deriv->NumCols() == input_dim_ &&
out_deriv.NumCols() == output_dim_);
int32 num_blocks = input_dim_ / output_dim_;
for (int32 i = 0; i < num_blocks; i++) {
CuSubMatrix<BaseFloat> in_deriv_block(*in_deriv, 0, in_deriv->NumRows(),
i * output_dim_, output_dim_);
in_deriv_block.CopyFromMat(out_deriv);
}
}
void SumReduceComponent::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<SumReduceComponent>", "<InputDim>");
ReadBasicType(is, binary, &input_dim_);
ExpectToken(is, binary, "<OutputDim>");
ReadBasicType(is, binary, &output_dim_);
ExpectToken(is, binary, "</SumReduceComponent>");
}
void SumReduceComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<SumReduceComponent>");
WriteToken(os, binary, "<InputDim>");
WriteBasicType(os, binary, input_dim_);
WriteToken(os, binary, "<OutputDim>");
WriteBasicType(os, binary, output_dim_);
WriteToken(os, binary, "</SumReduceComponent>");
}
void ElementwiseProductComponent::Init(int32 input_dim, int32 output_dim) {
input_dim_ = input_dim;
output_dim_ = output_dim;
KALDI_ASSERT(input_dim_ > 0 && output_dim_ >= 0);
KALDI_ASSERT(input_dim_ > output_dim_);
KALDI_ASSERT(input_dim_ % output_dim_ == 0);
}
void ElementwiseProductComponent::InitFromConfig(ConfigLine *cfl) {
int32 input_dim = 0;
int32 output_dim = 0;
bool ok = cfl->GetValue("output-dim", &output_dim) &&
cfl->GetValue("input-dim", &input_dim);
if (!ok || cfl->HasUnusedValues() || output_dim <= 0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
Init(input_dim, output_dim);
}
void ElementwiseProductComponent::Propagate(
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
KALDI_ASSERT(in.NumCols() == input_dim_);
int32 num_inputs = input_dim_ / output_dim_;
for (int32 i = 0; i < num_inputs; i++) {
CuSubMatrix<BaseFloat> current_in(in, 0, in.NumRows(),
i * output_dim_, output_dim_);
if (i == 0) {
out->CopyFromMat(current_in);
} else {
out->MulElements(current_in);
}
}
}
void ElementwiseProductComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update,
CuMatrixBase<BaseFloat> *in_deriv) const {
if (!in_deriv) return;
int32 num_inputs = input_dim_ / output_dim_;
for (int32 i = 0; i < num_inputs; i++) {
CuSubMatrix<BaseFloat> current_in_deriv(*in_deriv, 0, in_deriv->NumRows(),
i * output_dim_,
output_dim_);
current_in_deriv.CopyFromMat(out_deriv);
for (int32 j = 0; j < num_inputs; j++) {
if (i == j)
continue;
CuSubMatrix<BaseFloat> in_value_partition(in_value, 0,
in_value.NumRows(),
j * output_dim_,
output_dim_);
current_in_deriv.MulElements(in_value_partition);
}
}
}
void ElementwiseProductComponent::Read(std::istream &is, bool binary) {
ExpectOneOrTwoTokens(is, binary, "<ElementwiseProductComponent>",
"<InputDim>");
ReadBasicType(is, binary, &input_dim_);
ExpectToken(is, binary, "<OutputDim>");
ReadBasicType(is, binary, &output_dim_);
ExpectToken(is, binary, "</ElementwiseProductComponent>");
}
void ElementwiseProductComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<ElementwiseProductComponent>");
WriteToken(os, binary, "<InputDim>");
WriteBasicType(os, binary, input_dim_);
WriteToken(os, binary, "<OutputDim>");
WriteBasicType(os, binary, output_dim_);
WriteToken(os, binary, "</ElementwiseProductComponent>");
}
const BaseFloat NormalizeComponent::kSquaredNormFloor =
pow(2.0, NormalizeComponent::kExpSquaredNormFloor);
// This component modifies the vector of activations by scaling it
// so that the root-mean-square equals 1.0. It's important that its
// square root be exactly representable in float.
void NormalizeComponent::Init(int32 input_dim, BaseFloat target_rms,
bool add_log_stddev) {
KALDI_ASSERT(input_dim > 0);
KALDI_ASSERT(target_rms > 0);
input_dim_ = input_dim;
target_rms_ = target_rms;
add_log_stddev_ = add_log_stddev;
}
NormalizeComponent::NormalizeComponent(const NormalizeComponent &other):
input_dim_(other.input_dim_), target_rms_(other.target_rms_),
add_log_stddev_(other.add_log_stddev_) { }
void NormalizeComponent::InitFromConfig(ConfigLine *cfl) {
int32 input_dim = 0;
bool add_log_stddev = false;
BaseFloat target_rms = 1.0;
bool ok = cfl->GetValue("dim", &input_dim) ||
cfl->GetValue("input-dim", &input_dim);
cfl->GetValue("target-rms", &target_rms);
cfl->GetValue("add-log-stddev", &add_log_stddev);
if (!ok || cfl->HasUnusedValues() || input_dim <= 0 || target_rms <= 0.0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
Init(input_dim, target_rms, add_log_stddev);
}
void NormalizeComponent::Read(std::istream &is, bool binary) {
std::string token;
ReadToken(is, binary, &token);
if (token == "<NormalizeComponent>") {
ReadToken(is, binary, &token);
}
KALDI_ASSERT(token == "<Dim>" || token == "<InputDim>");
ReadBasicType(is, binary, &input_dim_); // Read dimension.
ReadToken(is, binary, &token);
// read target_rms_ if it is available.
if (token == "<TargetRms>") {
ReadBasicType(is, binary, &target_rms_);
ReadToken(is, binary, &token);
}
// Read add_log_stddev_ token, if it is available.
if (token == "<AddLogStddev>") {
ReadBasicType(is, binary, &add_log_stddev_);
ReadToken(is, binary, &token);
}
if (token == "<ValueAvg>") {
// back-compatibility code.
CuVector<double> temp;
temp.Read(is, binary);
ExpectToken(is, binary, "<DerivAvg>");
temp.Read(is, binary);
ExpectToken(is, binary, "<Count>");
double count;
ReadBasicType(is, binary, &count);
ReadToken(is, binary, &token);
}
KALDI_ASSERT(token == "</NormalizeComponent>");
}
void NormalizeComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<NormalizeComponent>");
WriteToken(os, binary, "<InputDim>");
WriteBasicType(os, binary, input_dim_);
WriteToken(os, binary, "<TargetRms>");
WriteBasicType(os, binary, target_rms_);
WriteToken(os, binary, "<AddLogStddev>");
WriteBasicType(os, binary, add_log_stddev_);
WriteToken(os, binary, "</NormalizeComponent>");
}
std::string NormalizeComponent::Info() const {
std::ostringstream stream;
stream << Type() << ", input-dim=" << InputDim()
<< ", output-dim=" << OutputDim() << ", target-rms=" << target_rms_
<< ", add-log-stddev=" << std::boolalpha << add_log_stddev_;
return stream.str();
}
// The output y_i = scale * x_i,
// and we want to RMS value of the y_i to equal target_rms,
// so y^t y = D * target_rms^2 (if y is one row of the input).
// we need to have scale = 1.0 / sqrt(x^t x / (D * target_rms^2)).
// there is also flooring involved, to avoid division-by-zero
// problems. It's important for the backprop, that the floor's
// square root is exactly representable as float.
// If add_log_stddev_ is true, log(max(epsi, sqrt(x^t x / D)))
// is an extra dimension of the output.
void NormalizeComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
KALDI_ASSERT(out->NumCols() == in.NumCols() + (add_log_stddev_ ? 1 : 0));
cu::NormalizePerRow(in, target_rms_, add_log_stddev_, out);
}
/*
A note on the derivative of NormalizeComponent...
let both row_in and row_out be vectors of dimension D.
Let p = row_in^T row_in / (D * target_rms^2), and let
f = 1.0 / sqrt(max(kSquaredNormFloor, p)), and we compute row_out as:
row_out = f row_in.
Suppose we have a quantity deriv_out which is the derivative
of the objective function w.r.t. row_out. We want to compute
deriv_in which is the derivative of the objective function w.r.t.
row_in. Let the objective function be F. One term is obvious: we have
deriv_in = f deriv_out + ....
next we have to take into account the derivative that gets back-propagated
through f. Obviously, dF/df = deriv_out^T row_in.
And df/dp = (p <= kSquaredNormFloor ? 0.0 : -0.5 p^{-1.5}) = (f == 1.0 / sqrt(kSquaredNormFloor) ? 0.0 : -0.5 f^3),
and dp/d(row_in) = 2/(D * target_rms^2) row_in. [it's vector_valued].
So this term in dF/d(row_in) equals:
dF/df df/dp dp/d(row_in) = 2/(D * target_rms^2) (f == 1.0 / sqrt(kSquaredNormFloor) ? 0.0 : -0.5 f^3) (deriv_out^T row_in) row_in
So
deriv_in = f deriv_out + (f == 1.0 ? 0.0 : -f^3 / (D * target_rms^2) ) (deriv_out^T row_in) row_in
if add_log_stddev_ true, the deriv_in has another term as
dF/dx_i = dF/df . df/dx_i => df/dx_i = x_i/(x^T x)
*/
void NormalizeComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &, // out_value
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update,
CuMatrixBase<BaseFloat> *in_deriv) const {
if (!in_deriv) return;
const CuSubMatrix<BaseFloat> out_deriv_no_log(out_deriv,
0, out_deriv.NumRows(),
0, input_dim_);
CuVector<BaseFloat> dot_products(out_deriv.NumRows());
dot_products.AddDiagMatMat(1.0, out_deriv_no_log, kNoTrans,
in_value, kTrans, 0.0);
CuVector<BaseFloat> in_norm(in_value.NumRows());
BaseFloat d_scaled = (in_value.NumCols() * target_rms_ * target_rms_);
in_norm.AddDiagMat2(1.0, in_value, kNoTrans, 0.0);
if (add_log_stddev_) {
CuVector<BaseFloat> log_stddev_deriv(in_norm), // log_stddev deriv as dF/dy .* (x^T x)^-1
out_deriv_for_stddev(out_deriv.NumRows(), kUndefined);
// f = log(sqrt(max(epsi, x^T x / D)))
// df/dx = epsi^2 * D < x^T x ? (1/(x^T x)) * x : 0.
// we don't compute this exactly below for the case wehn x^2 x is very
// small, but we do make sure that the deriv isn't infinity when the input
// is zero.
log_stddev_deriv.ApplyFloor(input_dim_ * kSquaredNormFloor);
log_stddev_deriv.ApplyPow(-1.0);
out_deriv_for_stddev.CopyColFromMat(out_deriv, (out_deriv.NumCols() - 1));
log_stddev_deriv.MulElements(out_deriv_for_stddev);
if (in_deriv)
in_deriv->AddDiagVecMat(1.0, log_stddev_deriv, in_value, kNoTrans, 1.0);
}
in_norm.Scale(1.0 / d_scaled);
in_norm.ApplyFloor(kSquaredNormFloor);
in_norm.ApplyPow(-0.5);
if (in_deriv) {
if (in_deriv->Data() != out_deriv_no_log.Data())
in_deriv->AddDiagVecMat(1.0, in_norm, out_deriv_no_log, kNoTrans, 1.0);
else
in_deriv->MulRowsVec(in_norm);
in_norm.ReplaceValue(1.0 / sqrt(kSquaredNormFloor), 0.0);
in_norm.ApplyPow(3.0);
dot_products.MulElements(in_norm);
in_deriv->AddDiagVecMat(-1.0 / d_scaled,
dot_products, in_value,
kNoTrans, 1.0);
}
}
void SigmoidComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
out->Sigmoid(in);
}
void SigmoidComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &,
const CuMatrixBase<BaseFloat> &out_value,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update_in,
CuMatrixBase<BaseFloat> *in_deriv) const {
if (in_deriv != NULL) {
in_deriv->DiffSigmoid(out_value, out_deriv);
SigmoidComponent *to_update = dynamic_cast<SigmoidComponent*>(to_update_in);
if (to_update != NULL)
RepairGradients(out_value, in_deriv, to_update);
}
}
void SigmoidComponent::RepairGradients(
const CuMatrixBase<BaseFloat> &out_value,
CuMatrixBase<BaseFloat> *in_deriv,
SigmoidComponent *to_update) const {
KALDI_ASSERT(to_update != NULL);
// maximum possible derivative of SigmoidComponent is 0.25.
// the default lower-threshold on the derivative, below which we
// add a term to the derivative to encourage the inputs to the sigmoid
// to be closer to zero, is 0.05, which means the derivative is on average
// 5 times smaller than its maximum possible value.
BaseFloat default_lower_threshold = 0.05;
// we use this 'repair_probability' (hardcoded for now) to limit
// this code to running on about half of the minibatches.
BaseFloat repair_probability = 0.5;
to_update->num_dims_processed_ += dim_;
if (self_repair_scale_ == 0.0 || count_ == 0.0 || deriv_sum_.Dim() != dim_ ||
RandUniform() > repair_probability)
return;
// check that the self-repair scale is in a reasonable range.
KALDI_ASSERT(self_repair_scale_ > 0.0 && self_repair_scale_ < 0.1);
BaseFloat unset = kUnsetThreshold; // -1000.0
BaseFloat lower_threshold = (self_repair_lower_threshold_ == unset ?
default_lower_threshold :
self_repair_lower_threshold_) *
count_;
if (self_repair_upper_threshold_ != unset) {
KALDI_ERR << "Do not set the self-repair-upper-threshold for sigmoid "
<< "components, it does nothing.";
}
// thresholds_vec is actually a 1-row matrix. (the ApplyHeaviside
// function isn't defined for vectors).
CuMatrix<BaseFloat> thresholds(1, dim_);
CuSubVector<BaseFloat> thresholds_vec(thresholds, 0);
thresholds_vec.AddVec(-1.0, deriv_sum_);
thresholds_vec.Add(lower_threshold);
thresholds.ApplyHeaviside();
to_update->num_dims_self_repaired_ += thresholds_vec.Sum();
// At this point, 'thresholds_vec' contains a 1 for each dimension of
// the output that is 'problematic', i.e. for which the avg-deriv
// is less than the self-repair lower threshold, and a 0 for
// each dimension that is not problematic.
// what we want to do is to add
// -self_repair_scale_ / repair_probability times (2 * output-valiue - 1.0)
// to the input derivative for each problematic dimension.
// Here, 2 * output - 1.0 is a version of the sigmoid that goes from -1.0 to
// 1.0, like a tanh. the negative sign is so that for inputs <0, we push them
// up towards 0, and for inputs >0, we push them down towards 0.
// Our use of this sigmoid-type function here is just a convenience since
// we have it available. We could use just about any function that is positive
// for inputs < 0 and negative for inputs > 0.
// We can rearrange the above as: for only the problematic columns,
// input-deriv -= 2 * self-repair-scale / repair-probabilty * output
// input-deriv += self-repair-scale / repair-probabilty
// which we can write as:
// input-deriv -= 2 * self-repair-scale / repair-probabilty * output * thresholds-vec
// input-deriv += self-repair-scale / repair-probabilty * thresholds-vec
in_deriv->AddMatDiagVec(-2.0 * self_repair_scale_ / repair_probability,
out_value, kNoTrans, thresholds_vec);
in_deriv->AddVecToRows(self_repair_scale_ / repair_probability,
thresholds_vec);
}
void SigmoidComponent::StoreStats(const CuMatrixBase<BaseFloat> &out_value) {
// only store stats about every other minibatch.
if (RandInt(0, 1) == 0)
return;
// derivative of the nonlinearity is out_value * (1.0 - out_value);
CuMatrix<BaseFloat> temp_deriv(out_value.NumRows(), out_value.NumCols(),
kUndefined);
temp_deriv.Set(1.0);
temp_deriv.AddMat(-1.0, out_value);
temp_deriv.MulElements(out_value);
StoreStatsInternal(out_value, &temp_deriv);
}
void NoOpComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
out->CopyFromMat(in);
}
void NoOpComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &,
const CuMatrixBase<BaseFloat> &,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update, // may be NULL; may be identical
// to "this" or different.
CuMatrixBase<BaseFloat> *in_deriv) const {
in_deriv->CopyFromMat(out_deriv);
}
void ClipGradientComponent::Read(std::istream &is, bool binary) {
// might not see the "<NaturalGradientAffineComponent>" part because
// of how ReadNew() works.
ExpectOneOrTwoTokens(is, binary, "<ClipGradientComponent>",
"<Dim>");
ReadBasicType(is, binary, &dim_);
ExpectToken(is, binary, "<ClippingThreshold>");
ReadBasicType(is, binary, &clipping_threshold_);
ExpectToken(is, binary, "<NormBasedClipping>");
ReadBasicType(is, binary, &norm_based_clipping_);
std::string token;
ReadToken(is, binary, &token);
if (token == "<SelfRepairClippedProportionThreshold>") {
ReadBasicType(is, binary, &self_repair_clipped_proportion_threshold_);
ExpectToken(is, binary, "<SelfRepairTarget>");
ReadBasicType(is, binary, &self_repair_target_);
ExpectToken(is, binary, "<SelfRepairScale>");
ReadBasicType(is, binary, &self_repair_scale_);
ExpectToken(is, binary, "<NumElementsClipped>");
} else {
self_repair_clipped_proportion_threshold_ = 1.0;
self_repair_target_ = 0.0;
self_repair_scale_ = 0.0;
KALDI_ASSERT(token == "<NumElementsClipped>");
}
ReadBasicType(is, binary, &num_clipped_);
ExpectToken(is, binary, "<NumElementsProcessed>");
ReadBasicType(is, binary, &count_);
ReadToken(is, binary, &token);
if (token == "<NumSelfRepaired>") {
ReadBasicType(is, binary, &num_self_repaired_);
ExpectToken(is, binary, "<NumBackpropped>");
ReadBasicType(is, binary, &num_backpropped_);
ExpectToken(is, binary, "</ClipGradientComponent>");
} else {
num_self_repaired_ = 0;
num_backpropped_ = 0;
KALDI_ASSERT(token == "</ClipGradientComponent>");
}
}
void ClipGradientComponent::Write(std::ostream &os, bool binary) const {
WriteToken(os, binary, "<ClipGradientComponent>");
WriteToken(os, binary, "<Dim>");
WriteBasicType(os, binary, dim_);
WriteToken(os, binary, "<ClippingThreshold>");
WriteBasicType(os, binary, clipping_threshold_);
WriteToken(os, binary, "<NormBasedClipping>");
WriteBasicType(os, binary, norm_based_clipping_);
WriteToken(os, binary, "<SelfRepairClippedProportionThreshold>");
WriteBasicType(os, binary, self_repair_clipped_proportion_threshold_);
WriteToken(os, binary, "<SelfRepairTarget>");
WriteBasicType(os, binary, self_repair_target_);
WriteToken(os, binary, "<SelfRepairScale>");
WriteBasicType(os, binary, self_repair_scale_);
WriteToken(os, binary, "<NumElementsClipped>");
WriteBasicType(os, binary, num_clipped_);
WriteToken(os, binary, "<NumElementsProcessed>");
WriteBasicType(os, binary, count_);
WriteToken(os, binary, "<NumSelfRepaired>");
WriteBasicType(os, binary, num_self_repaired_);
WriteToken(os, binary, "<NumBackpropped>");
WriteBasicType(os, binary, num_backpropped_);
WriteToken(os, binary, "</ClipGradientComponent>");
}
std::string ClipGradientComponent::Info() const {
std::ostringstream stream;
stream << Type() << ", dim=" << dim_
<< ", norm-based-clipping="
<< (norm_based_clipping_ ? "true" : "false")
<< ", clipping-threshold=" << clipping_threshold_
<< ", clipped-proportion="
<< (count_ > 0 ? static_cast<BaseFloat>(num_clipped_)/count_ : 0);
if (self_repair_scale_ != 0.0)
stream << ", self-repair-clipped-proportion-threshold="
<< self_repair_clipped_proportion_threshold_
<< ", self-repair-target=" << self_repair_target_
<< ", self-repair-scale=" << self_repair_scale_;
return stream.str();
}
void ClipGradientComponent::Init(int32 dim,
BaseFloat clipping_threshold,
bool norm_based_clipping,
BaseFloat self_repair_clipped_proportion_threshold,
BaseFloat self_repair_target,
BaseFloat self_repair_scale,
int32 num_clipped,
int32 count,
int32 num_self_repaired,
int32 num_backpropped) {
KALDI_ASSERT(clipping_threshold >= 0 && dim > 0 &&
self_repair_clipped_proportion_threshold >= 0.0 &&
self_repair_target >= 0.0 && self_repair_scale >= 0.0);
dim_ = dim;
norm_based_clipping_ = norm_based_clipping;
clipping_threshold_ = clipping_threshold;
self_repair_clipped_proportion_threshold_ =
self_repair_clipped_proportion_threshold;
self_repair_target_ = self_repair_target;
self_repair_scale_ = self_repair_scale;
num_clipped_ = num_clipped;
count_ = count;
num_self_repaired_ = num_self_repaired;
num_backpropped_ = num_backpropped;
}
void ClipGradientComponent::InitFromConfig(ConfigLine *cfl) {
int32 dim = 0;
bool ok = cfl->GetValue("dim", &dim);
bool norm_based_clipping = false;
BaseFloat clipping_threshold = 15.0;
BaseFloat self_repair_clipped_proportion_threshold = 0.01;
BaseFloat self_repair_target = 0.0;
BaseFloat self_repair_scale = 1.0;
cfl->GetValue("clipping-threshold", &clipping_threshold);
cfl->GetValue("norm-based-clipping", &norm_based_clipping);
cfl->GetValue("self-repair-clipped-proportion-threshold",
&self_repair_clipped_proportion_threshold);
cfl->GetValue("self-repair-target",
&self_repair_target);
cfl->GetValue("self-repair-scale", &self_repair_scale);
if (!ok || cfl->HasUnusedValues() ||
clipping_threshold < 0 || dim <= 0 ||
self_repair_clipped_proportion_threshold < 0.0 ||
self_repair_target < 0.0 || self_repair_scale < 0.0)
KALDI_ERR << "Invalid initializer for layer of type "
<< Type() << ": \"" << cfl->WholeLine() << "\"";
Init(dim, clipping_threshold, norm_based_clipping,
self_repair_clipped_proportion_threshold,
self_repair_target,
self_repair_scale, 0, 0, 0, 0);
}
void ClipGradientComponent::Propagate(
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
out->CopyFromMat(in);
}
void ClipGradientComponent::Backprop(const std::string &debug_info,
const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in_value,
const CuMatrixBase<BaseFloat> &,
const CuMatrixBase<BaseFloat> &out_deriv,
Component *to_update_in, // may be NULL; may be identical
// to "this" or different.
CuMatrixBase<BaseFloat> *in_deriv) const {
// the following statement will do nothing if in_deriv and out_deriv have same
// memory.
in_deriv->CopyFromMat(out_deriv);
ClipGradientComponent *to_update =
dynamic_cast<ClipGradientComponent*>(to_update_in);
if (clipping_threshold_ > 0) {
if (norm_based_clipping_) {
// each row in the derivative matrix, which corresponds to one sample in
// the mini-batch, is scaled to have a max-norm of clipping_threshold_
CuVector<BaseFloat> clipping_scales(in_deriv->NumRows());
clipping_scales.AddDiagMat2(pow(clipping_threshold_, -2), *in_deriv,
kNoTrans, 0.0);
// now clipping_scales contains the squared (norm of each row divided by
// clipping_threshold)
int32 num_not_scaled = clipping_scales.ApplyFloor(1.0);
// now clipping_scales contains min(1,
// squared-(norm/clipping_threshold))
if (num_not_scaled != clipping_scales.Dim()) {
clipping_scales.ApplyPow(-0.5);
// now clipping_scales contains max(1,
// clipping_threshold/vector_norm)
in_deriv->MulRowsVec(clipping_scales);
if (to_update != NULL)
to_update->num_clipped_ += (clipping_scales.Dim() - num_not_scaled);
}
if (to_update != NULL)
to_update->count_ += clipping_scales.Dim();
} else {
// each element of the derivative matrix, is clipped to be below the
// clipping_threshold_
in_deriv->ApplyCeiling(clipping_threshold_);
in_deriv->ApplyFloor(-1 * clipping_threshold_);
}
if (to_update != NULL) {
to_update->num_backpropped_ += 1;
RepairGradients(debug_info, in_value, in_deriv, to_update);
}
}
}
// This function will add a self-repair term to in-deriv, attempting to shrink
// the maginitude of the input towards self_repair_target_.
// This term is proportional to [-(input vector - self_repair_target_)].
// The avarage magnitude of this term is equal to
// [self_repair_scale_ * clipped_proportion * average norm of input derivative].
// We use norm of input derivative when computing the magnitude so that it is
// comparable to the magnitude of input derivative, especially when the gradient
// explosion is actually happening.
void ClipGradientComponent::RepairGradients(
const std::string &debug_info,
const CuMatrixBase<BaseFloat> &in_value,
CuMatrixBase<BaseFloat> *in_deriv, ClipGradientComponent *to_update) const {
KALDI_ASSERT(to_update != NULL);
// we use this 'repair_probability' (hardcoded for now) to limit
// this code to running on about half of the minibatches.
BaseFloat repair_probability = 0.5;
if (self_repair_clipped_proportion_threshold_ >= 1.0 ||
self_repair_scale_ == 0.0 || count_ == 0 ||
RandUniform() > repair_probability)
return;
KALDI_ASSERT(self_repair_target_ >= 0.0 && self_repair_scale_ > 0.0);
BaseFloat clipped_proportion =
(count_ > 0 ? static_cast<BaseFloat>(num_clipped_) / count_ : 0);
// in-deriv would be modified only when clipped_proportion exceeds the
// threshold
if (clipped_proportion <= self_repair_clipped_proportion_threshold_)
return;
to_update->num_self_repaired_ += 1;
if (to_update->debug_info_ == "") // get the component-node name
to_update->debug_info_ = debug_info;
if (to_update->num_self_repaired_ == 1)
KALDI_LOG << "ClipGradientComponent(node_name=" << debug_info
<< ")'s self-repair was activated as the first time at the "
<< to_update->num_backpropped_
<< "-th call of Backprop() in this training job.";
// sign_mat = sign(in_value), i.e.,
// An element in sign_mat is 1 if its corresponding element in in_value > 0,
// or -1 otherwise
CuMatrix<BaseFloat> sign_mat(in_value);
sign_mat.ApplyHeaviside();
sign_mat.Scale(2.0);
sign_mat.Add(-1.0);
// repair_mat =
// floor(abs(in_value) - self_repair_target_, 0) .* sign(in_value)
CuMatrix<BaseFloat> repair_mat(in_value);
repair_mat.ApplyPowAbs(1.0);
repair_mat.Add(-self_repair_target_);
repair_mat.ApplyFloor(0.0);
repair_mat.MulElements(sign_mat);
// magnitude =
// self_repair_scale_ * clipped_proportion * average norm of in-deriv
CuVector<BaseFloat> in_deriv_norm_vec(in_deriv->NumRows());
in_deriv_norm_vec.AddDiagMat2(1.0, *in_deriv, kNoTrans, 0.0);
in_deriv_norm_vec.ApplyPow(0.5);
double in_deriv_norm_sum = in_deriv_norm_vec.Sum();
BaseFloat magnitude = self_repair_scale_ * clipped_proportion *
(in_deriv_norm_sum / in_deriv_norm_vec.Dim());
CuVector<BaseFloat> repair_mat_norm_vec(repair_mat.NumRows());
repair_mat_norm_vec.AddDiagMat2(1.0, repair_mat, kNoTrans, 0.0);
repair_mat_norm_vec.ApplyPow(0.5);
double repair_mat_norm_sum = repair_mat_norm_vec.Sum();
double scale = 0.0;
if (repair_mat_norm_sum != 0.0)
scale = magnitude / (repair_mat_norm_sum / repair_mat_norm_vec.Dim());
// repair_mat is scaled so that on average the rows have the norm
// (magnitude / repair_probability). This will give higher magnitude of
// self-repair to input vectors that have larger absolute value, which tend to
// be those that are diverging.
in_deriv->AddMat(-scale / repair_probability, repair_mat);
CuVector<BaseFloat> in_deriv_repaired_norm_vec(in_deriv->NumRows());
in_deriv_repaired_norm_vec.AddDiagMat2(1.0, *in_deriv, kNoTrans, 0.0);
in_deriv_repaired_norm_vec.ApplyPow(0.5);
// scale in_deriv to have the same norm as that before adding the self-repair
// term, in order to avoid increase of the norm caused by self-repair,
// which may incur more clip of gradient and thus more self-repair
double in_deriv_repaired_norm_sum = in_deriv_repaired_norm_vec.Sum();
if (in_deriv_repaired_norm_sum != 0.0)
in_deriv->Scale(in_deriv_norm_sum / in_deriv_repaired_norm_sum);
}
void ClipGradientComponent::ZeroStats() {
count_ = 0.0;
num_clipped_ = 0.0;
num_self_repaired_ = 0;
num_backpropped_ = 0;
}
void ClipGradientComponent::Scale(BaseFloat scale) {
count_ *= scale;
num_clipped_ *= scale;
}
void ClipGradientComponent::Add(BaseFloat alpha, const Component &other_in) {
const ClipGradientComponent *other =
dynamic_cast<const ClipGradientComponent*>(&other_in);
KALDI_ASSERT(other != NULL);
count_ += alpha * other->count_;
num_clipped_ += alpha * other->num_clipped_;
}
void TanhComponent::Propagate(const ComponentPrecomputedIndexes *indexes,
const CuMatrixBase<BaseFloat> &in,
CuMatrixBase<BaseFloat> *out) const {
// Apply tanh function to each element of the output...
// the tanh function may be written as -1 + ( 2 / (1 + e^{-2 x})),
// which is a scaled and shifted sigmoid.
out->Tanh(in);
}
void TanhComponent::RepairGradients(
const CuMatrixBase<BaseFloat> &out_value,
CuMatrixBase<BaseFloat> *in_deriv,
TanhComponent *to_update) const {
KALDI_ASSERT(to_update != NULL);
// maximum possible derivative of SigmoidComponent is 1.0
// the default lower-threshold on the derivative, below which we
// add a term to the derivative to encourage the inputs to the sigmoid
// to be closer to zero, is 0.2, which means the derivative is on average
// 5 times smaller than its maximum possible value.
BaseFloat default_lower_threshold = 0.2;
// we use this 'repair_probability' (hardcoded for now) to limit
// this code to running on about half of the minibatches.
BaseFloat repair_probability = 0.5;
to_update->num_dims_processed_ += dim_;
if (self_repair_scale_ == 0.0 || count_ == 0.0 || deriv_sum_.Dim() != dim_ ||
RandUniform() > repair_probability)
return;
// check that the self-repair scale is in a reasonable range.
KALDI_ASSERT(self_repair_scale_ > 0.0 && self_repair_scale_ < 0.1);
BaseFloat unset = kUnsetThreshold; // -1000.0
BaseFloat lower_threshold = (self_repair_lower_threshold_ == unset ?
default_lower_threshold :
self_repair_lower_threshold_) *
count_;
if (self_repair_upper_threshold_ != unset) {
KALDI_ERR << "Do not set the self-repair-upper-threshold for sigmoid "
<< "components, it does nothing.";
}
// thresholds_vec is actually a 1-row matrix. (the ApplyHeaviside
// function isn't defined for vectors).
CuMatrix<BaseFloat> thresholds(1, dim_);
CuSubVector<BaseFloat> thresholds_vec(thresholds, 0);
thresholds_vec.AddVec(-1.0, deriv_sum_);
thresholds_vec.Add(lower_threshold);
thresholds.ApplyHeaviside();