DataProvider.h 13.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

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 <stdint.h>
#include <stdio.h>
Y
Yu Yang 已提交
19 20 21 22 23 24 25
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <mutex>
#include <vector>
Z
zhangjinchao01 已提交
26

Y
Yu Yang 已提交
27 28 29 30 31 32
#include "DataConfig.pb.h"
#include "paddle/math/Matrix.h"
#include "paddle/math/SparseMatrix.h"
#include "paddle/math/Vector.h"
#include "paddle/parameter/Argument.h"
#include "paddle/utils/ClassRegistrar.h"
L
liaogang 已提交
33
#include "paddle/utils/Common.h"
Y
Yu Yang 已提交
34
#include "paddle/utils/Locks.h"
Z
zhangjinchao01 已提交
35 36 37 38 39 40 41
#include "paddle/utils/Logging.h"
#include "paddle/utils/Queue.h"
#include "paddle/utils/ThreadLocal.h"
#include "paddle/utils/Util.h"

namespace paddle {
/**
Q
qijun 已提交
42
 * @def REGISTER_DATA_PROVIDER
43 44
 * @brief Macro for registering a data provider. The class type should contain
 *        a consturctor with parameter (DataConfig, bool).
Z
zhangjinchao01 已提交
45
 */
46 47 48 49 50 51 52 53 54
#define REGISTER_DATA_PROVIDER(__type_name, __class_name)                \
  static InitFunction __reg_type_##__type_name([]() {                    \
    DataProvider::registrar_.registerClass(                              \
        #__type_name,                                                    \
        [](DataConfig conf, ModelConfig, bool useGpu) -> DataProvider* { \
          DataProvider* dp = new __class_name(conf, useGpu);             \
          return dp;                                                     \
        });                                                              \
  })
55 56 57 58 59 60 61 62

/**
 * @def REGISTER_DATA_PROVIDER_EX
 * @brief Macro for registering a data provider, which contains a constructor
 *        with parameter (DataConfig, ModelConfig, bool).
 */
#define REGISTER_DATA_PROVIDER_EX(__type_name, __class_name)            \
  static InitFunction __reg_type_##__type_name([] {                     \
63 64
    DataProvider::registrar_.registerClass<__class_name>(#__type_name); \
  })
Z
zhangjinchao01 已提交
65 66 67 68 69

class DataBatch;
class BufferBatch;
typedef std::shared_ptr<DataBatch> DataBatchPtr;
typedef std::shared_ptr<BufferBatch> BufferBatchPtr;
Q
qijun 已提交
70 71 72
/**
 * @brief Data for batch training a neural network
 */
Z
zhangjinchao01 已提交
73
class DataBatch {
W
Wu Yi 已提交
74
 public:
Z
zhangjinchao01 已提交
75
  DataBatch() : size_(0) { data_.clear(); }
Q
qijun 已提交
76 77 78 79
  /**
   * @brief Get batch size
   * @return batch size
   */
Z
zhangjinchao01 已提交
80
  int64_t getSize() const { return size_; }
Q
qijun 已提交
81 82 83 84
  /**
   * @brief Get num of sequences of sequence data
   * @return num of sequences
   */
Z
zhangjinchao01 已提交
85 86 87 88 89 90
  int64_t getNumSequences() const {
    if (data_.empty()) return size_;
    return data_[0].sequenceStartPositions
               ? data_[0].sequenceStartPositions->getSize() - 1
               : size_;
  }
Q
qijun 已提交
91 92 93 94
  /**
   * @brief Set batch size
   * @param[in] size size
   */
Z
zhangjinchao01 已提交
95
  void setSize(int64_t size) { size_ = size; }
Q
qijun 已提交
96 97 98 99 100 101
  /**
   * @brief Get size of argument vector
   * @return size of argument vector
   * @note For usual supervised learning, input data and label is needed,
   * then there will be two argument.
   */
Z
zhangjinchao01 已提交
102 103
  int64_t getNumStreams() const { return data_.size(); }

Q
qijun 已提交
104 105 106 107 108
  /**
   * @brief Get a argument with index i
   * @param[in] i index in argument vector
   * @return a argument with index i
   */
Z
zhangjinchao01 已提交
109
  const Argument& getStream(int i) const { return data_[i]; }
Q
qijun 已提交
110 111 112 113
  /**
   * @brief Get all argument
   * @return an argument vector
   */
Z
zhangjinchao01 已提交
114
  std::vector<Argument>& getStreams() { return data_; }
Q
qijun 已提交
115 116 117 118
  /**
   * @brief Get all argument const
   * @return an argument vector
   */
Z
zhangjinchao01 已提交
119
  std::vector<Argument> getStreams() const { return data_; }
Q
qijun 已提交
120 121 122
  /**
   * @brief Clear DataBatch
   */
Z
zhangjinchao01 已提交
123 124 125 126 127 128
  void clear() {
    data_.clear();
    size_ = 0;
  }

