create_reader_op.cc 8.3 KB
Newer Older
F
fengjiayi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//   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/framework/op_registry.h"
#include "paddle/framework/reader.h"

namespace paddle {
namespace operators {

F
fengjiayi 已提交
21 22
static std::vector<framework::DDim> RestoreShapes(
    const std::vector<int>& shape_concat, const std::vector<int>& ranks) {
F
fengjiayi 已提交
23 24 25 26 27 28 29 30 31 32 33
  std::vector<framework::DDim> res;
  int offset = 0;
  for (int len : ranks) {
    auto start_it = shape_concat.begin() + offset;
    auto end_it = start_it + len;
    res.push_back(framework::make_ddim(std::vector<int>(start_it, end_it)));
    offset += len;
  }
  return res;
}

F
fengjiayi 已提交
34
// general infershape for file readers
F
fengjiayi 已提交
35
class CreateFileReaderInferShape : public framework::InferShapeBase {
F
fengjiayi 已提交
36 37 38
 public:
  void operator()(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
F
fengjiayi 已提交
39
                   "The output file reader should not be null.");
F
fengjiayi 已提交
40 41 42 43 44
    const auto shape_concat =
        ctx->Attrs().Get<std::vector<int>>("shape_concat");
    const auto ranks = ctx->Attrs().Get<std::vector<int>>("ranks");
    std::vector<framework::DDim> shapes = RestoreShapes(shape_concat, ranks);
    ctx->SetReaderDims("Out", shapes);
F
fengjiayi 已提交
45 46 47 48 49 50 51
  }
};

// general infershape for decorated readers
class CreateDecoratedReaderInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext* ctx) const override {
F
fengjiayi 已提交
52 53
    PADDLE_ENFORCE(ctx->HasInput("UnderlyingReader"),
                   "Input(UnderlyingReader) should not be null.");
F
fengjiayi 已提交
54 55
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "The output decorated reader should not be null.");
F
fengjiayi 已提交
56 57 58 59 60 61 62 63 64 65 66 67
    ctx->SetReaderDims("Out", ctx->GetReaderDims("UnderlyingReader"));
  }
};

// general var type inference for all readers
class CreateReaderInferVarType : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc& op_desc,
                  framework::BlockDesc* block) const override {
    std::string reader_name = op_desc.Output("Out")[0];
    framework::VarDesc* reader = block->FindVarRecursive(reader_name);
    reader->SetType(framework::proto::VarDesc::READER);
F
fengjiayi 已提交
68 69 70 71
  }
};

template <typename T>
F
fengjiayi 已提交
72
class CreateRandomDataGeneratorOp : public framework::OperatorBase {
F
fengjiayi 已提交
73 74 75 76 77 78
 public:
  using framework::OperatorBase::OperatorBase;
  void Run(const framework::Scope& scope,
           const platform::Place& dev_place) const override {
    const auto& shape_concat = Attr<std::vector<int>>("shape_concat");
    const auto& ranks = Attr<std::vector<int>>("ranks");
F
fengjiayi 已提交
79
    PADDLE_ENFORCE(!shape_concat.empty() && !ranks.empty());
F
fengjiayi 已提交
80 81 82 83
    PADDLE_ENFORCE_EQ(std::accumulate(ranks.begin(), ranks.end(), 0),
                      int(shape_concat.size()),
                      "The accumulate of all ranks should be equal to the "
                      "shape concat's length.");
F
fengjiayi 已提交
84
    std::vector<framework::DDim> shapes = RestoreShapes(shape_concat, ranks);
F
fengjiayi 已提交
85
    auto* out = scope.FindVar(Output("Out"))
F
fengjiayi 已提交
86
                    ->template GetMutable<framework::ReaderHolder>();
F
fengjiayi 已提交
87 88
    out->Reset(new framework::RandomDataGenerator<T>(shapes, Attr<float>("min"),
                                                     Attr<float>("max")));
F
fengjiayi 已提交
89 90 91
  }
};

F
fengjiayi 已提交
92 93
class CreateRandomDataGeneratorOpMaker
    : public framework::OpProtoAndCheckerMaker {
F
fengjiayi 已提交
94
 public:
F
fengjiayi 已提交
95
  CreateRandomDataGeneratorOpMaker(OpProto* op_proto, OpAttrChecker* op_checker)
F
fengjiayi 已提交
96
      : OpProtoAndCheckerMaker(op_proto, op_checker) {
F
fengjiayi 已提交
97
    AddOutput("Out", "(ReaderHolder) The created random reader.");
F
fengjiayi 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110
    AddAttr<std::vector<int>>("shape_concat",
                              "The concat of all data's shapes.");
    AddAttr<std::vector<int>>(
        "ranks",
        "The ranks of each data."
        "e.g."
        "shape_concat = [2,3,4,5,6]"
        "ranks = [3,2]"
        "It means the reader will generate two data each time,"
        "whose shapes are [2,3,4] and [5,6] respectively.");
    AddAttr<float>("min", "The lower bound of reader's uniform distribution.");
    AddAttr<float>("max", "The upper bound of reader's uniform distribution.");
    AddComment(R"DOC(
F
fengjiayi 已提交
111
      CreateRandomDataGenerator Operator
F
fengjiayi 已提交
112 113 114 115 116 117 118 119

      This Op creates a random reader. 
      The reader generates random data instead of really reading from files.
      Generated data follow an uniform distribution between 'min' and 'max'.
    )DOC");
  }
};

