reader.h 2.1 KB
Newer Older
F
fengjiayi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//   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.

#pragma once

F
fengjiayi 已提交
17 18 19
#include <memory>
#include <vector>

Y
Yi Wang 已提交
20 21
#include "paddle/fluid/framework/ddim.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
22 23
#include "paddle/fluid/platform/place.h"

F
fengjiayi 已提交
24 25 26
namespace paddle {
namespace framework {

F
fengjiayi 已提交
27
class ReaderBase {
F
fengjiayi 已提交
28
 public:
F
fengjiayi 已提交
29
  virtual void ReadNext(std::vector<LoDTensor>* out) = 0;
F
fengjiayi 已提交
30

F
fengjiayi 已提交
31 32
  virtual void ReInit() = 0;

Y
Yu Yang 已提交
33
  virtual ~ReaderBase();
F
fengjiayi 已提交
34 35
};

F
fengjiayi 已提交
36
class DecoratedReader : public ReaderBase {
F
fengjiayi 已提交
37
 public:
F
fengjiayi 已提交
38 39
  explicit DecoratedReader(const std::shared_ptr<ReaderBase>& reader)
      : ReaderBase(), reader_(reader) {
F
fengjiayi 已提交
40 41 42
    PADDLE_ENFORCE_NOT_NULL(reader_);
  }

F
fengjiayi 已提交
43 44
  void ReInit() override { reader_->ReInit(); }

F
fengjiayi 已提交
45
 protected:
F
fengjiayi 已提交
46
  std::shared_ptr<ReaderBase> reader_;
F
fengjiayi 已提交
47 48
};

Y
Yu Yang 已提交
49
class FileReader : public ReaderBase {
50
 public:
51
  FileReader() : ReaderBase() {}
52 53 54 55 56 57 58

  void ReadNext(std::vector<LoDTensor>* out) override;

 protected:
  virtual void ReadNextImpl(std::vector<LoDTensor>* out) = 0;
};

59 60
// The ReaderHolder is used as reader' unified wrapper,
// making it easier to access different type reader in Variables.
F
fengjiayi 已提交
61 62
class ReaderHolder {
 public:
F
fengjiayi 已提交
63
  void Reset(ReaderBase* reader) { reader_.reset(reader); }
F
fengjiayi 已提交
64

F
fengjiayi 已提交
65
  std::shared_ptr<ReaderBase> Get() const { return reader_; }
F
fengjiayi 已提交
66

67 68 69 70 71 72 73 74
  void ReadNext(std::vector<LoDTensor>* out) {
    PADDLE_ENFORCE_NOT_NULL(reader_);
    reader_->ReadNext(out);
  }
  void ReInit() {
    PADDLE_ENFORCE_NOT_NULL(reader_);
    reader_->ReInit();
  }
F
fengjiayi 已提交
75 76

 private:
F
fengjiayi 已提交
77
  std::shared_ptr<ReaderBase> reader_;
F
fengjiayi 已提交
78 79
};

F
fengjiayi 已提交
80 81
}  // namespace framework
}  // namespace paddle