data_feed.h 14.3 KB
Newer Older
W
Wang Guibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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

#include <fstream>
18
#include <future>  // NOLINT
W
Wang Guibao 已提交
19 20
#include <memory>
#include <mutex>  // NOLINT
21
#include <sstream>
W
Wang Guibao 已提交
22 23
#include <string>
#include <thread>  // NOLINT
24
#include <utility>
25
#include <vector>
W
Wang Guibao 已提交
26

27
#include "paddle/fluid/framework/blocking_queue.h"
W
Wang Guibao 已提交
28
#include "paddle/fluid/framework/data_feed.pb.h"
29
#include "paddle/fluid/framework/fleet/fleet_wrapper.h"
W
Wang Guibao 已提交
30 31 32 33
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/reader.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/operators/reader/blocking_queue.h"
34
#include "paddle/fluid/string/string_helper.h"
W
Wang Guibao 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

namespace paddle {
namespace framework {

// DataFeed is the base virtual class for all ohther DataFeeds.
// It is used to read files and parse the data for subsequent trainer.
// Example:
//   DataFeed* reader =
//   paddle::framework::DataFeedFactory::CreateDataFeed(data_feed_name);
//   reader->Init(data_feed_desc); // data_feed_desc is a protobuf object
//   reader->SetFileList(filelist);
//   const std::vector<std::string> & use_slot_alias =
//   reader->GetUseSlotAlias();
//   for (auto name: use_slot_alias){ // for binding memory
//     reader->AddFeedVar(scope->Var(name), name);
//   }
//   reader->Start();
//   while (reader->Next()) {
//      // trainer do something
//   }
class DataFeed {
 public:
57 58 59 60
  DataFeed() {
    mutex_for_pick_file_ = nullptr;
    file_idx_ = nullptr;
  }
W
Wang Guibao 已提交
61 62 63 64 65 66 67 68 69 70
  virtual ~DataFeed() {}
  virtual void Init(const paddle::framework::DataFeedDesc& data_feed_desc) = 0;
  virtual bool CheckFile(const char* filename) {
    PADDLE_THROW("This function(CheckFile) is not implemented.");
  }
  // Set filelist for DataFeed.
  // Pay attention that it must init all readers before call this function.
  // Otherwise, Init() function will init finish_set_filelist_ flag.
  virtual bool SetFileList(const std::vector<std::string>& files);
  virtual bool Start() = 0;
D
dongdaxiang 已提交
71

W
Wang Guibao 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  // The trainer calls the Next() function, and the DataFeed will load a new
  // batch to the feed_vec. The return value of this function is the batch
  // size of the current batch.
  virtual int Next() = 0;
  // Get all slots' alias which defined in protofile
  virtual const std::vector<std::string>& GetAllSlotAlias() {
    return all_slots_;
  }
  // Get used slots' alias which defined in protofile
  virtual const std::vector<std::string>& GetUseSlotAlias() {
    return use_slots_;
  }
  // This function is used for binding feed_vec memory
  virtual void AddFeedVar(Variable* var, const std::string& name);

87
  // This function will do nothing at default
88
  virtual void SetMemoryData(void* memory_data) {}
89
  // This function will do nothing at default
90
  virtual void SetMemoryDataMutex(std::mutex* mutex) {}
91
  // This function will do nothing at default
92
  virtual void SetThreadId(int thread_id) {}
93
  // This function will do nothing at default
94
  virtual void SetThreadNum(int thread_num) {}
95
  // This function will do nothing at default
96
  virtual void SetTrainerNum(int trainer_num) {}
X
xjqbest 已提交
97 98
  // This function will do nothing at default
  virtual void SetFleetSendBatchSize(int64_t size) {}
99 100 101
  virtual void SetFileListMutex(std::mutex* mutex) {
    mutex_for_pick_file_ = mutex;
  }
102
  virtual void SetFileListIndex(size_t* file_index) { file_idx_ = file_index; }
103 104 105 106 107 108
  virtual void LoadIntoMemory() {
    PADDLE_THROW("This function(LoadIntoMemory) is not implemented.");
  }
  virtual void LocalShuffle() {
    PADDLE_THROW("This function(LocalShuffle) is not implemented.");
  }
109
  virtual void GlobalShuffle() {
110 111
    PADDLE_THROW("This function(GlobalShuffle) is not implemented.");
  }
X
xujiaqi01 已提交
112
  // This function will do nothing at default
113
  virtual void FillMemoryDataToChannel() {}
114
  // This function will do nothing at default
115
  virtual void FillChannelToMemoryData() {}
116
  // This function will do nothing at default
117
  virtual void PutInsToChannel(const std::string& ins_str) {}
118 119 120
  virtual int64_t GetChannelDataSize() { return 0; }
  // This function will do nothing at default
  virtual void ReleaseChannelData() {}
121

W
Wang Guibao 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134
 protected:
  // The following three functions are used to check if it is executed in this
  // order:
  //   Init() -> SetFileList() -> Start() -> Next()
  virtual void CheckInit();
  virtual void CheckSetFileList();
  virtual void CheckStart();
  virtual void SetBatchSize(
      int batch);  // batch size will be set in Init() function
  // This function is used to pick one file from the global filelist(thread
  // safe).
  virtual bool PickOneFile(std::string* filename);

135 136 137
  std::vector<std::string> filelist_;
  size_t* file_idx_;
  std::mutex* mutex_for_pick_file_;
W
Wang Guibao 已提交
138 139 140 141 142 143 144 145 146 147