  /**
Q
qijun 已提交
129 130 131
   * @brief Append data to DataBatch
   * @param[in] data  matrix data
   * @note The order in which each data stream is appended must match the order
Z
zhangjinchao01 已提交
132 133 134 135 136 137 138 139 140 141
   * specified in stream_names of DataConfig. The stream_names can be obtained
   * using DataProvider::getStreamNames().
   */
  void appendData(MatrixPtr data) {
    Argument argu;
    argu.value = data;
    data_.push_back(argu);
  }

  /**
Q
qijun 已提交
142 143 144 145
   * @brief Append sequence data to DataBatch
   * @param[in] data                      matrix data
   * @param[in] sequenceStartPositions    sequence data
   * @note The order in which each data stream is appended must match the order
Z
zhangjinchao01 已提交
146 147 148 149 150 151 152 153 154 155
   * specified in stream_names of DataConfig. The stream_names can be obtained
   * using DataProvider::getStreamNames().
   */
  void appendData(const MatrixPtr& data,
                  const ICpuGpuVectorPtr& sequenceStartPositions) {
    Argument argu;
    argu.value = data;
    argu.sequenceStartPositions = sequenceStartPositions;
    data_.push_back(argu);
  }
Q
qijun 已提交
156 157 158 159 160
  /**
   * @brief Append label data
   * @param[in]  label    label data
   * @param[in]  value    matrix data, default null
   */
Z
zhangjinchao01 已提交
161 162 163 164 165 166 167
  void appendLabel(IVectorPtr label, MatrixPtr value = nullptr) {
    Argument argu;
    argu.ids = label;
    argu.value = value;
    data_.push_back(argu);
  }

Q
qijun 已提交
168 169 170 171 172
  /*
   * @brief Append argument
   * @param[in]  argus   DataBatch.getStreams()
   * @param[in]  size    DataBatch.getSize()
   * @param[in]  dataId  sub dataprovider id (in MultiDataProvider)
Z
zhangjinchao01 已提交
173
   */
174 175
  void appendArguments(const std::vector<Argument>& argus,
                       int size,
Z
zhangjinchao01 已提交
176 177 178 179 180 181 182 183
                       int dataId) {
    size_ += size;
    for (const auto& argu : argus) {
      data_.push_back(argu);
      data_.back().dataId = dataId;
    }
  }

W
Wu Yi 已提交
184
 protected:
Q
qijun 已提交
185 186 187
  /**
   * @brief batch size
   */
Z
zhangjinchao01 已提交
188
  int64_t size_;
Q
qijun 已提交
189 190 191 192
  /**
   * @brief A batch data consist of a Argument vector,
   * An argument corresponds to a type of input data.
   */
Z
zhangjinchao01 已提交
193 194 195 196
  std::vector<Argument> data_;
};

class BufferBatch {
W
Wu Yi 已提交
197
 public:
Z
zhangjinchao01 已提交
198 199 200 201 202 203 204 205 206 207
  BufferBatch() {
    hlStream_ = HPPL_STREAM_DEFAULT;
    hlEvent_ = NULL;
    batchData_ = NULL;
  }
  ~BufferBatch() {
    if (hlEvent_) {
      hl_destroy_event(hlEvent_);
      hlEvent_ = NULL;
    }
H
hedaoyuan 已提交
208 209
    delete batchData_;
    batchData_ = NULL;
Z
zhangjinchao01 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  }

  void setDataBatch(DataBatch* batchData) { batchData_ = batchData; }
  DataBatch* getDataBatch() { return batchData_; }

  void setCuStream(hl_stream_t stream) { hlStream_ = stream; }
  hl_stream_t getCuStream() const { return hlStream_; }

  void setCuEvent(hl_event_t event) { hlEvent_ = event; }

  hl_event_t getCuEvent() const { return hlEvent_; }

  void createCuEvent() {
    if (!hlEvent_) {
      hlStream_ = HPPL_STREAM_1;
      hl_create_event(&hlEvent_);
    }
  }

  void syncEvent() {
    if (hlEvent_) {
      hl_stream_wait_event(hlStream_, hlEvent_);
    }
  }

  void swap(BufferBatch* bufBatch);
  void clone(DataBatch* srcBatch, bool useGpu);

W
Wu Yi 已提交
238
 protected:
Z
zhangjinchao01 已提交
239 240 241 242 243 244 245 246 247 248 249
  DataBatch* batchData_;
  hl_stream_t hlStream_;
  hl_event_t hlEvent_;
};

class DataProvider;
typedef std::shared_ptr<DataProvider> DataProviderPtr;

typedef Queue<BufferBatch*> BufferBatchQueue;

