aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/data/slide_dataset_op.cc
blob: 5765c61f30fb535ade9d4e7e62e109e4c262f523 (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
/* 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 <deque>
#include <vector>

#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/batch_util.h"

namespace tensorflow {

namespace {

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

class SlideDatasetOp : public UnaryDatasetOpKernel {
 public:
  explicit SlideDatasetOp(OpKernelConstruction* ctx)
      : UnaryDatasetOpKernel(ctx) {}

  void MakeDataset(OpKernelContext* ctx, DatasetBase* input,
                   DatasetBase** output) override {
    int64 window_size = 0;
    OP_REQUIRES_OK(
        ctx, ParseScalarArgument<int64>(ctx, "window_size", &window_size));
    OP_REQUIRES(
        ctx, window_size > 0,
        errors::InvalidArgument("Window size must be greater than zero."));
    int64 window_shift = 0;
    OP_REQUIRES_OK(
        ctx, ParseScalarArgument<int64>(ctx, "window_shift", &window_shift));
    OP_REQUIRES(
        ctx, window_shift > 0,
        errors::InvalidArgument("Window shift must be greater than zero."));
    int64 window_stride = 0;
    OP_REQUIRES_OK(
        ctx, ParseScalarArgument<int64>(ctx, "window_stride", &window_stride));
    OP_REQUIRES(
        ctx, window_stride > 0,
        errors::InvalidArgument("window_stride must be greater than zero."));
    if (window_size == window_shift && window_stride == 1) {
      LOG(WARNING) << "window_shift: " << window_shift
                   << " is equal to window_size: " << window_size
                   << " and window_stride is 1, use `batch` instead.";
    }
    *output = new Dataset(ctx, window_size, window_shift, window_stride, input);
  }

 private:
  class Dataset : public GraphDatasetBase {
   public:
    Dataset(OpKernelContext* ctx, int64 window_size, int64 window_shift,
            int64 window_stride, const DatasetBase* input)
        : GraphDatasetBase(ctx),
          window_size_(window_size),
          window_shift_(window_shift),
          window_stride_(window_stride),
          input_(input) {
      input_->Ref();

      const auto& input_shapes = input_->output_shapes();
      output_shapes_.reserve(input_shapes.size());
      for (const auto& input_shape : input_shapes) {
        output_shapes_.emplace_back(
            PartialTensorShape({-1}).Concatenate(input_shape));
      }
    }

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

    std::unique_ptr<IteratorBase> MakeIteratorInternal(
        const string& prefix) const override {
      return std::unique_ptr<IteratorBase>(new Iterator(
          Iterator::Params{this, strings::StrCat(prefix, "::Slide")}));
    }

    const DataTypeVector& output_dtypes() const override {
      return input_->output_dtypes();
    }

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

    string DebugString() const override {
      return strings::StrCat("SlideDatasetOp(", window_size_, ", ",
                             window_shift_, ", ", window_stride_, ")::Dataset");
    }

   protected:
    Status AsGraphDefInternal(OpKernelContext* ctx, DatasetGraphDefBuilder* b,
                              Node** output) const override {
      Node* input_graph_node = nullptr;
      TF_RETURN_IF_ERROR(b->AddParentDataset(ctx, input_, &input_graph_node));
      Node* window_size = nullptr;
      Node* window_shift = nullptr;
      Node* window_stride = nullptr;
      TF_RETURN_IF_ERROR(b->AddScalar(window_size_, &window_size));
      TF_RETURN_IF_ERROR(b->AddScalar(window_shift_, &window_shift));
      TF_RETURN_IF_ERROR(b->AddScalar(window_stride_, &window_stride));
      TF_RETURN_IF_ERROR(b->AddDataset(
          this, {input_graph_node, window_size, window_shift, window_stride},
          output));
      return Status::OK();
    }

   private:
    class Iterator : public DatasetIterator<Dataset> {
     public:
      explicit Iterator(const Params& params)
          : DatasetIterator<Dataset>(params) {}

      Status Initialize(IteratorContext* ctx) override {
        return dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_);
      }

      Status GetNextInternal(IteratorContext* ctx,
                             std::vector<Tensor>* out_tensors,
                             bool* end_of_sequence) override {
        const int64 window_size = dataset()->window_size_;
        const int64 window_shift = dataset()->window_shift_;
        const int64 window_stride = dataset()->window_stride_;
        std::vector<std::vector<Tensor>> batch_elements;
        {
          mutex_lock l(mu_);
          if (!input_impl_) {
            *end_of_sequence = true;
            return Status::OK();
          }
          batch_elements.reserve(window_size);

          // Fill up buffer.
          size_t target_size = TargetBufferSize(window_size, window_stride);
          *end_of_sequence = false;
          for (size_t i = buffer_.size(); i < target_size && !*end_of_sequence;
               ++i) {
            std::vector<Tensor> element;
            TF_RETURN_IF_ERROR(
                input_impl_->GetNext(ctx, &element, end_of_sequence));
            if (!*end_of_sequence) {
              buffer_.push_back(std::move(element));
            } else {
              input_impl_.reset();
            }
          }

          // Drop the final smaller batch.
          if (buffer_.size() < target_size) {
            DCHECK(*end_of_sequence);
            return Status::OK();
          }

          for (size_t i = 0; i < window_size; ++i) {
            batch_elements.emplace_back(buffer_[window_stride * i]);
          }

          // Drop the data before the next iteration.
          if (window_shift >= buffer_.size()) {
            for (size_t i = buffer_.size(); i < window_shift; ++i) {
              bool end_of_input;
              std::vector<Tensor> element;
              TF_RETURN_IF_ERROR(
                  input_impl_->GetNext(ctx, &element, &end_of_input));
              if (end_of_input) {
                input_impl_.reset();
                break;
              }
            }
            buffer_.clear();
          } else {
            buffer_.erase(buffer_.begin(), buffer_.begin() + window_shift);
          }
        }

        // Construct output tensors.
        const size_t num_tuple_components = batch_elements[0].size();
        const int64 num_batch_elements = batch_elements.size();
        for (size_t component_index = 0; component_index < num_tuple_components;
             ++component_index) {
          const Tensor& first_element = batch_elements[0][component_index];
          TensorShape batch_component_shape({num_batch_elements});
          batch_component_shape.AppendShape(first_element.shape());
          Tensor batch_component(cpu_allocator(), first_element.dtype(),
                                 batch_component_shape);
          // Build the output tuple component by copying one slice
          // from each input element in the batch.
          for (size_t i = 0; i < num_batch_elements; ++i) {
            if (batch_elements[i][component_index].shape() !=
                first_element.shape()) {
              return errors::InvalidArgument(
                  "Cannot batch tensors with different shapes in component ",
                  component_index, ". First element had shape ",
                  first_element.shape().DebugString(), " and element ", i,
                  " had shape ",
                  batch_elements[i][component_index].shape().DebugString(),
                  ".");
            }
            TF_RETURN_IF_ERROR(batch_util::CopyElementToSlice(
                std::move(batch_elements[i][component_index]), &batch_component,
                i));
          }
          out_tensors->emplace_back(std::move(batch_component));
        }
        *end_of_sequence = false;
        return Status::OK();
      }

     protected:
      Status SaveInternal(IteratorStateWriter* writer) override {
        mutex_lock l(mu_);
        if (!input_impl_) {
          TF_RETURN_IF_ERROR(
              writer->WriteScalar(full_name("input_impl_empty"), ""));
        } else {
          TF_RETURN_IF_ERROR(SaveParent(writer, input_impl_));
        }
        // Save buffer.
        TF_RETURN_IF_ERROR(writer->WriteScalar(strings::StrCat("buffer_size"),
                                               buffer_.size()));
        for (int64 i = 0; i < buffer_.size(); i++) {
          TF_RETURN_IF_ERROR(writer->WriteScalar(
              strings::StrCat("buffer[", i, "]_size"), buffer_[i].size()));
          for (int64 j = 0; j < buffer_[i].size(); j++) {
            TF_RETURN_IF_ERROR(writer->WriteTensor(
                strings::StrCat("buffer[", i, "][", j, "]"), buffer_[i][j]));
          }
        }
        return Status::OK();
      }

      Status RestoreInternal(IteratorContext* ctx,
                             IteratorStateReader* reader) override {
        mutex_lock l(mu_);
        if (!reader->Contains(full_name("input_impl_empty"))) {
          TF_RETURN_IF_ERROR(RestoreParent(ctx, reader, input_impl_));
        } else {
          input_impl_.reset();
        }
        // Restore buffer.
        int64 buffer_size;
        TF_RETURN_IF_ERROR(
            reader->ReadScalar(strings::StrCat("buffer_size"), &buffer_size));
        buffer_.resize(buffer_size);
        for (int64 i = 0; i < buffer_size; i++) {
          int64 vector_size;
          TF_RETURN_IF_ERROR(reader->ReadScalar(
              strings::StrCat("buffer[", i, "]_size"), &vector_size));
          buffer_[i].resize(vector_size);
          for (int64 j = 0; j < vector_size; j++) {
            TF_RETURN_IF_ERROR(reader->ReadTensor(
                strings::StrCat("buffer[", i, "][", j, "]"), &buffer_[i][j]));
          }
        }
        return Status::OK();
      }

     private:
      size_t TargetBufferSize(int64 window_size, int64 window_stride) {
        return (window_size - 1) * window_stride + 1;
      }

      mutex mu_;
      std::deque<std::vector<Tensor>> buffer_ GUARDED_BY(mu_);
      std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_);
    };

    const int64 window_size_;
    const int64 window_shift_;
    const int64 window_stride_;
    const DatasetBase* const input_;
    std::vector<PartialTensorShape> output_shapes_;
  };
};

REGISTER_KERNEL_BUILDER(Name("SlideDataset").Device(DEVICE_CPU),
                        SlideDatasetOp);

}  // namespace

}  // namespace tensorflow