-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnnet-computation-graph.cc
More file actions
2001 lines (1825 loc) · 80.2 KB
/
nnet-computation-graph.cc
File metadata and controls
2001 lines (1825 loc) · 80.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// nnet3/nnet-computation-graph.cc
// Copyright 2015 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 <deque>
#include "nnet3/nnet-computation-graph.h"
#include "nnet3/nnet-graph.h"
namespace kaldi {
namespace nnet3 {
int32 ComputationGraph::GetCindexId(const Cindex &cindex,
bool input, bool *is_new) {
typedef unordered_map<Cindex, int32, CindexHasher> map_type;
int32 new_index = cindexes.size(); // we'll add this if we don't find it.
std::pair<map_type::iterator, bool> p = cindex_to_cindex_id_.insert(
std::pair<Cindex, int32>(cindex, new_index));
if (p.second == true) { // We added something to the hash.
*is_new = true;
KALDI_ASSERT(is_input.size() == cindexes.size());
cindexes.push_back(cindex);
is_input.push_back(input);
// make room for this "dependencies" entry.
dependencies.resize(new_index + 1);
return new_index;
} else { // We did not add anything.
*is_new = false;
return p.first->second;
}
}
int32 ComputationGraph::GetCindexId(const Cindex &cindex) const {
typedef unordered_map<Cindex, int32, CindexHasher> map_type;
map_type::const_iterator iter = cindex_to_cindex_id_.find(cindex);
if (iter == cindex_to_cindex_id_.end())
return -1;
else
return iter->second;
}
void ComputationGraph::Renumber(int32 start_cindex_id,
const std::vector<bool> &keep) {
int32 old_num_cindex_ids = cindexes.size();
KALDI_ASSERT(keep.size() == old_num_cindex_ids - start_cindex_id);
// count_before_renumbering is the number of cindex_ids >= start_cindex_id,
// before renumbering.
int32 count_before_renumbering = old_num_cindex_ids - start_cindex_id;
std::vector<int32> old2new(count_before_renumbering, -1), new2old;
new2old.reserve(old_num_cindex_ids);
for (int32 j = 0; j < count_before_renumbering; j++) {
if (keep[j]) {
old2new[j] = new2old.size() + start_cindex_id;
new2old.push_back(j + start_cindex_id);
}
}
// count_after_renumbering is the number of cindex_ids >= start_cindex_id,
// after renumbering.
int32 count_after_renumbering = new2old.size(),
new_num_cindex_ids = start_cindex_id + count_after_renumbering;
if (count_after_renumbering == count_before_renumbering) {
// this is an optimization for when we are not deleting any
// cindex-ids.
return;
}
for (int32 old_cindex_id = start_cindex_id;
old_cindex_id < old_num_cindex_ids; old_cindex_id++) {
int32 new_cindex_id = old2new[old_cindex_id - start_cindex_id];
Cindex &cindex = cindexes[old_cindex_id];
if (new_cindex_id == -1) {
cindex_to_cindex_id_.erase(cindex);
} else if (new_cindex_id != old_cindex_id) {
cindex_to_cindex_id_[cindex] = new_cindex_id;
}
}
std::vector<int32> temp;
for (int32 c = start_cindex_id; c < new_num_cindex_ids; c++) {
int32 d = new2old[c - start_cindex_id];
// note: d >= c, which is why we do not overwrite data here.
KALDI_PARANOID_ASSERT(d >= c);
cindexes[c] = cindexes[d];
is_input[c] = is_input[d];
// if c == d, we need to create a temporary copy.
const std::vector<int32> &src_dependencies =
(c == d ? (temp = dependencies[d]) : dependencies[d]);
std::vector<int32>::const_iterator
iter = src_dependencies.begin(), end = src_dependencies.end();
dependencies[c].clear();
for (; iter != end; ++iter) {
int32 old_dep = *iter;
if (old_dep < start_cindex_id) {
dependencies[c].push_back(old_dep);
} else {
int32 new_dep = old2new[old_dep - start_cindex_id];
if (new_dep != -1)
dependencies[c].push_back(new_dep);
else
KALDI_ERR << "Dependency on nonexistent cindex-id";
}
}
}
cindexes.resize(new_num_cindex_ids);
is_input.resize(new_num_cindex_ids);
dependencies.resize(new_num_cindex_ids);
}
void ComputationGraphBuilder::PrintCindexId(std::ostream &os,
int32 cindex_id) const {
KALDI_ASSERT(static_cast<size_t>(cindex_id) < graph_->cindexes.size());
const Cindex &cindex = graph_->cindexes[cindex_id];
const std::string &node_name = nnet_.GetNodeName(cindex.first);
os << node_name << '(' << cindex.second.n << ", " << cindex.second.t
<< ", " << cindex.second.x << ')';
}
void ComputationGraphBuilder::ExplainWhyNotComputable(
int32 first_cindex_id) const {
int32 max_lines_print = 100;
std::deque<int32> cindexes_to_explain;
cindexes_to_explain.push_back(first_cindex_id);
KALDI_ASSERT(graph_->cindexes.size() == graph_->dependencies.size());
std::ostringstream os;
os << "*** cindex ";
PrintCindexId(os, first_cindex_id);
os << " is not computable for the following reason: ***\n";
for (int32 num_lines_printed = 0;
num_lines_printed < max_lines_print && !cindexes_to_explain.empty();
num_lines_printed++) {
int32 cindex_id = cindexes_to_explain.front();
cindexes_to_explain.pop_front();
KALDI_ASSERT(static_cast<size_t>(cindex_id) < graph_->cindexes.size());
PrintCindexId(os, cindex_id);
os << " is " << static_cast<ComputableInfo>(
computable_info_[cindex_id]) << ", dependencies: ";
const std::vector<int32> dependencies = graph_->dependencies[cindex_id];
std::vector<int32>::const_iterator iter = dependencies.begin(),
end = dependencies.end();
for (; iter != end; iter++) {
int32 dep_cindex_id = *iter;
PrintCindexId(os, dep_cindex_id);
ComputableInfo status = static_cast<ComputableInfo>(
computable_info_[cindex_id]);
if (status != kComputable) {
os << '[' << status << ']';
cindexes_to_explain.push_back(dep_cindex_id);
}
if (iter+2 != end)
os << ", ";
}
os << "\n";
}
os << "\n";
KALDI_LOG << os.str();
}
void ComputationGraph::Print(std::ostream &os,
const std::vector<std::string> &node_names) {
int32 max_cindexes_per_line = 50, max_dependencies = 5,
num_cindexes = cindexes.size();
std::vector<std::pair<Cindex, std::vector<Cindex> > > pairs;
pairs.reserve(num_cindexes);
for (int32 cindex_id = 0; cindex_id < num_cindexes; cindex_id++) {
int32 size = dependencies[cindex_id].size();
std::vector<Cindex> deps(size);
for (size_t i = 0; i < size; i++)
deps[i] = cindexes[dependencies[cindex_id][i]];
std::sort(deps.begin(), deps.end());
pairs.push_back(std::pair<Cindex, std::vector<Cindex> >(cindexes[cindex_id],
deps));
}
std::sort(pairs.begin(), pairs.end());
int32 cur_start = 0;
for (int32 i = 0; i < num_cindexes; i++) {
if (pairs[i].first.first != pairs[cur_start].first.first) {
cur_start = i;
os << "\n";
}
if (i - cur_start < max_cindexes_per_line) {
os << "[ ";
PrintCindex(os, pairs[i].first, node_names);
if (! is_input[GetCindexId(pairs[i].first)]) {
// only print out dependences for cindexes that
// were not provided as inputs.
os << " -> ";
for (int32 j = 0; j < pairs[i].second.size(); j++) {
if (j < max_dependencies) {
PrintCindex(os, pairs[i].second[j], node_names);
if (j + 1 < pairs[i].second.size())
os << ", ";
} else if (j == max_dependencies) {
os << "...";
}
}
}
os << " ] ";
} else if (i - cur_start == max_cindexes_per_line) {
os << "...";
}
}
os << "\n";
}
// inline
void ComputationGraphBuilder::AddCindexId(int32 cindex_id,
bool is_input,
bool is_output) {
// If this cindex_id has just now been added to the graph, the following
// assert should succeed.
KALDI_PARANOID_ASSERT(cindex_id == computable_queued_.size() &&
cindex_id == computable_info_.size() &&
cindex_id == depend_on_this_.size() &&
cindex_id == usable_count_.size());
if (is_input) {
computable_info_.push_back(kComputable);
computable_queued_.push_back(false);
} else {
computable_info_.push_back(kUnknown);
// add to the queue of things for which we need to compute their computable
// status.
computable_queued_.push_back(false);
next_queue_.push_back(cindex_id);
}
depend_on_this_.push_back(std::vector<int32>());
usable_count_.push_back(is_output ? 1 : 0);
}
void ComputationGraphBuilder::AddInputs() {
int32 num_added = 0;
for (int32 i = 0; i < request_->inputs.size(); i++) {
int32 n = nnet_.GetNodeIndex(request_->inputs[i].name);
if (n == -1)
KALDI_ERR << "Network has no input with name "
<< request_->inputs[i].name;
NodeType t = nnet_.GetNode(n).node_type;
KALDI_ASSERT((t == kInput || t == kComponent) &&
"Inputs to graph only allowed for Input and Component nodes.");
for (int32 j = 0; j < request_->inputs[i].indexes.size(); j++) {
Cindex cindex(n, request_->inputs[i].indexes[j]);
bool is_input = true, is_new;
int32 cindex_id = graph_->GetCindexId(cindex, is_input, &is_new);
KALDI_ASSERT(is_new && "Input index seems to be listed more than once");
AddCindexId(cindex_id, true, false);
num_added++;
}
}
KALDI_ASSERT(num_added > 0 && "AddInputToGraph: nothing to add.");
}
void ComputationGraphBuilder::AddOutputs() {
int32 num_added = 0;
for (int32 i = 0; i < request_->outputs.size(); i++) {
int32 n = nnet_.GetNodeIndex(request_->outputs[i].name);
if (n == -1)
KALDI_ERR << "Network has no output with name "
<< request_->outputs[i].name;
for (int32 j = 0; j < request_->outputs[i].indexes.size(); j++) {
Cindex cindex(n, request_->outputs[i].indexes[j]);
bool is_input = false, is_new;
int32 cindex_id = graph_->GetCindexId(cindex, is_input, &is_new);
KALDI_ASSERT(is_new && "Output index seems to be listed more than once");
AddCindexId(cindex_id, false, true);
num_added++;
}
}
if (num_added == 0) {
KALDI_ERR << "Cannot process computation request with no outputs";
}
current_distance_ = 0;
// the calls to AddCindexId in this function will have added to next_queue_.
KALDI_ASSERT(current_queue_.empty());
current_queue_.swap(next_queue_);
}
bool ComputationGraphBuilder::AllOutputsAreComputable() const {
char is_computable_char = static_cast<char>(kComputable);
std::vector<char>::const_iterator iter = computable_info_.begin(),
end = computable_info_.end();
for (int32 cindex_id = 0; iter != end; ++iter, ++cindex_id) {
if (*iter != is_computable_char) { // is not computable.
int32 network_node = graph_->cindexes[cindex_id].first;
if (nnet_.IsOutputNode(network_node))
return false;
}
}
return true;
}
std::ostream& operator << (std::ostream &os,
const ComputationGraphBuilder::ComputableInfo &info) {
switch (info) {
case ComputationGraphBuilder::kUnknown: os << "kUnknown";
break;
case ComputationGraphBuilder::kComputable: os << "kComputable";
break;
case ComputationGraphBuilder::kNotComputable: os << "kNotComputable";
break;
case ComputationGraphBuilder::kWillNotCompute: os << "kWillNotCompute";
break;
default: os << "[invalid enum value]"; break;
}
return os;
}
// Prints logging info to explain why all outputs are not computable.
void ComputationGraphBuilder::ExplainWhyAllOutputsNotComputable() const {
std::vector<int32> outputs_not_computable;
int32 num_outputs_total = 0;
std::vector<Cindex>::const_iterator iter = graph_->cindexes.begin(),
end = graph_->cindexes.end();
for (int32 cindex_id = 0; iter != end; ++iter,++cindex_id) {
int32 network_node = iter->first;
ComputableInfo c = static_cast<ComputableInfo>(computable_info_[cindex_id]);
if (nnet_.IsOutputNode(network_node)) {
num_outputs_total++;
if (c != kComputable)
outputs_not_computable.push_back(cindex_id);
}
}
KALDI_ASSERT(!outputs_not_computable.empty() &&
"You called this function when everything was computable.");
int32 num_print = 10, num_not_computable = outputs_not_computable.size();
KALDI_LOG << num_not_computable << " output cindexes out of "
<< num_outputs_total << " were not computable.";
std::ostringstream os;
request_->Print(os);
KALDI_LOG << "Computation request was: " << os.str();
if (num_not_computable > num_print)
KALDI_LOG << "Printing the reasons for " << num_print << " of these.";
for (int32 i = 0; i < num_not_computable && i < num_print; i++)
ExplainWhyNotComputable(outputs_not_computable[i]);
}
// this function limits the dependencies of cindex_id "cindex_id" to just those
// which are actually used in computing it. It also clears the dependencies
// of those cindexes that are not computable.
void ComputationGraphBuilder::PruneDependencies(int32 cindex_id) {
ComputableInfo c = static_cast<ComputableInfo>(computable_info_[cindex_id]);
// by the time this is called, there should be no cindexes with unknown state.
KALDI_ASSERT(c != kUnknown);
if (c == kNotComputable || c == kWillNotCompute) {
// if something is not computable, there is no point
// keeping around its dependencies.
graph_->dependencies[cindex_id].clear();
return;
}
KALDI_ASSERT(c == kComputable);
const Cindex &cindex = graph_->cindexes[cindex_id];
int32 node_id = cindex.first;
const Index &index = cindex.second;
const NetworkNode &node = nnet_.GetNode(node_id);
std::vector<int32> &dependencies = graph_->dependencies[cindex_id];
std::sort(dependencies.begin(), dependencies.end());
std::vector<int32> used_cindex_ids;
switch (node.node_type) {
case kDescriptor: {
const Descriptor &desc = node.descriptor;
bool dont_care = false; // there should be no kUnknown, and we check this
CindexSet cindex_set(*graph_, computable_info_, dont_care);
std::vector<Cindex> used_cindexes;
bool ans = desc.IsComputable(index, cindex_set, &used_cindexes);
// If the next assert fails it could be a failure in the assumption that
// making more inputs available will never change something from not being
// computable to being computable; or it could be a bug elsewhere.
KALDI_ASSERT(ans);
size_t size = used_cindexes.size();
used_cindex_ids.resize(size);
for (size_t i = 0; i < size; i++) {
int32 dep_cindex_id = graph_->GetCindexId(used_cindexes[i]);
KALDI_ASSERT(dep_cindex_id != -1);
used_cindex_ids[i] = dep_cindex_id;
KALDI_ASSERT(std::binary_search(dependencies.begin(),
dependencies.end(),
dep_cindex_id));
}
break;
}
case kComponent: {
const Component *c = nnet_.GetComponent(node.u.component_index);
bool dont_care = false; // there should be no kUnknown, and we check this
// In the line below, node_id - 1 is the index of the component-input
// node-- the descriptor at the input to the component. We are interested
// in the set of inputs to the component that are computable.
IndexSet index_set(*graph_, computable_info_, node_id - 1, dont_care);
std::vector<Index> used_indexes;
bool ans = c->IsComputable(request_->misc_info, index, index_set,
&used_indexes);
// If the next assert fails it could be a failure in the assumption that
// making more inputs available will never change something from not being
// computable to being computable; or it could be a bug elsewhere.
KALDI_ASSERT(ans);
size_t size = used_indexes.size();
used_cindex_ids.resize(size);
for (size_t i = 0; i < size; i++) {
Cindex dep_cindex(node_id - 1, used_indexes[i]);
int32 dep_cindex_id = graph_->GetCindexId(dep_cindex);
KALDI_ASSERT(dep_cindex_id != -1);
used_cindex_ids[i] = dep_cindex_id;
KALDI_ASSERT(std::binary_search(dependencies.begin(),
dependencies.end(),
dep_cindex_id));
}
break;
}
case kDimRange:
KALDI_ASSERT(dependencies.size() == 1);
// there should be exactly one dependency and it is required, not
// optional, so there is nothing to do here. Return.
return;
case kInput:
KALDI_ASSERT(dependencies.empty());
// there is nothing to do; return.
return;
default:
KALDI_ERR << "Invalid node type";
}
SortAndUniq(&used_cindex_ids);
// the next statement modifies the graph.
dependencies.swap(used_cindex_ids);
}
ComputationGraphBuilder::ComputationGraphBuilder(
const Nnet &nnet,
ComputationGraph *graph):
nnet_(nnet), request_(NULL), graph_(graph),
current_distance_(-1) {
KALDI_ASSERT(graph_->cindexes.empty() &&
"ComputationGraphBuilder initialized with nonempty graph.");
}
void ComputationGraphBuilder::Compute(const ComputationRequest &request) {
if (request_ != NULL && graph_->segment_ends.empty()) {
// this check is relevant to multi-segment (i.e. online) computations.
KALDI_ERR << "You are calling things in the wrong order: should be "
<< "Compute(), Prune(), Compute, Prune(), ...";
}
int32 cur_segment_start = graph_->cindexes.size();
request_ = &request;
AddInputs();
AddOutputs(); // sets current_distance_ to 0.
// max_distance for debugging, to detect infinite recursion.
int32 max_distance = 10000;
while (current_distance_ < max_distance) {
BuildGraphOneIter();
// only check rarely if we're running at low verbose level.
if (GetVerboseLevel() >= 3 || RandInt(1, (current_distance_ + 1)) == 1)
Check(cur_segment_start);
// TODO: come up with a scheme to delay when we call
// UpdateAllComputableInfo().
UpdateAllComputableInfo();
if (current_queue_.empty()) // we're done.
break;
}
if (current_distance_ == max_distance)
KALDI_ERR << "Loop detected while building computation graph (bad "
<< "network topology?)";
if (RandInt(1, 2 * (graph_->segment_ends.size() + 1)) == 1)
Check(cur_segment_start);
}
void ComputationGraphBuilder::Check(int32 start_cindex_id) const {
int32 num_cindex_ids = graph_->cindexes.size();
for (int32 cindex_id = start_cindex_id; cindex_id < num_cindex_ids;
cindex_id += 1 + RandInt(0, num_cindex_ids / 100)) {
{ // check depend_on_this.
std::vector<int32> depend_on_this = depend_on_this_[cindex_id];
int32 size = depend_on_this.size();
std::sort(depend_on_this.begin(), depend_on_this.end());
KALDI_ASSERT(IsSortedAndUniq(depend_on_this));
for (size_t j = 0; j < size; j++) {
int32 other_cindex_id = depend_on_this[j];
// make sure appears in appropriate dependencies array.
const std::vector<int32> &dep = graph_->dependencies[other_cindex_id];
KALDI_ASSERT(std::count(dep.begin(), dep.end(), cindex_id) == 1);
}
}
{ // check dependencies.
std::vector<int32> dependencies = graph_->dependencies[cindex_id];
int32 size = dependencies.size();
std::sort(dependencies.begin(), dependencies.end());
KALDI_ASSERT(IsSortedAndUniq(dependencies));
for (size_t j = 0; j < size; j++) {
int32 dep_cindex_id = dependencies[j];
if (dep_cindex_id >= start_cindex_id) {
// make sure appears in appropriate depend_on_this_ array.
const std::vector<int32> &dep = depend_on_this_[dep_cindex_id];
KALDI_ASSERT(std::count(dep.begin(), dep.end(), cindex_id) == 1);
}
}
}
{
// check usable_count_
int32 node_index = graph_->cindexes[cindex_id].first;
int32 usable_count = usable_count_[cindex_id],
usable_count_recomputed = nnet_.IsOutputNode(node_index) ? 1 : 0;
std::vector<int32> depend_on_this = depend_on_this_[cindex_id];
int32 size = depend_on_this.size();
for (size_t j = 0; j < size; j++) {
int32 other_cindex_id = depend_on_this[j];
if (usable_count_[other_cindex_id] != 0 &&
computable_info_[other_cindex_id] != kNotComputable)
usable_count_recomputed++;
}
KALDI_ASSERT(usable_count == usable_count_recomputed);
}
// check computable_info_. note: this will not be accurate
// if the cindex_id is still queued to have dependencies added
// (in cur_queue_ or next_queue_).
if (computable_queue_.empty()) {
ComputationGraphBuilder::ComputableInfo c =
ComputeComputableInfo(cindex_id);
// the status doesn't have to be correct if it's kWillNotCompute,
// because these are cindex-ids that we chose not to compute
// because we determined they would not be useful, and
// ComputeComputableInfo() will never return this value.
if (c != computable_info_[cindex_id] &&
computable_info_[cindex_id] != kWillNotCompute) {
int32 count_cur = std::count(current_queue_.begin(),
current_queue_.end(), cindex_id),
count_next = std::count(next_queue_.begin(),
next_queue_.end(), cindex_id);
// if it wasn't queued, then something is wrong.
if (count_cur + count_next == 0)
KALDI_ERR << "Mismatch in computable status";
}
}
// check computable_queued_.
// note, the following checks might be a bit slow.
if (computable_queued_[cindex_id]) {
KALDI_ASSERT(std::count(computable_queue_.begin(),
computable_queue_.end(),
cindex_id) == 1);
} else {
KALDI_ASSERT(std::count(computable_queue_.begin(),
computable_queue_.end(),
cindex_id) == 0);
}
}
}
void ComputationGraphBuilder::Prune() {
// Since Prune() is called for each segment in turn [note: there
// will be only 1 segment in the normal non-online case], we
// only prune for the current, just-added segment.
int32 start_cindex_id = (graph_->segment_ends.empty() ? 0 :
graph_->segment_ends.back());
int32 num_cindex_ids = graph_->cindexes.size();
// Prune the dependencies to just those that are used (to remove
// optional dependencies that don't end up getting used).
for (int32 cindex_id = start_cindex_id;
cindex_id < num_cindex_ids; cindex_id++)
PruneDependencies(cindex_id);
// the following clears the elements of depend_on_this from start_cindex_id to
// num_cindex_ids - 1, without touching the entire array.
depend_on_this_.resize(start_cindex_id);
depend_on_this_.resize(num_cindex_ids);
std::vector<bool> required;
ComputeRequiredArray(start_cindex_id, &required);
std::vector<bool> keep(num_cindex_ids - start_cindex_id, false);
for (int32 c = start_cindex_id; c < num_cindex_ids; c++) {
if (required[c - start_cindex_id] || graph_->is_input[c]) {
KALDI_ASSERT(computable_info_[c] == kComputable &&
"You are calling Prune when not everything is computable.");
keep[c - start_cindex_id] = true;
}
}
graph_->Renumber(start_cindex_id, keep);
// We also need to renumber computable_info_ and usable_count_, which
// graph_->Renumber doesn't do for us, but we can make some shortcuts. We set
// all computable_info_ to kComputable because actually it all was kComputable
// (we checked when deciding what to keep); and we set the usable_count_ to 1
// for all the cindex_ids we just added... this is not 100% accurate
// according to the way we defined usable_count_, but it prevents additional
// computation since it is > 0 (notice that IncrementUsableCount and
// DecrementUsableCount may do some work when the usable_count goes to zero or
// from zero. Anyway, the usable-count for these cindex_ids for those "older
// segments" is not critical. [this information only gets used if we process
// additional segments as part of the compilation of an online computation.]
int32 new_num_cindex_ids = graph_->cindexes.size();
computable_info_.resize(start_cindex_id);
computable_info_.resize(new_num_cindex_ids, (char)kComputable);
usable_count_.resize(start_cindex_id);
usable_count_.resize(new_num_cindex_ids, 1);
// depend_on_this_ is a vector of vectors-- keeping track of the reverse of
// the dependencies-- and I believe we won't be needing this information any
// more past this point.
depend_on_this_.resize(start_cindex_id);
depend_on_this_.resize(new_num_cindex_ids);
// computable_queued_ also shouldn't be queried past this point, but
// I believe they should all be false at this point anyway (note that
// we assert below that computable_queue_ is empty).
computable_queued_.resize(new_num_cindex_ids);
KALDI_ASSERT(computable_queue_.empty());
graph_->segment_ends.push_back(new_num_cindex_ids);
}
// Add cindex_ids that this cindex_id depends on.
void ComputationGraphBuilder::AddDependencies(int32 cindex_id) {
if (static_cast<int32>(graph_->dependencies.size()) <= cindex_id) {
graph_->dependencies.resize(2 * cindex_id + 1);
}
Cindex cindex = graph_->cindexes[cindex_id];
// find the dependencies of this cindex.
int32 node_index = cindex.first;
const Index &index = cindex.second;
const NetworkNode &node = nnet_.GetNode(node_index);
std::vector<Cindex> input_cindexes;
// the following switch statement sets up "input_cindexes".
switch (node.node_type) {
case kDescriptor: {
// desc describes how this node obtains its input from other nodes.
const Descriptor &desc = node.descriptor;
desc.GetDependencies(index, &input_cindexes);
break;
}
case kComponent: {
int32 c = node.u.component_index;
const Component *component = nnet_.GetComponent(c);
std::vector<Index> input_indexes;
component->GetInputIndexes(request_->misc_info, index,
&input_indexes);
input_cindexes.resize(input_indexes.size());
for (size_t i = 0; i < input_indexes.size(); i++) {
input_cindexes[i].first = node_index - 1; // preceding node
input_cindexes[i].second = input_indexes[i];
}
break;
}
case kDimRange: {
input_cindexes.resize(1);
input_cindexes[0] = Cindex(node.u.node_index, index);
break;
}
case kInput:
break; // There will be no dependencies.
default:
KALDI_ERR << "Invalid node type";
}
int32 num_dependencies = input_cindexes.size();
// this "reserve" statement is to make sure the reference
// we declare below does not become invalid in the loop below
// (the call to graph_->GetCindexId() could add up to
// num_dependencies elements to the graph_->dependencies array
// and we want to avoid allocation).
// the RoundUpToNearestPowerOfTwo is for efficiency, to
// avoid too-frequent resizes.
graph_->dependencies.reserve(RoundUpToNearestPowerOfTwo(
graph_->dependencies.size() + num_dependencies));
std::vector<int32> &this_dep = graph_->dependencies[cindex_id];
this_dep.resize(num_dependencies);
for (size_t i = 0; i < num_dependencies; i++) {
bool is_input = false, is_new;
int32 dep_cindex_id = graph_->GetCindexId(input_cindexes[i],
is_input, &is_new);
this_dep[i] = dep_cindex_id;
if (is_new)
AddCindexId(dep_cindex_id, false, false);
// we will keep dependent's usable_count_ up to date below
}
// remove duplicates of dependencies.
SortAndUniq(&this_dep);
// set up the "depend_on_this_" array.
std::vector<int32>::const_iterator iter = this_dep.begin(),
end = this_dep.end();
// Populate the "depend_on_this_" array, and append the
// usable_count_ of things we depend on (see the definition
// of this quantity next to where it is declared).
// Note: before calling AddDependencies() we verified the following:
// computable_info_[cindex_id] == kUnknown
// and
// usable_count_[cindex_id] != 0
// which ensures that the conditions to increment the dependency's
// usable_count_ are satisfied.
for (; iter != end; ++iter) {
int32 dep_cindex_id = *iter;
depend_on_this_[dep_cindex_id].push_back(cindex_id);
IncrementUsableCount(dep_cindex_id);
}
// Now that we've added the dependencies, we can put this into
// the computable_queue_ to assess whether it's computable
KALDI_ASSERT(computable_info_[cindex_id] == kUnknown &&
!computable_queued_[cindex_id]);
// we think it'll be faster in the next line to do push_front instead of
// push_back; either one would be correct.
computable_queue_.push_front(cindex_id);
computable_queued_[cindex_id] = true;
}
ComputationGraphBuilder::ComputableInfo
ComputationGraphBuilder::ComputeComputableInfo(int32 cindex_id)
const {
const Cindex &cindex = graph_->cindexes[cindex_id];
int32 node_id = cindex.first;
const Index &index = cindex.second;
const NetworkNode &node = nnet_.GetNode(node_id);
switch (node.node_type) {
case kDescriptor: {
const Descriptor &desc = node.descriptor;
{
CindexSet cindex_set(*graph_, computable_info_, false);
if (desc.IsComputable(index, cindex_set, NULL)) {
// it's computable even without counting kUnknown inputs as computable
// [treat_unknown_as_computable = false] -> definitely computable.
return kComputable;
}
}
CindexSet cindex_set2(*graph_, computable_info_, true);
if (!desc.IsComputable(index, cindex_set2, NULL)) {
// it's not computable even when counting kUnknown inputs as
// computable [treat_unknown_as_computable = true] -> definitely not
// computable.
return kNotComputable;
}
return kUnknown;
}
case kComponent: {
const Component *c = nnet_.GetComponent(node.u.component_index);
const int32 input_node_id = node_id - 1;
{
IndexSet index_set(*graph_, computable_info_, input_node_id, false);
if (c->IsComputable(request_->misc_info, index, index_set, NULL)) {
// it's computable even without counting kUnknown inputs as computable
// [treat_unknown_as_computable = false] -> definitely computable.
return kComputable;
}
}
IndexSet index_set2(*graph_, computable_info_, input_node_id, true);
if (!c->IsComputable(request_->misc_info, index, index_set2, NULL)) {
// it's not computable even when counting kUnknown inputs as computable
// [treat_unknown_as_computable = true] -> definitely not computable.
return kNotComputable;
}
return kUnknown;
}
case kDimRange: {
Cindex input_cindex(node.u.node_index, index);
int32 input_cindex_id = graph_->GetCindexId(input_cindex);
if (input_cindex_id != -1)
return ComputableInfo(computable_info_[input_cindex_id]);
else
return kUnknown;
}
case kInput: {
// cindexes for input nodes that are part of the computation request will
// have graph_->is_input[cindex_id] == true; others will have
// graph_->is_input[cindex_id] == true.
return graph_->is_input[cindex_id] ? kComputable : kNotComputable;
}
default:
KALDI_ERR << "Invalid node type.";
return kUnknown; // suppress compiler warning.
}
}
void ComputationGraphBuilder::GetComputableInfo(
std::vector<std::vector<bool> > *computable) const {
KALDI_ASSERT(!graph_->cindexes.empty() &&
"You need to call this after Compute()!");
KALDI_ASSERT(!computable_info_.empty() &&
"You need to call this before Prune()!");
computable->clear();
computable->resize(request_->outputs.size());
for (size_t i = 0; i < request_->outputs.size(); i++) {
const IoSpecification &output = request_->outputs[i];
int32 n = nnet_.GetNodeIndex(output.name);
KALDI_ASSERT(n != -1);
int32 size = output.indexes.size();
std::vector<bool> &this_vec = (*computable)[i];
this_vec.resize(size);
for (size_t j = 0; j < size; j++) {
Cindex cindex(n, output.indexes[j]);
int32 cindex_id = graph_->GetCindexId(cindex);
KALDI_ASSERT(cindex_id != -1);
this_vec[j] = (computable_info_[cindex_id] == kComputable);
}
}
}
void ComputationGraphBuilder::UpdateComputableInfo(int32 cindex_id) {
// if the current computable_info_ for cindex_id value is not kUnknown, this
// cindex_id should not have been in the queue.
KALDI_ASSERT(static_cast<size_t>(cindex_id) < computable_info_.size());
char &output = computable_info_[cindex_id];
KALDI_ASSERT(output == kUnknown);
output = static_cast<char>(ComputeComputableInfo(cindex_id));
if (output != kUnknown) {
// The computable status of cindexes that depend on this cindex and whose
// status is currently kUnknown might now change, so if they are not in the
// computable queue, put them there.
std::vector<int32>::const_iterator iter = depend_on_this_[cindex_id].begin(),
end = depend_on_this_[cindex_id].end();
for (; iter != end; ++iter) {
int32 other_cindex_id = *iter;
if (computable_info_[other_cindex_id] == kUnknown &&
!computable_queued_[other_cindex_id]) {
computable_queue_.push_back(other_cindex_id);
computable_queued_[other_cindex_id] = true;
}
}
if (output == kNotComputable && usable_count_[cindex_id] != 0) {
// If we have just changed the computable state from kUnknown to
// kNotComputable, then given the way the usable_count_ is defined (see
// the declaration), this means that we must decrement the
// usable_count_ of all cindex_ids that we depend on.
std::vector<int32>::const_iterator
iter = graph_->dependencies[cindex_id].begin(),
end = graph_->dependencies[cindex_id].end();
for (; iter != end; ++iter) {
int32 dep_cindex_id = *iter;
DecrementUsableCount(dep_cindex_id);
}
}
}
}
void ComputationGraphBuilder::SetAsWillNotCompute(int32 cindex_id) {
KALDI_ASSERT(usable_count_[cindex_id] == 0);
computable_info_[cindex_id] = kWillNotCompute;
std::vector<int32>::const_iterator iter = depend_on_this_[cindex_id].begin(),
end = depend_on_this_[cindex_id].end();
for (; iter != end; ++iter) {
int32 other_cindex_id = *iter;
if (computable_info_[other_cindex_id] == kUnknown &&
!computable_queued_[other_cindex_id]) {
computable_queue_.push_back(other_cindex_id);
computable_queued_[other_cindex_id] = true;
}
}
}
void ComputationGraphBuilder::UpdateAllComputableInfo() {
while (!computable_queue_.empty()) {
int32 cindex_id = computable_queue_.front();
computable_queue_.pop_front();
computable_queued_[cindex_id] = false;
UpdateComputableInfo(cindex_id);
}
}
void ComputationGraphBuilder::IncrementUsableCount(int32 cindex_id) {
KALDI_PARANOID_ASSERT(static_cast<size_t>(cindex_id)<usable_count_.size());
// the next line post-increments the reachable count.
if (usable_count_[cindex_id]++ == 0 &&
computable_info_[cindex_id] != kNotComputable) {
std::vector<int32>::const_iterator
iter = graph_->dependencies[cindex_id].begin(),
end = graph_->dependencies[cindex_id].end();
for (; iter != end; ++iter) {
int32 dep_cindex_id = *iter;
IncrementUsableCount(dep_cindex_id);
}
}
}
void ComputationGraphBuilder::DecrementUsableCount(int32 cindex_id) {
KALDI_PARANOID_ASSERT(static_cast<size_t>(cindex_id)<usable_count_.size());
KALDI_PARANOID_ASSERT(usable_count_[cindex_id] > 0);
if (--usable_count_[cindex_id] == 0 &&
computable_info_[cindex_id] != kNotComputable) {
std::vector<int32>::const_iterator
iter = graph_->dependencies[cindex_id].begin(),
end = graph_->dependencies[cindex_id].end();
for (; iter != end; ++iter) {
int32 dep_cindex_id = *iter;
DecrementUsableCount(dep_cindex_id);
}
}
}
void ComputationGraphBuilder::BuildGraphOneIter() {
while (!current_queue_.empty()) {
int32 cindex_id = current_queue_.back();
current_queue_.pop_back();
KALDI_ASSERT(computable_info_[cindex_id] == kUnknown);
if (usable_count_[cindex_id] == 0)
SetAsWillNotCompute(cindex_id);
else
AddDependencies(cindex_id);
}
current_queue_.swap(next_queue_); // now next_queue_ will be empty.
current_distance_++;
}
void ComputationGraphBuilder::ComputeRequiredArray(
int32 start_cindex_id,
std::vector<bool> *required) const {
int32 num_cindex_ids = graph_->cindexes.size();
KALDI_ASSERT(num_cindex_ids >= start_cindex_id);
KALDI_ASSERT(computable_info_.size() == num_cindex_ids);
required->clear();
required->resize(num_cindex_ids - start_cindex_id, false);
// would be bool, but indexing c++ bool may be slow.
std::vector<char> is_output_node(nnet_.NumNodes());
for (int32 n = 0; n < nnet_.NumNodes(); n++)
is_output_node[n] = (char)(nnet_.IsOutputNode(n) ? 1 : 0);
std::vector<int32> queue;
for (int32 c = start_cindex_id; c < num_cindex_ids; c++) {
// First put the output cindex_ids into the queue.
int32 node_id = graph_->cindexes[c].first;
if (is_output_node[node_id]) {
(*required)[c - start_cindex_id] = true;
queue.push_back(c);
}
}
while (!queue.empty()) {
int32 c = queue.back();
queue.pop_back();
const std::vector<int32> &dependencies = graph_->dependencies[c];
std::vector<int32>::const_iterator iter = dependencies.begin(),
end = dependencies.end();
for (; iter != end; ++iter) {
int32 d = *iter;
if (d >= start_cindex_id && !(*required)[d - start_cindex_id]){
(*required)[d - start_cindex_id] = true;
queue.push_back(d);
}
}
}
// just check that we don't have any cindex_ids which are required but have
// usable_count_ == 0; this would indicate a bug somewhere.
for (int32 c = start_cindex_id; c < num_cindex_ids; c++)
KALDI_ASSERT(!((*required)[c - start_cindex_id] &&
(usable_count_[c] == 0)));
}
// make our own namespace for helper functions of ComputeComputationGraph.
namespace computation_graph {
// This function adds cindex_ids corresponding to each output
// index, to the graph.
void AddOutputToGraph(const ComputationRequest &request,
const Nnet &nnet,
ComputationGraph *graph) {
int32 num_added = 0;
for (int32 i = 0; i < request.outputs.size(); i++) {
int32 n = nnet.GetNodeIndex(request.outputs[i].name);
if (n == -1)
KALDI_ERR << "Network has no output with name "
<< request.outputs[i].name;
for (int32 j = 0; j < request.outputs[i].indexes.size(); j++) {
Cindex cindex(n, request.outputs[i].indexes[j]);