Skip to content

Commit fe19e92

Browse files
mrrytensorflower-gardener
authored andcommitted
Switch CallFrameInterface::GetArg(int, Tensor*) to take (int, const Tensor**).
This change is a micro-optimization that speeds up execution of `ArgOp::Compute()` in every `tf.function` invocation or `DirectSession::Run()` call. Previously, we would copy-construct a Tensor in the implementation of `GetArg()`, and then move that into `OpKernelContext::set_output()`. In effect, this involves two refcount operations on the underlying buffer, and three copies of the `TensorShape`. By instead outputting a pointer to the `const Tensor` in the frame, we avoid one of the refcount operations, and two of the `TensorShape` copies. One consequence of this change is that it becomes more difficult to create a `Tensor` on the fly in `GetArg()`. We were using that ability in two places: 1. In `DirectSession::RunCallable()` when one of the arguments has type `DT_RESOURCE`, and it is converted into a tensor (part of the tfdbg functionality, rarely used via this API). We fix that by (in the rare case it is necessary) performing the conversion eagerly in `RunCallable()`. 2. In the `MapDefunOp` implementation, when one of the arguments is to be sliced out of the tensor we're mapping over, the slice is created in `GetArg()`. We fix this by adding a mutable vector of slices to the specialized `CallFrame` implementation, storing the created tensor there, and returning a pointer to it. (Since `MapDefunOp` is only used in a graph rewrite context, a better fix here would be to add explicit `tf.slice()` ops to the graph, instead of relying on the call frame to do this work, because these might be possible to optimize further with Grappler.) PiperOrigin-RevId: 305983898 Change-Id: I0834777c27cd97204e8e3df052a08faf0dcf68f9
1 parent 0a3f4e1 commit fe19e92

10 files changed

Lines changed: 79 additions & 56 deletions

File tree