class DoubleBuffer {
W
Wu Yi 已提交
250
 public:
251
  DoubleBuffer(DataProvider* dataPool, bool useGpu, int64_t batchSize = 0);
Z
zhangjinchao01 已提交
252 253 254 255 256 257 258 259 260 261 262
  virtual ~DoubleBuffer();
  void removeOneBatch(DataBatch* dataBatch);

  void setBatchSize(int64_t newBatchSize) { batchSize_ = newBatchSize; }

  int64_t getBatchSize() { return batchSize_; }

  void startAsyncLoad();
  void finishAsyncLoad() {
    stopping_ = true;
    taskReadySem_.post();
X
xuwei06 已提交
263 264 265
    if (asyncLoader_) {
      asyncLoader_->join();
    }
Z
zhangjinchao01 已提交
266 267 268 269
  }

  void setPending(bool pending) { pending_ = pending; }

W
Wu Yi 已提交
270
 protected:
Z
zhangjinchao01 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  virtual void asyncLoadBatch();
  void insertOneBatch(DataBatch* batch);

  DataProvider* dataPool_;
  bool useGpu_;
  int32_t batchSize_;
  ThreadLocal<BufferBatchPtr> usingBatch_;
  BufferBatchQueue* dataQueue_;
  BufferBatchQueue* bufferQueue_;
  std::unique_ptr<std::thread> asyncLoader_;
  Semaphore taskReadySem_;
  bool stopping_;
  bool pending_;
};

/**
Q
qijun 已提交
287 288
 * @brief Base class for DataProvider, which supplies data for training
 * @note It can supplies multiple streams of data.
Z
zhangjinchao01 已提交
289 290 291 292
 * For typical supervised training, there are two streams:
 * one is for input, one is for label.
 */
class DataProvider {
W
Wu Yi 已提交
293
 public:
294
  static ClassRegistrar<DataProvider, DataConfig, ModelConfig, bool> registrar_;
Z
zhangjinchao01 已提交
295
  static DataProvider* create(const DataConfig& config,
296
                              const ModelConfig& modelConfig,
Z
zhangjinchao01 已提交
297 298
                              bool useGpu = FLAGS_use_gpu);

299 300 301
  /**
   * @brief create only used for unittest.
   */
302
  inline static DataProvider* create(const DataConfig& config,
Y
Yu Yang 已提交
303
                                     bool useGpu = FLAGS_use_gpu) {
304 305 306
    return create(config, ModelConfig(), useGpu);
  }

Z
zhangjinchao01 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320
  DataProvider(const DataConfig& config, bool useGpu)
      : config_(config),
        skipShuffle_(false),
        usageRatio_(config.usage_ratio()),
        useGpu_(useGpu) {
    if (config_.async_load_data()) {
      initAsyncLoader();
    }
  }
  virtual ~DataProvider() {}

  const DataConfig& getConfig() const { return config_; }

  void setSkipShuffle() { skipShuffle_ = true; }
Q
qijun 已提交
321 322 323 324 325 326 327

  /**
   * @brief Get next batch of training samples
   * @param[in]    size    size of training samples to get
   * @param[out]   batch   a batch of training samples
   * @return actual size of obtained training samples
   */
Z
zhangjinchao01 已提交
328 329 330
  int64_t getNextBatch(int64_t size, DataBatch* batch);

  /**
Q
qijun 已提交
331
   * @brief Shuffle the data set
Z
zhangjinchao01 已提交
332 333 334 335
   */
  virtual void shuffle() = 0;

  /**
Q
qijun 已提交
336 337
   * @brief reset all the value of index
   * @note reset() must be called before any calls to getNextBatch()
Z
zhangjinchao01 已提交
338 339 340 341 342 343 344 345 346 347
   * IMPORTANT: subclass reset() should always call the base class reset()
   * at the end of the function
   */
  virtual void reset() {
    if (doubleBuffer_ != nullptr) {
      doubleBuffer_->startAsyncLoad();
    }
  }

  /**
Q
qijun 已提交
348 349 350
   * @brief Get the size of training samples
   * @return the number of training samples in the data set.
   * @note return -1 to indicate unlimited number of samples.
Z
zhangjinchao01 已提交
351 352
   */
  virtual int64_t getSize() = 0;
353

Q
qijun 已提交
354 355 356 357 358 359
  /**
   * @brief Get next batch training samples internally
   * @param[in]    size      size of training samples to get
   * @param[out]   batch     a batch of training samples
   * @return actual size of obtained training samples
   */
Z
zhangjinchao01 已提交
360 361
  virtual int64_t getNextBatchInternal(int64_t size, DataBatch* batch) = 0;

W
Wu Yi 已提交
362
 protected:
Z
zhangjinchao01 已提交
363 364 365 366 367 368
  DataConfig config_;
  bool skipShuffle_;
  float usageRatio_;
  bool useGpu_;
  std::unique_ptr<DoubleBuffer> doubleBuffer_;
  ThreadLocal<std::vector<MatrixPtr>> constantSlots_;
Q
qijun 已提交
369 370 371 372 373 374
  /**
   * @@brief Get next batch training samples from buffer
   * @param[in]    size      size of training samples to get
   * @param[out]   batch     a batch of training samples
   * @return actual size of obtained training samples
   */
Z
zhangjinchao01 已提交
375 376 377 378 379 380 381 382 383 384
  int64_t getNextBatchFromBuffer(int64_t size, DataBatch* batch);

