aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/data/captured_function.cc
blob: ee58341cfd680393aaf8a67a8ab914204f7baf93 (plain)
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
/* 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.
==============================================================================*/
#include "tensorflow/core/kernels/data/captured_function.h"

#include <utility>

#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/cancellation.h"
#include "tensorflow/core/lib/gtl/optional.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/notification.h"

namespace tensorflow {

/* static */
Status CapturedFunction::Create(
    const NameAttrList& func, std::vector<Tensor> captured_inputs,
    std::unique_ptr<CapturedFunction>* out_function) {
  out_function->reset(new CapturedFunction(func, std::move(captured_inputs)));
  return Status::OK();
}

/* static */
Status CapturedFunction::Create(
    const NameAttrList& func, OpKernelContext* ctx, const string& argument,
    std::unique_ptr<CapturedFunction>* out_function) {
  OpInputList argument_inputs;
  TF_RETURN_IF_ERROR(ctx->input_list(argument, &argument_inputs));
  std::vector<Tensor> arguments_t;
  arguments_t.reserve(argument_inputs.size());
  for (const Tensor& t : argument_inputs) {
    arguments_t.push_back(t);
  }
  return CapturedFunction::Create(func, std::move(arguments_t), out_function);
}

CapturedFunction::~CapturedFunction() {
  if (lib_ != nullptr && f_handle_ != kInvalidHandle) {
    lib_->ReleaseHandle(f_handle_).IgnoreError();
  }
}

namespace {
class CallFrameBase : public CallFrameInterface {
 public:
  explicit CallFrameBase(DataTypeSlice ret_types)
      : ret_types_(ret_types), retvals_(ret_types.size()) {}

  // Caller methods.
  Status ConsumeRetvals(std::vector<Tensor>* retvals) {
    retvals->reserve(retvals_.size());
    int i = 0;
    for (auto&& val : retvals_) {
      if (!val) {
        return errors::Internal("No return value for index ", i, ".");
      }
      retvals->emplace_back(std::move(val.value()));
      ++i;
    }
    return Status::OK();
  }

  size_t num_retvals() const override { return retvals_.size(); }

  // Callee methods.
  Status SetRetval(int index, const Tensor& val) override {
    if (index < retvals_.size() && val.dtype() == ret_types_[index] &&
        !retvals_[index]) {
      retvals_[index] = val;
      return Status::OK();
    } else if (index >= retvals_.size()) {
      return errors::InvalidArgument("Return value ", index,
                                     " is out of range.");
    } else if (val.dtype() != ret_types_[index]) {
      return errors::InvalidArgument("Expected type ",
                                     DataTypeString(ret_types_[index]),
                                     " for return value ", index, " but got ",
                                     DataTypeString(val.dtype()), ".");
    } else {
      return errors::Internal("Attempted to set return value ", index,
                              " more than once.");
    }
  }

 private:
  DataTypeSlice ret_types_;
  std::vector<gtl::optional<Tensor>> retvals_;
  TF_DISALLOW_COPY_AND_ASSIGN(CallFrameBase);
};

class OwnedArgsCallFrame : public CallFrameBase {
 public:
  OwnedArgsCallFrame(std::vector<Tensor>&& args,
                     const std::vector<Tensor>* captured_inputs,
                     DataTypeSlice ret_types)
      : CallFrameBase(ret_types),
        args_(std::move(args)),
        captured_inputs_(captured_inputs) {}

  size_t num_args() const override {
    return args_.size() + captured_inputs_->size();
  }

  // Callee methods.
  Status GetArg(int index, Tensor* val) const override {
    if (index < args_.size() && args_[index].IsInitialized()) {
      // TODO(mrry): Consider making `CallFrameInterface::GetArg` non-const in
      // order to be able to `std::move(args_[index])` into `*val`.
      *val = args_[index];
      return Status::OK();
    } else if (index < args_.size() + captured_inputs_->size()) {
      *val = (*captured_inputs_)[index - args_.size()];
      return Status::OK();
    } else if (index >= args_.size() + captured_inputs_->size()) {
      return errors::InvalidArgument("Argument ", index, " is out of range.");
    } else {
      return errors::Internal("Attempted to get argument ", index,
                              " more than once.");
    }
  }

 private:
  std::vector<Tensor> args_;
  const std::vector<Tensor>* const captured_inputs_;  // Not owned.
};

class BorrowedArgsCallFrame : public CallFrameBase {
 public:
  BorrowedArgsCallFrame(const std::vector<Tensor>& args,
                        const std::vector<Tensor>* captured_inputs,
                        DataTypeSlice ret_types)
      : CallFrameBase(ret_types),
        args_(args),
        captured_inputs_(captured_inputs) {}

  size_t num_args() const override {
    return args_.size() + captured_inputs_->size();
  }