‎tensorflow/compiler/tf2xla/kernels/arg_op.cc‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,19 @@ class XlaArgOp : public XlaOpKernel {
3939
// compilation. Use the usual implementation of _Arg.
4040
auto frame = ctx->call_frame();
4141
if (frame != nullptr) {
42-
Tensor val;
42+
const Tensor* val;
4343
OP_REQUIRES_OK(ctx, frame->GetArg(index_, &val));
4444
// Types that cannot be copied using memcpy (like DT_STRING) are wrapped
4545
// in a DT_UINT8 and hence the type mismatches. Skip the test in such
4646
// cases. See XlaOpKernelContext::SetOutputExpression for details.
4747
if (DataTypeCanUseMemcpy(dtype_)) {
48-
OP_REQUIRES(ctx, val.dtype() == dtype_,
48+
OP_REQUIRES(ctx, val->dtype() == dtype_,
4949
errors::InvalidArgument(
50-
"Type mismatch: actual ", DataTypeString(val.dtype()),
50+
"Type mismatch: actual ", DataTypeString(val->dtype()),
5151
" vs. expect ", DataTypeString(dtype_)));
5252
}
5353
// Forwards the argument from the frame.
54-
ctx->op_kernel_context()->set_output(0, val);
54+
ctx->op_kernel_context()->set_output(0, *val);
5555
return;
5656
}
5757

‎tensorflow/core/common_runtime/direct_session.cc‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,14 +1867,11 @@ class DirectSession::RunCallableCallFrame : public CallFrameInterface {
18671867
return executors_and_keys_->output_types.size();
18681868
}
18691869

1870-
Status GetArg(int index, Tensor* val) const override {
1871-
if (index > feed_tensors_->size()) {
1870+
Status GetArg(int index, const Tensor** val) override {
1871+
if (TF_PREDICT_FALSE(index > feed_tensors_->size())) {
18721872
return errors::Internal("Args index out of bounds: ", index);
1873-
} else if (executors_and_keys_->input_types[index] == DT_RESOURCE) {
1874-
TF_RETURN_IF_ERROR(
1875-
session_->ResourceHandleToInputTensor((*feed_tensors_)[index], val));
18761873
} else {
1877-
*val = (*feed_tensors_)[index];
1874+
*val = &(*feed_tensors_)[index];
18781875
}
18791876
return Status::OK();
18801877
}
@@ -1947,16 +1944,37 @@ ::tensorflow::Status DirectSession::RunCallable(
19471944
}
19481945

19491946
size_t input_size = 0;
1947+
bool any_resource_feeds = false;
19501948
for (auto& tensor : feed_tensors) {
19511949
input_size += tensor.AllocatedBytes();
1950+
any_resource_feeds = any_resource_feeds || tensor.dtype() == DT_RESOURCE;
19521951
}
19531952
metrics::RecordGraphInputTensors(input_size);
19541953

1954+
std::unique_ptr<std::vector<Tensor>> converted_feed_tensors;
1955+
const std::vector<Tensor>* actual_feed_tensors;
1956+
1957+
if (TF_PREDICT_FALSE(any_resource_feeds)) {
1958+
converted_feed_tensors = absl::make_unique<std::vector<Tensor>>();
1959+
converted_feed_tensors->reserve(feed_tensors.size());
1960+
for (const Tensor& t : feed_tensors) {
1961+
if (t.dtype() == DT_RESOURCE) {
1962+
converted_feed_tensors->emplace_back();
1963+
Tensor* tensor_from_handle = &converted_feed_tensors->back();
1964+
TF_RETURN_IF_ERROR(ResourceHandleToInputTensor(t, tensor_from_handle));
1965+
} else {
1966+
converted_feed_tensors->emplace_back(t);
1967+
}
1968+
}
1969+
actual_feed_tensors = converted_feed_tensors.get();
1970+
} else {
1971+
actual_feed_tensors = &feed_tensors;
1972+
}
1973+
19551974
// A specialized CallFrame implementation that takes advantage of the
19561975
// optimized RunCallable interface.
1957-
1958-
RunCallableCallFrame call_frame(this, executors_and_keys.get(), &feed_tensors,
1959-
fetch_tensors);
1976+
RunCallableCallFrame call_frame(this, executors_and_keys.get(),
1977+
actual_feed_tensors, fetch_tensors);
19601978

19611979
if (LogMemory::IsEnabled()) {
19621980
LogMemory::RecordStep(step_id, run_state_args.handle);

‎tensorflow/core/common_runtime/process_function_library_runtime.cc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1434,9 +1434,9 @@ void ProcessFunctionLibraryRuntime::Run(
14341434
std::vector<Tensor> args;
14351435
args.reserve(frame->num_args());
14361436
for (size_t i = 0; i < frame->num_args(); ++i) {
1437-
Tensor arg;
1437+
const Tensor* arg;
14381438
Status s = frame->GetArg(i, &arg);
1439-
args.push_back(std::move(arg));
1439+
args.emplace_back(*arg);
14401440
if (!s.ok()) {
14411441
done(s);
14421442
}

‎tensorflow/core/framework/function.cc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,12 +1118,12 @@ Status FunctionCallFrame::ConsumeRetvals(std::vector<Tensor>* rets,
11181118
return Status::OK();
11191119
}
11201120

1121-
Status FunctionCallFrame::GetArg(int index, Tensor* val) const {
1121+
Status FunctionCallFrame::GetArg(int index, const Tensor** val) {
11221122
if (index < 0 || static_cast<size_t>(index) >= args_.size()) {
11231123
return errors::InvalidArgument("GetArg ", index, " is not within [0, ",
11241124
args_.size(), ")");
11251125
}
1126-
*val = args_[index];
1126+
*val = &args_[index];
11271127
return Status::OK();
11281128
}
11291129

‎tensorflow/core/framework/function.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ class CallFrameInterface {
274274
virtual size_t num_args() const = 0;
275275
virtual size_t num_retvals() const = 0;
276276

277-
virtual Status GetArg(int index, Tensor* val) const = 0;
277+
virtual Status GetArg(int index, const Tensor** val) = 0;
278278
virtual Status SetRetval(int index, const Tensor& val) = 0;
279279
};
280280

@@ -301,7 +301,7 @@ class FunctionCallFrame : public CallFrameInterface {
301301
size_t num_retvals() const override { return ret_types_.size(); }
302302

303303
// Callee methods.
304-
Status GetArg(int index, Tensor* val) const override;
304+
Status GetArg(int index, const Tensor** val) override;
305305
Status SetRetval(int index, const Tensor& val) override;
306306

307307
private:

‎tensorflow/core/framework/function_test.cc‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -912,9 +912,9 @@ TEST(FunctionCallFrame, Void_Void) {
912912
TF_EXPECT_OK(frame.SetArgs({}));
913913
auto a = test::AsTensor<float>({100});
914914
HasError(frame.SetArgs({a}), "Invalid argument");
915-
Tensor v;
915+
const Tensor* v;
916916
HasError(frame.GetArg(0, &v), "Invalid argument");
917-
HasError(frame.SetRetval(0, v), "Invalid argument");
917+
HasError(frame.SetRetval(0, *v), "Invalid argument");
918918
std::vector<Tensor> rets;
919919
TF_EXPECT_OK(frame.GetRetvals(&rets));
920920
EXPECT_EQ(rets.size(), 0);
@@ -930,28 +930,28 @@ TEST(FunctionCallFrame, Float_Float_Float) {
930930
"Invalid argument: Expects arg[1] to be float");
931931
TF_EXPECT_OK(frame.SetArgs({a, b}));
932932

933-
Tensor v;
933+
const Tensor* v;
934934
HasError(frame.GetArg(-1, &v), "Invalid argument");
935935
HasError(frame.GetArg(2, &v), "Invalid argument");
936936
TF_EXPECT_OK(frame.GetArg(0, &v));
937-
test::ExpectTensorEqual<float>(a, v);
937+
test::ExpectTensorEqual<float>(a, *v);
938938
TF_EXPECT_OK(frame.GetArg(1, &v));
939-
test::ExpectTensorEqual<float>(b, v);
939+
test::ExpectTensorEqual<float>(b, *v);
940940

941-
v = test::AsTensor<float>({-100});
942-
HasError(frame.SetRetval(-1, v), "Invalid argument");
943-
HasError(frame.SetRetval(1, v), "Invalid argument");
941+
Tensor w = test::AsTensor<float>({-100});
942+
HasError(frame.SetRetval(-1, w), "Invalid argument");
943+
HasError(frame.SetRetval(1, w), "Invalid argument");
944944
HasError(frame.SetRetval(0, test::AsTensor<int64>({-100})),
945945
"Invalid argument: Expects ret[0] to be float");
946946

947947
std::vector<Tensor> rets;
948948
HasError(frame.GetRetvals(&rets), "does not have value");
949-
TF_EXPECT_OK(frame.SetRetval(0, v));
950-
HasError(frame.SetRetval(0, v), "has already been set");
949+
TF_EXPECT_OK(frame.SetRetval(0, *v));
950+
HasError(frame.SetRetval(0, *v), "has already been set");
951951

952952
TF_EXPECT_OK(frame.GetRetvals(&rets));
953953
EXPECT_EQ(rets.size(), 1);
954-
test::ExpectTensorEqual<float>(rets[0], v);
954+
test::ExpectTensorEqual<float>(rets[0], *v);
955955
}
956956

957957
TEST(Canonicalize, Basic) {

‎tensorflow/core/kernels/data/captured_function.cc‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -309,14 +309,12 @@ class OwnedArgsCallFrame : public CallFrameBase {
309309
}
310310

311311
// Callee methods.
312-
Status GetArg(int index, Tensor* val) const override {
312+
Status GetArg(int index, const Tensor** val) override {
313313
if (index < args_.size()) {
314-
// TODO(mrry): Consider making `CallFrameInterface::GetArg` non-const in
315-
// order to be able to `std::move(args_[index])` into `*val`.
316-
*val = args_[index];
314+
*val = &args_[index];
317315
return Status::OK();
318316
} else if (index < args_.size() + captured_inputs_->size()) {
319-
*val = (*captured_inputs_)[index - args_.size()];
317+
*val = &(*captured_inputs_)[index - args_.size()];
320318
return Status::OK();
321319
} else {
322320
return errors::InvalidArgument("Argument ", index, " is out of range.");
@@ -342,12 +340,12 @@ class BorrowedArgsCallFrame : public CallFrameBase {
342340
}
343341

344342
// Callee methods.
345-
Status GetArg(int index, Tensor* val) const override {
343+
Status GetArg(int index, const Tensor** val) override {
346344
if (index < args_.size()) {
347-
*val = args_[index];
345+
*val = &args_[index];
348346
return Status::OK();
349347
} else if (index < args_.size() + captured_inputs_->size()) {
350-
*val = (*captured_inputs_)[index - args_.size()];
348+
*val = &(*captured_inputs_)[index - args_.size()];
351349
return Status::OK();
352350
} else {
353351
return errors::InvalidArgument("Argument ", index, " is out of range.");

‎tensorflow/core/kernels/data/map_defun_op.cc‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,10 @@ class MapDefunOp::MapFunctionCallFrame : public CallFrameInterface {
7777
public:
7878
MapFunctionCallFrame(ComputeOptions* compute_opts, OpKernel* kernel,
7979
size_t iter)
80-
: compute_opts_(compute_opts), kernel_(kernel), iter_(iter) {}
80+
: compute_opts_(compute_opts),
81+
kernel_(kernel),
82+
iter_(iter),
83+
sliced_args_(compute_opts_->args.size()) {}
8184

8285
~MapFunctionCallFrame() override = default;
8386

@@ -87,27 +90,32 @@ class MapDefunOp::MapFunctionCallFrame : public CallFrameInterface {
8790
return static_cast<size_t>(kernel_->num_outputs());
8891
}
8992

90-
Status GetArg(int index, Tensor* val) const override {
93+
Status GetArg(int index, const Tensor** val) override {
9194
if (index < 0 || index >= compute_opts_->args.size() +
9295
compute_opts_->captured_inputs.size()) {
9396
return errors::InvalidArgument("Mismatch in number of function inputs.");
9497
}
9598

9699
if (index >= compute_opts_->args.size()) {
97100
// The function is calling for a captured input
98-
*val = compute_opts_->captured_inputs[index - compute_opts_->args.size()];
101+
*val =
102+
&compute_opts_->captured_inputs[index - compute_opts_->args.size()];
99103
return Status::OK();
100104
}
101105

102-
bool result =
103-
val->CopyFrom(compute_opts_->args[index].Slice(iter_, iter_ + 1),
104-
compute_opts_->arg_shapes.at(index));
106+
// NOTE: If contention on mu_ becomes problematic, we could create a vector
107+
// of mutexes, each guarding a different element of sliced_args_.
108+
mutex_lock l(mu_);
109+
bool result = sliced_args_[index].CopyFrom(
110+
compute_opts_->args[index].Slice(iter_, iter_ + 1),
111+
compute_opts_->arg_shapes.at(index));
105112
if (!result) {
106113
return errors::Internal("GetArg failed.");
107-
} else if (!val->IsAligned()) {
114+
} else if (!sliced_args_[index].IsAligned()) {
108115
// Ensure alignment
109-
*val = tensor::DeepCopy(*val);
116+
sliced_args_[index] = tensor::DeepCopy(sliced_args_[index]);
110117
}
118+
*val = &sliced_args_[index];
111119
return Status::OK();
112120
}
113121

@@ -152,6 +160,8 @@ class MapDefunOp::MapFunctionCallFrame : public CallFrameInterface {
152160
ComputeOptions* const compute_opts_; // Not owned
153161
const OpKernel* kernel_;
154162
const size_t iter_;
163+
mutex mu_;
164+
std::vector<Tensor> sliced_args_ TF_GUARDED_BY(mu_);
155165
};
156166

157167
MapDefunOp::MapDefunOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {

‎tensorflow/core/kernels/data/single_threaded_executor.cc‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -284,14 +284,11 @@ class SingleThreadedExecutorImpl : public Executor {
284284
for (size_t i = 0; i < arg_output_locations_.size(); ++i) {
285285
const size_t num_destinations = arg_output_locations_[i].size();
286286
if (num_destinations > 0) {
287-
Tensor arg;
287+
const Tensor* arg;
288288
TF_CHECK_OK(args.call_frame->GetArg(i, &arg));
289-
for (size_t j = 0; j < num_destinations - 1; ++j) {
290-
inputs[arg_output_locations_[i][j]].Init(arg);
289+
for (size_t j = 0; j < num_destinations; ++j) {
290+
inputs[arg_output_locations_[i][j]].Init(*arg);
291291
}
292-
// Move `arg` to the last consumer to avoid the cost of copying it.
293-
inputs[arg_output_locations_[i][num_destinations - 1]].Init(
294-
std::move(arg));
295292
}
296293
}
297294

‎tensorflow/core/kernels/function_ops.cc‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,13 @@ ArgOp::ArgOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
4444
void ArgOp::Compute(OpKernelContext* ctx) {
4545
auto frame = ctx->call_frame();
4646
OP_REQUIRES(ctx, frame != nullptr, errors::Internal("no call frame"));
47-
Tensor val;
47+
const Tensor* val;
4848
OP_REQUIRES_OK(ctx, frame->GetArg(index_, &val));
49-
OP_REQUIRES(ctx, val.dtype() == dtype_,
49+
OP_REQUIRES(ctx, val->dtype() == dtype_,
5050
errors::InvalidArgument("Type mismatch: actual ",
51-
DataTypeString(val.dtype()),
51+
DataTypeString(val->dtype()),
5252
" vs. expect ", DataTypeString(dtype_)));
53-
ctx->set_output(0, std::move(val));
53+
ctx->set_output(0, *val);
5454
}
5555

5656
RetvalOp::RetvalOp(OpKernelConstruction* ctx) : OpKernel(ctx) {

0 commit comments

Comments
 (0)