data_feed.h 9.2 KB
Newer Older
W
wangguibao 已提交
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
/* 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. */

#ifndef PADDLE_FLUID_FRAMEWORK_DATA_FEED_H_
#define PADDLE_FLUID_FRAMEWORK_DATA_FEED_H_

#include <memory>
#include <set>
#include <map>
#include <string>
#include <thread>               // NOLINT
#include <vector>
#include <queue>
#include <mutex>                // NOLINT
#include <unordered_map>
#include <unordered_set>
#include <condition_variable>   // NOLINT
#include <fstream>
B
barrierye 已提交
30 31
#include <deque>
#include <atomic>
W
wangguibao 已提交
32 33 34 35

#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/scope.h"
B
barrierye 已提交
36
#include "paddle/fluid/framework/data_feed.pb.h"
W
wangguibao 已提交
37 38 39 40

namespace paddle {
namespace framework {

B
barrierye 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
class MixTensor {
 public:
  MixTensor(){}
  MixTensor(LoDTensor* lodtensor) {
    is_dense_ = false;
    lodtensor_ = lodtensor;
  }
  MixTensor(Tensor* tensor) {
    is_dense_ = true;
    tensor_ = tensor;
  }
  bool IsDense() {return is_dense_;}
  LoDTensor* GetLoDTensor(){
    if (is_dense_) {
      LOG(ERROR) << "error: let a dense var return a LoDTensor ptr";
B
barrierye 已提交
56
      exit(-1);
B
barrierye 已提交
57 58 59 60 61 62
    }
    return lodtensor_;
  }
  Tensor* GetTensor(){
    if (!is_dense_) {
      LOG(ERROR) << "error: let a sparse var return a Tensor ptr";
B
barrierye 已提交
63
      exit(-1);
B
barrierye 已提交
64 65 66 67 68 69 70
    }
    return tensor_;
  }
 private:
  bool is_dense_;
  LoDTensor* lodtensor_;
  Tensor* tensor_;
W
wangguibao 已提交
71 72
};

B
barrierye 已提交
73 74
template<typename T>
class BlockingQueue {
W
wangguibao 已提交
75
 public:
B
barrierye 已提交
76 77 78
  explicit BlockingQueue(size_t capacity = 32)
      : capacity_(capacity), closed_(false) {
    size_.store(0);
W
wangguibao 已提交
79
  }
B
barrierye 已提交
80 81 82
  
  void ReCap(size_t capacity) {
    capacity_ = capacity;
W
wangguibao 已提交
83 84
  }

B
barrierye 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  bool Send(const T& elem) {
    int c = -1;
    {
      std::unique_lock<std::mutex> lock(send_mutex_);
      send_cv_.wait(lock, [&] {return size_.load() < capacity_ || closed_;});
      if (closed_) {
        VLOG(5)
            << "WARNING: Sending an element to a closed reader::BlokcingQueue.";
        return false;
      }
      queue_.push_back(elem);
      c = size_.load();
      size_.fetch_add(1);
    }
    if (c + 1 < capacity_) {
      send_cv_.notify_one();
    }
W
wangguibao 已提交
102

B
barrierye 已提交
103 104 105 106 107 108
    if (c == 0) {
      std::unique_lock<std::mutex> lock(receive_mutex_);
      receive_cv_.notify_one();
    }
    return true;
  }
W
wangguibao 已提交
109

B
barrierye 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
  bool Receive(T* elem) {
    int c = -1;
    {
      std::unique_lock<std::mutex> lock(receive_mutex_);
      receive_cv_.wait(lock, [&] {return size_.load() != 0 || closed_;});
      if (size_.load() != 0) {
        *elem = queue_.front();
        queue_.pop_front();
        c = size_.load();
        size_.fetch_sub(1);
      } else {
        return false;
      }
    }
    if (c > 1) {
      receive_cv_.notify_one();
    }
    if (c == capacity_) {
      std::unique_lock<std::mutex> lock(send_mutex_);
      send_cv_.notify_one();
    }
    return true;
W
wangguibao 已提交
132 133
  }

B
barrierye 已提交
134 135 136 137 138 139
  void Close() {
    std::lock_guard<std::mutex> lock1(send_mutex_);
    std::lock_guard<std::mutex> lock2(receive_mutex_);
    closed_ = true;
    send_cv_.notify_all();
    receive_cv_.notify_all();
W
wangguibao 已提交
140 141
  }

B
barrierye 已提交
142 143 144 145 146 147 148 149 150 151 152
 private:
  size_t capacity_;
  std::atomic_size_t size_;
  bool closed_;
  std::deque<T> queue_;