  // Callee methods.
  Status GetArg(int index, Tensor* val) const override {
    if (index < args_.size() && args_[index].IsInitialized()) {
      *val = args_[index];
      return Status::OK();
    } else if (index < args_.size() + captured_inputs_->size()) {
      *val = (*captured_inputs_)[index - args_.size()];
      return Status::OK();
    } else if (index >= args_.size() + captured_inputs_->size()) {
      return errors::InvalidArgument("Argument ", index, " is out of range.");
    } else {
      return errors::Internal("Attempted to get argument ", index,
                              " more than once.");
    }
  }

 private:
  const std::vector<Tensor>& args_;                   // Not owned.
  const std::vector<Tensor>* const captured_inputs_;  // Not owned.
};

}  // namespace

Status CapturedFunction::MaybeInstantiate(
    IteratorContext* ctx, FunctionLibraryRuntime::Handle* out_handle) {
  mutex_lock l(mu_);
  if (lib_ == nullptr) {
    // The context's runtime will be used for all subsequent calls.
    lib_ = ctx->lib();
    DCHECK(f_handle_ == kInvalidHandle);
    FunctionLibraryRuntime::InstantiateOptions inst_opts;
    inst_opts.overlay_lib = ctx->function_library().get();
    inst_opts.state_handle = std::to_string(random::New64());
    TF_RETURN_IF_ERROR(lib_->Instantiate(func_.name(), AttrSlice(&func_.attr()),
                                         inst_opts, &f_handle_));
    const FunctionBody* fbody = lib_->GetFunctionBody(f_handle_);
    if (fbody == nullptr) {
      return errors::Internal("Failed to instantiate function body.");
    }
    ret_types_ = fbody->ret_types;
  } else {
    // TODO(mrry): Consider moving this under a shared lock, as it is
    // the common case.
    if (ctx->lib() != lib_) {
      return errors::Internal(
          "Captured function was called with a different "
          "FunctionLibraryRuntime*, which is not permitted.");
    }
  }
  *out_handle = f_handle_;
  return Status::OK();
}

Status CapturedFunction::Run(IteratorContext* ctx, std::vector<Tensor>&& args,
                             std::vector<Tensor>* rets) {
  FunctionLibraryRuntime::Handle handle;
  TF_RETURN_IF_ERROR(MaybeInstantiate(ctx, &handle));

  FunctionLibraryRuntime::Options f_opts;
  f_opts.step_id = CapturedFunction::generate_step_id();
  ScopedStepContainer step_container(f_opts.step_id, [ctx](const string& name) {
    ctx->lib()->device()->resource_manager()->Cleanup(name).IgnoreError();
  });
  f_opts.step_container = &step_container;
  f_opts.runner = ctx->runner();
  // TODO(mrry): Add cancellation manager support to IteratorContext
  // so that we can cancel running map functions. The local
  // cancellation manager here is created so that we can run kernels
  // (such as queue kernels) that depend on the non-nullness of
  // `OpKernelContext::cancellation_manager()`, but additional effort
  // will be required to plumb it through the `IteratorContext`.
  CancellationManager c_mgr;
  f_opts.cancellation_manager = &c_mgr;

  OwnedArgsCallFrame frame(std::move(args), &captured_inputs_, ret_types_);
  Notification n;
  Status s;
  ctx->lib()->Run(f_opts, handle, &frame, [&n, &s](Status func_status) {
    s.Update(func_status);
    n.Notify();
  });
  n.WaitForNotification();
  TF_RETURN_IF_ERROR(s);
  return frame.ConsumeRetvals(rets);
}

Status CapturedFunction::RunWithBorrowedArgs(IteratorContext* ctx,
                                             const std::vector<Tensor>& args,
                                             std::vector<Tensor>* rets) {
  FunctionLibraryRuntime::Handle handle;
  TF_RETURN_IF_ERROR(MaybeInstantiate(ctx, &handle));

  FunctionLibraryRuntime::Options f_opts;
  f_opts.step_id = CapturedFunction::generate_step_id();
  ScopedStepContainer step_container(f_opts.step_id, [ctx](const string& name) {
    ctx->lib()->device()->resource_manager()->Cleanup(name).IgnoreError();
  });
  f_opts.step_container = &step_container;
  f_opts.runner = ctx->runner();
  // TODO(mrry): Add cancellation manager support to IteratorContext
  // so that we can cancel running map functions. The local
  // cancellation manager here is created so that we can run kernels
  // (such as queue kernels) that depend on the non-nullness of
  // `OpKernelContext::cancellation_manager()`, but additional effort
  // will be required to plumb it through the `IteratorContext`.
  CancellationManager c_mgr;
  f_opts.cancellation_manager = &c_mgr;

  BorrowedArgsCallFrame frame(args, &captured_inputs_, ret_types_);
  Notification n;
  Status s;

  ctx->lib()->Run(f_opts, handle, &frame, [&n, &s](Status func_status) {
    s.Update(func_status);
    n.Notify();
  });
  n.WaitForNotification();
  TF_RETURN_IF_ERROR(s);
  return frame.ConsumeRetvals(rets);
}

Status CapturedFunction::Instantiate(IteratorContext* ctx) {
  FunctionLibraryRuntime::Handle unused_handle;
  TF_RETURN_IF_ERROR(MaybeInstantiate(ctx, &unused_handle));
  mutex_lock l(mu_);
  if (captured_runner_ == nullptr) {
    captured_runner_ = *ctx->runner();
  }
  return Status::OK();
}

Status CapturedFunction::RunInstantiated(const std::vector<Tensor>& args,
                                         std::vector<Tensor>* rets) {
  FunctionLibraryRuntime* lib;
  FunctionLibraryRuntime::Handle handle;
  std::function<void(std::function<void()>)>* runner;
  {
    tf_shared_lock l(mu_);
    if (lib_ == nullptr) {
      return errors::FailedPrecondition(
          "`CapturedFunction::Instantiate()` must be called before a call to "
          "`CapturedFunction::RunInstantiated()`.");
    }
    lib = lib_;
    handle = f_handle_;
    runner = &captured_runner_;
  }

  FunctionLibraryRuntime::Options f_opts;
  f_opts.step_id = CapturedFunction::generate_step_id();
  ScopedStepContainer step_container(f_opts.step_id, [lib](const string& name) {
    lib->device()->resource_manager()->Cleanup(name).IgnoreError();
  });
  f_opts.step_container = &step_container;
  f_opts.runner = runner;
  // TODO(mrry): Add cancellation manager support to IteratorContext
  // so that we can cancel running map functions. The local
  // cancellation manager here is created so that we can run kernels
  // (such as queue kernels) that depend on the non-nullness of
  // `OpKernelContext::cancellation_manager()`, but additional effort
  // will be required to plumb it through the `IteratorContext`.
  CancellationManager c_mgr;
  f_opts.cancellation_manager = &c_mgr;

  BorrowedArgsCallFrame frame(args, &captured_inputs_, ret_types_);
  Notification n;
  Status s;

  lib->Run(f_opts, handle, &frame, [&n, &s](Status func_status) {
    s.Update(func_status);
    n.Notify();
  });
  n.WaitForNotification();
  TF_RETURN_IF_ERROR(s);
  return frame.ConsumeRetvals(rets);
}

void CapturedFunction::RunAsync(IteratorContext* ctx,
                                std::vector<Tensor>&& args,
                                std::vector<Tensor>* rets,
                                FunctionLibraryRuntime::DoneCallback done) {
  // NOTE(mrry): This method does not transfer ownership of `ctx`, and it may
  // be deleted before `done` is called. Take care not to capture `ctx` in any
  // code that may execute asynchronously in this function.
  FunctionLibraryRuntime::Handle handle;
  Status s = MaybeInstantiate(ctx, &handle);
  if (!s.ok()) {
    done(s);
    return;
  }
  auto frame =
      new OwnedArgsCallFrame(std::move(args), &captured_inputs_, ret_types_);

  FunctionLibraryRuntime::Options f_opts;
  f_opts.step_id = CapturedFunction::generate_step_id();
  ResourceMgr* resource_mgr = ctx->lib()->device()->resource_manager();
  auto step_container = new ScopedStepContainer(
      f_opts.step_id, [resource_mgr](const string& name) {
        resource_mgr->Cleanup(name).IgnoreError();
      });
  f_opts.step_container = step_container;
  f_opts.runner = ctx->runner();
  // TODO(mrry): Add cancellation manager support to IteratorContext
  // so that we can cancel running map functions. The local
  // cancellation manager here is created so that we can run kernels
  // (such as queue kernels) that depend on the non-nullness of
  // `OpKernelContext::cancellation_manager()`, but additional effort
  // will be required to plumb it through the `IteratorContext`.
  auto c_mgr = new CancellationManager;
  f_opts.cancellation_manager = c_mgr;

  tf_shared_lock l(mu_);
  ctx->lib()->Run(f_opts, handle, frame,
                  std::bind(
                      [rets, step_container, c_mgr, frame](
                          FunctionLibraryRuntime::DoneCallback done,
                          // Begin unbound arguments.
                          Status s) {
                        delete step_container;
                        delete c_mgr;
                        if (s.ok()) {
                          s = frame->ConsumeRetvals(rets);
                        }
                        delete frame;
                        done(s);
                      },
                      std::move(done), std::placeholders::_1));
}

CapturedFunction::CapturedFunction(const NameAttrList& func,
                                   std::vector<Tensor> captured_inputs)
    : func_(func),
      lib_(nullptr),
      f_handle_(kInvalidHandle),
      captured_inputs_(std::move(captured_inputs)) {}

}  // namespace tensorflow