forked from tensorflow/tensorflow
/
execute.cc
1926 lines (1787 loc) · 76.2 KB
/
execute.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/common_runtime/eager/execute.h"
#include <cstddef>
#include <vector>
// clang-format off
// Required for IS_MOBILE_PLATFORM
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_replace.h"
#include "tensorflow/core/common_runtime/eager/eager_operation.h"
#include "tensorflow/core/framework/cancellation.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/protobuf.h"
// clang-format on
#include "absl/container/inlined_vector.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include "tensorflow/c/tf_tensor_internal.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/core/common_runtime/colocation_graph.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_set.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/common_runtime/eager/copy_to_device_node.h"
#include "tensorflow/core/common_runtime/eager/execute_node.h"
#include "tensorflow/core/common_runtime/eager/kernel_and_device.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/logging.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/tensor_reference.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/profiler/lib/scoped_memory_debug_annotation.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
#include "tensorflow/core/util/device_name_utils.h"
#if !defined(IS_MOBILE_PLATFORM)
#include "tensorflow/core/distributed_runtime/eager/eager_client.h"
#include "tensorflow/core/distributed_runtime/eager/remote_copy_node.h"
#include "tensorflow/core/distributed_runtime/eager/remote_mgr.h"
#include "tensorflow/core/distributed_runtime/eager/remote_execute_node.h"
#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h"
#endif // IS_MOBILE_PLATFORM
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/gtl/flatset.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/util/ptr_util.h"
#include "tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h"
#ifdef INTEL_MKL
#include "tensorflow/core/graph/mkl_graph_util.h"
#include "tensorflow/core/util/util.h"
#endif
namespace tensorflow {
namespace {
const string& DeviceNameOrUnspecified(Device* device) {
static string* unspecified_string = new string("<unspecified>");
return (device == nullptr) ? *unspecified_string : device->name();
}
// Returns whether a kernel should be cached.
bool KernelCacheEnabled(const OpDef& op_def) {
if (data::DatasetOpKernel::IsDatasetOp(op_def)) {
return false;
}
// TODO(b/162540360): Revisit a way to mark kernels as uncachable once we have
// 5+ kernels to exclude.
return true;
}
// This function expects *handle to point to an existing tensor handle that is
// currently on "handle_device", but where the operation expects that input to
// reside on "expected_input_device". The function will arrange for this
// transfer to happen and will return OK on success and will storage a new
// handle to the equivalent tensor on the correct device in "*result". Or if an
// error is encountered, it will return a non-OK status and set "*result" to
// nullptr.
//
// `op_device` is passed in explicitly because `op->device()` might be
// unset and we might have selected some specific device to run this op on.
Status CopyInputToExpectedDevice(EagerContext* ctx, EagerOperation* op,
Device* op_device,
TensorHandle* handle, // op->Inputs()[i]
int i, Device* handle_device,
Device* expected_input_device,
TensorHandle** result) {
// Should only be called when these don't match
DCHECK(expected_input_device != handle_device);
*result = nullptr;
const string& op_device_name = DeviceNameOrUnspecified(op_device);
switch (ctx->GetDevicePlacementPolicy()) {
case DEVICE_PLACEMENT_SILENT_FOR_INT32:
// TODO(xpan): See if we could bubble python related error up
// to python level.
if (handle->dtype == DT_INT32) {
// Note: enabling silent copies of int32 tensors to match behavior
// of graph mode.
break;
}
TF_FALLTHROUGH_INTENDED;
case DEVICE_PLACEMENT_EXPLICIT:
// tf.identity is allowed to copy, as indicated in the error message
// below.
if (op->Name() == "Identity" ||
op->Name() == "IdentityN"
// Constants start on CPU:0 and are copied via EagerConst to the
// current device.
|| op->Name() == "_EagerConst") {
break;
}
return errors::InvalidArgument(
"Tensors on conflicting devices:"
" cannot compute ",
op->Name(), " as input #", i, " was expected to be on ",
expected_input_device->name(), " but is actually on ",
handle_device->name(), " (operation running on ", op_device_name, ")",
" Tensors can be copied explicitly using:"
" `with tf.device(device_name): x = tf.identity(x)`"
" or transparently copied by using"
" tf.config.experimental.set_device_policy('silent')."
" Copying tensors between devices may slow down your model");
case DEVICE_PLACEMENT_WARN:
LOG(WARNING) << "before computing " << op->Name() << " input #" << i
<< " was expected to be on " << expected_input_device->name()
<< " but is actually on " << handle_device->name()
<< " (operation running on " << op_device_name
<< "). This triggers a copy which can be a performance "
"bottleneck.";
break;
case DEVICE_PLACEMENT_SILENT: // Do nothing.
break;
}
// We are only here if the policy is warn or silent copies, so we should
// trigger a copy.
TensorHandle* result_handle = nullptr;
profiler::TraceMe activity(
[&] {
return absl::StrCat("_Send input ", i, " from ", handle_device->name(),
" to ", expected_input_device->name());
},
profiler::TraceMeLevel::kInfo);
Status status =
EagerCopyToDevice(handle, ctx, &op->Executor(), expected_input_device,
/* mirror= */ true, &result_handle);
activity.Stop();
if (!status.ok()) {
return Status(
status.code(),
absl::StrCat("Failed copying input tensor from ", handle_device->name(),
" to ", expected_input_device->name(), " in order to run ",
op->Name(), ": ", status.error_message()));
}
*result = result_handle;
return Status::OK();
}
// `op_device_name` the name of the device on which the op will run, if any.
// For functions running using function library runtime, the device can be
// unspecified.
Status ValidateInputTypeAndPlacement(
EagerContext* ctx, EagerOperation* op,
const core::RefCountPtr<KernelAndDevice>& kernel) {
profiler::TraceMe activity("ValidateInputTypeAndPlacement",
profiler::TraceMeLevel::kInfo);
const int n_inputs = op->Inputs().size();
if (kernel->num_inputs() != n_inputs) {
return errors::InvalidArgument("expected ", kernel->num_inputs(),
" inputs, got ", n_inputs);
}
const bool is_function = kernel->IsFunction();
if (n_inputs > 0) {
const DataType* input_types = &kernel->input_dtypes()[0];
const absl::InlinedVector<TensorHandle*, 4>* handles;
TF_RETURN_IF_ERROR(op->TensorHandleInputs(&handles));
for (int i = 0; i < n_inputs; ++i) {
TensorHandle* handle = (*handles)[i];
Device* expected_device = kernel->InputDevice(i);
if (!kernel->IsFunction() && handle->Type() == TensorHandle::PACKED) {
// Extract a handle on the op device from a packed input.
// This happens when a function is marked for XLA compilation.
// MaybePackInputTensor guarantees that a primitive op has no packed
// input at this point.
for (int j = 0; j < handle->NumPackedHandles(); ++j) {
TensorHandle* h = nullptr;
TF_RETURN_IF_ERROR(handle->ExtractPackedHandle(j, &h));
if ((h->op_device() != nullptr) &&
(h->op_device()->name() == op->DeviceName())) {
op->UpdateInput(i, h);
handle = h;
break;
}
}
}
Device* handle_device = handle->DeviceOrHostCPU(*ctx);
const bool maybe_copy =
!is_function || handle->Type() != TensorHandle::REMOTE;
// If the input is already on the right device, then nothing to do.
if (expected_device != handle_device && maybe_copy) {
TF_RETURN_IF_ERROR(CopyInputToExpectedDevice(ctx, op, kernel->device(),
handle, i, handle_device,
expected_device, &handle));
op->UpdateInput(i, handle);
// Unref handle since it has a ref as an input now
handle->Unref();
}
if (handle->dtype != input_types[i]) {
return errors::InvalidArgument(
"cannot compute ", op->Name(), " as input #", i, "(zero-based)",
" was expected to be a ", DataTypeString(input_types[i]),
" tensor but is a ", DataTypeString(handle->dtype), " tensor");
}
}
}
return Status::OK();
}
Status GetOutputDTypes(EagerOperation* op, DataTypeVector* output_dtypes) {
const auto& node_def = op->MutableAttrs()->BuildNodeDef();
const OpDef* op_def = nullptr;
const FunctionDef* function_def =
op->EagerContext().FuncLibDef()->Find(op->Name());
if (function_def != nullptr) {
op_def = &(function_def->signature());
} else {
TF_RETURN_IF_ERROR(OpDefForOp(op->Name().c_str(), &op_def));
}
TF_RETURN_IF_ERROR(OutputTypesForNode(node_def, *op_def, output_dtypes));
return Status::OK();
}
inline tensorflow::Fprint128 FingerprintCat128(const tensorflow::Fprint128& a,
const tensorflow::Fprint128& b) {
return {tensorflow::FingerprintCat64(a.low64, b.low64),
tensorflow::FingerprintCat64(a.high64, b.high64)};
}
inline tensorflow::Fprint128 FingerprintCat128(const tensorflow::Fprint128& a,
const int64_t b) {
auto x = tensorflow::FingerprintCat64(a.low64, b);
return {x, tensorflow::FingerprintCat64(a.high64, x)};
}
Status GetDeviceForInput(const EagerContext& ctx, TensorHandle* tensor_handle,
Device** result) {
Device* cpu_device = ctx.HostCPU();
string device_name;
if (tensor_handle->Type() != TensorHandle::LOCAL) {
Device* device = tensor_handle->device();
device_name = device != nullptr ? device->name() : cpu_device->name();
*result = (device == nullptr ? cpu_device : device);
} else if (tensor_handle->dtype == DT_RESOURCE) {
// Use the resource's actual device because it is the device that will
// influence partitioning the multi-device function.
const Tensor* tensor;
// TODO(fishx): Avoid blocking here.
TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor));
const ResourceHandle& handle = tensor->flat<ResourceHandle>()(0);
device_name = handle.device();
Device* input_device;
TF_RETURN_IF_ERROR(
ctx.FindDeviceFromName(device_name.c_str(), &input_device));
*result = input_device;
} else {
Device* device = tensor_handle->device();
const bool is_tpu = device != nullptr && device->device_type() == "TPU";
// int32 return values can be placed on TPUs.
const bool use_host_memory =
is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype)
: MTypeFromDType(tensor_handle->dtype);
if (use_host_memory) {
*result = cpu_device;
} else {
device_name = device != nullptr ? device->name() : cpu_device->name();
*result = (device == nullptr ? cpu_device : device);
}
}
return Status::OK();
}
// Appends a TensorShape object to Fprint128 hash.
// For best performance, we would like to avoid dynamic memory allocation in
// this function.
// If "shape" has unknown rank, we attach "?" to hashed content; otherwise we
// attach every dim size to hashed content.
void AppendTensorShapeToFingerprint(const PartialTensorShape& shape,
Fprint128* fingerprint) {
if (shape.unknown_rank()) {
char c = '?';
*fingerprint = FingerprintCat128(*fingerprint, c);
} else {
for (int i = 0; i < shape.dims(); i++) {
int64_t dim = shape.dim_size(i);
*fingerprint = FingerprintCat128(*fingerprint, dim);
}
}
}
Status GetFuncAttr(const EagerOperation* op, const EagerContext& ctx,
const char* attr_name, bool* value) {
Status status = op->Attrs().Get(attr_name, value);
if (status.ok()) {
VLOG(2) << "Caller explicitly specifies "
<< (attr_name ? "=true " : "=false, ") << op->DebugString();
return Status::OK();
}
const FunctionDef* function_def =
ctx.pflr()->GetFunctionLibraryDefinition()->Find(op->Name());
if (function_def == nullptr) {
return errors::NotFound("Failed to find function '", op->Name(), "'");
}
status = GetNodeAttr(AttrSlice(&function_def->attr()), attr_name, value);
if (status.ok()) {
VLOG(2) << "Function definition explicitly specifies "
<< (attr_name ? "=true" : "=false");
return Status::OK();
}
return status;
}
Status MustCompileWithXLA(const EagerOperation* op, const EagerContext& ctx,
bool* compile_with_xla) {
if (!op->is_function()) {
*compile_with_xla = false;
return Status::OK();
}
if (op->remote_func_params().has_value() &&
op->remote_func_params().value().step_id.has_value()) {
// If the op is a component of a multi-device function, don't compile it
// with XLA.
*compile_with_xla = false;
return Status::OK();
}
Status status = GetFuncAttr(op, ctx, kXlaMustCompileAttr, compile_with_xla);
if (status.ok()) {
return Status::OK();
}
// No explicit requests. Compile for XLA devices by default.
if (op->GetDeviceParsedName().type == "TPU" ||
op->GetDeviceParsedName().type == "XLA_GPU" ||
op->GetDeviceParsedName().type == "XLA_CPU") {
VLOG(2) << "Compiling " << op->Name()
<< " with XLA because it is running on an XLA device "
<< op->GetDeviceParsedName().type;
*compile_with_xla = true;
} else {
*compile_with_xla = false;
}
return Status::OK();
}
Status VerifyWrappableInCallOp(const OpDef& opdef, EagerOperation* op) {
absl::flat_hash_set<string> opdef_attrs;
for (const auto& attr : opdef.attr()) {
opdef_attrs.insert(attr.name());
}
const auto& node_def = op->MutableAttrs()->BuildNodeDef();
for (const auto& attr : node_def.attr()) {
if (opdef_attrs.find(attr.first) == opdef_attrs.end()) {
return errors::Unimplemented("EagerOperation: ", op->Name(),
" has a private attr '", attr.first, "'.");
}
}
return Status::OK();
}
using ProtoArgListType = protobuf::RepeatedPtrField<OpDef_ArgDef>;
string EscapeOrigName(const string& orig_name) {
// Replace _ with __ in the original name to avoid name conflicts.
return absl::StrReplaceAll(orig_name, {{"_", "__"}});
}
// Variadic args are flattened during wrapping. This utility returns the name
// of a flattened arg/attr.
string GetFlatName(const string orig_name, int index) {
return absl::StrCat(EscapeOrigName(orig_name), "_", index);
}
// Builds the name of the wrapping FunctionDef for an eager op.
//
// For ops without variadic inputs/outputs, the name is simply __wrapped_OpType.
//
// For ops with variadic inputs/outputs, the arity of each variadic attr is
// encoded in the name. For example:
//
// IdentityN[T:[DT_FLOAT, DT_INT64]] -> __wrapped__IdentityN_T_2
// Concat[N:2, T:DT_FLOAT] -> __wrapped__Concat_N_2
Status BuildWrappedOpName(EagerOperation* op, const OpDef& opdef,
const AbstractOpAttrs* op_attrs, string* name) {
string fname = absl::StrCat("__wrapped__", EscapeOrigName(op->Name()));
// For every variadic arg in `args`, populates `attr_to_len` with
// (attr_name, len(arg)).
auto FillAttrToLen = [op_attrs, op](
const ProtoArgListType& args,
absl::btree_map<string, int>* attr_to_len) {
for (const auto& arg : args) {
if (!arg.type_list_attr().empty()) {
gtl::InlinedVector<DataType, 4> type_list;
TF_RETURN_IF_ERROR(
op_attrs->GetTypeList(arg.type_list_attr(), &type_list));
(*attr_to_len)[arg.type_list_attr()] = type_list.size();
} else if (!arg.number_attr().empty()) {
int64_t number_attr;
if (!op_attrs->GetInt(arg.number_attr(), &number_attr)) {
return errors::Internal("Unable to read attr ", arg.number_attr(),
" for op ", op->Name());
}
(*attr_to_len)[arg.number_attr()] = number_attr;
}
}
return Status::OK();
};
absl::btree_map<string, int> attr_to_len;
TF_RETURN_IF_ERROR(FillAttrToLen(opdef.input_arg(), &attr_to_len));
TF_RETURN_IF_ERROR(FillAttrToLen(opdef.output_arg(), &attr_to_len));
for (auto& name_len : attr_to_len) {
absl::StrAppend(&fname, "_", name_len.first, "_", name_len.second);
}
// The NodeDef in the FunctionDef gets placed on `op-DeviceName()` to ensure
// placement consistency with eager mode.
// TODO(b/200153278): Ideally we would just forward the call op's device at
// runtime but currently there is no way to do it so we incur the cost of
// creating extra FunctionDefs.
absl::StrAppend(&fname, "_device_", op->DeviceName());
*name = fname;
return Status::OK();
}
// Builds the signature of the wrapping FunctionDef for an eager op.
//
// For ops without variadic inputs/outputs, the signature is the same as the
// OpDef of the original op.
//
// Variadic inputs/outputs get flattened since we do not support executing
// functions with variadic signatures.
//
// TODO(srbs): These examples should be tests.
//
// Examples:
//
// Mixed type list:
//
// op {
// name: "IdentityN"
// input_arg {
// name: "input"
// type_list_attr: "T"
// }
// output_arg {
// name: "output"
// type_list_attr: "T"
// }
// attr {
// name: "T"
// type: "list(type)"
// has_minimum: true
// minimum: 1
// }
// }
//
// With two inputs T=[DT_FLOAT, DT_INT64] would convert to
//
// op {
// name: "__wrapped__IdentityN_T_2"
// input_arg {
// name: "input_0"
// type_attr: "T_0"
// }
// input_arg {
// name: "input_1"
// type_attr: "T_1"
// }
// output_arg {
// name: "output_0"
// type_attr: "T_0"
// }
// output_arg {
// name: "output_1"
// type_attr: "T_1"
// }
// attr {
// name: "T_0"
// type: "type"
// }
// attr {
// name: "T_1"
// type: "type"
// }
// attr {
// name: "T"
// type: "list(type)"
// has_minimum: true
// minimum: 1
// }
// }
//
// Note that the list(type) attr is preserved so that it can get copied to the
// inner op via a placeholder. This allows additional verification.
//
// Single type list:
//
// op {
// name: "ConcatV2"
// input_arg {
// name: "values"
// type_attr: "T"
// number_attr: "N"
// }
// attr {
// name: "N"
// type: "int"
// has_minimum: true
// minimum: 2
// }
// attr {
// name: "T"
// type: "type"
// }
// [axis, output, Tidx are simply copied]
// }
//
// With two inputs N=2 would convert to:
//
// op {
// name: "__wrapped__ConcatV2_N_2"
// input_arg {
// name: "values_0"
// type_attr: "T"
// }
// input_arg {
// name: "values_1"
// type_attr: "T"
// }
// attr {
// name: "N"
// type: "int"
// has_minimum: true
// minimum: 2
// }
// attr {
// name: "T"
// type: "type"
// }
// [axis, output, Tidx are simply copied]
// }
//
// Note that the N attr is preserved so that it can get copied to the
// inner op via a placeholder. This allows additional verification.
Status BuildWrappedOpSignature(EagerOperation* op, const OpDef& opdef,
const string& fname, OpDef& signature) {
signature = opdef;
signature.clear_input_arg();
signature.clear_output_arg();
signature.set_name(fname);
auto op_attrs = op->GetOpAttrs();
auto FillSignatureArgs = [op_attrs, op](
const ProtoArgListType& opdef_args,
ProtoArgListType* sig_args,
absl::flat_hash_set<string>& new_attrs) {
for (const auto& arg : opdef_args) {
if (!arg.type_list_attr().empty()) {
gtl::InlinedVector<DataType, 4> type_list;
TF_RETURN_IF_ERROR(
op_attrs->GetTypeList(arg.type_list_attr(), &type_list));
for (size_t i = 0; i < type_list.size(); i++) {
auto arg_def = sig_args->Add();
arg_def->set_name(GetFlatName(arg.name(), i));
auto attr_name = GetFlatName(arg.type_list_attr(), i);
new_attrs.insert(attr_name);
arg_def->set_type_attr(std::move(attr_name));
}
} else if (!arg.number_attr().empty()) {
int64_t number_attr;
if (!op_attrs->GetInt(arg.number_attr(), &number_attr)) {
return errors::Internal("Unable to read attr ", arg.number_attr(),
" for op ", op->Name());
}
for (size_t i = 0; i < number_attr; i++) {
auto arg_def = sig_args->Add();
arg_def->set_name(GetFlatName(arg.name(), i));
if (!arg.type_attr().empty()) {
arg_def->set_type_attr(arg.type_attr());
} else {
arg_def->set_type(arg.type());
}
}
} else {
auto arg_def = sig_args->Add();
*arg_def = arg;
arg_def->set_name(EscapeOrigName(arg.name()));
if (!arg.type_attr().empty()) {
// Don't escape: type attrs are still referenced by the original name.
arg_def->set_type_attr(arg.type_attr());
}
}
}
return Status::OK();
};
absl::flat_hash_set<string> new_attrs;
TF_RETURN_IF_ERROR(FillSignatureArgs(
opdef.input_arg(), signature.mutable_input_arg(), new_attrs));
TF_RETURN_IF_ERROR(FillSignatureArgs(
opdef.output_arg(), signature.mutable_output_arg(), new_attrs));
for (auto& attr_name : new_attrs) {
auto attr_def = signature.mutable_attr()->Add();
attr_def->set_name(attr_name);
attr_def->set_type("type");
}
return Status::OK();
}
// For mixed type inputs "list(type)" we create new attributes in the signature
// for each element tensor (See examples in BuildWrappedOpSignature). Here
// we construct the values for those attributes and set them on the wrapped op.
Status AddMixedTypeListAttrs(EagerOperation* wrapped_op,
const AbstractOpAttrs* op_attrs,
const OpDef& opdef) {
auto FillAttrsToAdd =
[op_attrs](const ProtoArgListType& opdef_args,
absl::flat_hash_map<string, DataType>* attrs_to_add) {
for (const auto& arg : opdef_args) {
if (!arg.type_list_attr().empty()) {
gtl::InlinedVector<DataType, 4> type_list;
TF_RETURN_IF_ERROR(
op_attrs->GetTypeList(arg.type_list_attr(), &type_list));
for (size_t i = 0; i < type_list.size(); i++) {
auto attr_name = GetFlatName(arg.type_list_attr(), i);
(*attrs_to_add)[attr_name] = type_list[i];
}
}
}
return Status::OK();
};
absl::flat_hash_map<string, DataType> attrs_to_add;
TF_RETURN_IF_ERROR(FillAttrsToAdd(opdef.input_arg(), &attrs_to_add));
TF_RETURN_IF_ERROR(FillAttrsToAdd(opdef.output_arg(), &attrs_to_add));
for (auto& name_type : attrs_to_add) {
TF_RETURN_IF_ERROR(
wrapped_op->SetAttrType(name_type.first.data(), name_type.second));
}
// TODO(srbs): Rename all original attributes using EscapeOrigName.
return Status::OK();
}
// Maps the op's outputs to the function outputs. Mainly useful for variadic
// outputs which need to be flattened.
Status PopulateRetMap(FunctionDef* fdef, const AbstractOpAttrs* op_attrs,
const EagerOperation* op, const OpDef& opdef,
const OpDef& signature, const string& node_name) {
int next_sig_output = 0;
for (size_t i = 0; i < opdef.output_arg_size(); i++) {
const auto& output_arg = opdef.output_arg(i);
if (!output_arg.type_list_attr().empty()) {
gtl::InlinedVector<DataType, 4> type_list;
TF_RETURN_IF_ERROR(
op_attrs->GetTypeList(output_arg.type_list_attr(), &type_list));
for (int j = 0; j < type_list.size(); j++) {
(*fdef->mutable_ret())[signature.output_arg(next_sig_output++).name()] =
absl::StrCat(node_name, ":", output_arg.name(), ":", j);
}
} else if (!output_arg.number_attr().empty()) {
int64_t number_attr;
if (!op_attrs->GetInt(output_arg.number_attr(), &number_attr)) {
return errors::Internal("Unable to read attr ",
output_arg.number_attr(), " for op ",
op->Name());
}
for (int j = 0; j < number_attr; j++) {
(*fdef->mutable_ret())[signature.output_arg(next_sig_output++).name()] =
absl::StrCat(node_name, ":", output_arg.name(), ":", j);
}
} else {
(*fdef->mutable_ret())[signature.output_arg(next_sig_output++).name()] =
absl::StrCat(node_name, ":", output_arg.name(), ":0");
}
}
return Status::OK();
}
Status WrapInCallOp(EagerOperation* op, EagerOperation** wrapped_op) {
DCHECK(!op->is_function());
const OpDef& opdef = OpRegistry::Global()->LookUp(op->Name())->op_def;
// Raise an error for ops which don't support wrapping yet. This includes
// ops with list inputs/outputs and ops with private attrs.
// TODO(srbs): Support list inputs/outputs.
TF_RETURN_IF_ERROR(VerifyWrappableInCallOp(opdef, op));
// Build a FunctionDef containing op as a node and register with context.
// TODO(srbs): Here we are unable to distinguish between a FunctionDef for
// a wrapped eager op and an existing user defined function registered with
// the context e.g. with something like
// @tf.function
// def __wrapped__Add(x, y):
// ...
// This can be avoided by introducing a dict in EagerContext that stores a
// mapping from the eager op's name to its unique FunctionDef name.
auto op_attrs = op->GetOpAttrs();
string fname;
TF_RETURN_IF_ERROR(BuildWrappedOpName(op, opdef, op_attrs, &fname));
if (!op->EagerContext().GetFunctionDef(fname)) {
FunctionDef fdef;
// Set signature.
TF_RETURN_IF_ERROR(
BuildWrappedOpSignature(op, opdef, fname, *fdef.mutable_signature()));
// Add node.
NodeDef* ndef = fdef.add_node_def();
ndef->set_op(op->Name());
ndef->set_name(op->Name()); // This could be anything.
const auto& signature = fdef.signature();
for (size_t i = 0; i < signature.input_arg_size(); i++) {
ndef->add_input(absl::StrCat(fdef.signature().input_arg(i).name(), ":0"));
}
// TODO(srbs): Private attrs on the op are dropped here and applied to
// the call op instead. If this causes problems we might have to copy those
// attrs to this ndef. That would require updating fname to contain a hash
// of such attributes.
for (const auto& attr : opdef.attr()) {
(*ndef->mutable_attr())[attr.name()].set_placeholder(attr.name());
}
// Set the device of this node to be the exact same one that eager mode
// would have used.
// TODO(b/200153278): Ideally we would just forward the call op's device at
// runtime but currently there is no way to do it.
ndef->set_device(op->DeviceName());
#ifdef INTEL_MKL
if (IsMKLEnabled() &&
absl::StartsWith(op->Name(), mkl_op_registry::kMklOpPrefix)) {
// All MKL eager ops have `_kernel` private attribute that needs to be set
// to a fixed label.
AttrValue attr_kernel;
attr_kernel.set_s(mkl_op_registry::kMklNameChangeOpLabel);
(*ndef->mutable_attr()).insert({"_kernel", attr_kernel});
}
#endif // INTEL_MKL
// Set `ret` map.
TF_RETURN_IF_ERROR(
PopulateRetMap(&fdef, op_attrs, op, opdef, signature, ndef->name()));
VLOG(1) << fdef.DebugString();
TF_RETURN_IF_ERROR(op->EagerContext().AddFunctionDef(std::move(fdef)));
}
// Build the call op.
auto& ctx = op->EagerContext();
AbstractOperationPtr call_op(ctx.CreateOperation());
TF_RETURN_IF_ERROR(call_op->Reset(fname.c_str(), op->DeviceName().c_str()));
for (auto t : op->Inputs()) {
TF_RETURN_IF_ERROR(call_op->AddInput(t));
}
*wrapped_op = down_cast<EagerOperation*>(call_op.release());
// Attributes on the elementary eager operation are applied to the call op and
// to the NodeDef inside the FunctionDef. This allows us to have a single
// FunctionDef for different attribute values. When the function is
// instantiated, these attributes get forwarded to the NodeDef. This is done
// by setting the AttrValue.placeholder field for the NodeDef attrs.
(*wrapped_op)->AddAttrs(op_attrs);
return AddMixedTypeListAttrs(*wrapped_op, op_attrs, opdef);
}
Status GetOrCreateKernelAndDevice(
EagerOperation* op, TensorHandle** retvals, int* num_retvals,
core::RefCountPtr<KernelAndDevice>* out_kernel) {
EagerContext& ctx = op->EagerContext();
Device* device = absl::get<Device*>(op->Device());
Fprint128 cache_key = op->MutableAttrs()->CacheKey(op->DeviceName());
/// Include soft placement policy in cache key since the placement strategy
// can change and thus affect which kernel is picked.
cache_key = FingerprintCat128(cache_key, ctx.AllowSoftPlacement());
// The launch-time rendezvous reuse setting is bundled with the kernel, so we
// need to include it in the cache key.
cache_key =
FingerprintCat128(cache_key, ctx.GetReuseRendezvousForFunctions());
std::vector<Device*> input_dev_ptrs;
absl::flat_hash_map<string, const std::vector<string>*> composite_devices;
std::unordered_map<int, DtypeAndPartialTensorShape>
input_resource_variable_dtypes_and_shapes;
// We can eliminate some overhead by running simple functions using regular
// CallOp kernel. However, it is tricky to figure out which functions should
// be run using CallOp. Also, currently CallOp runs neither optimization
// passes (needed for TPU/XLA) nor grappler.
// Here are some cases where a function should be run in multi-device mode:
// - Function takes at least two resources on different devices.
// - Function takes a resource on deviceA and a body op explicitly placed
// on deviceB.
// - Function has a colocation constraint.
// - Function has an explicit device annotation (which might not be using
// full canonical device name) different from op_device. Note that false
// positives are ok.
// - Function has a node or a (node) attribute that can potentially make
// the function multi-device after a rewrite pass (e.g. various XLA/TPU
// special nodes and attributes)
if (op->is_function() || ctx.RunEagerOpAsFunction()) {
profiler::TraceMe activity("EagerCopyToDeviceAndAddCacheKey",
profiler::TraceMeLevel::kInfo);
input_dev_ptrs.reserve(op->Inputs().size());
const absl::InlinedVector<TensorHandle*, 4>* inputs;
TF_RETURN_IF_ERROR(op->TensorHandleInputs(&inputs));
for (int i = 0, end = inputs->size(); i < end; i++) {
TensorHandle* input = (*inputs)[i];
// Get device for this input, and add it to 'cache_key'.
Device* input_device;
TF_RETURN_IF_ERROR(GetDeviceForInput(ctx, input, &input_device));
VLOG(1) << op->Name() << ":input:" << i << " " << input_device->name();
input_dev_ptrs.push_back(input_device);
CompositeDevice* composite_device = nullptr;
if (ctx.FindCompositeDeviceFromName(input_device->name(),
&composite_device)
.ok()) {
composite_devices[input_device->name()] =
composite_device->underlying_devices();
}
cache_key =
FingerprintCat128(cache_key, Fingerprint128(input_device->name()));
// If input is a ResourceHandle, get its resource handle dtypes and shapes
// and add them to 'cache_key'.
if (input->dtype == DT_RESOURCE) {
// We only care about data type and shape for resource variable inputs.
// But we have no way to tell if input is resource variable (other than
// looking it up in ResourceMgr, which is slow). So we just get
// resource_dtypes_and_shapes for all DT_RESOURCE inputs. If
// resource_dtypes_and_shapes is not empty, take the first element.
std::vector<DtypeAndPartialTensorShape> resource_dtypes_and_shapes;
TF_RETURN_IF_ERROR(input->GetResourceHandleDtypesAndShapes(
&resource_dtypes_and_shapes));
if (!resource_dtypes_and_shapes.empty()) {
const DtypeAndPartialTensorShape& dtype_and_shape =
resource_dtypes_and_shapes.at(0);
input_resource_variable_dtypes_and_shapes[i] = dtype_and_shape;
// Add _Arg index, dtype and shape to "cache_key".
cache_key = FingerprintCat128(cache_key, i);
DataType dtype = dtype_and_shape.dtype;
cache_key = FingerprintCat128(cache_key, dtype);
AppendTensorShapeToFingerprint(dtype_and_shape.shape, &cache_key);
}
}
}
}
core::RefCountPtr<KernelAndDevice> kernel = ctx.GetCachedKernel(cache_key);
AbstractOperationPtr wrapped_op_releaser;
if (kernel == nullptr) {
VLOG(2) << "Creating new kernel for " << op->Name() << " on device "
<< DeviceNameOrUnspecified(absl::get<Device*>(op->Device()));
bool run_function_with_flr = false;
bool function_outputs_on_op_device = false;
if (op->is_function()) {
bool compile_with_xla;
TF_RETURN_IF_ERROR(MustCompileWithXLA(op, ctx, &compile_with_xla));
if (compile_with_xla) {
// Note that it is not ideal, but currently correct, to set this
// attribute after computing the kernel cache key above.
// Note: If the attribute is already set to true, this is a noop.
op->MutableAttrs()->Set(kXlaMustCompileAttr, true);
} else {
run_function_with_flr = true;
}
GetFuncAttr(op, ctx, kOutputsOnOpDevice, &function_outputs_on_op_device)
.IgnoreError();
}
VLOG(2) << op->Name() << " function_outputs_on_op_device: "
<< function_outputs_on_op_device;
if (device == nullptr) {
// Here in local execute, set preferred device to be on the local task to
// avoid placing op on a remote device with higher priority.
const DeviceNameUtils::ParsedName& preferred_device =
DeviceNameUtils::HasSomeDetails(op->GetDeviceParsedName())
? op->GetDeviceParsedName()
: DeviceNameUtils::AddressSpace(ctx.HostCPUParsedName());
// Note: We use the unwrapped op for inferring the device.
// Without this, when wrapping CPU-only ops like RangeDataset we would
// place the wrapped op on a GPU (if one is available) which leads to
// errors because placer pins the function output nodes to GPU thereby
// forcing a H2D copy of the dataset variant which is not supported.
const NodeDef& ndef = op->MutableAttrs()->BuildNodeDef();
TF_RETURN_IF_ERROR(ctx.SelectDevice(preferred_device, ndef, &device));
VLOG(1) << "PreferredDevice " << op->Name() << ": " << preferred_device;
VLOG(1) << "Placer place op [" << op->Name()
<< "] on device: " << device->name();
VLOG(4) << "Available kernels for " << op->Name() << " are"
<< KernelsRegisteredForOp(op->Name());
op->SetDevice(device);
} else {
VLOG(1) << "Device for [" << op->Name()
<< "] already set to: " << device->name();
}
// Note: We wrap the eager op AFTER the device has been inferred to ensure
// that placement of the NodeDef in the function is exactly the same as in
// eager mode. This is specially important for cases where the
// preferred device is not the actual device on which the op is run.
// E.g. the preferred device for a `RangeDataset` op could be set to `GPU`
// but `ctx->SelectDevice` would still place it on CPU. Placer on the other
// hand would throw an error.
//
// Note: The wrapped function is never jit compiled but rather run via the
// FLR. This is needed because certain ops e.g. `VarHandleOp` can not be
// jit compiled. Ideally we would run this via the jit compiled path and
// expect unsupported ops to be outside compiled but that is not supported
// on GPUs right now.
if (ctx.RunEagerOpAsFunction() && !op->is_function()) {
EagerOperation* wrapped_op = nullptr;
TF_RETURN_IF_ERROR(WrapInCallOp(op, &wrapped_op));
DCHECK(wrapped_op);
DCHECK(wrapped_op->is_function());
wrapped_op_releaser.reset(wrapped_op);
op = wrapped_op;
run_function_with_flr = true;
}
const NodeDef& ndef = op->MutableAttrs()->BuildNodeDef();
FunctionLibraryRuntime* flr =
device == nullptr ? nullptr : ctx.func_lib(device);
if (device != nullptr && flr == nullptr) {
return errors::NotFound(
"Unable to find a FunctionLibraryRuntime corresponding to device ",
device->name());
}
auto runner = (flr != nullptr && flr->runner() != nullptr) ? flr->runner()
: ctx.runner();
GraphCollector* graph_collector = nullptr;
if (ctx.ShouldStoreGraphs()) {
graph_collector = ctx.GetGraphCollector();
}
// Treat the function as multi_device only when we are not compiling
// it wholly with XLA. When compiling wholly with XLA, flr->CreateKernel
// will create an XlaLaunchOp kernel to compile and run the function.
if (run_function_with_flr) {
// Multi-device functions don't use the rendezvous from eager context.
// If we use that rendezvous, multiple concurrent calls to the same
// function will likely result in collisions. However, this also means
// that we don't support legitimate sending/receiving across function
// boundary.
VLOG(2) << "Running " << ndef.op() << " using multi-device function. "
<< "Full node_def=" << ndef.DebugString();
std::function<int64_t()> get_op_id = nullptr;
#if !defined(IS_MOBILE_PLATFORM)
get_op_id = [&ctx]() { return ctx.RemoteMgr()->NextOpId(); };
#endif // IS_MOBILE_PLATFORM
kernel.reset(new KernelAndDeviceFunc(
flr, ctx.pflr(), std::move(input_dev_ptrs),
std::move(composite_devices),
std::move(input_resource_variable_dtypes_and_shapes), runner,
ctx.GetCollectiveExecutorHandle(), ctx.HostCPU(), op->Name(),