aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/flat_map_dataset_op.cc
blob: 5b22a922b2d8129569d07381c7a6f01ab93a197a (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
/* 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/dataset.h"

#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/random/random.h"

#include "tensorflow/core/kernels/captured_function.h"

namespace tensorflow {

namespace {

// See documentation in ../ops/iterator_ops.cc for a high-level
// description of the following op.

class FlatMapDatasetOp : public OpKernel {
 public:
  explicit FlatMapDatasetOp(OpKernelConstruction* ctx)
      : OpKernel(ctx), graph_def_version_(ctx->graph_def_version()) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("f", &func_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
  }

  void Compute(OpKernelContext* ctx) override {
    DatasetBase* input;
    OP_REQUIRES_OK(ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &input));
    core::ScopedUnref unref_input(input);

    OpInputList inputs;
    OP_REQUIRES_OK(ctx, ctx->input_list("other_arguments", &inputs));
    std::vector<Tensor> other_arguments;
    other_arguments.reserve(inputs.size());
    for (const Tensor& t : inputs) {
      other_arguments.push_back(t);
    }

    std::unique_ptr<CapturedFunction> captured_func;
    OP_REQUIRES_OK(ctx, CapturedFunction::Create(ctx, func_, graph_def_version_,
                                                 std::move(other_arguments),
                                                 &captured_func));

    DatasetBase* dataset = new Dataset(input, std::move(captured_func),
                                       output_types_, output_shapes_);

    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &output));
    ResourceHandle handle = MakeResourceHandle<DatasetBase>(
        ctx, ctx->step_container()->name(), name());
    OP_REQUIRES_OK(ctx, CreateResource(ctx, handle, dataset));
    output->flat<ResourceHandle>()(0) = handle;
  }

 private:
  class Dataset : public DatasetBase {
   public:
    Dataset(const DatasetBase* input,
            std::unique_ptr<CapturedFunction> captured_func,
            const DataTypeVector& output_types,
            const std::vector<PartialTensorShape>& output_shapes)
        : input_(input),
          captured_func_(std::move(captured_func)),
          output_types_(output_types),
          output_shapes_(output_shapes) {
      input_->Ref();
    }

    ~Dataset() override { input_->Unref(); }

    std::unique_ptr<IteratorBase> MakeIterator() const override {
      return std::unique_ptr<IteratorBase>(new Iterator(this));
    }

    const DataTypeVector& output_dtypes() const override {
      return output_types_;
    }
    const std::vector<PartialTensorShape>& output_shapes() const override {
      return output_shapes_;
    }

    string DebugString() override { return "FlatMapDatasetOp::Dataset"; }

   private:
    class Iterator : public DatasetIterator<Dataset> {
     public:
      explicit Iterator(const Dataset* dataset)
          : DatasetIterator<Dataset>(dataset),
            input_impl_(dataset->input_->MakeIterator()) {}

      Status GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors,
                     bool* end_of_sequence) override {
        mutex_lock l(mu_);
        do {
          if (current_element_iterator_) {
            // We are currently precessing a mapped element, so try to get the
            // next subelement.
            bool end_of_element;
            TF_RETURN_IF_ERROR(current_element_iterator_->GetNext(
                ctx, out_tensors, &end_of_element));
            if (!end_of_element) {
              // Produce the subelement as output.
              *end_of_sequence = false;
              return Status::OK();
            }

            // We have reached the end of the current element, so maybe move on
            // to the next element.
            current_element_iterator_.reset();
          }

          // Get the next element from the input dataset.
          std::vector<Tensor> args;
          TF_RETURN_IF_ERROR(input_impl_->GetNext(ctx, &args, end_of_sequence));
          if (*end_of_sequence) {
            return Status::OK();
          }

          FunctionLibraryRuntime::Options opts;
          opts.runner = ctx->runner();
          // Choose a step ID that is guaranteed not to clash with any
          // Session-generated step ID. DirectSession only generates
          // non-negative step IDs (contiguous, starting from 0), and
          // MasterSession generates 56-bit random step IDs whose MSB
          // is always 0, so a negative random step ID should suffice.
          opts.step_id = -std::abs(static_cast<int64>(random::New64()));
          ScopedStepContainer step_container(
              opts.step_id, [this, ctx](const string& name) {
                dataset()
                    ->captured_func_->resource_manager()
                    ->Cleanup(name)
                    .IgnoreError();
              });
          opts.step_container = &step_container;
          std::vector<Tensor> return_values;
          TF_RETURN_IF_ERROR(
              dataset()->captured_func_->Run(opts, args, &return_values));

          if (!(return_values.size() == 1 &&
                return_values[0].dtype() == DT_RESOURCE &&
                TensorShapeUtils::IsScalar(return_values[0].shape()))) {
            return errors::InvalidArgument(
                "`f` must return a single scalar of dtype DT_RESOURCE.");
          }

          // Retrieve the dataset that was created in `f`.
          DatasetBase* returned_dataset;
          const ResourceHandle& dataset_resource =
              return_values[0].scalar<ResourceHandle>()();

          // NOTE(mrry): We cannot use the core `LookupResource()` or
          // `DeleteResource()` functions, because we have an
          // `IteratorContext*` and not an `OpKernelContext*`, so we
          // replicate the necessary functionality here.
          auto type_index = MakeTypeIndex<DatasetBase>();
          if (type_index.hash_code() != dataset_resource.hash_code()) {
            return errors::InvalidArgument(
                "`f` must return a Dataset resource.");
          }
          TF_RETURN_IF_ERROR(
              dataset()->captured_func_->resource_manager()->Lookup(
                  dataset_resource.container(), dataset_resource.name(),
                  &returned_dataset));
          core::ScopedUnref unref_dataset(returned_dataset);

          // Create an iterator for the dataset that was returned by
          // `f`. This transfers ownership of the dataset to the
          // iterator, so we can delete it from the resource manager.
          current_element_iterator_ = returned_dataset->MakeIterator();
          TF_RETURN_IF_ERROR(
              dataset()
                  ->captured_func_->resource_manager()
                  ->Delete<DatasetBase>(dataset_resource.container(),
                                        dataset_resource.name()));
        } while (true);
      }

     private:
      mutex mu_;
      const std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_);
      std::unique_ptr<IteratorBase> current_element_iterator_ GUARDED_BY(mu_);
    };

    const DatasetBase* const input_;
    const std::unique_ptr<CapturedFunction> captured_func_;
    const DataTypeVector output_types_;
    const std::vector<PartialTensorShape> output_shapes_;
  };

  const int graph_def_version_;
  DataTypeVector output_types_;
  std::vector<PartialTensorShape> output_shapes_;
  const NameAttrList* func_;
};

REGISTER_KERNEL_BUILDER(Name("FlatMapDataset").Device(DEVICE_CPU),
                        FlatMapDatasetOp);

}  // namespace

}  // namespace tensorflow