  // the alias of used slots, and its order is determined by
  // data_feed_desc(proto object)
  std::vector<std::string> use_slots_;
  std::vector<bool> use_slots_is_dense_;

  // the alias of all slots, and its order is determined by data_feed_desc(proto
  // object)
  std::vector<std::string> all_slots_;
  std::vector<std::string> all_slots_type_;
148
  std::vector<std::vector<int>> use_slots_shape_;
149 150
  std::vector<int> inductive_shape_index_;
  std::vector<int> total_dims_without_inductive_;
W
Wang Guibao 已提交
151 152 153 154
  std::vector<int>
      use_slots_index_;  // -1: not used; >=0: the index of use_slots_

  // The data read by DataFeed will be stored here
155
  std::vector<LoDTensor*> feed_vec_;
W
Wang Guibao 已提交
156 157 158 159 160 161 162

  // the batch size defined by user
  int default_batch_size_;
  // current batch size
  int batch_size_;

  bool finish_init_;
163
  bool finish_set_filelist_;
W
Wang Guibao 已提交
164
  bool finish_start_;
165
  std::string pipe_command_;
W
Wang Guibao 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
};

// PrivateQueueDataFeed is the base virtual class for ohther DataFeeds.
// It use a read-thread to read file and parse data to a private-queue
// (thread level), and get data from this queue when trainer call Next().
template <typename T>
class PrivateQueueDataFeed : public DataFeed {
 public:
  PrivateQueueDataFeed() {}
  virtual ~PrivateQueueDataFeed() {}
  virtual void Init(const paddle::framework::DataFeedDesc& data_feed_desc) = 0;
  virtual bool Start();
  virtual int Next();

 protected:
  // The thread implementation function for reading file and parse.
  virtual void ReadThread();
  // This function is used to set private-queue size, and the most
  // efficient when the queue size is close to the batch size.
  virtual void SetQueueSize(int queue_size);
  // The reading and parsing method called in the ReadThread.
  virtual bool ParseOneInstance(T* instance) = 0;
D
dongdaxiang 已提交
188
  virtual bool ParseOneInstanceFromPipe(T* instance) = 0;
W
Wang Guibao 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202
  // This function is used to put instance to vec_ins
  virtual void AddInstanceToInsVec(T* vec_ins, const T& instance,
                                   int index) = 0;
  // This function is used to put ins_vec to feed_vec
  virtual void PutToFeedVec(const T& ins_vec) = 0;