  void initAsyncLoader();
};

/**
 * A data provider which does nothing. It only serves as providing
 * necessary configurations such as stream_names
 */
class DummyDataProvider : public DataProvider {
W
Wu Yi 已提交
385
 public:
Z
zhangjinchao01 已提交
386 387 388 389 390 391 392 393 394 395 396 397
  DummyDataProvider(const DataConfig& config, bool useGpu)
      : DataProvider(config, useGpu) {}
  virtual void shuffle() {}
  virtual void reset() { DataProvider::reset(); }
  virtual int64_t getSize() { return 0; }
  virtual int64_t getNextBatchInternal(int64_t size, DataBatch* batch) {
    (void)size;
    (void)batch;
    return 0;
  }
};

398 399 400
/**
 * Data provider for one input and one integer label.
 */
Z
zhangjinchao01 已提交
401
class SimpleDataProviderBase : public DataProvider {
W
Wu Yi 已提交
402
 protected:
403 404 405 406
  /// sample feature dimension
  int64_t sampleDim_;
  /// the number of samples
  int64_t bufferCapacity_;
Z
zhangjinchao01 已提交
407
  int64_t sampleNumInBuf_;
408 409 410 411
  /// next item to read in buffer
  int64_t nextItemIndex_;
  /// some user defined info for validation
  bool withInfo_;
Z
zhangjinchao01 已提交
412

413
  /// data buffer: bufferCapacity_ * nDataDim_
Z
zhangjinchao01 已提交
414 415
  CpuMatrixPtr hInputDataBuf_;

416
  /// label buffer:bufferCapacity_ * 1
Z
zhangjinchao01 已提交
417 418
  CpuIVectorPtr hInputLabelBuf_;

419
  /// info buffer:bufferCapacity_ * 1
Z
zhangjinchao01 已提交
420 421 422 423 424 425 426 427
  CpuIVectorPtr hInputInfoBuf_;

  ThreadLocal<MatrixPtr> dataBatch_;
  ThreadLocal<IVectorPtr> labelBatch_;
  ThreadLocal<IVectorPtr> infoBatch_;

  RWLock lock_;

W
Wu Yi 已提交
428
 public:
Z
zhangjinchao01 已提交
429 430 431 432 433 434 435 436 437 438 439
  SimpleDataProviderBase(const DataConfig& config, bool useGpu, bool withInfo);
  ~SimpleDataProviderBase() {}

  void shuffle();

  virtual void reset();

  virtual int64_t getSize();

  virtual int64_t getNextBatchInternal(int64_t size, DataBatch* batch);

440
  /// return the number of samples in the buffer
Z
zhangjinchao01 已提交
441 442
  int64_t fillBuffer();

W
Wu Yi 已提交
443
 protected:
Z
zhangjinchao01 已提交
444 445 446 447 448 449 450 451 452 453
  /**
   * @brief Fill at most size samples into data and label.
   *
   * Each input is stored in contiguous memory locations in data.
   *
   * data[n * sampleDim_] .. data[n * sampleDim_ + sampleDim_ - 1] is for
   * the input of the n-th sample.
   *
   * label[n] is the label for the n-th sample.
   */
454 455 456
  virtual int64_t fillBufferImp(real* data,
                                int* label,
                                int* info,
Z
zhangjinchao01 已提交
457 458 459 460
                                int64_t size) = 0;
};

class SimpleDataProvider : public SimpleDataProviderBase {
W
Wu Yi 已提交
461
 public:
Z
zhangjinchao01 已提交
462 463 464 465
  SimpleDataProvider(const DataConfig& config, bool useGpu);
  ~SimpleDataProvider();
  virtual void reset();

W
Wu Yi 已提交
466
 protected:
Z
zhangjinchao01 已提交
467 468
  void loadData(const std::string& fileName);
  void loadDataFile(const std::string& fileName);
469 470 471
  virtual int64_t fillBufferImp(real* data,
                                int* label,
                                int* info,
Z
zhangjinchao01 已提交
472 473
                                int64_t size);

W
Wu Yi 已提交
474
 protected:
Z
zhangjinchao01 已提交
475 476 477 478 479 480
  size_t currentSampleIndex_;
  std::vector<int> labels_;
  std::vector<real> data_;
};

}  // namespace paddle