create_batch_reader_op.cc 5.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//   Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/operators/reader/reader_op_registry.h"

namespace paddle {
namespace operators {
namespace reader {

class BatchReader : public framework::DecoratedReader {
 public:
F
fengjiayi 已提交
23 24 25
  BatchReader(const std::shared_ptr<ReaderBase>& reader, int batch_size,
              bool discard_leftover)
      : DecoratedReader(reader),
Y
yuyang18 已提交
26
        batch_size_(static_cast<size_t>(batch_size)),
F
fengjiayi 已提交
27
        discard_leftover_(discard_leftover) {
28 29 30
    buffer_.reserve(batch_size_);
  }

31
  void ReadNextImpl(std::vector<framework::LoDTensor>* out) override;
32 33

 private:
Y
yuyang18 已提交
34
  size_t batch_size_;
F
fengjiayi 已提交
35
  bool discard_leftover_;
36 37 38 39 40 41 42 43 44 45 46 47
  std::vector<std::vector<framework::LoDTensor>> buffer_;
};

class CreateBatchReaderOp : public framework::OperatorBase {
 public:
  using framework::OperatorBase::OperatorBase;

 private:
  void RunImpl(const framework::Scope& scope,
               const platform::Place& dev_place) const override {
    auto* out = scope.FindVar(Output("Out"))
                    ->template GetMutable<framework::ReaderHolder>();
F
fengjiayi 已提交
48 49 50 51 52
    if (out->Get() != nullptr) {
      return;
    }
    const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader"))
                                        ->Get<framework::ReaderHolder>();
53
    out->Reset(framework::MakeDecoratedReader<BatchReader>(
54 55
        underlying_reader, Attr<int>("batch_size"),
        Attr<bool>("discard_leftover")));
56 57 58 59
  }
};

class CreateBatchReaderOpMaker : public DecoratedReaderMakerBase {
Y
Yu Yang 已提交
60 61
 protected:
  void Apply() override {
62 63 64
    AddAttr<int>("batch_size",
                 "How many instances the batch reader yields each time.")
        .GreaterThan(0);
F
fengjiayi 已提交
65 66 67 68
    AddAttr<bool>("discard_leftover",
                  "If true, the leftover instances that are not enough for a "
                  "new batch will be discarded.")
        .SetDefault(true);
69 70 71 72 73 74 75 76 77
    AddComment(R"DOC(
      CreateBatchReader Operator

      A batch reader takes another reader as its 'underlying reader',
      gathers the underlying reader's outputs and then yields them in batches.
    )DOC");
  }
};

78
void BatchReader::ReadNextImpl(std::vector<framework::LoDTensor>* out) {
79 80
  buffer_.clear();
  buffer_.reserve(batch_size_);
Y
yuyang18 已提交
81
  for (size_t i = 0; i < batch_size_; ++i) {
F
fengjiayi 已提交
82 83
    buffer_.push_back(std::vector<framework::LoDTensor>());
    reader_->ReadNext(&buffer_.back());
F
fengjiayi 已提交
84
    if (buffer_.back().empty()) {
F
fengjiayi 已提交
85
      buffer_.pop_back();
86 87 88
      break;
    }
  }
F
fengjiayi 已提交
89 90 91
  if (discard_leftover_ && buffer_.size() < batch_size_) {
    buffer_.clear();
  }
92 93 94 95 96 97
  // Concat instances
  out->clear();
  if (buffer_.empty()) {
    // if buffer_ is empty, the 'out' will return as an empty vector.
    return;
  }
Y
yuyang18 已提交
98
  size_t out_num = buffer_[0].size();
99
  out->reserve(out_num);
Y
yuyang18 已提交
100
  for (size_t j = 0; j < out_num; ++j) {
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
    // Merge shape and check date type
    std::type_index batch_type = buffer_[0][j].type();
    framework::DDim batch_shape = buffer_[0][j].dims();
    for (size_t i = 1; i < buffer_.size(); ++i) {
      std::type_index ins_type = buffer_[i][j].type();
      framework::DDim ins_shape = buffer_[i][j].dims();
      PADDLE_ENFORCE_EQ(batch_type, ins_type);
      PADDLE_ENFORCE_EQ(slice_ddim(batch_shape, 1, batch_shape.size()),
                        slice_ddim(ins_shape, 1, ins_shape.size()));
      PADDLE_ENFORCE_GT(ins_shape[0], 0);
      batch_shape[0] += ins_shape[0];
    }

    framework::LoDTensor out_tensor;
    out_tensor.Resize(batch_shape);
    out_tensor.mutable_data(platform::CPUPlace(), batch_type);
    int64_t dst_offset = 0;

    // Merge lod and data
    framework::LoD batch_lod;
    for (size_t i = 0; i < buffer_.size(); ++i) {
      framework::DDim ins_shape = buffer_[i][j].dims();
      framework::LoD ins_lod = buffer_[i][j].lod();
      if (i == 0) {
        batch_lod = ins_lod;
      } else {
        PADDLE_ENFORCE_EQ(batch_lod.size(), ins_lod.size());
        for (size_t level_idx = 0; level_idx < batch_lod.size(); ++level_idx) {
          auto& lod_level = batch_lod[level_idx];
          for (size_t k = 1; k < ins_lod[level_idx].size(); ++k) {
            lod_level.push_back(ins_lod[level_idx][k] + lod_level.back());
          }
        }
      }
      auto dst = out_tensor.Slice(dst_offset, dst_offset + ins_shape[0]);
      TensorCopy(buffer_[i][j], platform::CPUPlace(), &dst);
      dst_offset += ins_shape[0];
    }
    out_tensor.set_lod(batch_lod);
    out->push_back(out_tensor);
  }
}

}  // namespace reader
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators::reader;
REGISTER_DECORATED_READER_OPERATOR(create_batch_reader,
                                   ops::CreateBatchReaderOp,
                                   ops::CreateBatchReaderOpMaker);