-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
nnet-utils.cc
2328 lines (2145 loc) · 97.7 KB
/
nnet-utils.cc
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-utils.cc
// Copyright 2015 Johns Hopkins University (author: Daniel Povey)
// 2016 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 <iomanip>
#include "nnet3/nnet-utils.h"
#include "nnet3/nnet-graph.h"
#include "nnet3/nnet-simple-component.h"
#include "nnet3/nnet-normalize-component.h"
#include "nnet3/nnet-general-component.h"
#include "nnet3/nnet-convolutional-component.h"
#include "nnet3/nnet-parse.h"
#include "nnet3/nnet-computation-graph.h"
#include "nnet3/nnet-diagnostics.h"
namespace kaldi {
namespace nnet3 {
int32 NumOutputNodes(const Nnet &nnet) {
int32 ans = 0;
for (int32 n = 0; n < nnet.NumNodes(); n++)
if (nnet.IsOutputNode(n))
ans++;
return ans;
}
int32 NumInputNodes(const Nnet &nnet) {
int32 ans = 0;
for (int32 n = 0; n < nnet.NumNodes(); n++)
if (nnet.IsInputNode(n))
ans++;
return ans;
}
bool IsSimpleNnet(const Nnet &nnet) {
// check that we have an output node and called "output".
if (nnet.GetNodeIndex("output") == -1 ||
!nnet.IsOutputNode(nnet.GetNodeIndex("output")))
return false;
// check that there is an input node named "input".
if (nnet.GetNodeIndex("input") == -1 ||
!nnet.IsInputNode(nnet.GetNodeIndex("input")))
return false;
// if there was just one input, then it was named
// "input" and everything checks out.
if (NumInputNodes(nnet) == 1)
return true;
// Otherwise, there should be input node with name "input" and one
// should be called "ivector".
return nnet.GetNodeIndex("ivector") != -1 &&
nnet.IsInputNode(nnet.GetNodeIndex("ivector"));
}
void EvaluateComputationRequest(
const Nnet &nnet,
const ComputationRequest &request,
std::vector<std::vector<bool> > *is_computable) {
ComputationGraph graph;
ComputationGraphBuilder builder(nnet, &graph);
builder.Compute(request);
builder.GetComputableInfo(is_computable);
if (GetVerboseLevel() >= 4) {
std::ostringstream graph_pretty;
graph.Print(graph_pretty, nnet.GetNodeNames());
KALDI_VLOG(4) << "Graph is " << graph_pretty.str();
}
}
// This non-exported function is used in ComputeSimpleNnetContext
// to compute the left and right context of the nnet for a particular
// window size and shift-length.
// It returns false if no outputs were computable, meaning the left and
// right context could not be computed. (Normally this means the window
// size is too small).
static bool ComputeSimpleNnetContextForShift(
const Nnet &nnet,
int32 input_start,
int32 window_size,
int32 *left_context,
int32 *right_context) {
int32 input_end = input_start + window_size;
IoSpecification input;
input.name = "input";
IoSpecification output;
output.name = "output";
IoSpecification ivector; // we might or might not use this.
ivector.name = "ivector";
int32 n = rand() % 10;
// in the IoSpecification for now we we will request all the same indexes at
// output that we requested at input.
for (int32 t = input_start; t < input_end; t++) {
input.indexes.push_back(Index(n, t));
output.indexes.push_back(Index(n, t));
}
// most networks will just require the ivector at time t = 0,
// but this might not always be the case, and some might use rounding
// descriptors with the iVector which might require it at an earlier
// frame than the regular input, so we provide the iVector in as wide a range
// as it might possibly be needed.
for (int32 t = input_start - nnet.Modulus(); t < input_end; t++) {
ivector.indexes.push_back(Index(n, t));
}
ComputationRequest request;
request.inputs.push_back(input);
request.outputs.push_back(output);
if (nnet.GetNodeIndex("ivector") != -1)
request.inputs.push_back(ivector);
std::vector<std::vector<bool> > computable;
EvaluateComputationRequest(nnet, request, &computable);
KALDI_ASSERT(computable.size() == 1);
std::vector<bool> &output_ok = computable[0];
std::vector<bool>::iterator iter =
std::find(output_ok.begin(), output_ok.end(), true);
int32 first_ok = iter - output_ok.begin();
int32 first_not_ok = std::find(iter, output_ok.end(), false) -
output_ok.begin();
if (first_ok == window_size || first_not_ok <= first_ok)
return false;
*left_context = first_ok;
*right_context = window_size - first_not_ok;
return true;
}
void ComputeSimpleNnetContext(const Nnet &nnet,
int32 *left_context,
int32 *right_context) {
KALDI_ASSERT(IsSimpleNnet(nnet));
int32 modulus = nnet.Modulus();
// modulus >= 1 is a number such that the network ought to be
// invariant to time shifts (of both the input and output) that
// are a multiple of this number. We need to test all shifts modulo
// this number in case the left and right context vary at all within
// this range.
std::vector<int32> left_contexts(modulus + 1);
std::vector<int32> right_contexts(modulus + 1);
// window_size is a number which needs to be greater than the total context
// of the nnet, else we won't be able to work out the context. Large window
// size will make this code slow, so we start off with small window size, and
// if it isn't enough, we keep doubling it up to a maximum.
int32 window_size = 40, max_window_size = 800;
while (window_size < max_window_size) {
// by going "<= modulus" instead of "< modulus" we do one more computation
// than we really need; it becomes a sanity check.
int32 input_start;
for (input_start = 0; input_start <= modulus; input_start++) {
if (!ComputeSimpleNnetContextForShift(nnet, input_start, window_size,
&(left_contexts[input_start]),
&(right_contexts[input_start])))
break;
}
if (input_start <= modulus) {
// We broke from the loop over 'input_start', which means there was
// a failure in ComputeSimpleNnextContextForShift-- we assume at
// this point that it was because window_size was too small.
window_size *= 2;
continue;
}
KALDI_ASSERT(left_contexts[0] == left_contexts[modulus] &&
"nnet does not have the properties we expect.");
KALDI_ASSERT(right_contexts[0] == right_contexts[modulus] &&
"nnet does not have the properties we expect.");
*left_context =
*std::max_element(left_contexts.begin(), left_contexts.end());
*right_context =
*std::max_element(right_contexts.begin(), right_contexts.end());
// Success.
return;
}
KALDI_ERR << "Failure in ComputeSimpleNnetContext (perhaps not a simple nnet?)";
}
void PerturbParams(BaseFloat stddev,
Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
UpdatableComponent *u_comp = dynamic_cast<UpdatableComponent*>(comp);
KALDI_ASSERT(u_comp != NULL);
u_comp->PerturbParams(stddev);
}
}
}
void ComponentDotProducts(const Nnet &nnet1,
const Nnet &nnet2,
VectorBase<BaseFloat> *dot_prod) {
KALDI_ASSERT(nnet1.NumComponents() == nnet2.NumComponents());
int32 updatable_c = 0;
for (int32 c = 0; c < nnet1.NumComponents(); c++) {
const Component *comp1 = nnet1.GetComponent(c),
*comp2 = nnet2.GetComponent(c);
if (comp1->Properties() & kUpdatableComponent) {
const UpdatableComponent
*u_comp1 = dynamic_cast<const UpdatableComponent*>(comp1),
*u_comp2 = dynamic_cast<const UpdatableComponent*>(comp2);
KALDI_ASSERT(u_comp1 != NULL && u_comp2 != NULL);
dot_prod->Data()[updatable_c] = u_comp1->DotProduct(*u_comp2);
updatable_c++;
}
}
KALDI_ASSERT(updatable_c == dot_prod->Dim());
}
std::string PrintVectorPerUpdatableComponent(const Nnet &nnet,
const VectorBase<BaseFloat> &vec) {
std::ostringstream os;
os << "[ ";
KALDI_ASSERT(NumUpdatableComponents(nnet) == vec.Dim());
int32 updatable_c = 0;
for (int32 c = 0; c < nnet.NumComponents(); c++) {
const Component *comp = nnet.GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
const std::string &component_name = nnet.GetComponentName(c);
os << component_name << ':' << vec(updatable_c) << ' ';
updatable_c++;
}
}
KALDI_ASSERT(updatable_c == vec.Dim());
os << ']';
return os.str();
}
BaseFloat DotProduct(const Nnet &nnet1,
const Nnet &nnet2) {
KALDI_ASSERT(nnet1.NumComponents() == nnet2.NumComponents());
BaseFloat ans = 0.0;
for (int32 c = 0; c < nnet1.NumComponents(); c++) {
const Component *comp1 = nnet1.GetComponent(c),
*comp2 = nnet2.GetComponent(c);
if (comp1->Properties() & kUpdatableComponent) {
const UpdatableComponent
*u_comp1 = dynamic_cast<const UpdatableComponent*>(comp1),
*u_comp2 = dynamic_cast<const UpdatableComponent*>(comp2);
KALDI_ASSERT(u_comp1 != NULL && u_comp2 != NULL);
ans += u_comp1->DotProduct(*u_comp2);
}
}
return ans;
}
void ZeroComponentStats(Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
comp->ZeroStats(); // for some components, this won't do anything.
}
}
void SetLearningRate(BaseFloat learning_rate,
Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(comp);
if (uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
uc->SetUnderlyingLearningRate(learning_rate);
}
}
}
void SetNnetAsGradient(Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
UpdatableComponent *u_comp = dynamic_cast<UpdatableComponent*>(comp);
KALDI_ASSERT(u_comp != NULL);
u_comp->SetAsGradient();
}
}
}
void SetRequireDirectInput(bool b, Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
if (dynamic_cast<StatisticsPoolingComponent*>(comp) != NULL)
dynamic_cast<StatisticsPoolingComponent*>(comp)->SetRequireDirectInput(b);
}
}
void ScaleNnet(BaseFloat scale, Nnet *nnet) {
if (scale == 1.0) return;
else {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
comp->Scale(scale);
}
}
}
void AddNnetComponents(const Nnet &src, const Vector<BaseFloat> &alphas,
BaseFloat scale, Nnet *dest) {
if (src.NumComponents() != dest->NumComponents())
KALDI_ERR << "Trying to add incompatible nnets.";
int32 i = 0;
for (int32 c = 0; c < src.NumComponents(); c++) {
const Component *src_comp = src.GetComponent(c);
Component *dest_comp = dest->GetComponent(c);
if (src_comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
const UpdatableComponent *src_uc =
dynamic_cast<const UpdatableComponent*>(src_comp);
UpdatableComponent *dest_uc =
dynamic_cast<UpdatableComponent*>(dest_comp);
if (src_uc == NULL || dest_uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
KALDI_ASSERT(i < alphas.Dim());
dest_uc->Add(alphas(i++), *src_uc);
} else { // add stored stats
dest_comp->Add(scale, *src_comp);
}
}
KALDI_ASSERT(i == alphas.Dim());
}
void AddNnet(const Nnet &src, BaseFloat alpha, Nnet *dest) {
if (src.NumComponents() != dest->NumComponents())
KALDI_ERR << "Trying to add incompatible nnets.";
for (int32 c = 0; c < src.NumComponents(); c++) {
const Component *src_comp = src.GetComponent(c);
Component *dest_comp = dest->GetComponent(c);
dest_comp->Add(alpha, *src_comp);
}
}
int32 NumParameters(const Nnet &src) {
int32 ans = 0;
for (int32 c = 0; c < src.NumComponents(); c++) {
const Component *comp = src.GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
const UpdatableComponent *uc =
dynamic_cast<const UpdatableComponent*>(comp);
if (uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
ans += uc->NumParameters();
}
}
return ans;
}
void VectorizeNnet(const Nnet &src,
VectorBase<BaseFloat> *parameters) {
KALDI_ASSERT(parameters->Dim() == NumParameters(src));
int32 dim_offset = 0;
for (int32 c = 0; c < src.NumComponents(); c++) {
const Component *comp = src.GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
const UpdatableComponent *uc =
dynamic_cast<const UpdatableComponent*>(comp);
if (uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
int32 this_dim = uc->NumParameters();
SubVector<BaseFloat> this_part(*parameters, dim_offset, this_dim);
uc->Vectorize(&this_part);
dim_offset += this_dim;
}
}
}
void UnVectorizeNnet(const VectorBase<BaseFloat> ¶meters,
Nnet *dest) {
KALDI_ASSERT(parameters.Dim() == NumParameters(*dest));
int32 dim_offset = 0;
for (int32 c = 0; c < dest->NumComponents(); c++) {
Component *comp = dest->GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(comp);
if (uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
int32 this_dim = uc->NumParameters();
const SubVector<BaseFloat> this_part(parameters, dim_offset, this_dim);
uc->UnVectorize(this_part);
dim_offset += this_dim;
}
}
}
int32 NumUpdatableComponents(const Nnet &dest) {
int32 ans = 0;
for (int32 c = 0; c < dest.NumComponents(); c++) {
const Component *comp = dest.GetComponent(c);
if (comp->Properties() & kUpdatableComponent)
ans++;
}
return ans;
}
void FreezeNaturalGradient(bool freeze, Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
if (comp->Properties() & kUpdatableComponent) {
// For now all updatable components inherit from class UpdatableComponent.
// If that changes in future, we will change this code.
UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(comp);
if (uc == NULL)
KALDI_ERR << "Updatable component does not inherit from class "
"UpdatableComponent; change this code.";
uc->FreezeNaturalGradient(freeze);
}
}
}
void ConvertRepeatedToBlockAffine(CompositeComponent *c_component) {
for(int32 i = 0; i < c_component->NumComponents(); i++) {
const Component *c = c_component->GetComponent(i);
KALDI_ASSERT(c->Type() != "CompositeComponent" &&
"Nesting CompositeComponent within CompositeComponent is not allowed.\n"
"(We may change this as more complicated components are introduced.)");
if(c->Type() == "RepeatedAffineComponent" ||
c->Type() == "NaturalGradientRepeatedAffineComponent") {
// N.B.: NaturalGradientRepeatedAffineComponent is a subclass of
// RepeatedAffineComponent.
const RepeatedAffineComponent *rac =
dynamic_cast<const RepeatedAffineComponent*>(c);
KALDI_ASSERT(rac != NULL);
BlockAffineComponent *bac = new BlockAffineComponent(*rac);
// following call deletes rac
c_component->SetComponent(i, bac);
}
}
}
void ConvertRepeatedToBlockAffine(Nnet *nnet) {
for(int32 i = 0; i < nnet->NumComponents(); i++) {
const Component *const_c = nnet->GetComponent(i);
if(const_c->Type() == "RepeatedAffineComponent" ||
const_c->Type() == "NaturalGradientRepeatedAffineComponent") {
// N.B.: NaturalGradientRepeatedAffineComponent is a subclass of
// RepeatedAffineComponent.
const RepeatedAffineComponent *rac =
dynamic_cast<const RepeatedAffineComponent*>(const_c);
KALDI_ASSERT(rac != NULL);
BlockAffineComponent *bac = new BlockAffineComponent(*rac);
// following call deletes rac
nnet->SetComponent(i, bac);
} else if (const_c->Type() == "CompositeComponent") {
// We must modify the composite component, so we use the
// non-const GetComponent() call here.
Component *c = nnet->GetComponent(i);
CompositeComponent *cc = dynamic_cast<CompositeComponent*>(c);
KALDI_ASSERT(cc != NULL);
ConvertRepeatedToBlockAffine(cc);
}
}
}
std::string NnetInfo(const Nnet &nnet) {
std::ostringstream ostr;
if (IsSimpleNnet(nnet)) {
int32 left_context, right_context;
// this call will crash if the nnet is not 'simple'.
ComputeSimpleNnetContext(nnet, &left_context, &right_context);
ostr << "left-context: " << left_context << "\n";
ostr << "right-context: " << right_context << "\n";
}
ostr << "input-dim: " << nnet.InputDim("input") << "\n";
ostr << "ivector-dim: " << nnet.InputDim("ivector") << "\n";
ostr << "output-dim: " << nnet.OutputDim("output") << "\n";
ostr << "# Nnet info follows.\n";
ostr << nnet.Info();
return ostr.str();
}
void SetDropoutProportion(BaseFloat dropout_proportion,
Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
DropoutComponent *dc = dynamic_cast<DropoutComponent*>(comp);
if (dc != NULL)
dc->SetDropoutProportion(dropout_proportion);
DropoutMaskComponent *mc =
dynamic_cast<DropoutMaskComponent*>(nnet->GetComponent(c));
if (mc != NULL)
mc->SetDropoutProportion(dropout_proportion);
GeneralDropoutComponent *gdc =
dynamic_cast<GeneralDropoutComponent*>(nnet->GetComponent(c));
if (gdc != NULL)
gdc->SetDropoutProportion(dropout_proportion);
}
}
bool HasBatchnorm(const Nnet &nnet) {
for (int32 c = 0; c < nnet.NumComponents(); c++) {
const Component *comp = nnet.GetComponent(c);
if (dynamic_cast<const BatchNormComponent*>(comp) != NULL)
return true;
}
return false;
}
void ScaleBatchnormStats(BaseFloat batchnorm_stats_scale,
Nnet *nnet) {
KALDI_ASSERT(batchnorm_stats_scale >= 0.0 && batchnorm_stats_scale <= 1.0);
if (batchnorm_stats_scale == 1.0)
return;
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
BatchNormComponent *bc = dynamic_cast<BatchNormComponent*>(comp);
if (bc != NULL)
bc->Scale(batchnorm_stats_scale);
}
}
void RecomputeStats(const std::vector<NnetExample> &egs, Nnet *nnet) {
KALDI_LOG << "Recomputing stats on nnet (affects batch-norm)";
ZeroComponentStats(nnet);
NnetComputeProbOptions opts;
opts.store_component_stats = true;
NnetComputeProb prob_computer(opts, nnet);
for (size_t i = 0; i < egs.size(); i++)
prob_computer.Compute(egs[i]);
prob_computer.PrintTotalStats();
KALDI_LOG << "Done recomputing stats.";
}
void SetBatchnormTestMode(bool test_mode, Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
BatchNormComponent *bc = dynamic_cast<BatchNormComponent*>(comp);
if (bc != NULL)
bc->SetTestMode(test_mode);
}
}
void SetDropoutTestMode(bool test_mode, Nnet *nnet) {
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
RandomComponent *rc = dynamic_cast<RandomComponent*>(comp);
if (rc != NULL)
rc->SetTestMode(test_mode);
}
}
void ResetGenerators(Nnet *nnet){
for (int32 c = 0; c < nnet->NumComponents(); c++) {
Component *comp = nnet->GetComponent(c);
RandomComponent *rc = dynamic_cast<RandomComponent*>(comp);
if (rc != NULL)
rc->ResetGenerator();
}
}
void FindOrphanComponents(const Nnet &nnet, std::vector<int32> *components) {
int32 num_components = nnet.NumComponents(), num_nodes = nnet.NumNodes();
std::vector<bool> is_used(num_components, false);
for (int32 i = 0; i < num_nodes; i++) {
if (nnet.IsComponentNode(i)) {
int32 c = nnet.GetNode(i).u.component_index;
KALDI_ASSERT(c >= 0 && c < num_components);
is_used[c] = true;
}
}
components->clear();
for (int32 i = 0; i < num_components; i++)
if (!is_used[i])
components->push_back(i);
}
void FindOrphanNodes(const Nnet &nnet, std::vector<int32> *nodes) {
std::vector<std::vector<int32> > depend_on_graph, dependency_graph;
NnetToDirectedGraph(nnet, &depend_on_graph);
// depend_on_graph[i] is a list of all the nodes that depend on i.
ComputeGraphTranspose(depend_on_graph, &dependency_graph);
// dependency_graph[i] is a list of all the nodes that i depends on,
// to be computed.
// Find all nodes required to produce the outputs.
int32 num_nodes = nnet.NumNodes();
assert(num_nodes == static_cast<int32>(dependency_graph.size()));
std::vector<bool> node_is_required(num_nodes, false);
std::vector<int32> queue;
for (int32 i = 0; i < num_nodes; i++) {
if (nnet.IsOutputNode(i))
queue.push_back(i);
}
while (!queue.empty()) {
int32 i = queue.back();
queue.pop_back();
if (!node_is_required[i]) {
node_is_required[i] = true;
for (size_t j = 0; j < dependency_graph[i].size(); j++)
queue.push_back(dependency_graph[i][j]);
}
}
nodes->clear();
for (int32 i = 0; i < num_nodes; i++) {
if (!node_is_required[i])
nodes->push_back(i);
}
}
// Parameters used in applying SVD:
// 1. Energy threshold : For each Affine weights layer in the original baseline nnet3 model,
// we perform SVD based factoring of the weights matrix of the layer,
// into a singular values (left diagonal) matrix, and two Eigen matrices.
//
// SVD : Wx = UEV, U,V are Eigen matrices, and E is the singularity matrix)
//
// We take the center matrix E, and consider only the Singular values which contribute
// to (Energy-threshold) times the total Energy of Singularity parameters.
// These Singularity parameters are actually sorted in descending order and lower
// values are pruned out until the Total energy (Sum of squares) of the pruned set
// of parameters is just above (Energy-threshold * Total init energy). The values which
// are pruned away are replaced with 0 in the Singularity matrix
// and the Weights matrix after SVD is derived with shrinked dimensions.
//
// 2. Shrinkage-threshold : If the Shrinkage ratio of the SVD refactored Weights matrix
// is higher than Shrinkage-threshold for any of the Tdnn layers,
// the SVD process is aborted for that particular Affine weights layer.
//
// this class implements the internals of the edit directive 'apply-svd'.
class SvdApplier {
public:
SvdApplier(const std::string component_name_pattern,
int32 bottleneck_dim,
BaseFloat energy_threshold,
BaseFloat shrinkage_threshold,
Nnet *nnet): nnet_(nnet),
bottleneck_dim_(bottleneck_dim),
energy_threshold_(energy_threshold),
shrinkage_threshold_(shrinkage_threshold),
component_name_pattern_(component_name_pattern) { }
void ApplySvd() {
DecomposeComponents();
if (!modified_component_info_.empty())
ModifyTopology();
KALDI_LOG << "Decomposed " << modified_component_info_.size()
<< " components with SVD dimension " << bottleneck_dim_;
}
private:
// This function finds components to decompose and decomposes them, adding _a and
// _b versions of those components to the nnet while not removing the original
// ones. Does not affect the graph topology.
void DecomposeComponents() {
int32 num_components = nnet_->NumComponents();
modification_index_.resize(num_components, -1);
for (int32 c = 0; c < num_components; c++) {
Component *component = nnet_->GetComponent(c);
std::string component_name = nnet_->GetComponentName(c);
if (NameMatchesPattern(component_name.c_str(),
component_name_pattern_.c_str())) {
AffineComponent *affine = dynamic_cast<AffineComponent*>(component);
if (affine == NULL) {
KALDI_WARN << "Not decomposing component " << component_name
<< " as it is not an AffineComponent.";
continue;
}
int32 input_dim = affine->InputDim(),
output_dim = affine->OutputDim();
if (input_dim <= bottleneck_dim_ || output_dim <= bottleneck_dim_) {
KALDI_WARN << "Not decomposing component " << component_name
<< " with SVD to rank " << bottleneck_dim_
<< " because its dimension is " << input_dim
<< " -> " << output_dim;
continue;
}
Component *component_a = NULL, *component_b = NULL;
if (DecomposeComponent(component_name, *affine, &component_a, &component_b)) {
size_t n = modified_component_info_.size();
modification_index_[c] = n;
modified_component_info_.resize(n + 1);
ModifiedComponentInfo &info = modified_component_info_[n];
info.component_index = c;
info.component_name = component_name;
info.component_name_a = component_name + "_a";
info.component_name_b = component_name + "_b";
if (nnet_->GetComponentIndex(info.component_name_a) >= 0)
KALDI_ERR << "Neural network already has a component named "
<< info.component_name_a;
if (nnet_->GetComponentIndex(info.component_name_b) >= 0)
KALDI_ERR << "Neural network already has a component named "
<< info.component_name_b;
info.component_a_index = nnet_->AddComponent(info.component_name_a,
component_a);
info.component_b_index = nnet_->AddComponent(info.component_name_b,
component_b);
}
}
}
KALDI_LOG << "Converted " << modified_component_info_.size()
<< " components to FixedAffineComponent.";
}
// This function finds the minimum index of
// the Descending order sorted [input_vector],
// over a range of indices from [lower] to [upper] index,
// for which the sum of elements upto the found min. index is greater
// than [min_val].
// We add one to this index to return the reduced dimension value.
int32 GetReducedDimension(const Vector<BaseFloat> &input_vector,
int32 lower,
int32 upper,
BaseFloat min_val) {
BaseFloat sum = 0;
int32 i = 0;
for (i = lower; i <= upper; i++) {
sum = sum + input_vector(i);
if (sum >= min_val) break;
}
return (i+1);
}
// Here we perform SVD based refactorig of an input Affine component.
// After applying SVD , we sort the Singularity values in descending order,
// and take the subset of values which contribute to energy_threshold times
// total original sum of squared singular values, and then refactor the Affine
// component using only these selected singular values, thus making the bottleneck
// dim of the refactored Affine layer equal to the no. of Singular values selected.
// This function returs false if the shrinkage ratio of the total no. of parameters,
// after the above SVD based refactoring, is greater than shrinkage threshold.
//
bool DecomposeComponent(const std::string &component_name,
const AffineComponent &affine,
Component **component_a_out,
Component **component_b_out) {
int32 input_dim = affine.InputDim(), output_dim = affine.OutputDim();
Matrix<BaseFloat> linear_params(affine.LinearParams());
Vector<BaseFloat> bias_params(affine.BiasParams());
int32 middle_dim = std::min<int32>(input_dim, output_dim);
// note: 'linear_params' is of dimension output_dim by input_dim.
Vector<BaseFloat> s(middle_dim);
Matrix<BaseFloat> A(middle_dim, input_dim),
B(output_dim, middle_dim);
linear_params.Svd(&s, &B, &A);
// make sure the singular values are sorted from greatest to least value.
SortSvd(&s, &B, &A);
Vector<BaseFloat> s2(s.Dim());
s2.AddVec2(1.0, s);
BaseFloat s2_sum_orig = s2.Sum();
KALDI_ASSERT(energy_threshold_ < 1);
KALDI_ASSERT(shrinkage_threshold_ < 1);
if (energy_threshold_ > 0) {
BaseFloat min_singular_sum = energy_threshold_ * s2_sum_orig;
bottleneck_dim_ = GetReducedDimension(s2, 0, s2.Dim()-1, min_singular_sum);
}
SubVector<BaseFloat> this_part(s2, 0, bottleneck_dim_);
BaseFloat s2_sum_reduced = this_part.Sum();
BaseFloat shrinkage_ratio =
static_cast<BaseFloat>(bottleneck_dim_ * (input_dim+output_dim))
/ static_cast<BaseFloat>(input_dim * output_dim);
if (shrinkage_ratio > shrinkage_threshold_) {
KALDI_LOG << "Shrinkage ratio " << shrinkage_ratio
<< " greater than threshold : " << shrinkage_threshold_
<< " Skipping SVD for this layer.";
return false;
}
s.Resize(bottleneck_dim_, kCopyData);
A.Resize(bottleneck_dim_, input_dim, kCopyData);
B.Resize(output_dim, bottleneck_dim_, kCopyData);
KALDI_LOG << "For component " << component_name
<< " singular value squared sum changed by "
<< (s2_sum_orig - s2_sum_reduced)
<< " (from " << s2_sum_orig << " to " << s2_sum_reduced << ")";
KALDI_LOG << "For component " << component_name
<< " dimension reduced from "
<< " (" << input_dim << "," << output_dim << ")"
<< " to [(" << input_dim << "," << bottleneck_dim_
<< "), (" << bottleneck_dim_ << "," << output_dim <<")]";
KALDI_LOG << "shrinkage ratio : " << shrinkage_ratio;
// we'll divide the singular values equally between the two
// parameter matrices.
s.ApplyPow(0.5);
A.MulRowsVec(s);
B.MulColsVec(s);
CuMatrix<BaseFloat> A_cuda(A), B_cuda(B);
CuVector<BaseFloat> bias_params_cuda(bias_params);
LinearComponent *component_a = new LinearComponent(A_cuda);
NaturalGradientAffineComponent *component_b =
new NaturalGradientAffineComponent(B_cuda, bias_params_cuda);
// set the learning rates, max-change, and so on.
component_a->SetUpdatableConfigs(affine);
component_b->SetUpdatableConfigs(affine);
*component_a_out = component_a;
*component_b_out = component_b;
return true;
}
// This function modifies the topology of the neural network, splitting
// up the components we're modifying into two parts.
// Suppose we have something like:
// component-node name=some_node component=some_component input=
// nodes_to_modify will be a list of component-node indexes that we
// need to split into two. These will be nodes like
// component-node name=component_node_name component=component_name input=xxx
// where 'component_name' is one of the components that we're splitting.
// node_names_modified is nnet_->node_names_ except with, for the nodes that
// we are splitting in two, "some_node_name" replaced with
// "some_node_name_b" (the second of the two split nodes).
void ModifyTopology() {
std::set<int32> nodes_to_modify;
std::vector<std::string> node_names_orig = nnet_->GetNodeNames(),
node_names_modified = node_names_orig;
// The following loop sets up 'nodes_to_modify' and 'node_names_modified'.
for (int32 n = 0; n < nnet_->NumNodes(); n++) {
if (nnet_->IsComponentNode(n)) {
NetworkNode &node = nnet_->GetNode(n);
int32 component_index = node.u.component_index,
modification_index = modification_index_[component_index];
if (modification_index >= 0) {
// This is a component-node for one of the components that we're
// splitting in two.
nodes_to_modify.insert(n);
std::string node_name = node_names_orig[n],
node_name_b = node_name + "_b";
node_names_modified[n] = node_name_b;
}
}
}
// config_os is a stream to which we are printing lines that we'll later
// read using nnet_->ReadConfig().
std::ostringstream config_os;
// The following loop writes to 'config_os'. The the code is modified from
// the private function Nnet::GetAsConfigLine(), and from
// Nnet::GetConfigLines().
for (int32 n = 0; n < nnet_->NumNodes(); n++) {
if (nnet_->IsComponentInputNode(n) || nnet_->IsInputNode(n)) {
// component-input descriptor nodes aren't handled separately from their
// associated components (we deal with them along with their
// component-node); and input-nodes won't be affected so we don't have
// to print anything.
continue;
}
const NetworkNode &node = nnet_->GetNode(n);
int32 c = node.u.component_index; // 'c' will only be meaningful if the
// node is a component-node.
std::string node_name = node_names_orig[n];
if (node.node_type == kComponent && modification_index_[c] >= 0) {
ModifiedComponentInfo &info = modified_component_info_[
modification_index_[c]];
std::string node_name_a = node_name + "_a",
node_name_b = node_name + "_b";
// we print two component-nodes, the "a" an "b". The original
// one will later be removed when we call RemoveOrphanNodes().
config_os << "component-node name=" << node_name_a << " component="
<< info.component_name_a << " input=";
nnet_->GetNode(n-1).descriptor.WriteConfig(config_os, node_names_modified);
config_os << "\n";
config_os << "component-node name=" << node_name_b << " component="
<< info.component_name_b << " input=" << node_name_a << "\n";
} else {
// This code is modified from Nnet::GetAsConfigLine(). The key difference
// is that we're using node_names_modified, which will replace all the
// nodes we're splitting with their "b" versions.
switch (node.node_type) {
case kDescriptor:
// assert that it's an output-descriptor, not one describing the input to
// a component-node.
KALDI_ASSERT(nnet_->IsOutputNode(n));
config_os << "output-node name=" << node_name << " input=";
node.descriptor.WriteConfig(config_os, node_names_modified);
config_os << " objective=" << (node.u.objective_type == kLinear ?
"linear" : "quadratic");
break;
case kComponent:
config_os << "component-node name=" << node_name << " component="
<< nnet_->GetComponentName(node.u.component_index)
<< " input=";
nnet_->GetNode(n-1).descriptor.WriteConfig(config_os,
node_names_modified);
break;
case kDimRange:
config_os << "dim-range-node name=" << node_name << " input-node="
<< node_names_modified[node.u.node_index]
<< " dim-offset=" << node.dim_offset
<< " dim=" << node.dim;
break;
default:
KALDI_ERR << "Unexpected node type.";
}
config_os << "\n";
}
}
std::istringstream config_is(config_os.str());
nnet_->ReadConfig(config_is);
nnet_->RemoveOrphanNodes();
nnet_->RemoveOrphanComponents();
}
// modification_index_ is a vector with dimension equal to the number of
// components nnet_ had at entry. For each component that we are decomposing,
// it contains an index >= 0 into the 'component_info_' vector; for each
// component that we are not decomposing, it contains -1.
// with SVD.
std::vector<int32> modification_index_;
struct ModifiedComponentInfo {
int32 component_index; // Index of the component we are modifying.
std::string component_name; // The original name of the component,
// e.g. "some_component".
std::string component_name_a; // The original name of the component, plus "_a"
// e.g. "some_component_a".
std::string component_name_b; // The original name of the component, plus "_b"
// e.g. "some_component_b".
int32 component_a_index; // component-index of the left part of the
// decomposed component, which will have a name
// like "some_component_a".
int32 component_b_index; // component-index of the right part of the
// decomposed component, which will have a name
// like "some_component_b".
};
std::vector<ModifiedComponentInfo> modified_component_info_;
Nnet *nnet_;
int32 bottleneck_dim_;
BaseFloat energy_threshold_;
BaseFloat shrinkage_threshold_;
std::string component_name_pattern_;
};
/*
Does an update that moves M closer to being a (matrix with orthonormal rows)
times 'scale'. Note: this will diverge if we start off with singular values
too far from 'scale'.
This function requires 'scale' to be nonzero. If 'scale' is negative, then it
will be set internally to the value that ensures the change in M is orthogonal to
M (viewed as a vector).
*/
void ConstrainOrthonormalInternal(BaseFloat scale,
const std::string &component_name,
CuMatrixBase<BaseFloat> *M) {
KALDI_ASSERT(scale != 0.0);
// We'd like to enforce the rows of M to be orthonormal.
// define P = M M^T. If P is unit then M has orthonormal rows.
// We actually want P to equal scale^2 * I, so that M's rows are
// orthogonal with 2-norms equal to 'scale'.
// We (notionally) add to the objective function, the value
// -alpha times the sum of squared elements of Q = (P - scale^2 * I).
int32 rows = M->NumRows(), cols = M->NumCols();
CuMatrix<BaseFloat> M_update(rows, cols);
CuMatrix<BaseFloat> P(rows, rows);
P.SymAddMat2(1.0, *M, kNoTrans, 0.0);
P.CopyLowerToUpper();
// The 'update_speed' is a constant that determines how fast we approach a
// matrix with the desired properties (larger -> faster). Larger values will