F
fengjiayi 已提交
120 121 122 123 124
class CreateShuffleReaderOp : public framework::OperatorBase {
 public:
  using framework::OperatorBase::OperatorBase;
  void Run(const framework::Scope& scope,
           const platform::Place& dev_place) const override {
F
fengjiayi 已提交
125
    const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader"))
F
fengjiayi 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138
                                        ->Get<framework::ReaderHolder>();
    auto* out = scope.FindVar(Output("Out"))
                    ->template GetMutable<framework::ReaderHolder>();
    out->Reset(new framework::ShuffleReader(underlying_reader.Get(),
                                            Attr<int>("buffer_size")));
  }
};

class CreateShuffleReaderOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  CreateShuffleReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(op_proto, op_checker) {
    AddInput(
F
fengjiayi 已提交
139
        "UnderlyingReader",
F
fengjiayi 已提交
140 141 142 143 144 145 146
        "(ReaderHolder) The underlying reader for creating a shuffle reader.");
    AddOutput("Out", "(ReaderHolder) The created shuffle reader.");
    AddAttr<int>("buffer_size", "The shuffle buffer size.").GreaterThan(0);
    AddComment(R"DOC(
      CreateShuffleReader Operator

      A shuffle reader takes another reader as its 'underlying reader'
F
fengjiayi 已提交
147 148 149 150 151 152 153 154 155 156
      and yields the underlying reader's outputs in a shuffled order. 
    )DOC");
  }
};

class CreateBatchReaderOp : public framework::OperatorBase {
 public:
  using framework::OperatorBase::OperatorBase;
  void Run(const framework::Scope& scope,
           const platform::Place& dev_place) const override {
F
fengjiayi 已提交
157
    const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader"))
F
fengjiayi 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170
                                        ->Get<framework::ReaderHolder>();
    auto* out = scope.FindVar(Output("Out"))
                    ->template GetMutable<framework::ReaderHolder>();
    out->Reset(new framework::BatchReader(underlying_reader.Get(),
                                          Attr<int>("batch_size")));
  }
};

class CreateBatchReaderOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  CreateBatchReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker)
      : OpProtoAndCheckerMaker(op_proto, op_checker) {
    AddInput(
F
fengjiayi 已提交
171
        "UnderlyingReader",
F
fengjiayi 已提交
172 173 174 175 176 177 178 179 180 181
        "(ReaderHolder) The underlying reader for creating a batch reader.");
    AddOutput("Out", "(ReaderHolder) The created batch reader.");
    AddAttr<int>("batch_size",
                 "How many instances the batch reader yields each time.")
        .GreaterThan(0);
    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. 
F
fengjiayi 已提交
182 183 184 185
    )DOC");
  }
};

F
fengjiayi 已提交
186 187 188 189
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
F
fengjiayi 已提交
190 191
REGISTER_OPERATOR(create_random_data_generator,
                  ops::CreateRandomDataGeneratorOp<float>,
F
fengjiayi 已提交
192
                  ops::CreateFileReaderInferShape,
F
fengjiayi 已提交
193
                  ops::CreateRandomDataGeneratorOpMaker,
F
fengjiayi 已提交
194 195
                  paddle::framework::EmptyGradOpMaker,
                  ops::CreateReaderInferVarType);
F
fengjiayi 已提交
196
REGISTER_OPERATOR(create_shuffle_reader, ops::CreateShuffleReaderOp,
F
fengjiayi 已提交
197
                  ops::CreateDecoratedReaderInferShape,
F
fengjiayi 已提交
198
                  ops::CreateShuffleReaderOpMaker,
F
fengjiayi 已提交
199 200
                  paddle::framework::EmptyGradOpMaker,
                  ops::CreateReaderInferVarType);
F
fengjiayi 已提交
201 202 203
REGISTER_OPERATOR(create_batch_reader, ops::CreateBatchReaderOp,
                  ops::CreateDecoratedReaderInferShape,
                  ops::CreateBatchReaderOpMaker,
F
fengjiayi 已提交
204 205
                  paddle::framework::EmptyGradOpMaker,
                  ops::CreateReaderInferVarType);