Repository navigation
Expand file tree
/
Copy pathcaptured_function.h
More file actions
274 lines (224 loc) · 10.9 KB
/
Copy pathcaptured_function.h
File metadata and controls
274 lines (224 loc) · 10.9 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
/* Copyright 2017 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_DATA_CAPTURED_FUNCTION_H_
#define TENSORFLOW_CORE_KERNELS_DATA_CAPTURED_FUNCTION_H_
#include <memory>
#include <vector>
#include "tensorflow/core/framework/cancellation.h"
#include "tensorflow/core/framework/dataset.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/model.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/macros.h"
namespace tensorflow {
class Device;
class OpKernelContext;
class ResourceMgr;
namespace data {
class CapturedFunction;
class InstantiatedCapturedFunction;
// Creates an iterator for a dataset which is created by applying the given
// function to the given input element.
Status MakeIteratorFromInputElement(
IteratorContext* ctx, const IteratorBase* parent,
const std::vector<Tensor>& input_element, int64 thread_index,
const InstantiatedCapturedFunction& inst_captured_func, StringPiece prefix,
std::unique_ptr<IteratorBase>* out_iterator);
// Determines whether the given node is stateful.
Status IsNodeStateful(const FunctionLibraryDefinition& library,
const NodeDef& node);
struct ShortCircuitInfo {
std::vector<int> indices;
std::vector<bool> can_move;
};
// Metadata shared across all captures of the same function.
class FunctionMetadata {
public:
struct Params {
bool use_inter_op_parallelism = true;
bool use_default_device = true;
};
// Creates a new instance of the `FunctionMetadata` class, fetching function
// from a context argument.
static Status Create(tensorflow::OpKernelConstruction* ctx,
const string& func_name, Params params,
std::shared_ptr<FunctionMetadata>* out_metadata);
// Creates a new instance of the `FunctionMetadata` class, using the provided
// function.
static Status Create(tensorflow::OpKernelConstruction* ctx,
NameAttrList&& func, Params params,
std::shared_ptr<FunctionMetadata>* out_metadata);
// Returns the named list of function arguments.
const NameAttrList& func() const { return func_; }
// Returns a borrowed pointer to the function library that contains the
// transitive closure of definitions used by the function.
const FunctionLibraryDefinition* lib_def() const { return lib_def_.get(); }
// Returns short-circuit information.
const ShortCircuitInfo& short_circuit_info() const {
return short_circuit_info_;
}
// Indicates whether a default device should be used for executing function
// ops.
bool use_default_device() const { return use_default_device_; }
// Indicates whether to use inter-op parallelism for execution of the
// function.
bool use_inter_op_parallelism() const { return use_inter_op_parallelism_; }
// Indicates whether the function should a multi-device function backend.
bool use_multi_device_function() const { return use_multi_device_function_; }
private:
FunctionMetadata(NameAttrList&& func, Params params)
: func_(std::move(func)),
use_default_device_(params.use_default_device),
use_inter_op_parallelism_(params.use_inter_op_parallelism) {}
NameAttrList func_;
std::unique_ptr<FunctionLibraryDefinition> lib_def_ = nullptr;
ShortCircuitInfo short_circuit_info_;
bool use_default_device_ = true;
bool use_inter_op_parallelism_ = true;
bool use_multi_device_function_ = true;
};
// A `CapturedFunction` encapsulates a TensorFlow function, plus any "captured"
// arguments that it closed over in the user program.
class CapturedFunction {
public:
// Creates a new instance using a list of named attributes, fetching captured
// inputs from a context argument.
static Status Create(OpKernelContext* ctx,
std::shared_ptr<const FunctionMetadata> metadata,
const string& argument_name,
std::unique_ptr<CapturedFunction>* out_function);
// Creates a new instance using a list of named attributes, using provided
// captured inputs.
static Status Create(OpKernelContext* ctx,
std::shared_ptr<const FunctionMetadata> metadata,
std::vector<Tensor>&& captured_inputs,
std::unique_ptr<CapturedFunction>* out_function);
// Adds the definition of this captured function into the given graph,
// returning its captured inputs and types through the respective output
// arguments.
Status AddToGraph(SerializationContext* ctx,
DatasetBase::DatasetGraphDefBuilder* b,
std::vector<Node*>* other_arguments,
DataTypeVector* other_arguments_types) const;
// Instantiates this function for use in the given context, providing an
// InstantiatedCapturedFunction that can be used to execute functions.
Status Instantiate(IteratorContext* ctx,
std::unique_ptr<InstantiatedCapturedFunction>*
instantiated_captured_function);
// Determines whether the captured function is stateful.
Status CheckExternalState() const;
// Returns the additional captured inputs that will be passed to the function.
const std::vector<Tensor>& captured_inputs() const {
return captured_inputs_;
}
// Returns the named list of function arguments.
const NameAttrList& func() const { return metadata_->func(); }
// Returns the transitive set of function definition required to instantiate
// this function.
const FunctionLibraryDefinition* lib_def() const {
return metadata_->lib_def();
}
// If every function output corresponds to one of its inputs, the method
// returns the mapping from output indices to input indices. Otherwise, it
// returns an empty list.
const ShortCircuitInfo& short_circuit_info() const {
return metadata_->short_circuit_info();
}
// Indicates whether the function should use inter op parallelism.
bool use_inter_op_parallelism() const {
return metadata_->use_inter_op_parallelism();
}
private:
CapturedFunction(std::shared_ptr<const FunctionMetadata> metadata,
std::vector<Tensor> captured_inputs);
Status IsMultiDevice(IteratorContext* ctx, bool* is_multi_device) const;
const std::shared_ptr<const FunctionMetadata> metadata_;
const std::vector<Tensor> captured_inputs_;
TF_DISALLOW_COPY_AND_ASSIGN(CapturedFunction);
};
// `InstantiatedCapturedFunction` encapsulates all the runtime support needed
// to execute a tensorflow function.
//
// While `CapturedFunction` encapsulates constant attributes of the function,
// such as its name and captured arguments, `InstantiatedCapturedFunction`
// encapsulates runtime aspects, such as `FunctionLibraryRuntime` and function
// handle.
//
// The `Iterator` related classes use `InstantiatedCapturedFunction` to execute
// functions outside of the normal `OpKernel::Compute()` context.
class InstantiatedCapturedFunction {
public:
// Creates a new instance of the `InstantiatedCapturedFunction` class from the
// given inputs.
static Status Create(
FunctionLibraryRuntime* lib, FunctionLibraryRuntime::Handle f_handle,
DataTypeVector ret_types,
std::function<void(std::function<void()>)> runner,
CapturedFunction* captured_func, bool is_multi_device,
std::unique_ptr<InstantiatedCapturedFunction>* out_function);
// Runs the instantiated captured function. This method takes ownership of
// the tensors in `args`, in order to be able to deallocate them as early as
// possible. Use `RunWithBorrowedArgs()` if the caller needs to retain
// ownership of the `args`.
Status Run(IteratorContext* ctx, std::vector<Tensor>&& args,
std::vector<Tensor>* rets) const;
// Synchronously runs the captured function on the given `args`, and stores
// the results in `*rets`. Prefer to use `Run()` or `RunAsync()` when
// possible.
Status RunWithBorrowedArgs(IteratorContext* ctx,
const std::vector<Tensor>& args,
std::vector<Tensor>* rets) const;
// Synchronously runs the captured function on the given `args`, and stores
// the results in `*rets`. Prefer to use `Run()` or `RunAsync()` when
// possible. This can be useful for calling a captured function in cases where
// an `IteratorContext*` is not available (such as a destructor).
//
// TODO(b/144278100): Avoid running functions without IteratorContext.
Status RunInstantiated(const std::vector<Tensor>& args,
std::vector<Tensor>* rets);
// Asynchronously runs the captured function on the given `args`, stores the
// results in `*rets`, and calls the given `done` callback when the function
// returns. This method takes ownership of the tensors in `args`, in order to
// be able to deallocate them as early as possible.
void RunAsync(IteratorContext* ctx, std::vector<Tensor>&& args,
std::vector<Tensor>* rets,
FunctionLibraryRuntime::DoneCallback done,
const std::shared_ptr<model::Node>& node) const;
private:
InstantiatedCapturedFunction(
FunctionLibraryRuntime* lib, FunctionLibraryRuntime::Handle f_handle,
DataTypeVector ret_types,
std::function<void(std::function<void()>)> runner,
CapturedFunction* captured_func, bool is_multi_device);
// Determines whether a rendezvous object should be created when running the
// instantiated function.
bool ShouldCreateRendezvous() const;
FunctionLibraryRuntime* const lib_; // Not owned.
const FunctionLibraryRuntime::Handle f_handle_;
const DataTypeVector ret_types_;
// Note: We capture the runner at function instantiation time to be able to
// run the function without `IteratorContext` via `RunInstantiated`.
std::function<void(std::function<void()>)> captured_runner_;
CapturedFunction* const captured_func_; // Not owned.
const bool is_multi_device_;
TF_DISALLOW_COPY_AND_ASSIGN(InstantiatedCapturedFunction);
};
} // namespace data
// TODO(b/114112161): Remove these aliases when all users have moved over to the
// `tensorflow::data` namespace.
using data::CapturedFunction;
} // namespace tensorflow
#endif // TENSORFLOW_CORE_KERNELS_DATA_CAPTURED_FUNCTION_H_