  mutable std::mutex send_mutex_;
  mutable std::mutex receive_mutex_;
  mutable std::condition_variable send_cv_;
  mutable std::condition_variable receive_cv_;
};
153

B
barrierye 已提交
154 155 156 157
class DataFeed {
 public:
  DataFeed() {}
  virtual ~DataFeed() {}
B
barrierye 已提交
158
  virtual void Init(paddle::framework::DataFeedDesc& data_feed_desc) = 0;
B
barrierye 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171
  // for some datafeeds may not be able to implement this interface
  virtual bool CheckFile(const char* filename) {
    LOG(ERROR) << "error: The function CheckFile is not implemented";
    return false;
  }
  virtual bool SetFileList(const std::vector<std::string>& files); 
  virtual bool Start() = 0;
  virtual bool Next() = 0;
  virtual void SetBatchSize(int batch) { default_batch_size_ = batch; }
  virtual int GetBatchSize() { return batch_size_; }
  // for subclass with queue
  virtual void SetQueueSize(int queue_size) {
    LOG(ERROR) << "error: The function SetQueueSize is not implemented";
B
barrierye 已提交
172
    exit(-1);
B
barrierye 已提交
173 174 175 176
  }
  // for subclass with buffer
  virtual void SetBufferSize(int buffer_size) {
    LOG(ERROR) << "error: The function SetBufferSize is not implemented";
B
barrierye 已提交
177
    exit(-1);
B
barrierye 已提交
178 179 180 181 182
  }
  virtual const std::vector<std::string>& GetAllSlots() {return all_slots_;}
  virtual const std::vector<std::string>& GetUseSlots() {return use_slots_;}
  std::vector<MixTensor>& GetFeedVec() {return feed_vec_;}
  virtual void AddFeedVar(Variable* var, const std::string& name);
W
wangguibao 已提交
183
 protected:
B
barrierye 已提交
184 185
  // Check if it is executed in this order:
  //   Init -> SetFileList/BindingMemory -> Start -> Next
B
barrierye 已提交
186 187 188
  virtual void CheckInit();
  virtual void CheckSetFileList();
  virtual void CheckStart();
B
barrierye 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  virtual bool PickOneFile(std::string& filename);
  
  static std::vector<std::string> filelist_;
  static size_t file_idx_;
  static std::mutex mutex_for_pick_file_;
  
  std::vector<std::string> use_slots_;
  std::vector<bool> use_slots_is_dense_;

  std::vector<std::string> all_slots_;
  std::vector<std::string> all_slots_type_;
  std::vector<int> use_slots_index_; // -1: not used; >=0: the index of use_slots_
  
  std::vector<MixTensor> feed_vec_;
  
W
wangguibao 已提交
204 205
  int default_batch_size_;
  int batch_size_;
B
barrierye 已提交
206 207 208 209 210

  bool finish_init_;
  bool finish_set_filelist_;
  bool finish_binding_memory_;
  bool finish_start_;
W
wangguibao 已提交
211 212
};

B
barrierye 已提交
213 214
template<typename T>
class PrivateQueueDataFeed : public DataFeed {
215
 public:
B
barrierye 已提交
216 217
  PrivateQueueDataFeed() {}
  virtual ~PrivateQueueDataFeed() {}
B
barrierye 已提交
218
  virtual void Init(paddle::framework::DataFeedDesc& data_feed_desc) = 0;
B
barrierye 已提交
219 220 221 222 223 224 225 226 227
  virtual bool Start();
  virtual bool Next(); // no buffer
  virtual void SetQueueSize(int queue_size);

