-
Notifications
You must be signed in to change notification settings - Fork 74k
/
functional_ops.cc
1085 lines (980 loc) · 37.2 KB
/
functional_ops.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 <unordered_map>
#include <utility>
#include "tensorflow/core/framework/types.h"
#include "tensorflow/tsl/platform/refcount.h"
#define EIGEN_USE_THREADS
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/casts.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/profiler/lib/traceme.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef FunctionLibraryRuntime::Handle FHandle;
typedef std::vector<Tensor> TensorVec;
namespace {
// Helper to instantiate function "func" in the library "lib".
Status Instantiate(FunctionLibraryRuntime* lib, const NameAttrList& func,
FunctionLibraryRuntime::Handle* handle) {
return lib->Instantiate(func.name(), AttrSlice(&func.attr()), handle);
}
Status Instantiate(OpKernelContext* ctx, const NameAttrList& func,
FunctionLibraryRuntime::Handle* handle) {
FunctionLibraryRuntime::InstantiateOptions opts;
opts.executor_type = ctx->executor_type();
return ctx->function_library()->Instantiate(
func.name(), AttrSlice(&func.attr()), opts, handle);
}
// If "t" is a scalar of a supported type, returns t != 0 in "*v".
Status ToBool(gtl::ArraySlice<Tensor> t, bool* v) {
if (t.size() != 1) {
return errors::InvalidArgument(
"Expected a single scalar which can be converted to a boolean, got ",
t.size(), " tensors.");
}
if (TensorShapeUtils::IsScalar(t[0].shape())) {
switch (t[0].dtype()) {
#define CASE(T) \
case DataTypeToEnum<T>::value: \
*v = t[0].scalar<T>()() != 0; \
break;
CASE(float);
CASE(double);
CASE(int32);
CASE(uint8);
CASE(int16);
CASE(int8);
CASE(int64_t);
#undef CASE
case DT_BOOL:
*v = t[0].scalar<bool>()();
break;
case DT_STRING:
*v = !t[0].scalar<tstring>()().empty();
break;
default:
return errors::InvalidArgument(DataTypeString(t[0].dtype()),
" cannot be converted to a boolean");
}
} else {
*v = t[0].NumElements() > 0;
}
return OkStatus();
}
// Sets "rets" to be the output of "ctx". Validates rets' types based
// on "kernel".
Status SetOutputs(const OpKernel* kernel, OpKernelContext* ctx,
gtl::ArraySlice<Tensor> rets) {
if (rets.size() != ctx->num_outputs()) {
return errors::Internal("Expect to produce ", ctx->num_outputs(),
" tensors, but only get ", rets.size());
}
for (int i = 0; i < rets.size(); ++i) {
if (rets[i].dtype() != kernel->output_type(i)) {
return errors::Internal("Expect ", i, "-th output is of type ",
DataTypeString(kernel->output_type(i)),
" but get ", DataTypeString(rets[i].dtype()));
}
ctx->set_output(i, rets[i]);
}
return OkStatus();
}
void SetRunOptions(OpKernelContext* ctx, FunctionLibraryRuntime::Options* opts,
bool always_collect_stats) {
opts->rendezvous = ctx->rendezvous();
opts->cancellation_manager = ctx->cancellation_manager();
opts->collective_executor = ctx->collective_executor();
if (always_collect_stats) {
opts->stats_collector = ctx->stats_collector();
}
opts->runner = ctx->runner();
opts->run_all_kernels_inline = ctx->run_all_kernels_inline();
opts->step_container = ctx->step_container();
}
class IfOp : public AsyncOpKernel {
public:
explicit IfOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
OP_REQUIRES(ctx, ctx->function_library() != nullptr,
errors::Internal("No function library"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("then_branch", &then_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("else_branch", &else_func_));
}
~IfOp() override {
for (const auto& it : handles_) {
auto lib = it.second.second.GetNewRef();
if (lib == nullptr) {
LOG(INFO) << "FunctionLibraryRuntime already destroyed.";
continue;
}
Status then_status = lib->ReleaseHandle(it.second.first.first);
if (!then_status.ok()) {
LOG(INFO) << "Ignoring error while destructing IfOp then function: "
<< then_status;
}
Status else_status = lib->ReleaseHandle(it.second.first.second);
if (!else_status.ok()) {
LOG(INFO) << "Ignoring error while destructing IfOp else function: "
<< else_status;
}
}
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
FHandle then_handle;
FHandle else_handle;
OP_REQUIRES_OK_ASYNC(ctx, GetHandles(ctx, &then_handle, &else_handle),
done);
bool cond;
OP_REQUIRES_OK(ctx, ToBool({ctx->input(0)}, &cond));
(new State(this, ctx, cond, then_handle, else_handle, done))->Start();
}
private:
NameAttrList then_func_;
NameAttrList else_func_;
mutex mu_;
// TODO(binghu): Use struct to hold the value to improve readability.
std::unordered_map<FunctionLibraryRuntime*,
std::pair<std::pair<FHandle, FHandle>,
tsl::core::WeakPtr<FunctionLibraryRuntime>>>
handles_ ABSL_GUARDED_BY(mu_);
class State {
public:
State(IfOp* kernel, OpKernelContext* ctx, bool cond, FHandle then_handle,
FHandle else_handle, DoneCallback done)
: kernel_(kernel),
ctx_(ctx),
cond_(cond),
then_handle_(then_handle),
else_handle_(else_handle),
done_(std::move(done)),
lib_(CHECK_NOTNULL(ctx_->function_library())),
opts_(ctx->step_id()) {
SetRunOptions(ctx_, &opts_, true /* always_collect_stats */);
for (int i = 1; i < ctx_->num_inputs(); ++i) {
args_.push_back(ctx_->input(i));
}
}
~State() = default;
void Start() {
FHandle handle = cond_ ? then_handle_ : else_handle_;
rets_.clear();
profiler::TraceMe trace_me("IfOp");
lib_->Run(
// Evaluate one of the branch.
opts_, handle, args_, &rets_,
// Done callback
[this](Status s) {
if (s.ok()) {
s = SetOutputs(kernel_, ctx_, rets_);
}
ctx_->SetStatus(s);
DoneCallback captured_done(std::move(done_));
delete this;
captured_done();
});
}
private:
IfOp* const kernel_;
OpKernelContext* const ctx_;
const bool cond_;
FHandle then_handle_;
FHandle else_handle_;
DoneCallback done_;
FunctionLibraryRuntime* const lib_;
FunctionLibraryRuntime::Options opts_;
TensorVec args_;
TensorVec rets_;
};
Status GetHandles(OpKernelContext* ctx, FHandle* then_handle,
FHandle* else_handle) {
// TODO(b/37549631): Because this op has `SetIsStateful()` in its
// op registration, this kernel may be shared by multiple
// subgraphs, which have different associated
// `FunctionLibraryRuntime` objects and hence different `FHandle`
// namespaces. We currently work around this by caching the map
// from `FunctionLibraryRuntime*` to `FHandle` pairs for the two
// functions this op uses.
auto lib = ctx->function_library();
if (lib == nullptr) return errors::Internal("No function library");
*then_handle = kInvalidHandle;
*else_handle = kInvalidHandle;
{
tf_shared_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*then_handle = iter->second.first.first;
*else_handle = iter->second.first.second;
}
}
if (TF_PREDICT_FALSE(*then_handle == kInvalidHandle)) {
mutex_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*then_handle = iter->second.first.first;
*else_handle = iter->second.first.second;
} else {
TF_RETURN_IF_ERROR(Instantiate(ctx, then_func_, then_handle));
TF_RETURN_IF_ERROR(Instantiate(ctx, else_func_, else_handle));
handles_[lib] =
std::make_pair(std::make_pair(*then_handle, *else_handle),
tsl::core::WeakPtr<FunctionLibraryRuntime>(lib));
}
}
return OkStatus();
}
};
class CaseOp : public AsyncOpKernel {
public:
explicit CaseOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
OP_REQUIRES(ctx, ctx->function_library() != nullptr,
errors::Internal("No function library"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("branches", &branch_funcs_));
}
~CaseOp() override {
for (const auto& it : handles_) {
auto lib = it.second.second.GetNewRef();
if (lib == nullptr) {
LOG(INFO) << "FunctionLibraryRuntime already destroyed.";
continue;
}
for (const auto& handle : it.second.first) {
Status status = lib->ReleaseHandle(handle);
if (!status.ok()) {
LOG(INFO)
<< "Ignoring error while destructing CaseOp branch function: "
<< status;
}
}
}
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
const Tensor& branch_index = ctx->input(0);
OP_REQUIRES_ASYNC(ctx, TensorShapeUtils::IsScalar(branch_index.shape()),
errors::InvalidArgument("branch_index must be scalar"),
done);
int32_t branch = branch_index.scalar<int32>()();
std::vector<FHandle> branch_handles(branch_funcs_.size());
OP_REQUIRES_OK_ASYNC(ctx, GetHandles(ctx, branch_handles), done);
(new State(this, ctx, branch, branch_handles, done))->Start();
}
private:
std::vector<NameAttrList> branch_funcs_;
mutex mu_;
std::unordered_map<FunctionLibraryRuntime*,
std::pair<std::vector<FHandle>,
tsl::core::WeakPtr<FunctionLibraryRuntime>>>
handles_ ABSL_GUARDED_BY(mu_);
Status GetHandles(OpKernelContext* ctx,
std::vector<FHandle>& branch_handles) {
// TODO(b/37549631): Because this op has `SetIsStateful()` in its
// op registration, this kernel may be shared by multiple
// subgraphs, which have different associated
// `FunctionLibraryRuntime` objects and hence different `FHandle`
// namespaces. We currently work around this by caching the map
// from `FunctionLibraryRuntime*` to `FHandle` pairs for the two
// functions this op uses.
auto lib = ctx->function_library();
if (lib == nullptr) return errors::Internal("No function library");
std::vector<FHandle> handles;
{
tf_shared_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
handles.assign(iter->second.first.begin(), iter->second.first.end());
}
}
if (TF_PREDICT_FALSE(handles.empty())) {
mutex_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
handles.assign(iter->second.first.begin(), iter->second.first.end());
} else {
for (int i = 0; i < branch_funcs_.size(); i++) {
handles.resize(branch_funcs_.size());
TF_RETURN_IF_ERROR(Instantiate(ctx, branch_funcs_[i], &handles[i]));
}
handles_[lib] = std::make_pair(
handles, tsl::core::WeakPtr<FunctionLibraryRuntime>(lib));
}
}
branch_handles.assign(handles.begin(), handles.end());
return OkStatus();
}
class State {
public:
State(CaseOp* kernel, OpKernelContext* ctx, int branch,
const std::vector<FHandle>& branch_handles, DoneCallback done)
: kernel_(kernel),
ctx_(ctx),
branch_(branch),
branch_handles_(branch_handles),
done_(std::move(done)),
lib_(CHECK_NOTNULL(ctx_->function_library())),
opts_(ctx->step_id()) {
SetRunOptions(ctx_, &opts_, true /* always_collect_stats */);
for (int i = 1; i < ctx_->num_inputs(); ++i) {
args_.push_back(ctx_->input(i));
}
}
~State() = default;
void Start() {
int branch = branch_;
// The last branch is the default branch.
if (branch < 0 || branch >= branch_handles_.size()) {
branch = branch_handles_.size() - 1;
}
rets_.clear();
profiler::TraceMe trace_me("CaseOp");
lib_->Run(
// Evaluate one of the branch.
opts_, branch_handles_[branch], args_, &rets_,
// Done callback
[this](Status s) {
if (s.ok()) {
s = SetOutputs(kernel_, ctx_, rets_);
}
ctx_->SetStatus(s);
DoneCallback captured_done(std::move(done_));
delete this;
captured_done();
});
}
private:
CaseOp* const kernel_;
OpKernelContext* const ctx_;
const int branch_;
std::vector<FHandle> branch_handles_;
DoneCallback done_;
FunctionLibraryRuntime* const lib_;
FunctionLibraryRuntime::Options opts_;
TensorVec args_;
TensorVec rets_;
};
};
// TODO(drpng): remove this.
REGISTER_KERNEL_BUILDER(Name("_If").Device(DEVICE_CPU), IfOp);
REGISTER_KERNEL_BUILDER(Name("_If").Device(DEVICE_DEFAULT).HostMemory("cond"),
IfOp);
REGISTER_KERNEL_BUILDER(Name("If").Device(DEVICE_CPU), IfOp);
REGISTER_KERNEL_BUILDER(Name("If").Device(DEVICE_DEFAULT).HostMemory("cond"),
IfOp);
REGISTER_KERNEL_BUILDER(Name("Case").Device(DEVICE_CPU), CaseOp);
REGISTER_KERNEL_BUILDER(
Name("Case").Device(DEVICE_DEFAULT).HostMemory("branch_index"), CaseOp);
REGISTER_KERNEL_BUILDER(Name("StatelessCase").Device(DEVICE_CPU), CaseOp);
REGISTER_KERNEL_BUILDER(
Name("StatelessCase").Device(DEVICE_DEFAULT).HostMemory("branch_index"),
CaseOp);
REGISTER_KERNEL_BUILDER(Name("StatelessIf").Device(DEVICE_CPU), IfOp);
REGISTER_KERNEL_BUILDER(
Name("StatelessIf").Device(DEVICE_DEFAULT).HostMemory("cond"), IfOp);
class WhileOp : public AsyncOpKernel {
public:
explicit WhileOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
OP_REQUIRES(ctx, ctx->function_library() != nullptr,
errors::Internal("No function library"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("cond", &cond_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("body", &body_func_));
}
~WhileOp() override {
for (const auto& it : handles_) {
auto lib = it.second.second.GetNewRef();
if (lib == nullptr) {
LOG(INFO) << "FunctionLibraryRuntime already destroyed.";
continue;
}
Status cond_status = lib->ReleaseHandle(it.second.first.first);
if (!cond_status.ok()) {
LOG(INFO)
<< "Ignoring error while destructing WhileOp condition function: "
<< cond_status;
}
Status body_status = lib->ReleaseHandle(it.second.first.second);
if (!body_status.ok()) {
LOG(INFO) << "Ignoring error while destructing WhileOp body function: "
<< body_status;
}
}
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
if (ctx->run_all_kernels_inline()) {
// Use the non-callback-based implementation when kernels (and function
// callbacks) execute inline to avoid stack overflow.
OP_REQUIRES_OK_ASYNC(ctx, DoComputeSync(ctx), done);
done();
} else {
FHandle cond_handle;
FHandle body_handle;
OP_REQUIRES_OK_ASYNC(ctx, GetHandles(ctx, &cond_handle, &body_handle),
done);
(new State(this, ctx, cond_handle, body_handle, done))->Start();
}
}
void Compute(OpKernelContext* ctx) override {
// Use the non-callback-based implementation when the synchronous Compute()
// method is invoked, because the caller is explicitly donating a thread.
Status s = DoComputeSync(ctx);
// NOTE: Unfortunately, we cannot use OP_REQUIRES_OK here, because this is
// still an AsyncOpKernel, and there is a run-time check to avoid calling
// OP_REQUIRES_OK in AsyncOpKernel::ComputeAsync() (which would deadlock in
// the event of an error).
if (TF_PREDICT_FALSE(!s.ok())) {
ctx->SetStatus(s);
}
}
private:
NameAttrList cond_func_;
NameAttrList body_func_;
mutex mu_;
std::unordered_map<FunctionLibraryRuntime*,
std::pair<std::pair<FHandle, FHandle>,
tsl::core::WeakPtr<FunctionLibraryRuntime>>>
handles_ ABSL_GUARDED_BY(mu_);
static Status CondResultToBool(OpKernelContext* ctx,
const FunctionLibraryRuntime::Options& opts,
const Tensor& cond_t, bool* out_result) {
bool is_pluggable = ctx->op_device_context() &&
ctx->op_device_context()->IsPluggableDevice();
const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info =
ctx->device()->tensorflow_accelerator_device_info();
const bool is_hostmem_dtype =
cond_t.dtype() == DT_INT32 || cond_t.dtype() == DT_INT64;
if (!is_hostmem_dtype && (is_pluggable || accelerator_device_info) &&
(opts.rets_alloc_attrs.empty() ||
!opts.rets_alloc_attrs[0].on_host())) {
// Copy the ret value to host if it's allocated on device.
Device* device = down_cast<Device*>(ctx->device());
DeviceContext* device_ctx = ctx->op_device_context();
Tensor host_cond_t = Tensor(cond_t.dtype(), cond_t.shape());
TF_RETURN_IF_ERROR(device_ctx->CopyDeviceTensorToCPUSync(
&cond_t, /*tensor_name=*/"", device, &host_cond_t));
return ToBool({host_cond_t}, out_result);
}
return ToBool({cond_t}, out_result);
}
// The initial loop variable args are the inputs to the kernel.
//
// We attempt to forward the input so that it can be consumed inside the
// body function (and participate in buffer forwarding, etc.).
static void GetArgsFromContext(OpKernelContext* ctx,
std::vector<Tensor>* out_args,
DataTypeVector* out_var_types) {
const int num_loop_vars = ctx->num_inputs();
out_args->reserve(num_loop_vars);
out_var_types->resize(num_loop_vars);
for (int i = 0; i < num_loop_vars; ++i) {
const Tensor& input = ctx->input(i);
(*out_var_types)[i] = input.dtype();
std::unique_ptr<Tensor> maybe_forwarded_input = ctx->forward_input(
i, /* output_index= */ OpKernelContext::Params::kNoReservation,
input.dtype(), input.shape(), ctx->input_memory_type(i),
ctx->input_alloc_attr(i));
if (maybe_forwarded_input) {
out_args->push_back(std::move(*maybe_forwarded_input));
} else {
out_args->push_back(input);
}
}
}
class BodyFuncCallFrame : public CallFrameInterface {
public:
BodyFuncCallFrame(std::vector<Tensor>* args, std::vector<Tensor>* retvals,
DataTypeSlice ret_types)
: args_(args), retvals_(retvals), ret_types_(ret_types) {}
size_t num_args() const override { return args_->size(); }
size_t num_retvals() const override { return retvals_->size(); }
Status GetArg(int index, const Tensor** val) override {
if (index < args_->size()) {
*val = &(*args_)[index];
return OkStatus();
} else {
return errors::InvalidArgument("Argument ", index, " is out of range.");
}
}
void ConsumeArg(int index, Tensor* val) override {
DCHECK_GE(index, 0);
DCHECK_LT(index, args_->size());
*val = std::move((*args_)[index]);
}
bool CanConsumeArg(int index) const override {
return index >= 0 && index < args_->size();
}
Status SetRetval(int index, const Tensor& val) override {
if (TF_PREDICT_FALSE(index < 0)) {
return errors::InvalidArgument(
"Expected non-negative return value index, but got: ", index, ".");
} else if (TF_PREDICT_FALSE(index >= retvals_->size())) {
return errors::InvalidArgument("While loop body returned ", index + 1,
" arguments. Expected: ", num_retvals(),
".");
} else if (TF_PREDICT_FALSE(val.dtype() != ret_types_[index])) {
return errors::InvalidArgument("Expected type ",
DataTypeString(ret_types_[index]),
" for return value ", index, " but got ",
DataTypeString(val.dtype()), ".");
}
(*retvals_)[index] = val;
return OkStatus();
}
private:
std::vector<Tensor>* const args_; // Not owned.
std::vector<Tensor>* const retvals_; // Not owned.
DataTypeSlice ret_types_;
TF_DISALLOW_COPY_AND_ASSIGN(BodyFuncCallFrame);
};
class State {
public:
State(WhileOp* kernel, OpKernelContext* ctx, FHandle cond_handle,
FHandle body_handle, DoneCallback done)
: kernel_(kernel),
ctx_(ctx),
cond_handle_(cond_handle),
body_handle_(body_handle),
done_(std::move(done)),
lib_(CHECK_NOTNULL(ctx_->function_library())),
opts_(ctx->step_id()) {
SetRunOptions(ctx_, &opts_, false /* always_collect_stats */);
GetArgsFromContext(ctx, &args_, &loop_var_types_);
body_frame_ =
std::make_unique<BodyFuncCallFrame>(&args_, &rets_, loop_var_types_);
}
~State() = default;
void Start() { EvalCond(); }
private:
WhileOp* const kernel_;
OpKernelContext* const ctx_;
const FHandle cond_handle_;
const FHandle body_handle_;
const DoneCallback done_;
FunctionLibraryRuntime* const lib_;
FunctionLibraryRuntime::Options opts_;
TensorVec args_;
TensorVec rets_;
DataTypeVector loop_var_types_;
std::unique_ptr<BodyFuncCallFrame> body_frame_;
void EvalCond() {
profiler::TraceMe trace_me("WhileOp-EvalCond");
lib_->Run(
// Evaluate the condition.
opts_, cond_handle_, args_, &rets_,
// Done cb.
[this](const Status& s) {
if (!s.ok()) {
return Finish(s);
}
StartBody();
});
}
void StartBody() {
Status s;
if (rets_.size() != 1) {
s = errors::InvalidArgument(
"Expected a single scalar return value from WhileOp cond, got ",
rets_.size(), " tensors.");
return Finish(s);
}
if (!s.ok()) {
return Finish(s);
}
bool cond;
s = CondResultToBool(ctx_, opts_, rets_[0], &cond);
if (!s.ok()) {
return Finish(s);
}
if (!cond) {
return Finish(OkStatus());
}
rets_.clear();
rets_.resize(args_.size());
profiler::TraceMe trace_me("WhileOp-StartBody");
lib_->Run(
// Evaluate the body.
opts_, body_handle_, body_frame_.get(),
// Done callback
[this](const Status& s) {
if (!s.ok()) {
return Finish(s);
}
if (args_.size() != rets_.size()) {
return Finish(errors::InvalidArgument(
"While loop body returned ", rets_.size(),
" arguments. Expected: ", args_.size()));
}
args_.clear();
using std::swap;
swap(args_, rets_);
EvalCond();
});
}
void Finish(Status s) {
if (s.ok()) {
s = SetOutputs(kernel_, ctx_, args_);
}
ctx_->SetStatus(s);
done_();
delete this;
}
};
Status DoComputeSync(OpKernelContext* ctx) {
FHandle cond_handle;
FHandle body_handle;
TF_RETURN_IF_ERROR(GetHandles(ctx, &cond_handle, &body_handle));
auto lib = ctx->function_library();
FunctionLibraryRuntime::Options opts;
SetRunOptions(ctx, &opts, false /* always_collect_stats */);
// Pre-allocate argument and return value vectors for the cond and body
// functions.
std::vector<Tensor> args;
const int num_loop_vars = ctx->num_inputs();
DataTypeVector loop_var_types(num_loop_vars);
GetArgsFromContext(ctx, &args, &loop_var_types);
std::vector<Tensor> cond_rets;
cond_rets.reserve(1);
std::vector<Tensor> body_rets;
body_rets.reserve(num_loop_vars);
// Implement the logic of the while loop as a single C++ do-while loop that
// executes the cond and body functions synchronously.
do {
// Evaluate the cond function on the current loop variables.
{
profiler::TraceMe trace_me("WhileOp-EvalCond");
TF_RETURN_IF_ERROR(lib->RunSync(opts, cond_handle, args, &cond_rets));
}
if (cond_rets.size() != 1) {
return errors::InvalidArgument(
"Expected a single scalar return value from WhileOp cond, got ",
cond_rets.size(), " tensors.");
}
// If the cond function evaluates to false, we are done: output the
// current loop variables.
bool cond_result;
TF_RETURN_IF_ERROR(
CondResultToBool(ctx, opts, cond_rets[0], &cond_result));
if (!cond_result) {
return SetOutputs(this, ctx, args);
}
// Evaluate the body function on the current loop variables, to get an
// updated vector of loop variables.
{
profiler::TraceMe trace_me("WhileOp-StartBody");
body_rets.resize(num_loop_vars);
BodyFuncCallFrame call_frame(&args, &body_rets, loop_var_types);
TF_RETURN_IF_ERROR(lib->RunSync(opts, body_handle, &call_frame));
}
std::swap(body_rets, args);
body_rets.clear();
} while (true);
}
Status GetHandles(OpKernelContext* ctx, FHandle* cond_handle,
FHandle* body_handle) {
// TODO(b/37549631): Because this op has `SetIsStateful()` in its
// op registration, this kernel may be shared by multiple
// subgraphs, which have different associated
// `FunctionLibraryRuntime` objects and hence different `FHandle`
// namespaces. We currently work around this by caching the map
// from `FunctionLibraryRuntime*` to `FHandle` pairs for the two
// functions this op uses.
auto lib = ctx->function_library();
if (lib == nullptr) return errors::Internal("No function library");
*cond_handle = kInvalidHandle;
*body_handle = kInvalidHandle;
{
tf_shared_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*cond_handle = iter->second.first.first;
*body_handle = iter->second.first.second;
}
}
if (TF_PREDICT_FALSE(*cond_handle == kInvalidHandle)) {
mutex_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*cond_handle = iter->second.first.first;
*body_handle = iter->second.first.second;
} else {
TF_RETURN_IF_ERROR(Instantiate(ctx, cond_func_, cond_handle));
TF_RETURN_IF_ERROR(Instantiate(ctx, body_func_, body_handle));
handles_[lib] =
std::make_pair(std::make_pair(*cond_handle, *body_handle),
tsl::core::WeakPtr<FunctionLibraryRuntime>(lib));
}
}
return OkStatus();
}
};
// TODO(drpng): remove these.
REGISTER_KERNEL_BUILDER(Name("_While").Device(DEVICE_CPU), WhileOp);
REGISTER_KERNEL_BUILDER(Name("_While").Device(DEVICE_DEFAULT), WhileOp);
REGISTER_KERNEL_BUILDER(Name("While").Device(DEVICE_CPU), WhileOp);
REGISTER_KERNEL_BUILDER(Name("While").Device(DEVICE_DEFAULT), WhileOp);
REGISTER_KERNEL_BUILDER(Name("StatelessWhile").Device(DEVICE_CPU), WhileOp);
REGISTER_KERNEL_BUILDER(Name("StatelessWhile").Device(DEVICE_DEFAULT), WhileOp);
class ToBoolOp : public OpKernel {
public:
explicit ToBoolOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
bool b;
OP_REQUIRES_OK(ctx, ToBool({ctx->input(0)}, &b));
Tensor* out;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &out));
out->scalar<bool>()() = b;
}
};
REGISTER_KERNEL_BUILDER(Name("ToBool").Device(DEVICE_CPU), ToBoolOp);
Status GetScalar(OpKernelContext* ctx, int index, int32* value,
const char* label) {
Tensor t = ctx->input(index);
if (!TensorShapeUtils::IsScalar(t.shape())) {
return errors::InvalidArgument(label, " must be a scalar, but ",
t.shape().DebugString());
}
*value = t.scalar<int32>()();
return OkStatus();
}
class ForOp : public AsyncOpKernel {
public:
explicit ForOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
OP_REQUIRES(ctx, ctx->function_library() != nullptr,
errors::Internal("No function library"));
OP_REQUIRES_OK(ctx, ctx->GetAttr("body", &body_func_));
}
~ForOp() override {
for (const auto& it : handles_) {
auto lib = it.second.second.GetNewRef();
if (lib == nullptr) {
LOG(INFO) << "FunctionLibraryRuntime already destroyed.";
continue;
}
Status status = lib->ReleaseHandle(it.second.first);
if (!status.ok()) {
LOG(INFO) << "Ignoring error while destructing ForOp body function: "
<< status;
}
}
}
void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override {
FHandle body_handle;
OP_REQUIRES_OK_ASYNC(ctx, GetHandles(ctx, &body_handle), done);
(new State(this, ctx, body_handle, done))->Start();
}
private:
NameAttrList body_func_;
mutex mu_;
std::unordered_map<
FunctionLibraryRuntime*,
std::pair<FHandle, tsl::core::WeakPtr<FunctionLibraryRuntime>>>
handles_ ABSL_GUARDED_BY(mu_);
Status GetHandles(OpKernelContext* ctx, FHandle* body_handle) {
// TODO(b/37549631): Because this op has `SetIsStateful()` in its
// op registration, this kernel may be shared by multiple
// subgraphs, which have different associated
// `FunctionLibraryRuntime` objects and hence different `FHandle`
// namespaces. We currently work around this by caching the map
// from `FunctionLibraryRuntime*` to `FHandle` pairs for the two
// functions this op uses.
auto lib = ctx->function_library();
if (lib == nullptr) return errors::Internal("No function library");
*body_handle = kInvalidHandle;
{
tf_shared_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*body_handle = iter->second.first;
}
}
if (TF_PREDICT_FALSE(*body_handle == kInvalidHandle)) {
mutex_lock l(mu_);
const auto iter = handles_.find(lib);
if (TF_PREDICT_TRUE(iter != handles_.end())) {
*body_handle = iter->second.first;
} else {
TF_RETURN_IF_ERROR(Instantiate(ctx, body_func_, body_handle));
handles_[lib] = std::make_pair(
*body_handle, tsl::core::WeakPtr<FunctionLibraryRuntime>(lib));
}
}
return OkStatus();
}
class State {
public:
State(ForOp* kernel, OpKernelContext* ctx, FHandle handle,
DoneCallback done)
: kernel_(kernel),
ctx_(ctx),
body_handle_(handle),
done_(std::move(done)),
lib_(CHECK_NOTNULL(ctx_->function_library())),
opts_(ctx->step_id()),
args_(1 + ctx_->num_inputs() - 3) {
args_[0] = Tensor(DT_INT32, {});
iter_ = &args_[0].scalar<int32>()();
const int32_t num_loop_inputs = ctx_->num_inputs() - 3;
rets_.reserve(num_loop_inputs);
for (int i = 0; i < num_loop_inputs; ++i) {
rets_.push_back(ctx_->input(3 + i));
}
}
~State() = default;
void Start() {
Status s = StartLoop();
if (!s.ok()) Finish(s);
}
private:
ForOp* const kernel_;
OpKernelContext* const ctx_;
FHandle body_handle_;
const DoneCallback done_;
FunctionLibraryRuntime* const lib_;
FunctionLibraryRuntime::Options opts_;
TensorVec args_;
TensorVec rets_;
int32* iter_; // points to args_[0].
int32 limit_;
int32 delta_;
// If an error e is returned, caller must call Finish(e).
// If OK is returned, the async loop execution has been started.
Status StartLoop() {
SetRunOptions(ctx_, &opts_, false /* always_collect_stats */);
TF_RETURN_IF_ERROR(GetScalar(ctx_, 0, iter_, "start"));
TF_RETURN_IF_ERROR(GetScalar(ctx_, 1, &limit_, "limit"));
TF_RETURN_IF_ERROR(GetScalar(ctx_, 2, &delta_, "delta"));
if ((delta_ > 0 && *iter_ <= limit_) ||
(delta_ < 0 && *iter_ >= limit_) ||
(delta_ == 0 && *iter_ == limit_)) {
RunNext();
return OkStatus();
} else {
return errors::InvalidArgument("Invalid start/limit/delta: ", *iter_,
" ", limit_, " ", delta_);
}
}
void RunNext() {
bool done_loop;
if (delta_ > 0) {
done_loop = *iter_ >= limit_;
} else {
done_loop = *iter_ <= limit_;
}
if (done_loop) {
Finish(OkStatus());
return;
}
if (rets_.size() >= args_.size()) {
Finish(errors::InvalidArgument(
"For loop body returned ", rets_.size(),
" arguments. Expected: ", args_.size() - 1));
return;
}
for (int i = 0; i < rets_.size(); ++i) {
args_[1 + i] = std::move(rets_[i]);
}
rets_.clear();
profiler::TraceMe trace_me("ForOp");
lib_->Run(opts_, body_handle_, args_, &rets_, [this](const Status& s) {
if (s.ok()) {
*iter_ += delta_;
RunNext();
} else {
Finish(s);
}
});
}
void Finish(Status s) {
if (s.ok()) {
s = SetOutputs(kernel_, ctx_, rets_);
}
ctx_->SetStatus(s);
done_();