  // The thread for read files
  std::thread read_thread_;
  // using ifstream one line and one line parse is faster
  // than using fread one buffer and one buffer parse.
  //   for a 601M real data:
  //     ifstream one line and one line parse: 6034 ms
  //     fread one buffer and one buffer parse: 7097 ms
  std::ifstream file_;
D
dongdaxiang 已提交
203
  std::shared_ptr<FILE> fp_;
W
Wang Guibao 已提交
204
  size_t queue_size_;
205
  string::LineFileReader reader_;
W
Wang Guibao 已提交
206 207 208 209
  // The queue for store parsed data
  std::unique_ptr<paddle::operators::reader::BlockingQueue<T>> queue_;
};

210 211 212 213 214
template <typename T>
class InMemoryDataFeed : public PrivateQueueDataFeed<T> {
 public:
  InMemoryDataFeed();
  virtual ~InMemoryDataFeed() {}
215
  virtual void Init(const paddle::framework::DataFeedDesc& data_feed_desc) = 0;
216 217
  virtual bool Start();
  virtual int Next();
218 219 220 221 222
  virtual void SetMemoryData(void* memory_data);
  virtual void SetMemoryDataMutex(std::mutex* mutex);
  virtual void SetThreadId(int thread_id);
  virtual void SetThreadNum(int thread_num);
  virtual void SetTrainerNum(int trainer_num);
X
xjqbest 已提交
223
  virtual void SetFleetSendBatchSize(int64_t size);
224
  virtual void PutInsToChannel(const std::string& ins_str);
225 226
  virtual void FillMemoryDataToChannel();
  virtual void FillChannelToMemoryData();
227 228
  virtual void LoadIntoMemory();
  virtual void LocalShuffle();
229
  virtual void GlobalShuffle();
230 231
  virtual int64_t GetChannelDataSize();
  virtual void ReleaseChannelData();
X
xujiaqi01 已提交
232

233
 protected:
234
  virtual void AddInstanceToInsVec(T* vec_ins, const T& instance,
X
xujiaqi01 已提交
235
                                   int index) = 0;
236 237 238
  virtual bool ParseOneInstance(T* instance) = 0;
  virtual bool ParseOneInstanceFromPipe(T* instance) = 0;
  virtual void PutToFeedVec(const T& ins_vec) = 0;
239 240 241
  virtual void SerializeIns(const std::vector<T*>& ins, std::string* str) = 0;
  virtual void DeserializeIns(std::vector<T>* ins, const std::string& str) = 0;
  virtual std::pair<int64_t, int64_t> GetMemoryDataInterval();
242

243 244 245
  int thread_id_;
  int thread_num_;
  int trainer_num_;
246
  uint32_t rand_seed;
247 248
  std::vector<T>* memory_data_;
  std::mutex* mutex_for_update_memory_data_;
249 250 251 252 253 254
  // when read ins, we put ins from one channel to the other,
  // and when finish reading, we set cur_channel = 1 - cur_channel,
  // so if cur_channel=0, all data are in shuffled_ins_, else shuffled_ins_out_
  int cur_channel_;
  std::shared_ptr<paddle::framework::BlockingQueue<T>> shuffled_ins_;
  std::shared_ptr<paddle::framework::BlockingQueue<T>> shuffled_ins_out_;
255
  int64_t fleet_send_batch_size_;
256 257 258
  // sleep after send is to slow down sending data, but it's trick,
  // should be removed later.
  int64_t fleet_send_sleep_seconds_;
259 260
};

W
Wang Guibao 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
// This class define the data type of instance(ins_vec) in MultiSlotDataFeed
class MultiSlotType {
 public:
  MultiSlotType() {}
  ~MultiSlotType() {}
  void Init(const std::string& type) {
    CheckType(type);
    if (type_[0] == 'f') {
      float_feasign_.clear();
    } else if (type_[0] == 'u') {
      uint64_feasign_.clear();
    }
    type_ = type;
  }
  void InitOffset() {
    offset_.resize(1);
    // LoDTensor' lod is counted from 0, the size of lod
    // is one size larger than the size of data.
    offset_[0] = 0;
  }
  const std::vector<size_t>& GetOffset() const { return offset_; }
282
  std::vector<size_t>& MutableOffset() { return offset_; }
W
Wang Guibao 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  void AddValue(const float v) {
    CheckFloat();
    float_feasign_.push_back(v);
  }
  void AddValue(const uint64_t v) {
    CheckUint64();
    uint64_feasign_.push_back(v);
  }
  void AddIns(const MultiSlotType& ins) {
    if (ins.GetType()[0] == 'f') {  // float
      CheckFloat();
      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
      CheckUint64();
      auto& vec = ins.GetUint64Data();
      offset_.push_back(offset_.back() + vec.size());
      uint64_feasign_.insert(uint64_feasign_.end(), vec.begin(), vec.end());
    }
  }
  const std::vector<float>& GetFloatData() const { return float_feasign_; }
305
  std::vector<float>& MutableFloatData() { return float_feasign_; }
W
Wang Guibao 已提交
306
  const std::vector<uint64_t>& GetUint64Data() const { return uint64_feasign_; }
307
  std::vector<uint64_t>& MutableUint64Data() { return uint64_feasign_; }
W
Wang Guibao 已提交
308
  const std::string& GetType() const { return type_; }
309
  std::string& MutableType() { return type_; }
W
Wang Guibao 已提交
310

X
xujiaqi01 已提交
311 312
  std::string DebugString() {
    std::stringstream ss;
313 314
    ss << "\ntype: " << type_ << "\n";
    ss << "offset: ";
X
xujiaqi01 已提交
315 316 317 318
    ss << "[";
    for (const size_t& i : offset_) {
      ss << offset_[i] << ",";
    }
319
    ss << "]\ndata: [";
X
xujiaqi01 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332
    if (type_[0] == 'f') {
      for (const float& i : float_feasign_) {
        ss << i << ",";
      }
    } else {
      for (const uint64_t& i : uint64_feasign_) {
        ss << i << ",";
      }
    }
    ss << "]\n";
    return ss.str();
  }

W
Wang Guibao 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
 private:
  void CheckType(const std::string& type) const {
    PADDLE_ENFORCE((type == "uint64") || (type == "float"),
                   "There is no this type<%s>.", type);
  }
  void CheckFloat() const {
    PADDLE_ENFORCE(type_[0] == 'f', "Add %s value to float slot.", type_);
  }
  void CheckUint64() const {
    PADDLE_ENFORCE(type_[0] == 'u', "Add %s value to uint64 slot.", type_);
  }
  std::vector<float> float_feasign_;
  std::vector<uint64_t> uint64_feasign_;
  std::string type_;
  std::vector<size_t> offset_;
};

// This DataFeed is used to feed multi-slot type data.
// The format of multi-slot type data:
//   [n feasign_0 feasign_1 ... feasign_n]*
class MultiSlotDataFeed
    : public PrivateQueueDataFeed<std::vector<MultiSlotType>> {
 public:
  MultiSlotDataFeed() {}
  virtual ~MultiSlotDataFeed() {}
  virtual void Init(const paddle::framework::DataFeedDesc& data_feed_desc);
  virtual bool CheckFile(const char* filename);
D
dongdaxiang 已提交
360
  // virtual void ReadThread();
W
Wang Guibao 已提交
361 362

 protected:
D
dongdaxiang 已提交
363
  virtual void ReadThread();
W
Wang Guibao 已提交
364 365 366 367
  virtual void AddInstanceToInsVec(std::vector<MultiSlotType>* vec_ins,
                                   const std::vector<MultiSlotType>& instance,
                                   int index);
  virtual bool ParseOneInstance(std::vector<MultiSlotType>* instance);
D
dongdaxiang 已提交
368
  virtual bool ParseOneInstanceFromPipe(std::vector<MultiSlotType>* instance);
W
Wang Guibao 已提交
369 370
  virtual void PutToFeedVec(const std::vector<MultiSlotType>& ins_vec);
};
371 372 373 374 375 376 377

class MultiSlotInMemoryDataFeed
    : public InMemoryDataFeed<std::vector<MultiSlotType>> {
 public:
  MultiSlotInMemoryDataFeed() {}
  virtual ~MultiSlotInMemoryDataFeed() {}
  virtual void Init(const paddle::framework::DataFeedDesc& data_feed_desc);
378

379 380 381 382 383 384 385
 protected:
  virtual void AddInstanceToInsVec(std::vector<MultiSlotType>* vec_ins,
                                   const std::vector<MultiSlotType>& instance,
                                   int index);
  virtual bool ParseOneInstance(std::vector<MultiSlotType>* instance);
  virtual bool ParseOneInstanceFromPipe(std::vector<MultiSlotType>* instance);
  virtual void PutToFeedVec(const std::vector<MultiSlotType>& ins_vec);
386
  virtual void SerializeIns(const std::vector<std::vector<MultiSlotType>*>& ins,
X
xujiaqi01 已提交
387
                            std::string* str);
388
  virtual void DeserializeIns(std::vector<std::vector<MultiSlotType>>* ins,
X
xujiaqi01 已提交
389
                              const std::string& str);
390 391
};

W
Wang Guibao 已提交
392 393
}  // namespace framework
}  // namespace paddle