 protected:
  virtual void ReadThread();
  virtual bool ParseOneInstance(T& instance) = 0;
  virtual void AddInstanceToInsVec(T& vec_ins, T& instance, int index) = 0;
  virtual void PutToFeedVec(T& ins_vec) = 0;
228

B
barrierye 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  std::thread read_thread_; // the thread for read files
  /* using ifstream one line and one line parse is faster 
   * than using fread one buffer and one buffer parse.
   *   for 601M JingPai data:
   *     ifstream one line and one line parse: 6034 ms
   *     fread one buffer and one buffer parse: 7097 ms */
  std::ifstream file_;
  size_t queue_size_;
  // The elements in the queue are one piece of data, 
  // with multiple fields in each piece of data
  BlockingQueue<T> queue_;
};

class MultiSlotType {
 public:
  MultiSlotType() {
    float_feasign_.clear();
    uint64_feasign_.clear();
    offset_.resize(1);
    offset_[0] = 0;
  }
  ~MultiSlotType() {}
  void SetType(std::string& type) {
B
barrierye 已提交
252
    CheckType(type);
B
barrierye 已提交
253 254 255 256 257 258
    type_ = type;
  }
  std::vector<size_t>& GetOffset() {
    return offset_;
  }
  void AddValue(float v) {
B
barrierye 已提交
259
    CheckFloat();
B
barrierye 已提交
260 261 262
    float_feasign_.push_back(v);
  }
  void AddValue(uint64_t v) {
B
barrierye 已提交
263
    CheckUint64();
B
barrierye 已提交
264 265 266 267
    uint64_feasign_.push_back(v);
  }
  void AddIns(MultiSlotType& ins) {
    if (ins.GetType()[0] == 'f') { //float
B
barrierye 已提交
268
      CheckFloat();
B
barrierye 已提交
269 270 271 272
      auto& vec = ins.GetFloatData();
      offset_.push_back(offset_.back() + vec.size());
      float_feasign_.insert(float_feasign_.end(), vec.begin(), vec.end());
    } else if (ins.GetType()[0] == 'u') { //uint64
B
barrierye 已提交
273
      CheckUint64();
B
barrierye 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      auto& vec = ins.GetUint64Data();
      offset_.push_back(offset_.back() + vec.size());
      uint64_feasign_.insert(uint64_feasign_.end(), vec.begin(), vec.end());
    }
  }
  std::vector<float>& GetFloatData() {
    return float_feasign_;
  }
  std::vector<uint64_t>& GetUint64Data() {
    return uint64_feasign_;
  }
  std::string& GetType() {
    return type_;
  }
 private:
B
barrierye 已提交
289
  void CheckType(std::string& type) {
B
barrierye 已提交
290 291 292
    if (type != "uint64" && type != "float") {
      // check in here
      LOG(ERROR) << "error: here is no this type";
B
barrierye 已提交
293
      exit(-1);
B
barrierye 已提交
294 295
    }
  }
B
barrierye 已提交
296
  void CheckFloat() {
B
barrierye 已提交
297 298
    if (type_[0] != 'f') { //float
      LOG(ERROR) << "error: add " << type_ << " value to float slot";
B
barrierye 已提交
299
      exit(-1);
B
barrierye 已提交
300 301
    }
  }
B
barrierye 已提交
302
  void CheckUint64() {
B
barrierye 已提交
303 304
    if (type_[0] != 'u') { //uint64
      LOG(ERROR) << "error: add " << type_ << " value to uint64 slot";
B
barrierye 已提交
305
      exit(-1);
B
barrierye 已提交
306 307 308 309 310 311 312 313 314 315 316 317
    }
  }
  std::vector<float> float_feasign_;
  std::vector<uint64_t> uint64_feasign_;
  std::string type_;
  std::vector<size_t> offset_;
};

class MultiSlotDataFeed : public PrivateQueueDataFeed<std::vector<MultiSlotType>> {
 public:
  MultiSlotDataFeed() {}
  virtual ~MultiSlotDataFeed() {}
B
barrierye 已提交
318 319
  virtual void Init(paddle::framework::DataFeedDesc& data_feed_desc);
  virtual bool CheckFile(const char* filename);
B
barrierye 已提交
320 321 322 323 324 325 326
 protected:
  virtual void AddInstanceToInsVec(std::vector<MultiSlotType>& vec_ins, 
      std::vector<MultiSlotType>& instance, int index);
  virtual bool ParseOneInstance(std::vector<MultiSlotType>& instance);
  virtual void PutToFeedVec(std::vector<MultiSlotType>& ins_vec);
};

W
wangguibao 已提交
327 328 329 330 331
}   // namespace framework
}   // namespace paddle

#endif  // PADDLE_FLUID_FRAMEWORK_DATA_FEED_H_
/* vim: set expandtab ts=2 sw=2 sts=2 tw=100: */