Repository navigation
Expand file tree
/
Copy pathmodel.cc
More file actions
1518 lines (1382 loc) · 56.6 KB
/
Copy pathmodel.cc
File metadata and controls
1518 lines (1382 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/model.h"
#include <memory>
#include "absl/time/clock.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
namespace data {
namespace model {
namespace {
// Wrapper for the square function to reduce verbosity.
inline double Square(double x) { return x * x; }
// The first input of InterleaveMany corresponds to the input dataset whose
// elements are used to create the (derived) input datasets whose elements are
// interleaved as output.
//
// TODO(jsimsa): model the first input
class InterleaveMany : public Node {
public:
using Node::Node;
virtual ~InterleaveMany() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
return std::make_shared<InterleaveMany>(
Args{id_, name_, std::move(output)});
}
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
if (num_inputs() <= 1) {
(*input_times)[long_name()] = inherited_input_time;
return;
}
// Here `inherited_input_time + SelfProcessingTimeLocked()` is the average
// input time for InterleaveMany node to call one of the
// `(num_inputs() - 1)` input nodes (except first input) to return an
// element. Regardless of the `block_length` parameter of InterleaveMany
// node, the average input time for any of the `(num_inputs() - 1)` input
// nodes to be called is computed as:
double input_time = (inherited_input_time + SelfProcessingTimeLocked()) *
static_cast<double>(num_inputs() - 1);
(*input_times)[long_name()] = input_time;
}
// The output time is the sum of the self processing time and the average
// output time of inputs comprising the interleave "cycle".
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (num_inputs() <= 1) {
(*output_times)[long_name()] = self_processing_time;
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
gradients->erase(node->long_name());
}
}
return;
}
double inputs_output_time =
(OutputTimeForInputs(*output_times) -
(*output_times)[inputs_.front()->long_name()]) /
static_cast<double>(num_inputs() - 1);
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
auto* gradient = gtl::FindOrNull(*gradients, node->long_name());
if (gradient) {
*gradient /= static_cast<double>(num_inputs() - 1);
}
}
(*output_time_gradients)[long_name()] =
OutputTimeGradientsForInputs(*output_time_gradients) -
(*output_time_gradients)[inputs_.front()->long_name()];
// Set derivatives w.r.t. tunable parameters of the subtree rooted in the
// first input equal to 0 since its output time is excluded from
// computations.
absl::flat_hash_map<string, std::shared_ptr<Parameter>>
first_input_parameters;
inputs_.front()->CollectTunableParameters(&first_input_parameters);
for (auto& pair : first_input_parameters) {
(*gradients)[pair.first] = 0.0L;
}
}
(*output_times)[long_name()] = self_processing_time + inputs_output_time;
}
// The processing time is the sum of the self processing time and the average
// processing time of inputs comprising the interleave "cycle".
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (processing_times) {
(*processing_times)[long_name()] = self_processing_time;
}
if (num_inputs() <= 1) {
(*total_processing_times)[long_name()] = self_processing_time;
return;
}
double inputs_processing_time =
(TotalProcessingTimeForInputs(*total_processing_times) -
(*total_processing_times)[inputs_.front()->long_name()]) /
static_cast<double>(num_inputs() - 1);
(*total_processing_times)[long_name()] =
self_processing_time + inputs_processing_time;
}
};
// The first input of AsyncInterleaveMany corresponds to the input dataset whose
// elements are used to create the (derived) input datasets whose elements are
// interleaved as output.
//
// TODO(jsimsa): model the first input
class AsyncInterleaveMany : public Node {
public:
AsyncInterleaveMany(Node::Args args,
std::vector<std::shared_ptr<Parameter>> parameters)
: Node(args) {
for (auto& parameter : parameters) {
parameters_[parameter->name] = std::move(parameter);
}
}
virtual ~AsyncInterleaveMany() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
std::vector<std::shared_ptr<Parameter>> parameters;
for (auto& pair : parameters_) {
parameters.push_back(pair.second);
}
return std::make_shared<AsyncInterleaveMany>(
Args{id_, name_, std::move(output)}, parameters);
}
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
if (num_inputs() <= 1) {
(*input_times)[long_name()] = inherited_input_time;
return;
}
// Here `inherited_input_time + SelfProcessingTimeLocked()` is the average
// input time for AsyncInterleaveMany node to call one of the
// `(num_inputs() - 1)` input nodes (except first input) to return an
// element. Regardless of the `block_length` parameter of
// AsyncInterleaveMany node, the average input time for any of the
// `(num_inputs() - 1)` input nodes to be called is computed as:
double input_time = (inherited_input_time + SelfProcessingTimeLocked()) *
static_cast<double>(num_inputs() - 1);
(*input_times)[long_name()] = input_time;
}
// The output time is the sum of self processing time and expected wait time
// from the buffer model estimated using
// `ComputeWaitTime(producer_time, consumer_time, parallelism, ...)`, where
// `producer_time` is the average output time of inputs comprising the
// interleave "cycle" divided by `parallelism`, `consumer_time` is the
// `input_time` specified through `input_times` divided by `num_inputs() - 1`,
// and if the node has parallelism parameter, then `buffer_size` is derived
// from `parallelism`.
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (num_inputs() <= 1) {
(*output_times)[long_name()] = self_processing_time;
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
gradients->erase(node->long_name());
}
}
return;
}
double output_time, wait_time, consumer_time, producer_time;
double input_time = input_times.at(long_name());
consumer_time = input_time / static_cast<double>(num_inputs() - 1);
double parallelism = num_inputs() - 1; // default to cycle length
auto* parameter = gtl::FindOrNull(parameters_, kParallelism);
if (parameter) {
parallelism = std::min(parallelism, (*parameter)->value);
}
double output_time_for_inputs =
OutputTimeForInputs(*output_times) -
(*output_times)[inputs_.front()->long_name()];
producer_time = output_time_for_inputs /
static_cast<double>(num_inputs() - 1) / parallelism;
if (gradients) {
double producer_time_der = 0.0L;
double consumer_time_der = 0.0L;
double buffer_size_der = 0.0L;
wait_time = ComputeWaitTime(producer_time, consumer_time, parallelism,
&producer_time_der, &consumer_time_der,
&buffer_size_der);
double inputs_time_der_sum =
OutputTimeGradientsForInputs(*output_time_gradients);
(*output_time_gradients)[long_name()] =
consumer_time_der +
producer_time_der * inputs_time_der_sum / parallelism;
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
auto* gradient = gtl::FindOrNull(*gradients, node->long_name());
if (gradient) {
*gradient *= (producer_time_der /
static_cast<double>(num_inputs() - 1) / parallelism);
}
}
// Set derivatives w.r.t. tunable parameters of the subtree rooted in the
// first input equal to 0 since its output time is excluded from
// computations.
absl::flat_hash_map<string, std::shared_ptr<Parameter>>
first_input_parameters;
inputs_.front()->CollectTunableParameters(&first_input_parameters);
for (auto& pair : first_input_parameters) {
(*gradients)[pair.first] = 0.0L;
}
// Add derivative w.r.t. own parallelism parameter.
if (parameter && (*parameter)->state->tunable) {
(*gradients)[long_name()] =
buffer_size_der - producer_time_der * producer_time / parallelism;
}
} else {
wait_time = ComputeWaitTime(producer_time, consumer_time, parallelism,
/*producer_time_derivative=*/nullptr,
/*consumer_time_derivative=*/nullptr,
/*buffer_size_derivative=*/nullptr);
}
output_time = self_processing_time + wait_time;
(*output_times)[long_name()] = output_time;
}
// The processing time is the sum of the self processing time and the average
// processing time of inputs comprising the interleave "cycle".
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (processing_times) {
(*processing_times)[long_name()] = self_processing_time;
}
if (num_inputs() <= 1) {
(*total_processing_times)[long_name()] = self_processing_time;
return;
}
double inputs_processing_time =
(TotalProcessingTimeForInputs(*total_processing_times) -
(*total_processing_times)[inputs_.front()->long_name()]) /
static_cast<double>(num_inputs() - 1);
(*total_processing_times)[long_name()] =
self_processing_time + inputs_processing_time;
}
};
class KnownRatio : public Node {
public:
KnownRatio(Node::Args args, int64 ratio) : Node(args), ratio_(ratio) {}
virtual ~KnownRatio() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
return std::make_shared<KnownRatio>(Args{id_, name_, std::move(output)},
ratio_);
}
// The input time is the sum of inherited input time and self processing time,
// divided by `ratio_`.
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
if (ratio_ == 0) {
(*input_times)[long_name()] = inherited_input_time;
return;
}
double input_time =
(inherited_input_time + SelfProcessingTimeLocked()) / ratio_;
(*input_times)[long_name()] = input_time;
}
// The output time is the sum of the self processing time and the product of
// `ratio_` and the sum of output times of inputs.
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (ratio_ == 0) {
(*output_times)[long_name()] = self_processing_time;
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
gradients->erase(node->long_name());
}
}
return;
}
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
auto* gradient = gtl::FindOrNull(*gradients, node->long_name());
if (gradient) {
*gradient *= ratio_;
}
}
(*output_time_gradients)[long_name()] =
OutputTimeGradientsForInputs(*output_time_gradients);
}
double inputs_output_time = ratio_ * OutputTimeForInputs(*output_times);
(*output_times)[long_name()] = self_processing_time + inputs_output_time;
}
// The processing time is the sum of the self processing time and the product
// of `ratio_` and the sum of processing times of inputs.
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (processing_times) {
(*processing_times)[long_name()] = self_processing_time;
}
if (ratio_ == 0) {
(*total_processing_times)[long_name()] = self_processing_time;
return;
}
double inputs_processing_time =
ratio_ * TotalProcessingTimeForInputs(*total_processing_times);
(*total_processing_times)[long_name()] =
self_processing_time + inputs_processing_time;
}
private:
const double ratio_;
};
class AsyncKnownRatio : public Node {
public:
AsyncKnownRatio(Node::Args args, double ratio,
std::vector<std::shared_ptr<Parameter>> parameters)
: Node(args), ratio_(ratio) {
for (auto& parameter : parameters) {
parameters_[parameter->name] = std::move(parameter);
}
}
virtual ~AsyncKnownRatio() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
std::vector<std::shared_ptr<Parameter>> parameters;
for (auto& pair : parameters_) {
parameters.push_back(pair.second);
}
return std::make_shared<AsyncKnownRatio>(
Args{id_, name_, std::move(output)}, ratio_, parameters);
}
// The input time is the sum of inherited input time and parallelism adjusted
// self processing time, divided by `ratio_`.
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
double parallelism = 1.0;
auto* parallelism_parameter = gtl::FindOrNull(parameters_, kParallelism);
if (parallelism_parameter) {
parallelism = (*parallelism_parameter)->value;
}
if (ratio_ == 0.0) {
(*input_times)[long_name()] =
inherited_input_time + SelfProcessingTimeLocked() / parallelism;
return;
}
double input_time =
(inherited_input_time + SelfProcessingTimeLocked() / parallelism) /
ratio_;
(*input_times)[long_name()] = input_time;
}
// The output time is the sum of parallelism adjusted self processing time and
// expected wait time from the buffer model estimated using
// `ComputeWaitTime(producer_time, consumer_time, parallelism, ...)`, where
// `producer_time` is the product of `ratio_` and the sum of output times of
// inputs, `consumer_time` is the product of `ratio_` and the `input_time`
// specified through `input_times` (since for each element stored in the
// buffer, the inputs need to be called `ratio_` times), and if the node has
// parallelism parameter, then `buffer_size` is derived from `parallelism`.
//
// Current implementation assumes that there is at most 1 parameter per node.
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double parallelism = 1.0;
double buffer_size = 0.0;
auto* parallelism_parameter = gtl::FindOrNull(parameters_, kParallelism);
auto* buffer_size_parameter = gtl::FindOrNull(parameters_, kBufferSize);
if (parallelism_parameter) {
parallelism = (*parallelism_parameter)->value;
buffer_size = parallelism;
} else if (buffer_size_parameter) {
buffer_size = (*buffer_size_parameter)->value;
}
double self_processing_time = SelfProcessingTimeLocked();
double output_time, wait_time, consumer_time, producer_time;
double input_time = input_times.at(long_name());
if (ratio_ == 0) {
consumer_time = input_time;
producer_time = 0.0L;
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
gradients->erase(node->long_name());
}
double producer_time_der = 0.0L;
double consumer_time_der = 0.0L;
double buffer_size_der = 0.0L;
wait_time = ComputeWaitTime(producer_time, consumer_time, buffer_size,
&producer_time_der, &consumer_time_der,
&buffer_size_der);
(*output_time_gradients)[long_name()] = consumer_time_der;
if (parallelism_parameter && (*parallelism_parameter)->state->tunable) {
(*gradients)[long_name()] = -(1.0L + consumer_time_der) *
self_processing_time /
Square(parallelism) +
buffer_size_der;
} else if (buffer_size_parameter &&
(*buffer_size_parameter)->state->tunable) {
(*gradients)[long_name()] = buffer_size_der;
}
} else {
wait_time = ComputeWaitTime(producer_time, consumer_time, buffer_size,
/*producer_time_derivative=*/nullptr,
/*consumer_time_derivative=*/nullptr,
/*buffer_size_derivative=*/nullptr);
}
output_time = self_processing_time / parallelism + wait_time;
(*output_times)[long_name()] = output_time;
return;
}
consumer_time = input_time * ratio_;
producer_time = ratio_ * OutputTimeForInputs(*output_times);
if (gradients) {
double producer_time_der = 0.0L;
double consumer_time_der = 0.0L;
double buffer_size_der = 0.0L;
wait_time = ComputeWaitTime(producer_time, consumer_time, buffer_size,
&producer_time_der, &consumer_time_der,
&buffer_size_der);
double inputs_time_der_sum =
OutputTimeGradientsForInputs(*output_time_gradients);
(*output_time_gradients)[long_name()] =
consumer_time_der + producer_time_der * inputs_time_der_sum;
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
auto* gradient = gtl::FindOrNull(*gradients, node->long_name());
if (gradient) {
*gradient *= (ratio_ * producer_time_der);
}
}
// Add derivative w.r.t. own parameter if it's tunable.
if (parallelism_parameter && (*parallelism_parameter)->state->tunable) {
(*gradients)[long_name()] =
buffer_size_der - (1.0L + consumer_time_der +
producer_time_der * inputs_time_der_sum) *
self_processing_time / Square(parallelism);
} else if (buffer_size_parameter &&
(*buffer_size_parameter)->state->tunable) {
(*gradients)[long_name()] = buffer_size_der;
}
} else {
wait_time = ComputeWaitTime(producer_time, consumer_time, buffer_size,
/*producer_time_derivative=*/nullptr,
/*consumer_time_derivative=*/nullptr,
/*buffer_size_derivative=*/nullptr);
}
output_time = self_processing_time / parallelism + wait_time;
(*output_times)[long_name()] = output_time;
}
// The processing time is the sum of the self processing time and the product
// of `ratio_` and the sum of processing times of inputs.
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (processing_times) {
(*processing_times)[long_name()] = self_processing_time;
}
if (ratio_ == 0) {
(*total_processing_times)[long_name()] = self_processing_time;
return;
}
double inputs_processing_time =
ratio_ * TotalProcessingTimeForInputs(*total_processing_times);
(*total_processing_times)[long_name()] =
self_processing_time + inputs_processing_time;
}
private:
const double ratio_;
};
class UnknownRatio : public Node {
public:
using Node::Node;
virtual ~UnknownRatio() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
return std::make_shared<UnknownRatio>(Args{id_, name_, std::move(output)});
}
// The input time is the sum of inherited input time and self processing time,
// divided by the ratio estimate.
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
if (num_elements_ == 0 || inputs_.empty() ||
inputs_.front()->num_elements() == 0) {
(*input_times)[long_name()] = inherited_input_time;
return;
}
std::shared_ptr<Node> input = inputs_.front();
double ratio = static_cast<double>(input->num_elements()) /
static_cast<double>(num_elements_);
double input_time =
(inherited_input_time + SelfProcessingTimeLocked()) / ratio;
(*input_times)[long_name()] = input_time;
}
// The output time is the sum of the self processing time and the product of
// the ratio estimate and the sum of output times of inputs.
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (num_elements_ == 0 || inputs_.empty() ||
inputs_.front()->num_elements() == 0) {
(*output_times)[long_name()] = self_processing_time;
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
gradients->erase(node->long_name());
}
}
return;
}
// TODO(jsimsa): The current implementation assumes that the number of input
// elements consumed per output is the same across all inputs.
double ratio = static_cast<double>(inputs_.front()->num_elements()) /
static_cast<double>(num_elements_);
if (gradients) {
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
auto* gradient = gtl::FindOrNull(*gradients, node->long_name());
if (gradient) {
*gradient *= ratio;
}
}
(*output_time_gradients)[long_name()] =
OutputTimeGradientsForInputs(*output_time_gradients);
}
double inputs_output_time = ratio * OutputTimeForInputs(*output_times);
(*output_times)[long_name()] = self_processing_time + inputs_output_time;
}
// The processing time is the sum of the self processing time and the product
// of the ratio estimate and the sum of processing times of inputs.
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
double self_processing_time = SelfProcessingTimeLocked();
if (processing_times) {
(*processing_times)[long_name()] = self_processing_time;
}
if (inputs_.empty() || num_elements_ == 0) {
(*total_processing_times)[long_name()] = self_processing_time;
return;
}
// TODO(jsimsa): The current implementation assumes that the number of input
// elements consumed per output is the same across all inputs.
std::shared_ptr<Node> input = inputs_.front();
double ratio = static_cast<double>(input->num_elements()) /
static_cast<double>(num_elements_);
double inputs_processing_time =
ratio * TotalProcessingTimeForInputs(*total_processing_times);
(*total_processing_times)[long_name()] =
self_processing_time + inputs_processing_time;
}
};
class Unknown : public Node {
public:
using Node::Node;
virtual ~Unknown() {}
protected:
std::shared_ptr<Node> Clone(std::shared_ptr<Node> output) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
return std::make_shared<Unknown>(Args{id_, name_, std::move(output)});
}
// The input time is the inherited input time.
void InputTimeLocked(absl::flat_hash_map<string, double>* input_times)
const override TF_SHARED_LOCKS_REQUIRED(mu_) {
double inherited_input_time;
if (output_) {
inherited_input_time = (*input_times)[output_->long_name()];
} else {
inherited_input_time =
gtl::FindWithDefault(*input_times, kInputTimeKey, 0.0L);
}
(*input_times)[long_name()] = inherited_input_time;
}
// The output time is the sum of output times of inputs.
void OutputTimeLocked(
const absl::flat_hash_map<string, double>& input_times,
absl::flat_hash_map<string, double>* gradients,
absl::flat_hash_map<string, double>* output_times,
absl::flat_hash_map<string, double>* output_time_gradients) const override
TF_SHARED_LOCKS_REQUIRED(mu_) {
(*output_times)[long_name()] = OutputTimeForInputs(*output_times);
if (gradients) {
(*output_time_gradients)[long_name()] =
OutputTimeGradientsForInputs(*output_time_gradients);
}
}
// The processing time is the sum of processing times of inputs.
void TotalProcessingTimeLocked(
absl::flat_hash_map<string, double>* processing_times,
absl::flat_hash_map<string, double>* total_processing_times) override
TF_SHARED_LOCKS_REQUIRED(mu_) {
if (processing_times) {
(*processing_times)[long_name()] = SelfProcessingTimeLocked();
}
(*total_processing_times)[long_name()] =
TotalProcessingTimeForInputs(*total_processing_times);
}
};
} // namespace
thread_local int64 Node::work_start_;
std::shared_ptr<Parameter> MakeParameter(const string& name,
std::shared_ptr<SharedState> state,
double min, double max) {
return std::make_shared<Parameter>(name, state, min, max);
}
std::shared_ptr<Node> MakeInterleaveManyNode(Node::Args args) {
return std::make_shared<InterleaveMany>(std::move(args));
}
std::shared_ptr<Node> MakeAsyncInterleaveManyNode(
Node::Args args, std::vector<std::shared_ptr<Parameter>> parameters) {
return std::make_shared<AsyncInterleaveMany>(std::move(args),
std::move(parameters));
}
std::shared_ptr<Node> MakeKnownRatioNode(Node::Args args, double ratio) {
return std::make_shared<KnownRatio>(std::move(args), ratio);
}
std::shared_ptr<Node> MakeAsyncKnownRatioNode(
Node::Args args, double ratio,
std::vector<std::shared_ptr<Parameter>> parameters) {
return std::make_shared<AsyncKnownRatio>(std::move(args), ratio,
std::move(parameters));
}
std::shared_ptr<Node> MakeSourceNode(Node::Args args) {
return MakeKnownRatioNode(std::move(args), 0);
}
std::shared_ptr<Node> MakeUnknownRatioNode(Node::Args args) {
return std::make_shared<UnknownRatio>(std::move(args));
}
std::shared_ptr<Node> MakeUnknownNode(Node::Args args) {
return std::make_shared<Unknown>(std::move(args));
}
double Node::ComputeWaitTime(const double& producer_time,
const double& consumer_time,
const double& buffer_size,
double* producer_time_derivative,
double* consumer_time_derivative,
double* buffer_size_derivative) {
// If we set x=`consumer_time`, y=`producer_time`, n=`buffer_size`,
// p=`p_buffer_empty`, T=`wait_time`, then we have:
// if y = 0, then p = 0;
// elif x = 0, then p = 1;
// elif x = y, then p = 1 / (n+1);
// else p = [1 - x/y] / [1 - power(x/y, n+1)].
//
// We also have T = p * y, and derivatives of T w.r.t. x, y, n are computed:
// dT/dx = dp/dx * y,
// dT/dy = p + dp/dy * y,
// dT/dn = dp/dn * y.
// Then the remaining work is to compute dp/dx, dp/dy, dp/dn by considering
// different cases and substitute the values into above formulas.
// Case 1: if producer is infinitely fast. The buffer will always be full.
// Wait time will always be 0.
if (producer_time == 0) {
if (producer_time_derivative) {
// Note a common error is `*producer_time_derivative = 0` since p=0 on the
// line y=0 doesn't imply dp/dy = 0 there. Actually to compute dp/dy at
// (x,0), we need to consider lim_{dy->0+} [p(x,dy)-p(x,0)] / dy, where
// p(x,0)=0 and p(x,dy) = [1 - x/dy] / [1 - power(x/dy, n+1)].
if (buffer_size == 0 || consumer_time == 0) {
*producer_time_derivative = 1.0L;
} else {
*producer_time_derivative = 0.0L;
}
}
if (consumer_time_derivative) {
*consumer_time_derivative = 0.0L;
}
if (buffer_size_derivative) {
*buffer_size_derivative = 0.0L;
}
return 0.0L;
}
// Case 2: if consumer is infinitely fast. Wait time is always the time to
// produce an output.
if (consumer_time == 0) {
if (producer_time_derivative) {
*producer_time_derivative = 1.0L;
}
if (consumer_time_derivative) {
// Note a common error is `*consumer_time_derivative = 0` since p=1 on the
// line x=0 doesn't imply dp/dx = 0 there. Actually to compute dp/dx at
// (0,y), we need to consider lim_{dx->0+} [p(dx,y)-p(0,y)] / dx, where
// p(0,y)=1, p(dx,y) = [1 - dx/y] / [1 - power(dx/y, n+1)] if y!=0.
if (buffer_size == 0) {
*consumer_time_derivative = 0.0L;
} else {
*consumer_time_derivative = -1.0L;
}
}
if (buffer_size_derivative) {
*buffer_size_derivative = 0.0L;
}
return producer_time;
}
// Case 3: the consumer and the producer are equally fast. Expected wait time
// decreases linearly with the size of the buffer.
if (consumer_time == producer_time) {
const double p_buffer_empty = 1.0L / (buffer_size + 1.0L);
const double p_buffer_empty_der =
-buffer_size / (2.0L * buffer_size + 2.0L);
if (producer_time_derivative) {
// Note a common error is `*producer_time_derivative = p_buffer_empty`
// since p=1/(n+1) on the line x=y doesn't imply dp/dy = 0 there. Actually
// to compute dp/dy at (y,y), we need to consider
// lim_{dy->0} [p(y,y+dy)-p(y,y)] / dy, where p(y,y)=1/(n+1),
// p(y,y+dy) = [1 - y/(y+dy)] / [1 - power(y/(y+dy), n+1)].
*producer_time_derivative = p_buffer_empty - p_buffer_empty_der;
}
if (consumer_time_derivative) {
// Note a common error is `*consumer_time_derivative = 0` since
// p=1/(n+1) on the line x=y doesn't imply dp/dx = 0 there. Actually to
// compute dp/dx at (x,x), we need to consider
// lim_{dx->0} [p(x+dx,x)-p(x,x)] / dx, where p(x,x)=1/(n+1),
// p(x+dx,x) = [1 - (x+dx)/x] / [1 - power((x+dx)/x, n+1)].
*consumer_time_derivative = p_buffer_empty_der;
}
if (buffer_size_derivative) {
*buffer_size_derivative = -producer_time / Square(buffer_size + 1.0L);
}
return p_buffer_empty * producer_time;
}
// Case 4: the consumer is slower than the producer and neither is infinitely
// fast. Case 4 and Case 5 actually follow same formula. Separate them for
// numerical computation reasons.
if (consumer_time > producer_time) {
const double ratio = producer_time / consumer_time;
const double ratio_pow = std::pow(ratio, buffer_size);
const double p_buffer_empty =
ratio_pow * (1.0L - ratio) / (1.0L - ratio * ratio_pow);
const double p_buffer_empty_der =
(buffer_size - (buffer_size + 1.0L) * ratio + ratio_pow * ratio) *
ratio_pow / ratio / Square(1.0L - ratio_pow * ratio);
if (producer_time_derivative) {
*producer_time_derivative = p_buffer_empty + p_buffer_empty_der * ratio;
}
if (consumer_time_derivative) {
*consumer_time_derivative = -p_buffer_empty_der * Square(ratio);
}
if (buffer_size_derivative) {
*buffer_size_derivative = p_buffer_empty / (1.0L - ratio_pow * ratio) *
std::log(ratio) * producer_time;
}
return p_buffer_empty * producer_time;
}
// Case 5: the producer is slower than the consumer and neither is infinitely
// fast.
const double ratio = consumer_time / producer_time;
const double ratio_pow = std::pow(ratio, buffer_size);
const double p_buffer_empty = (1.0L - ratio) / (1.0L - ratio_pow * ratio);
const double p_buffer_empty_der =
((buffer_size + 1.0L - buffer_size * ratio) * ratio_pow - 1.0L) /
Square(1.0L - ratio_pow * ratio);
if (producer_time_derivative) {
*producer_time_derivative = p_buffer_empty - p_buffer_empty_der * ratio;
}
if (consumer_time_derivative) {
*consumer_time_derivative = p_buffer_empty_der;
}
if (buffer_size_derivative) {
*buffer_size_derivative = p_buffer_empty / (1.0L - ratio_pow * ratio) *
ratio_pow * ratio * std::log(ratio) *
producer_time;
}
return p_buffer_empty * producer_time;
}
void Node::CollectTunableParameters(
absl::flat_hash_map<string, std::shared_ptr<Parameter>>* parameters) const {
tf_shared_lock l(mu_);
// Collect tunable parameters from the leaves of the nodes tree to the root.
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
tf_shared_lock l(node->mu_);
node->CollectTunableParametersHelper(parameters);
}
CollectTunableParametersHelper(parameters);
}
string Node::DebugString() const {
absl::flat_hash_map<string, string> debug_strings;
tf_shared_lock l(mu_);
// Build up the debug string from the leaves of the nodes tree to the root.
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
tf_shared_lock l(node->mu_);
node->DebugStringHelper(&debug_strings);
}
DebugStringHelper(&debug_strings);
return debug_strings[long_name()];
}
void Node::FlushMetrics() {
if (!record_metrics_) {
return;
}
metrics_.record_bytes_consumed(bytes_consumed_);
metrics_.record_bytes_produced(bytes_produced_);
metrics_.record_num_elements(num_elements_);
}
double Node::OutputTime(absl::flat_hash_map<string, double>* input_times,
absl::flat_hash_map<string, double>* gradients) const {
// To store the output time gradient w.r.t. input time (if `gradients` is not
// `nullptr`) and the output time for each node.
absl::flat_hash_map<string, double> output_time_gradients, output_times;
tf_shared_lock l(mu_);
auto nodes = CollectNodes(TraversalOrder::BFS);
// Computes and stores input time for each node from the root to leaves of the
// nodes tree.
InputTimeLocked(input_times);
for (const auto& node : nodes) {
tf_shared_lock l(node->mu_);
node->InputTimeLocked(input_times);
}
std::reverse(nodes.begin(), nodes.end());
// Computes and stores the output time and output time gradient w.r.t. input
// time (if `gradients` is not `nullptr`) for each node from leaves of the
// nodes tree to the root.
for (const auto& node : nodes) {
tf_shared_lock l(node->mu_);
node->OutputTimeLocked(*input_times, gradients, &output_times,
&output_time_gradients);
}
OutputTimeLocked(*input_times, gradients, &output_times,
&output_time_gradients);
return output_times[long_name()];
}
std::shared_ptr<Node> Node::Snapshot(std::shared_ptr<Node> output) const {
NodePairList node_pairs;
auto result = SnapshotHelper(output, &node_pairs);
while (!node_pairs.empty()) {
auto node_pair = node_pairs.front();
node_pairs.pop_front();
std::shared_ptr<Node> input_node = node_pair.first,
parent_node_copy = node_pair.second;
parent_node_copy->add_input(
input_node->SnapshotHelper(parent_node_copy, &node_pairs));
}
return result;
}
double Node::SelfProcessingTime() const {
tf_shared_lock l(mu_);
return SelfProcessingTimeLocked();
}
double Node::TotalBufferedBytes() const {
absl::flat_hash_map<string, double> total_bytes;
tf_shared_lock l(mu_);
// Compute total buffered bytes from the leaves of the nodes tree to the root.
for (const auto& node : CollectNodes(TraversalOrder::REVERSE_BFS)) {
tf_shared_lock l(node->mu_);