-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathexecutor.cc
More file actions
1810 lines (1616 loc) · 66.6 KB
/
executor.cc
File metadata and controls
1810 lines (1616 loc) · 66.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 2015 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/common_runtime/executor.h"
#include <algorithm>
#include <atomic>
#include <memory>
#include <queue>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "tensorflow/core/common_runtime/costmodel.h"
#include "tensorflow/core/common_runtime/costmodel_manager.h"
#include "tensorflow/core/common_runtime/entry.h"
#include "tensorflow/core/common_runtime/executor_factory.h"
#include "tensorflow/core/common_runtime/graph_view.h"
#include "tensorflow/core/common_runtime/immutable_executor_state.h"
#include "tensorflow/core/common_runtime/kernel_stat.h"
#include "tensorflow/core/common_runtime/pending_counts.h"
#include "tensorflow/core/common_runtime/propagator_state.h"
#include "tensorflow/core/common_runtime/renamed_device.h"
#include "tensorflow/core/common_runtime/simple_propagator_state.h"
#include "tensorflow/core/common_runtime/step_stats_collector.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/cancellation.h"
#include "tensorflow/core/framework/collective.h"
#include "tensorflow/core/framework/control_flow.h"
#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_segment.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_reference.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/edgeset.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/gtl/manual_constructor.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/platform/context.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/profile_utils/cpu_utils.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/tracing.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/internal/traceme_recorder.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/profiler/nvtx_utils.h"
#include "tensorflow/core/util/env_var.h"
#include "tensorflow/core/util/tensor_slice_reader_cache.h"
namespace tensorflow {
namespace {
// 1-D, 0 element tensor.
static const Tensor* const kEmptyTensor = new Tensor;
// Helper routines for collecting step stats.
namespace nodestats {
inline int64 NowInNsec() { return Env::Default()->NowNanos(); }
void SetScheduled(NodeExecStatsInterface* stats, int64 micros) {
if (!stats) return;
stats->SetScheduled(micros * EnvTime::kMicrosToNanos);
}
void SetAllStart(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->RecordExecutorStarted();
}
void SetOpStart(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->RecordComputeStarted();
}
void SetOpEnd(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->RecordComputeEnded();
}
void SetAllEnd(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->RecordExecutorEnded();
}
void SetOutput(NodeExecStatsInterface* stats, int slot, const Tensor* v) {
if (!stats) return;
stats->SetOutput(slot, v);
}
void SetMemory(NodeExecStatsInterface* stats, OpKernelContext* ctx) {
if (!stats) return;
stats->SetMemory(ctx);
}
void SetParentID(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->SetParentID(tracing::CallingContext::GetCurrentContext());
}
void SetActivityID(NodeExecStatsInterface* stats) {
if (!stats) return;
stats->SetActivityID(tracing::CallingContext::GetAndPush());
}
static const std::string enable_cost_model_env_name =
"ENABLE_EXECUTE_COST_MODEL";
} // namespace nodestats
// Time the execution of kernels (in CPU cycles). Used to dynamically identify
// inexpensive kernels which can be dispatched inline.
struct KernelTimer {
uint64 start_cycles = profile_utils::CpuUtils::GetCurrentClockCycle();
uint64 ElapsedCycles() {
return profile_utils::CpuUtils::GetCurrentClockCycle() - start_cycles;
}
};
// TODO(b/152925936): Re-evaluate these constants with current usage patterns.
typedef gtl::InlinedVector<TensorValue, 4> TensorValueVec;
typedef gtl::InlinedVector<AllocatorAttributes, 4> AllocatorAttributeVec;
class ExecutorImpl : public Executor {
public:
explicit ExecutorImpl(const LocalExecutorParams& p)
: immutable_state_(p) {
Status s = ReadBoolFromEnvVar(
nodestats::enable_cost_model_env_name, true, &enable_cost_model_);
if (!s.ok()) {
LOG(WARNING) << "Read ENABLE_EXECUTE_COST_MODEL envrionment error. "
<< s.error_message();
}
}
~ExecutorImpl() {
if (cost_model_) {
delete cost_model_;
}
}
Status Initialize(const Graph& graph) {
TF_RETURN_IF_ERROR(immutable_state_.Initialize(graph));
kernel_stats_.Initialize(immutable_state_.graph_view(), &graph);
if (immutable_state_.params().run_cost_model_executor) {
immutable_state_.InitializeScheduleInfo(&kernel_stats_, graph);
}
return Status::OK();
}
void RunAsync(const Args& args, DoneCallback done) override;
ExecutorInternal::ExecuteCostModel* TryToBuildCostModel();
ImmutableExecutorState& GetImmutableState() {
return immutable_state_;
}
ExecutorInternal::KernelStats* GetKernelStat() {
return &kernel_stats_;
}
private:
template <class PropagatorStateType>
friend class ExecutorState;
ImmutableExecutorState immutable_state_;
ExecutorInternal::KernelStats kernel_stats_;
bool enable_cost_model_ = false;
std::atomic<int> build_cost_model_counter_{0};
ExecutorInternal::ExecuteCostModel* cost_model_ = nullptr;
TF_DISALLOW_COPY_AND_ASSIGN(ExecutorImpl);
};
// The state associated with one invocation of ExecutorImpl::Run.
//
// ExecutorState dispatches nodes when they become ready, and delegates to an
// instance of `PropagatorStateType` to keep track of how many predecessors of a
// are still pending.
//
// The template argument `class PropagatorStateType` must define the following
// public members:
// * A type `TaggedNode`, representing a node to be processed, with public
// members:
// * `const NodeItem& get_node_item() const`
// * `bool get_is_dead() const`
// * A type `TaggedNodeReadyQueue`, representing a queue of nodes to be
// processed, with public members (having the same meanings as in an
// `std::vector<TaggedNode>`):
// * `void push_back(const TaggedNode& node)`
// * `TaggedNode front() const`
// * `void pop_front()`
// * `bool empty() const`
// * A type `TaggedNodeSeq`, representing a list of nodes to be scheduled, with
// public members (having the same meanings as in an
// `std::vector<TaggedNode>`):
// * `size_t size() const`
// * `bool empty() const`
// * `void clear()`
// * `const_iterator begin() const`
// * `const_iterator end() const`
// * A public constructor, `PropagatorStateType(const ImmutableExecutorState&
// immutable_state, int64 step_id)`.
// * The following public methods:
// * `void ActivateRoots(gtl::ArraySlice<const NodeItem*> roots,
// TaggedNodeSeq* ready)`, which creates `TaggedNode` instances for the
// nodes in `roots` and adds them to `*ready`
// * `void PropagateOutputs(const TaggedNode& tagged_node, EntryVector*
// outputs, TaggedNodeSeq* ready)`, which propagates `outputs` from the
// given `tagged_node` to the destinations of its output edges, and adds
// any newly runnable nodes to `*ready`
// * `Entry* GetInputTensors(const TaggedNode& tagged_node) const`, which
// returns a pointer to the input tensors for the given `tagged_node`
// * `FrameAndIter GetFrameAndIter(const TaggedNode& tagged_node) const`,
// which creates a `FrameAndIter` for the given `tagged_node`
// * `void DumpState()`, which dumps the dynamic state of the executing graph
// * `void MaybeMarkStarted(const TaggedNode& tagged_node)`, which records
// that a node has started
// * `void MaybeMarkCompleted(const TaggedNode& tagged_node)`, which records
// that a node has completed
//
// See `PropagatorState` in "./propagator_state.h" for an example of a type that
// can be used to instantiate `PropagatorStateType`.
template <class PropagatorStateType>
class ExecutorState {
public:
ExecutorState(const Executor::Args& args,
const ImmutableExecutorState& immutable_state_,
ExecutorInternal::KernelStats* kernel_stats_);
ExecutorState(const Executor::Args& args,
const ImmutableExecutorState& immutable_state_,
ExecutorInternal::KernelStats* kernel_stats_,
ExecutorInternal::ExecuteCostModel* cm);
virtual ~ExecutorState();
void RunAsync(Executor::DoneCallback done);
ExecutorInternal::KernelStats* GetKernelStats() const {
return kernel_stats_;
}
protected:
// Use `TaggedNode` types defined by `PropagatorStateType`.
typedef typename PropagatorStateType::TaggedNode TaggedNode;
typedef
typename PropagatorStateType::TaggedNodeReadyQueue TaggedNodeReadyQueue;
typedef typename PropagatorStateType::TaggedNodeSeq TaggedNodeSeq;
struct AsyncState;
// Process a ready node in current thread.
void Process(TaggedNode node, int64_t scheduled_nsec);
void BatchProcess(std::vector<TaggedNode> nodes, int nodes_count, int64_t scheduled_nsec);
Status ProcessSync(const NodeItem& item, OpKernelContext::Params* params,
EntryVector* outputs, NodeExecStatsInterface* stats);
void ProcessAsync(const NodeItem& item, const OpKernelContext::Params& params,
const TaggedNode& tagged_node, Entry* first_input,
NodeExecStatsInterface* stats);
void ProcessNoop(NodeExecStatsInterface* stats);
void ProcessConstTensor(const NodeItem& item, EntryVector* outputs,
NodeExecStatsInterface* stats);
// Before invoking item->kernel, fills in its "inputs".
Status PrepareInputs(const NodeItem& item, Entry* first_input,
TensorValueVec* inputs,
AllocatorAttributeVec* input_alloc_attrs,
bool* is_input_dead,
std::vector<bool>* is_input_dead_details);
// After item->kernel computation is done, processes its outputs.
Status ProcessOutputs(const NodeItem& item, OpKernelContext* ctx,
Entry* outputs, NodeExecStatsInterface* stats);
// Called after each node finishes. Takes ownership of "stats". Returns true
// if execution has completed.
//
// This method will clear `*ready` before returning.
bool NodeDone(const Status& s, TaggedNodeSeq* ready,
NodeExecStatsInterface* stats,
TaggedNodeReadyQueue* inline_ready);
// Schedule all the expensive nodes in '*ready', and put all the inexpensive
// nodes in 'ready' into 'inline_ready'.
//
// This method will clear `*ready` before returning.
//
// REQUIRES: `!ready->empty()`.
virtual void ScheduleReady(TaggedNodeSeq* ready, TaggedNodeReadyQueue* inline_ready);
// A wrapper for runner_ to keep track of the pending queue length. Op
// execution should dispatch work using this function instead of using runner_
// directly.
template <typename Closure>
void RunTask(Closure&& c);
// Clean up when this executor is done.
void Finish();
void ScheduleFinish();
void MaybeCollectKernelStats();
// Contains the device context assigned by the device at the beginning of a
// step.
DeviceContext* device_context_ = nullptr;
const bool vlog_; // true if VLOG_IS_ON(1). Used to check vlog cheaply.
// true if LogMemory::IsEnabled(). Used to check memory enabled cheaply.
const bool log_memory_;
int64_t step_id_;
int64_t round_step_id_;
int64_t start_time_usecs_ = 0;
// The deadline for the session to complete by. Empty if unspecified.
absl::optional<absl::Time> deadline_;
// Maximum number of kernels that can be scheduled inline. If lots of kernels
// are ready at the same time, scheduling them in one thread can be very slow.
// TODO(fishx): Make it configurable if necessary.
static constexpr uint64 kInlineScheduleReadyThreshold = 500;
// Not owned.
//RendezvousInterface* rendezvous_;
Rendezvous* rendezvous_;
Executor::RendezvousFactory* create_rendezvous_ = nullptr;
Rendezvous* global_rendezvous_;
CollectiveExecutor* collective_executor_ = nullptr;
SessionState* session_state_;
string session_handle_;
const SessionMetadata* session_metadata_ = nullptr;
TensorStore* tensor_store_;
// Step-local container.
ScopedStepContainer* step_container_;
StepStatsCollectorInterface* const stats_collector_;
const tracing::EventCollector* const event_collector_;
Context context_;
// QUESTION: Make it a checkpoint::TensorSliceReaderCacheWrapper
// instead of a pointer? (avoids having to delete).
checkpoint::TensorSliceReaderCacheWrapper* slice_reader_cache_;
CallFrameInterface* call_frame_;
const ImmutableExecutorState& immutable_state_;
ExecutorInternal::KernelStats* const kernel_stats_;
ExecutorInternal::ExecuteCostModel* const cost_model_;
CancellationManager* cancellation_manager_;
// If not null, use this device to schedule intra-op operation
std::unique_ptr<DeviceBase> user_device_;
Executor::Args::Runner runner_ = nullptr;
Executor::Args::CostRunner cost_runner_ = nullptr;
bool sync_on_finish_;
ExecutorPolicy executor_policy_ =
ExecutorPolicy::USE_NORMAL_EXECUTOR;
PropagatorStateType propagator_;
// Invoked when the execution finishes.
Executor::DoneCallback done_cb_;
std::atomic_int_fast32_t num_outstanding_ops_;
// Available via OpKernelContext to every OpKernel invocation.
mutex num_deferred_ops_mu_;
int64_t num_deferred_ops_ TF_GUARDED_BY(num_deferred_ops_mu_) = 0;
bool finish_when_deferred_ops_done_ TF_GUARDED_BY(num_deferred_ops_mu_) =
false;
// Ref Tensors of input of send op
mutex* ref_send_inputs_mu_ptr_;
std::vector<std::unique_ptr<TensorReference>>* ref_send_inputs_ptr_;
bool merge_compute_and_copy_stream_;
mutex mu_;
Status status_ TF_GUARDED_BY(mu_);
};
template <class PropagatorStateType>
class InlineExecutorState : public ExecutorState<PropagatorStateType> {
public:
InlineExecutorState(const Executor::Args& args,
const ImmutableExecutorState& immutable_state_,
ExecutorInternal::KernelStats* kernel_stats_)
: ExecutorState<PropagatorStateType>(
args, immutable_state_, kernel_stats_) {}
~InlineExecutorState() {}
protected:
// Use `TaggedNode` types defined by `PropagatorStateType`.
typedef typename PropagatorStateType::TaggedNode TaggedNode;
typedef
typename PropagatorStateType::TaggedNodeReadyQueue TaggedNodeReadyQueue;
typedef typename PropagatorStateType::TaggedNodeSeq TaggedNodeSeq;
void ScheduleReady(TaggedNodeSeq* ready, TaggedNodeReadyQueue* inline_ready);
};
template <class PropagatorStateType>
class CostExecutorState : public ExecutorState<PropagatorStateType> {
public:
CostExecutorState(const Executor::Args& args,
const ImmutableExecutorState& immutable_state_,
ExecutorInternal::KernelStats* kernel_stats_,
ExecutorInternal::ExecuteCostModel* cm)
: ExecutorState<PropagatorStateType>(
args, immutable_state_, kernel_stats_, cm) {}
~CostExecutorState() {}
protected:
// Use `TaggedNode` types defined by `PropagatorStateType`.
typedef typename PropagatorStateType::TaggedNode TaggedNode;
typedef
typename PropagatorStateType::TaggedNodeReadyQueue TaggedNodeReadyQueue;
typedef typename PropagatorStateType::TaggedNodeSeq TaggedNodeSeq;
void ScheduleReady(TaggedNodeSeq* ready, TaggedNodeReadyQueue* inline_ready);
private:
template <typename Closure>
void CostRunTask(Closure&& c, int64 cost);
void CostScheduleReady(TaggedNodeSeq* ready, TaggedNodeReadyQueue* inline_ready);
void CostProcess(TaggedNode node, int64_t scheduled_nsec) {
this->Process(node, scheduled_nsec);
}
void CostBatchProcess(std::vector<TaggedNode> nodes,
int nodes_count, int64_t scheduled_nsec) {
this->BatchProcess(nodes, nodes_count, scheduled_nsec);
}
};
class ExecutorStateFactory {
public:
template <class PropagatorStateType>
static ExecutorState<PropagatorStateType>* Create(
const Executor::Args& args, ExecutorImpl* impl) {
ImmutableExecutorState& immutable_state = impl->GetImmutableState();
ExecutorInternal::KernelStats* kernel_stats = impl->GetKernelStat();
// InlineExecuteState
if (args.executor_policy == ExecutorPolicy::USE_INLINE_EXECUTOR) {
return new InlineExecutorState<PropagatorStateType>(
args, immutable_state, kernel_stats);
} else if (args.cost_runner &&
args.executor_policy == ExecutorPolicy::USE_COST_MODEL_EXECUTOR) {
// TODO: FIXME consider function lib executor, set cost_runner for it?
// Schedule by cost model
ExecutorInternal::ExecuteCostModel* cm = impl->TryToBuildCostModel();
return new CostExecutorState<PropagatorStateType>(
args, immutable_state, kernel_stats, cm);
} else {
// normal schedule
return new ExecutorState<PropagatorStateType>(
args, immutable_state, kernel_stats);
}
}
};
// Sort node according cost from which ExecutorState
template <class PropagatorStateType>
struct SortTaggedNode {
typedef typename PropagatorStateType::TaggedNode TaggedNode;
SortTaggedNode(const std::vector<int64>* immutable_accumulative_cost) :
immutable_accumulative_cost_(immutable_accumulative_cost) {}
bool operator()(const TaggedNode& n1, const TaggedNode& n2) {
return (*immutable_accumulative_cost_)[n1.get_node_item().node->id()] >
(*immutable_accumulative_cost_)[n2.get_node_item().node->id()];
}
const std::vector<int64>* immutable_accumulative_cost_;
};
template <class PropagatorStateType>
ExecutorState<PropagatorStateType>::ExecutorState(
const Executor::Args& args, const ImmutableExecutorState& immutable_state,
ExecutorInternal::KernelStats* kernel_stats)
: ExecutorState(args, immutable_state, kernel_stats, nullptr) {}
template <class PropagatorStateType>
ExecutorState<PropagatorStateType>::ExecutorState(
const Executor::Args& args, const ImmutableExecutorState& immutable_state,
ExecutorInternal::KernelStats* kernel_stats,
ExecutorInternal::ExecuteCostModel* cm)
: vlog_(VLOG_IS_ON(1)),
log_memory_(LogMemory::IsEnabled()),
step_id_(args.step_id),
round_step_id_(args.round_step_id),
start_time_usecs_(args.start_time_usecs),
deadline_(args.deadline),
rendezvous_(args.rendezvous),
create_rendezvous_(const_cast<Executor::RendezvousFactory*>(
&(immutable_state.params().rendezvous_factory))),
global_rendezvous_(args.global_rendezvous),
collective_executor_(args.collective_executor),
session_state_(args.session_state),
session_handle_(args.session_handle),
session_metadata_(immutable_state.params().session_metadata),
tensor_store_(args.tensor_store),
step_container_(args.step_container),
stats_collector_(args.stats_collector),
event_collector_(
tracing::GetEventCollector(tracing::EventCategory::kCompute)),
context_(ContextKind::kThread),
slice_reader_cache_(new checkpoint::TensorSliceReaderCacheWrapper),
call_frame_(args.call_frame),
immutable_state_(immutable_state),
kernel_stats_(kernel_stats),
cost_model_(cm),
cancellation_manager_(args.cancellation_manager),
runner_(args.runner),
cost_runner_(args.cost_runner),
sync_on_finish_(args.sync_on_finish),
executor_policy_(args.executor_policy),
propagator_(immutable_state, step_id_, vlog_),
num_outstanding_ops_(0),
ref_send_inputs_mu_ptr_(args.ref_send_inputs_mu_ptr.get()),
ref_send_inputs_ptr_(args.ref_send_inputs_ptr),
merge_compute_and_copy_stream_(args.merge_compute_and_copy_stream) {
// TODO: FIXME Consider function lib executor later
//if (args.cost_runner == nullptr) {
// LOG(FATAL) << "cost_runner is nullptr, please check the args.";
//}
if (args.user_intra_op_threadpool != nullptr) {
Device* device = immutable_state_.params().device;
user_device_ = RenamedDevice::NewRenamedDevice(
device->name(), device, false, false, args.user_intra_op_threadpool);
}
}
template <class PropagatorStateType>
ExecutorState<PropagatorStateType>::~ExecutorState() {
if (device_context_) {
device_context_->Unref();
}
delete slice_reader_cache_;
}
template <class PropagatorStateType>
template <typename Closure>
void ExecutorState<PropagatorStateType>::RunTask(Closure&& c) {
// mutable is needed because std::forward<Closure> in the lambda body may move
// the Closure `c`.
runner_([c = std::forward<Closure>(c)]() mutable {
std::forward<Closure>(c)();
});
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::RunAsync(Executor::DoneCallback done) {
MaybeCollectKernelStats();
TaggedNodeSeq ready;
// Ask the device to fill in the device context map.
Device* device = immutable_state_.params().device;
const Status get_context_status =
device->TryGetDeviceContext(&device_context_);
if (!get_context_status.ok()) {
delete this;
done(get_context_status);
return;
}
// Initialize the ready queue.
ready.reserve(immutable_state_.root_nodes().size());
propagator_.ActivateRoots(immutable_state_.root_nodes(), &ready);
num_outstanding_ops_ = ready.size();
if (ready.empty()) {
delete this;
done(Status::OK());
} else {
done_cb_ = std::move(done);
// Schedule to run all the ready ops in thread pool.
ScheduleReady(&ready, nullptr);
}
}
// State kept alive for executing an asynchronous node in another
// thread. NOTE: We need to make a copy of p.input and p.input_alloc_attrs for
// asynchronous kernels because OpKernelContext methods like input_type(i) needs
// the param points to valid input type vector. It's not an issue for
// sync kernels because these vectors are kept on the stack.
template <class PropagatorStateType>
struct ExecutorState<PropagatorStateType>::AsyncState {
AsyncState(const OpKernelContext::Params& p, const TaggedNode& _tagged_node,
const NodeItem* _item, Entry* _first_input,
NodeExecStatsInterface* _stats)
: saved_inputs(*p.inputs),
saved_input_alloc_attrs(*p.input_alloc_attrs),
params(p),
tagged_node(_tagged_node),
item(_item),
first_input(_first_input),
// ParamsButClearingEigenGPUDevice does equivalent of
// params.eigen_gpu_device = nullptr;
ctx(ParamsButClearingEigenGPUDevice(¶ms), item->num_outputs),
stats(_stats) {
params.inputs = &saved_inputs;
params.input_alloc_attrs = &saved_input_alloc_attrs;
}
TensorValueVec saved_inputs;
AllocatorAttributeVec saved_input_alloc_attrs;
OpKernelContext::Params params;
TaggedNode tagged_node;
const NodeItem* item;
Entry* first_input;
OpKernelContext ctx;
NodeExecStatsInterface* stats;
private:
OpKernelContext::Params* ParamsButClearingEigenGPUDevice(
OpKernelContext::Params* p) {
// Ensure OpKernelContext constructor will make a new eigen GPU device if
// necessary.
p->eigen_gpu_device = nullptr; // Force allocation
return p;
}
};
// Returns true if `item` might be traced by the given trace and event
// collectors. Returns false only if `item` definitely will not be traced.
bool MightTrace(const NodeItem& item,
const tracing::EventCollector* event_collector) {
// Tracing will only be enabled if either `event_collector` is non null,
// or `trace_collector` is non-null and enabled for this particular kernel.
// Although `profiler::TraceMe`, `tracing::ScopedAnnotation`, and
// `tracing::ScopedRegion` check subsets of these properties internally in
// their constructors, the cost of passing the necessary arguments to them can
// be significant, so we avoid constructing them in the common case (when we
// know they will not be used).
if (event_collector != nullptr) {
return true;
}
if (tracing::ScopedAnnotation::IsEnabled()) return true;
return profiler::TraceMeRecorder::Active(
profiler::GetTFTraceMeLevel(item.kernel->IsExpensive()));
}
template <class PropagatorStateType>
Status ExecutorState<PropagatorStateType>::ProcessSync(
const NodeItem& item, OpKernelContext::Params* params, EntryVector* outputs,
NodeExecStatsInterface* stats) {
Status s;
OpKernelContext ctx(params, item.num_outputs);
OpKernel* op_kernel = item.kernel;
Device* device = immutable_state_.params().device;
if (item.virtual_device.get() != nullptr) {
device = item.virtual_device.get();
}
if (merge_compute_and_copy_stream_ &&
(op_kernel->type_string() == "_HostSend" ||
(op_kernel->type_string() == "_Send" &&
device->parsed_name().type == "CPU")) &&
item.node->attrs().Find("recv_device")->s().find("GPU") != string::npos &&
(*params->inputs)[0].tensor->NumElements() > 0) {
CHECK(item.num_inputs == 1); // send op allow one tensor
{
mutex_lock l(*ref_send_inputs_mu_ptr_);
ref_send_inputs_ptr_->push_back(
absl::make_unique<TensorReference>(*((*params->inputs)[0].tensor)));
}
}
nodestats::SetOpStart(stats);
ExecutorInternal::KernelStatsInfo kernel_stat_buffer;
kernel_stats_->StartCollectOp(&item, &kernel_stat_buffer);
const bool is_expensive = kernel_stats_->IsExpensive(item);
if (TF_PREDICT_FALSE(MightTrace(item, event_collector_))) {
const string& op_name = op_kernel->name();
int64 id = step_id_;
if (step_container_ && step_container_->StepId()) {
id = step_container_->StepId();
}
const string kernel_label = strings::StrCat(
op_name, ":", op_kernel->type_string(), "#id=", id,
",device=", device->name(), ",async=false#");
tracing::ScopedRegion region(tracing::EventCategory::kCompute,
op_name);
// 'TraceMe' will trace the OpKernel scheduling time.
profiler::TraceMe activity(
absl::string_view(kernel_label),
profiler::GetTFTraceMeLevel(op_kernel->IsExpensive()));
// 'ScopedAnnotation' will trace the OpKernel execution time.
tracing::ScopedAnnotation annotation(kernel_label);
device->Compute(op_kernel, &ctx);
} else if (kernel_stats_->HasExpensiveMarker(item)) {
KernelTimer timer;
device->Compute(op_kernel, &ctx);
// For expensive kernels, always update the cost estimate. For inexpensive
// kernels, update the cost estimate with ~1/16 probability. This assumes
// that the last 4 bits of the CPU cycle count is uniformly distributed.
constexpr int kKernelExecutionTrackingInvocationSkipCount = 16;
if (is_expensive ||
timer.start_cycles % kKernelExecutionTrackingInvocationSkipCount == 0) {
kernel_stats_->UpdateCostEstimate(item, timer.ElapsedCycles());
}
} else {
device->Compute(op_kernel, &ctx);
}
kernel_stats_->StopCollectOp(&item,
const_cast<ExecutorInternal::KernelStatsInfo*>(&kernel_stat_buffer));
nodestats::SetOpEnd(stats);
if (outputs->size() < item.num_outputs) outputs->resize(item.num_outputs);
s = ProcessOutputs(item, &ctx, outputs->data(), stats);
nodestats::SetMemory(stats, &ctx);
return s;
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::ProcessAsync(
const NodeItem& item, const OpKernelContext::Params& params,
const TaggedNode& tagged_node, Entry* first_input,
NodeExecStatsInterface* stats) {
AsyncOpKernel* async_kernel = item.kernel->AsAsync();
DCHECK(async_kernel != nullptr);
AsyncState* state =
new AsyncState(params, tagged_node, &item, first_input, stats);
ExecutorInternal::KernelStatsInfo kernel_stat_buffer;
kernel_stats_->StartCollectOp(&item, &kernel_stat_buffer);
auto done = [this, state, kernel_stat_buffer{std::move(kernel_stat_buffer)}]() {
Device* device = immutable_state_.params().device;
NodeExecStatsInterface* stats = state->stats; // Shorthand
Entry* first_input = state->first_input; // Shorthand
nodestats::SetOpEnd(stats);
this->GetKernelStats()->StopCollectOp(state->item,
const_cast<ExecutorInternal::KernelStatsInfo*>(&kernel_stat_buffer));
EntryVector outputs(state->item->num_outputs);
Status s = ProcessOutputs(*state->item, &state->ctx, outputs.data(), stats);
nodestats::SetMemory(stats, &state->ctx);
if (vlog_) {
VLOG(2) << "Async kernel done: " << state->item->node->id() << " step "
<< step_id_ << " " << SummarizeNodeDef(state->item->kernel->def())
<< (state->tagged_node.get_is_dead() ? " is dead" : "")
<< " device: " << device->name();
}
// Clears inputs.
const int num_inputs = state->item->num_inputs;
for (int i = 0; i < num_inputs; ++i) {
(first_input + i)->ClearVal();
}
propagator_.MaybeMarkCompleted(state->tagged_node);
TaggedNodeSeq ready;
if (s.ok()) {
propagator_.PropagateOutputs(state->tagged_node, &outputs, &ready);
}
outputs.clear();
const bool completed = NodeDone(s, &ready, stats, nullptr);
delete state;
if (completed) ScheduleFinish();
};
nodestats::SetOpStart(stats);
{
profiler::TraceMe activity(
[&] {
int64 id = step_id_;
if (step_container_ && step_container_->StepId()) {
id = step_container_->StepId();
}
return strings::StrCat(
async_kernel->name(), ":", async_kernel->type_string(),
"#id=", id, ",device=", immutable_state_.params().device->name(),
",async=true#");
},
profiler::GetTFTraceMeLevel(async_kernel->IsExpensive()));
immutable_state_.params().device->ComputeAsync(async_kernel, &state->ctx,
std::move(done));
}
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::ProcessNoop(
NodeExecStatsInterface* stats) {
nodestats::SetOpStart(stats);
nodestats::SetOpEnd(stats);
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::ProcessConstTensor(
const NodeItem& item, EntryVector* outputs, NodeExecStatsInterface* stats) {
nodestats::SetOpStart(stats);
nodestats::SetOpEnd(stats);
Entry& output = (*outputs)[0];
output.state = Entry::State::HAS_CONST_TENSOR;
output.const_tensor = item.const_tensor;
output.alloc_attr = item.output_attrs()[0];
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::Process(
TaggedNode tagged_node, int64_t scheduled_nsec) {
std::vector<TaggedNode> nodes;
nodes.push_back(tagged_node);
BatchProcess(nodes, 1, scheduled_nsec);
}
template <class PropagatorStateType>
void ExecutorState<PropagatorStateType>::BatchProcess(std::vector<TaggedNode> nodes,
int nodes_count,
int64_t scheduled_nsec) {
WithContext wc(context_);
TaggedNodeSeq ready;
TaggedNodeReadyQueue inline_ready;
// Parameters passed to OpKernel::Compute.
TensorValueVec inputs;
AllocatorAttributeVec input_alloc_attrs;
OpKernelContext::Params params;
params.step_id = step_id_;
params.round_step_id = round_step_id_;
// Override device's threadpool if user provides an intra_op_threadpool
Device* device = immutable_state_.params().device;
if (user_device_) {
params.device = user_device_.get();
} else {
params.device = device;
}
params.start_time_usecs = start_time_usecs_;
params.deadline = deadline_;
params.log_memory = log_memory_;
params.rendezvous = rendezvous_;
params.create_rendezvous = create_rendezvous_;
params.global_rendezvous = global_rendezvous_;
params.collective_executor = collective_executor_;
params.session_state = session_state_;
params.session_handle = session_handle_;
params.session_metadata = session_metadata_;
params.tensor_store = tensor_store_;
params.cancellation_manager = cancellation_manager_;
params.call_frame = call_frame_;
params.function_library = immutable_state_.params().function_library;
params.resource_manager = device->resource_manager();
params.step_container = step_container_;
params.slice_reader_cache = slice_reader_cache_;
params.inputs = &inputs;
params.input_alloc_attrs = &input_alloc_attrs;
params.runner = &runner_;
params.run_all_kernels_inline =
(executor_policy_ == ExecutorPolicy::USE_INLINE_EXECUTOR);
params.stats_collector = stats_collector_;
params.inc_num_deferred_ops_function = [this]() {
mutex_lock lock(num_deferred_ops_mu_);
num_deferred_ops_++;
};
params.dec_num_deferred_ops_function = [this]() {
bool finish_when_deferred_ops_done = false;
{
mutex_lock lock(num_deferred_ops_mu_);
num_deferred_ops_--;
if (num_deferred_ops_ == 0) {
finish_when_deferred_ops_done = finish_when_deferred_ops_done_;
}
}
// Invoke Finish if the graph processing has completed. Finish is always
// called exactly once per ExecutorState, either here if there are any
// deferred ops, or in ScheduleFinish if there aren't any deferred ops.
if (finish_when_deferred_ops_done) Finish();
};
// Set the device_context for this device, if it exists.
params.op_device_context = device_context_;
Status s;
NodeExecStatsInterface* stats = nullptr;
EntryVector outputs(1);
bool completed = false;
for (size_t i = 0; i < nodes_count; ++i) {
inline_ready.push_back(nodes[i]);
}
TaggedNode tagged_node;
while (!inline_ready.empty()) {
tagged_node = inline_ready.front();
inline_ready.pop_front();
const NodeItem& item = tagged_node.get_node_item();
const int id = item.node->id();
propagator_.MaybeMarkStarted(tagged_node);
if (item.virtual_device.get() != nullptr) {
params.device = item.virtual_device.get();
}
params.track_allocations = false;
stats = nullptr;
if (stats_collector_ && !tagged_node.get_is_dead()) {
stats = stats_collector_->CreateNodeExecStats(&item.kernel->def());
// Track allocations if and only if we are collecting statistics, and
// `stats` object is expecting allocations to be tracked.
params.track_allocations = stats ? stats->TrackAllocations() : false;
nodestats::SetScheduled(stats, scheduled_nsec);
nodestats::SetAllStart(stats);
nodestats::SetParentID(stats);
nodestats::SetActivityID(stats);
}
if (vlog_) {
VLOG(1) << "Process node: " << id << " step " << params.step_id << " "
<< SummarizeNodeDef(item.kernel->def())
<< (tagged_node.get_is_dead() ? " is dead" : "")
<< " device: " << device->name();
}
Entry* first_input = propagator_.GetInputTensors(tagged_node);
// Only execute this node if it is not dead or it is a send/recv
// transfer node. For transfer nodes, we need to propagate the "dead"
// bit even when the node is dead.
bool launched_asynchronously = false;
if (tagged_node.get_is_dead() && !item.is_transfer_node) {
if (outputs.size() < item.num_outputs) outputs.resize(item.num_outputs);
} else if (TF_PREDICT_FALSE(item.is_noop)) {
ProcessNoop(stats);
} else if (item.const_tensor != nullptr && !params.track_allocations) {
ProcessConstTensor(item, &outputs, stats);
} else {
// Prepares inputs.
bool is_input_dead = false;
std::vector<bool> is_input_dead_details;
s = PrepareInputs(item, first_input, &inputs, &input_alloc_attrs,
&is_input_dead, &is_input_dead_details);
if (!s.ok()) {
// Clear inputs.
const int num_inputs = item.num_inputs;
for (int i = 0; i < num_inputs; ++i) {
(first_input + i)->ClearVal();
}
propagator_.MaybeMarkCompleted(tagged_node);
// Continue to process the nodes in 'inline_ready'.
completed = NodeDone(s, &ready, stats, &inline_ready);
continue;
}
// Set up compute params.
params.op_kernel = item.kernel;
params.frame_iter = propagator_.GetFrameAndIter(tagged_node);
params.is_input_dead = is_input_dead;
params.is_input_dead_details = is_input_dead_details;
params.output_attr_array = item.output_attrs();
params.forward_from_array = item.forward_from();
params.outputs_required_array = item.outputs_required.get();
if (item.kernel_is_async) {
ProcessAsync(item, params, tagged_node, first_input, stats);
launched_asynchronously = true;
} else {
s = ProcessSync(item, ¶ms, &outputs, stats);
}