PyDataProvider2.cpp 28.5 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

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_NO_PYTHON

17
#include <Python.h>
Y
Yu Yang 已提交
18
#include <numpy/numpyconfig.h>
Z
zhangjinchao01 已提交
19 20 21
#include <stdio.h>
#include <stdlib.h>
#include <list>
Y
Yu Yang 已提交
22
#include <unordered_set>
23 24
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
Z
zhangjinchao01 已提交
25 26

#include "DataProvider.h"
27 28

#include "paddle/utils/Locks.h"
Y
Yu Yang 已提交
29
#include "paddle/utils/PythonUtil.h"
30
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
31 32 33

namespace paddle {

34 35 36
namespace unittest {

static std::unique_ptr<std::function<void(size_t /*poolActualSize */)>>
37
    OnPoolFilled;
38 39 40 41 42 43 44 45

namespace pydp2 {

void setOnPoolFilledHook(const std::function<void(size_t)>& callback) {
  OnPoolFilled.reset(new std::function<void(size_t)>());
  *OnPoolFilled = callback;
}

46
void clearOnPoolFilledHook() { OnPoolFilled.reset(); }
47 48 49 50

}  // namespace pydp2
}  // namespace unittest

Z
zhangjinchao01 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
/**
 * Slot type
 */
enum SlotType {
  ST_DENSE = 0,
  ST_NON_SPARSE_VALUE = 1,
  ST_SPARSE_VALUE = 2,
  ST_INDEX = 3
};

/**
 * Sequence type
 */
64
enum SeqType { SQT_NONE = 0, SQT_SEQ, SQT_SUBSEQ };
Z
zhangjinchao01 已提交
65 66 67 68 69

/**
 * Cache Type.
 */
enum CacheType {
70
  NO_CACHE = 0,           // Each pass will load data from PyDataProvider2.
Z
zhangjinchao01 已提交
71 72 73 74 75 76 77 78 79 80 81
  CACHE_PASS_IN_MEM = 1,  // First pass will load data from PyDataProvider2,
                          // then cache all data in memory. Load data from
                          // memory in rest passes.
};

struct SlotHeader {  // Slot Header will parse from python object's slots field.
  size_t dim;
  SlotType slotType;
  SeqType seqType;
};

82 83
inline std::ostream& operator<<(std::ostream& os, const SlotHeader& header) {
  os << "Dim = " << header.dim << " Type = " << header.slotType
Z
zhangjinchao01 已提交
84 85 86 87 88 89 90 91 92 93 94 95
     << " SeqType = " << header.seqType;
  return os;
}

/**
 * FieldScanner Interface.
 *
 * It will read python object, and fill to argument's each slot.
 * There are two steps, prepare and fill. Scanner will alloc memory during
 * prepare step, fill data into argument during fill step.
 */
class IFieldScanner {
W
Wu Yi 已提交
96
 public:
Z
zhangjinchao01 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  DISABLE_COPY(IFieldScanner);
  /**
   * Ctor.
   * @param headerPtr slot header that scanner belong to.
   */
  explicit IFieldScanner(SlotHeader* headerPtr) : headerPtr_(headerPtr) {}
  virtual ~IFieldScanner() {}

  /**
   * Start prepare step.
   */
  virtual void startPrepare(Argument& argument) {}

  /**
   * Prepare step.
   *
   * @note the obj could be a timestep of sample or whole sample. It depends
   * what scanner it is.
   */
  virtual void prepare(Argument& argument, PyObject* obj) {}

  /**
   * Finish Prepare step.
   */
  virtual void finishPrepare(Argument& argument) {}

  /**
   * Start fill step.
   */
  virtual void startFill(Argument& argument) {}

  /**
   * Fill step.
   *
   * @note the obj could be a timestep of sample or whole sample. It depends
   * what scanner it is.
   */
  virtual void fill(Argument& argument, PyObject* obj) {}

  /**
   * Finish fill step.
   */
  virtual void finishFill(Argument& argument) {}

  /**
   * Factory method. Create a scanner by header. The final scanner may be
   * combine many scanners.
   *
   * @note Fatal if header is not support.
   */
  static IFieldScanner* create(SlotHeader* header);

W
Wu Yi 已提交
149
 protected:
Z
zhangjinchao01 已提交
150 151 152 153 154 155 156
  SlotHeader* headerPtr_;
};

/**
 * Py Data Provider Cache Interface.
 */
class IPyDataProviderCache {
W
Wu Yi 已提交
157
 public:
Z
zhangjinchao01 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  virtual ~IPyDataProviderCache() {}

  /**
   * invoke when DataProvider::reset()
   * @return true if read data from python.
   */
  virtual bool reset() = 0;

  /**
   * invoke when these data are used by DataProvider, and need to clear.
   * @param [inout] data used data.
   *
   * @note The implemented class must clear these data array. Or if you want to
   * delete the PyObjectPtr later, you should make sure the paddle process only
   * have one active thread calling python code (use PyGuard otherwise).
   */
  virtual void drop(std::deque<PyObjectPtr>* data) = 0;

  /**
   * Return whole data in cache.
   */
  virtual std::deque<PyObjectPtr>* load() = 0;

  /**
   * Factory method. Convert CacheType to IPyDataProviderCache*
   */
  static IPyDataProviderCache* create(CacheType ct);
};

/**
 * PyDataProvider2.
 *
 * For usage, please refer python module 'paddle.trainer.PyDataProvider2'
 *
 * Here, we start a thread to read data. It is totally asynchronous for reading
 * data. And it support cache strategies.
 */
class PyDataProvider2 : public DataProvider {
W
Wu Yi 已提交
196
 public:
Z
zhangjinchao01 已提交
197 198 199 200
  /**
   * Ctor
   */
  PyDataProvider2(const DataConfig& config,
201
                  const ModelConfig& modelConfig,
Z
zhangjinchao01 已提交
202
                  bool useGpu)
203 204
      : DataProvider(config, useGpu), callingContextCreated_(2) {
    if (PyArray_API == NULL) import_array();
Z
zhangjinchao01 已提交
205 206 207 208
    auto& args = config.load_data_args();
    PyObjectPtr kwargs = PyObjectPtr(PyDict_New());
    if (!args.empty()) {
      kwargs = callPythonFuncRetPyObj(
209
          "paddle.trainer.PyDataProvider2", "deserialize_args", {args});
Z
zhangjinchao01 已提交
210 211 212 213
    }

    py::DictHelper kwargsDict(kwargs);
    kwargsDict.setBool("is_train", !config.for_test());
214 215 216 217 218 219
    std::vector<std::string> inputs;
    inputs.reserve(modelConfig.input_layer_names().size());
    std::copy(modelConfig.input_layer_names().begin(),
              modelConfig.input_layer_names().end(),
              std::back_inserter(inputs));
    kwargsDict.setStringList("input_order", inputs);
Z
zhangjinchao01 已提交
220 221 222 223 224 225 226

    // kwargs is keyword arguemts to create object.
    this->createPyDataObj(config.load_data_module(),
                          config.load_data_object(),
                          config.files(),
                          std::move(kwargs));
    DBG << "Instance " << instance_.get() << " loaded.";
227
    this->readPyFields(config.for_test());
Z
zhangjinchao01 已提交
228 229 230 231 232 233 234
    DBG << "Py Field Done";
  }

  /**
   * Dtor
   * @note will stop loading thread when destructing
   */
235
  virtual ~PyDataProvider2() { resetImpl(false); }
Z
zhangjinchao01 已提交
236

W
Wu Yi 已提交
237
 private:
Z
zhangjinchao01 已提交
238 239 240
  void createPyDataObj(const std::string& model,
                       const std::string& className,
                       const std::string& fileListName,
241 242 243
                       PyObjectPtr&& kwargs  // NOLINT
                       ) {
    LOG(INFO) << "loading dataprovider " << model << "::" << className;
Z
zhangjinchao01 已提交
244

245
    PyObjectPtr module = py::import(model);
Z
zhangjinchao01 已提交
246 247
    PyObjectPtr moduleDict(PyModule_GetDict(module.get()));
    CHECK_PY(moduleDict) << "Invoke module.__dict__ error";
248
    PyObjectPtr cls(PyDict_GetItemString(moduleDict.get(), className.c_str()));
Z
zhangjinchao01 已提交
249 250 251 252 253 254
    CHECK_PY(cls) << "load class " << className.c_str() << "error";

    // If there are multiple python instance share same module, the PyObjectPtr
    // only for instance will make python reference-count error.
    //
    // So here, we increase reference count manually.
Y
Yu Yang 已提交
255 256 257
    Py_XINCREF(module.get());
    Py_XINCREF(moduleDict.get());
    Py_XINCREF(cls.get());
Z
zhangjinchao01 已提交
258 259 260 261 262 263 264 265 266 267

    PyObjectPtr fileListInPy = loadPyFileLists(fileListName);
    PyDict_SetItemString(kwargs.get(), "file_list", fileListInPy.get());
    {
      PyGuard guard;
      instance_.reset(PyObject_Call(cls.get(), zeroTuple_.get(), kwargs.get()));
    }
    CHECK_PY(instance_) << "Cannot Create instance";
  }

268
  void readPyFields(bool testing) {
Z
zhangjinchao01 已提交
269 270
    py::ObjectHelper self(this->instance_);
    bool ok;
271

272 273
    this->skipShuffle_ =
        !self.getBoolAttr("should_shuffle", &ok /*isBoolType*/);
274 275 276 277 278 279
    if (!ok) {
      this->skipShuffle_ = testing;  // shuffle when is training, skip shuffle
                                     // when is testing.
    }
    DBG << "Provider Skip Shuffle " << this->skipShuffle_;

Z
zhangjinchao01 已提交
280 281 282 283
    this->poolSize_ = self.getIntAttr<size_t>("pool_size", &ok);
    if (!ok) {
      this->poolSize_ = -1UL;
    }
284 285 286 287 288 289
    this->minPoolSize_ = self.getIntAttr<size_t>("min_pool_size", &ok);
    if (!ok) {
      this->minPoolSize_ = -1UL;
    }
    this->minPoolSize_ = std::min(this->poolSize_, this->minPoolSize_);

Z
zhangjinchao01 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    this->canOverBatchSize_ = self.getBoolAttr("can_over_batch_size");

    calcBatchSize_.reset(self.getAttr("calc_batch_size"));
    if (this->calcBatchSize_ && !py::isCallable(this->calcBatchSize_)) {
      this->calcBatchSize_.reset();
    }

    generator_.reset(self.getAttr("generator"));
    CHECK(py::isCallable(generator_));

    // Reading slots.
    PyObjectPtr slotsPtr(self.getAttr("slots"));
    py::SequenceHelper slots(slotsPtr);
    headers_.reserve(slots.size());
    for (size_t i = 0; i < slots.size(); ++i) {
      headers_.emplace_back();
      auto& header = headers_.back();
      PyObject* hdPtr = slots[i];
      CHECK(hdPtr != nullptr);
      Py_XINCREF(hdPtr);
      PyObjectPtr headerPtrWrap(hdPtr);
      py::ObjectHelper hd(headerPtrWrap);
      header.dim = hd.getIntAttrWithError<size_t>("dim");
313 314
      header.seqType = (SeqType)hd.getIntAttrWithError<int>("seq_type");
      header.slotType = (SlotType)hd.getIntAttrWithError<int>("type");
Z
zhangjinchao01 已提交
315 316 317
    }

    DBG << "Data header size " << headers_.size();
318
    for (auto& header : headers_) {
Z
zhangjinchao01 已提交
319 320 321 322 323 324 325 326 327 328
      DBG << header;
    }
    cache_.reset(IPyDataProviderCache::create(
        (CacheType)self.getIntAttrWithError<int>("cache")));
  }

  PyObjectPtr loadPyFileLists(const std::string& fileListName) {
    loadFileList(fileListName, fileLists_);
    PyObject* lst = PyList_New(fileLists_.size());
    for (size_t i = 0; i < fileLists_.size(); ++i) {
329
      PyList_SET_ITEM(lst, i, PyString_FromString(fileLists_[i].c_str()));
Z
zhangjinchao01 已提交
330 331 332 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
    }
    return PyObjectPtr(lst);
  }

  void loadThread() {
    DBG << "Creating context";
    for (auto& filename : fileLists_) {
      PyGuard g;
      py::CallableHelper generator(this->generator_);
      generator.setArgsSize(2);
      generator.getArgs().set(0, instance_);
      generator.getArgs().set(1, PyString_FromString(filename.c_str()), true);
      callingContexts_.emplace_back(generator());
      CHECK_PY(callingContexts_.back()) << "Generator error.";
      CHECK(PyIter_Check(callingContexts_.back()));
    }
    DBG << "Create context done";
    callingContextCreated_.wait();

    PositionRandom p(skipShuffle_);

    while (!exit_ && !callingContexts_.empty()) {
      PyObject* data = nullptr;

      {  // Read data.
        size_t cid = p(callingContexts_.size());
        bool atEnd;
        data = py::iterNext(callingContexts_[cid], &atEnd);
        if (atEnd || data == nullptr) {
359 360 361 362
          if (cid != 0) {
            std::swap(callingContexts_[cid], callingContexts_[0]);
            cid = 0;
          }
363 364 365 366 367 368

          PyObjectPtr front;
          {
            std::unique_lock<std::mutex> l(mtx_);
            front = pop_get_front(callingContexts_);
          }
369 370
          {
            PyGuard g;
371
            front.reset();
372
          }
Z
zhangjinchao01 已提交
373 374 375 376 377 378 379
          this->pullCV_.notify_all();
          continue;
        }
      }

      size_t additionalBatchSize = 1;
      if (calcBatchSize_) {
380
        PyGuard guard;
Z
zhangjinchao01 已提交
381 382 383 384 385 386 387 388 389 390
        py::CallableHelper calcBatchSize(this->calcBatchSize_);
        calcBatchSize.setArgsSize(1);
        calcBatchSize.getArgs().set(0, data);
        PyObjectPtr bs(calcBatchSize());
        CHECK_PY(bs);
        bool ok;
        additionalBatchSize = py::castInt<size_t>(bs.get(), &ok);
        CHECK(ok) << "CalcBatchSize must return int or long";
      }

391
      if (this->loadThread_) {  // wait poolActualSize < poolSize;
Z
zhangjinchao01 已提交
392
        std::unique_lock<std::mutex> l(mtx_);
F
fengjiayi 已提交
393
        pushCV_.wait(l, [this] { return this->poolActualSize_ < poolSize_; });
Z
zhangjinchao01 已提交
394 395 396 397 398 399 400
      }

      {
        std::lock_guard<std::mutex> guard(mtx_);
        poolActualSize_ += additionalBatchSize;
        dataPool_.emplace_back(data);
      }
401
      pullCV_.notify_all();
Z
zhangjinchao01 已提交
402 403 404 405 406 407
    }
    DBG << "load thread end";
  }

  inline void resetImpl(bool startNewThread) {
    DBG << "Reseting " << startNewThread;
Y
Yu Yang 已提交
408
    exit_.store(true);
Z
zhangjinchao01 已提交
409 410 411 412 413 414 415
    if (loadThread_) {  // is loading.
      loadThread_->join();
      loadThread_.reset();
    }
    {
      PyGuard g;
      callingContexts_.clear();
Y
Yu Yang 已提交
416 417 418 419 420 421
      this->pullCV_.notify_one();
    }

    std::lock_guard<std::mutex> guard(mutexForReset_);
    {
      PyGuard g;
Z
zhangjinchao01 已提交
422 423 424
      dataPool_.clear();
    }
    poolActualSize_ = 0;
Y
Yu Yang 已提交
425

Z
zhangjinchao01 已提交
426 427 428
    if (startNewThread && cache_->reset()) {
      DBG << "Start new thread.";
      loadThread_.reset(new std::thread([this] {
Y
Yu Yang 已提交
429
        exit_ = false;
Z
zhangjinchao01 已提交
430 431 432 433 434
        loadThread();
      }));
      callingContextCreated_.wait();
    }
    DBG << "Reset done";
Y
Yu Yang 已提交
435
    exit_ = false;
Z
zhangjinchao01 已提交
436 437
  }

W
Wu Yi 已提交
438
 private:
Z
zhangjinchao01 已提交
439 440
  std::unique_ptr<std::thread> loadThread_;
  std::atomic<bool> exit_;
441
  std::deque<PyObjectPtr> callingContexts_;
Z
zhangjinchao01 已提交
442 443 444 445 446
  std::deque<PyObjectPtr> dataPool_;
  size_t poolActualSize_;
  std::condition_variable pushCV_;
  std::condition_variable pullCV_;
  std::mutex mtx_;
447

Y
Yu Yang 已提交
448 449
  std::mutex mutexForReset_;

Z
zhangjinchao01 已提交
450 451 452 453 454
  ThreadBarrier callingContextCreated_;
  std::unique_ptr<IPyDataProviderCache> cache_;

  PyObjectPtr instance_;
  size_t poolSize_;
455
  size_t minPoolSize_;
Z
zhangjinchao01 已提交
456 457 458 459 460 461 462 463
  bool canOverBatchSize_;
  PyObjectPtr calcBatchSize_;
  PyObjectPtr generator_;
  std::vector<std::string> fileLists_;
  std::vector<SlotHeader> headers_;
  static PyObjectPtr zeroTuple_;

  class PositionRandom {
W
Wu Yi 已提交
464
   public:
465 466
    inline explicit PositionRandom(bool skipRand)
        : eng_(ThreadLocalRandomEngine::get()), skipRand_(skipRand) {}
Z
zhangjinchao01 已提交
467

468
    inline size_t operator()(size_t len) {
Z
zhangjinchao01 已提交
469 470 471 472 473 474 475 476 477 478
      if (!skipRand_) {
        if (!dist_ || dist_->b() != len - 1) {
          dist_.reset(new std::uniform_int_distribution<size_t>(0, len - 1));
        }
        return (*dist_)(eng_);
      } else {
        return 0;
      }
    }

W
Wu Yi 已提交
479
   private:
Z
zhangjinchao01 已提交
480 481 482 483 484 485
    std::default_random_engine& eng_;
    std::unique_ptr<std::uniform_int_distribution<size_t>> dist_;
    bool skipRand_;
  };

  // DataProvider interface
W
Wu Yi 已提交
486
 public:
Z
zhangjinchao01 已提交
487 488 489 490 491
  /**
   * Resetting the PyDataProvider. May start reading thread here.
   */
  virtual void reset() {
    resetImpl(true);
492
    DataProvider::reset();
Z
zhangjinchao01 已提交
493 494 495 496 497 498
  }

  /**
   * Shuffle. Do nothing because PyDataProvider do shuffle implicitly by random
   * select data from datapool.
   */
499
  void shuffle() {}
Z
zhangjinchao01 已提交
500 501 502 503

  /**
   * Not limited size.
   */
504
  int64_t getSize() { return -1; }
Z
zhangjinchao01 已提交
505 506 507 508

  /**
   * Loading a batch of data.
   */
509
  int64_t getNextBatchInternal(int64_t size_, DataBatch* batch) {
Y
Yu Yang 已提交
510
    std::lock_guard<std::mutex> guard(mutexForReset_);
511
    REGISTER_TIMER("PyDP2.getNextBatchInternal")
Z
zhangjinchao01 已提交
512
    CHECK_GE(size_, 0);
513
    size_t size = (size_t)size_;
Z
zhangjinchao01 已提交
514 515 516 517
    if (loadThread_) {  // loading from thread should wait for data pool ready.
                        // but, loading from cache, cache object should ensure
                        // data pool ready.
      std::unique_lock<std::mutex> l(mtx_);
Y
Yu Yang 已提交
518 519 520 521
      pullCV_.wait(l, [this, &size] {
        return this->poolActualSize_ >= std::max(size, this->minPoolSize_) ||
               callingContexts_.empty();
      });
522 523 524 525

      if (unittest::OnPoolFilled) {
        (*unittest::OnPoolFilled)(this->poolActualSize_);
      }
Z
zhangjinchao01 已提交
526 527 528 529 530 531 532 533 534 535
    }
    std::deque<PyObjectPtr> data;
    size_t bsize = 0;
    std::deque<PyObjectPtr>* poolPtr = nullptr;

    if (this->loadThread_) {  // loading from thread.
      poolPtr = &this->dataPool_;
    } else {  // loading from cache.
      poolPtr = this->cache_->load();
    }
Y
Yu Yang 已提交
536 537 538 539
    if (exit_) {
      // PyDataProvider is destructing.
      return 0;
    }
Z
zhangjinchao01 已提交
540 541 542 543 544
    CHECK(poolPtr != nullptr);

    std::deque<PyObjectPtr>& pool = *poolPtr;

    while (bsize < size && !pool.empty()) {
545 546
      {
        // move data from pool to data
Z
zhangjinchao01 已提交
547 548 549 550 551 552 553 554 555
        std::lock_guard<std::mutex> guard(mtx_);
        if (skipShuffle_) {
          size_t i = 0;
          CHECK(pool[i] != nullptr);
          data.emplace_back(std::move(pool[i]));
          pool.pop_front();
        } else {  // when shuffle, use swap to drop only last pool element.
          size_t i = ThreadLocalRand::rand() % pool.size();
          CHECK(pool[i] != nullptr);
556 557
          if (i != 0) {
            std::swap(pool[i], pool.front());
Z
zhangjinchao01 已提交
558
          }
559 560
          data.emplace_back(std::move(pool.front()));
          pool.pop_front();
Z
zhangjinchao01 已提交
561
        }
562

Z
zhangjinchao01 已提交
563
        if (calcBatchSize_) {  // custom calc batch size.
564
          PyGuard guard;
Z
zhangjinchao01 已提交
565 566 567 568 569 570
          Py_INCREF(data.back().get());
          py::CallableHelper calcBatchSize(calcBatchSize_);
          calcBatchSize.setArgsSize(1);
          calcBatchSize.getArgs().set(0, data.back());
          PyObjectPtr customBatchSize(calcBatchSize());
          bool ok;
571
          size_t tmp = py::castInt<size_t>(customBatchSize.get(), &ok);
Z
zhangjinchao01 已提交
572
          CHECK(ok) << "calc_batch_size must return int";
573 574 575 576 577 578 579 580 581

          if (bsize + tmp > size && !canOverBatchSize_) {
            // Put data back.
            pool.push_front(std::move(data.back()));
            data.pop_back();
            break;
          } else {
            bsize += tmp;
          }
Z
zhangjinchao01 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        } else {
          bsize += 1;
        }
      }
    }

    if (this->loadThread_) {
      {
        std::lock_guard<std::mutex> g(mtx_);
        poolActualSize_ -= bsize;
      }
      this->pushCV_.notify_all();
    }

    if (bsize == 0) {  // end of pass. In data pool, cannot get any data.
      return 0;
    }

    DataBatch cpuBatch;
    cpuBatch.setSize(bsize);
    auto& inArgs = cpuBatch.getStreams();
    inArgs.resize(headers_.size());
604
    std::vector<std::unique_ptr<IFieldScanner>> scanners;
Z
zhangjinchao01 已提交
605 606 607 608 609
    scanners.reserve(headers_.size());
    for (auto& header : headers_) {
      scanners.emplace_back(IFieldScanner::create(&header));
    }
    DBG << "Scanner created.";
610
    for (size_t i = 0; i < headers_.size(); ++i) {
Z
zhangjinchao01 已提交
611 612
      scanners[i]->startPrepare(inArgs[i]);
    }
613
    for (auto& d : data) {
Z
zhangjinchao01 已提交
614
      py::SequenceHelper s(d);
615
      for (size_t i = 0; i < headers_.size(); ++i) {
Z
zhangjinchao01 已提交
616 617 618
        scanners[i]->prepare(inArgs[i], s[i]);
      }
    }
619
    for (size_t i = 0; i < headers_.size(); ++i) {
Z
zhangjinchao01 已提交
620 621
      scanners[i]->finishPrepare(inArgs[i]);
    }
622
    for (size_t i = 0; i < headers_.size(); ++i) {
Z
zhangjinchao01 已提交
623 624
      scanners[i]->startFill(inArgs[i]);
    }
625
    for (auto& d : data) {
Z
zhangjinchao01 已提交
626 627 628 629 630 631
      py::SequenceHelper s(d);
      for (size_t i = 0; i < headers_.size(); ++i) {
        scanners[i]->fill(inArgs[i], s[i]);
      }
    }

632
    for (size_t i = 0; i < headers_.size(); ++i) {
Z
zhangjinchao01 已提交
633 634 635
      scanners[i]->finishFill(inArgs[i]);
    }

636 637 638 639 640
    {
      PyGuard g;
      cache_->drop(&data);
    }

Z
zhangjinchao01 已提交
641 642 643 644 645 646 647
    DBG << "Reading CPU Batch Done.";

    if (useGpu_) {
      std::vector<Argument>& cpuArguments = cpuBatch.getStreams();
      DataBatch& gpuBatch = *batch;
      std::vector<Argument>& gpuArguments = gpuBatch.getStreams();
      gpuArguments.resize(cpuArguments.size());
648
      gpuBatch.setSize(bsize);
Z
zhangjinchao01 已提交
649
      for (size_t i = 0; i < headers_.size(); ++i) {
650 651
        gpuArguments[i].resizeAndCopyFrom(
            cpuArguments[i], useGpu_, HPPL_STREAM_1);
Z
zhangjinchao01 已提交
652 653 654 655 656 657 658 659 660 661 662
      }
      hl_stream_synchronize(HPPL_STREAM_1);
    } else {
      *batch = cpuBatch;
    }
    return bsize;
  }
};

PyObjectPtr PyDataProvider2::zeroTuple_(PyTuple_New(0));

663 664
REGISTER_DATA_PROVIDER_EX(py2, PyDataProvider2);

Z
zhangjinchao01 已提交
665 666 667
/**
 * Scanner for dense slot.
 */
668
class DenseScanner : public IFieldScanner {
W
Wu Yi 已提交
669
 public:
670
  explicit DenseScanner(SlotHeader* ptr) : IFieldScanner(ptr), height_(0) {}
Z
zhangjinchao01 已提交
671 672 673 674 675 676

  /**
   * Prepare.
   * @param argument target argument
   * @param obj each timestep of a sample.
   */
677
  virtual void prepare(Argument& argument, PyObject* obj) { ++height_; }
Z
zhangjinchao01 已提交
678

679 680 681
  virtual void finishPrepare(Argument& argument) {
    Matrix::resizeOrCreate(
        argument.value, height_, headerPtr_->dim, false, false);
Z
zhangjinchao01 已提交
682 683 684 685 686 687 688 689
    height_ = 0;
  }

  /**
   * Fill argument from obj.
   * @param argument
   * @param obj
   */
690
  virtual void fill(Argument& argument, PyObject* obj) {
Z
zhangjinchao01 已提交
691
    real* dat = argument.value->getData() + height_ * headerPtr_->dim;
692
    if (PyArray_Check(obj)) {
693 694 695 696 697 698 699 700 701 702 703 704 705 706
      auto dtype = PyArray_DTYPE((PyArrayObject*)obj);
      if (dtype->type == 'f' && dtype->elsize == sizeof(real)) {
        real* data = (real*)PyArray_DATA((PyArrayObject*)obj);
        auto sz = PyArray_SIZE((PyArrayObject*)obj);
        std::copy(data, data + sz, dat);
      } else {
        LOG(FATAL) << "You should yield float" << sizeof(real) * 8 << " array";
      }
    } else {
      py::SequenceHelper s(obj);
      // TODO(yuyang18): Here we can use AVX or SSE to accelerate memory copy.
      for (size_t i = 0; i < headerPtr_->dim; ++i) {
        dat[i] = (real)s.getDouble(i);
      }
Z
zhangjinchao01 已提交
707 708 709 710
    }
    ++height_;
  }

W
Wu Yi 已提交
711
 private:
Z
zhangjinchao01 已提交
712 713 714 715 716 717
  size_t height_;
};

/**
 * Scanner for index slot
 */
718
class IndexScanner : public IFieldScanner {
W
Wu Yi 已提交
719
 public:
720
  explicit IndexScanner(SlotHeader* ptr) : IFieldScanner(ptr), cnt_(0) {}
Z
zhangjinchao01 已提交
721 722 723 724 725 726

  /**
   * Prepare memory space.
   *
   * @note obj is a single timestep of sample
   */
727
  virtual void prepare(Argument& argument, PyObject* obj) { ++cnt_; }
Z
zhangjinchao01 已提交
728

729
  virtual void finishPrepare(Argument& argument) {
Z
zhangjinchao01 已提交
730 731 732 733 734 735 736
    IVector::resizeOrCreate(argument.ids, cnt_, false);
    cnt_ = 0;
  }

  /**
   * Fill one index to argument.
   */
737
  virtual void fill(Argument& argument, PyObject* obj) {
Z
zhangjinchao01 已提交
738
    bool ok;
739
    argument.ids->getData()[cnt_++] = py::castInt<int>(obj, &ok);
Z
zhangjinchao01 已提交
740 741 742
    CHECK(ok) << "Cannot cast int " << py::repr(obj);
  }

W
Wu Yi 已提交
743
 private:
Z
zhangjinchao01 已提交
744 745 746 747
  size_t cnt_;
};

class SparseNonValueScanner : public IFieldScanner {
W
Wu Yi 已提交
748
 public:
749 750
  explicit SparseNonValueScanner(SlotHeader* ptr)
      : IFieldScanner(ptr), nnz_(0), height_(0) {}
Z
zhangjinchao01 已提交
751 752 753 754 755

  /**
   * Prepare memory space
   * @note obj is a timestep of one sample.
   */
756
  virtual void prepare(Argument& argument, PyObject* obj) {
Z
zhangjinchao01 已提交
757 758 759 760
    ++height_;
    nnz_ += py::SequenceHelper(obj).size();
  }

761 762 763
  virtual void finishPrepare(Argument& argument) {
    Matrix::resizeOrCreateSparseMatrix(
        argument.value, height_, headerPtr_->dim, nnz_, NO_VALUE);
Z
zhangjinchao01 已提交
764 765
  }

766 767
  virtual void startFill(Argument& argument) {
    auto smat = (CpuSparseMatrix*)(argument.value.get());
Z
zhangjinchao01 已提交
768 769 770 771 772 773 774 775 776 777 778 779
    smat->getRows()[0] = 0;
    nnz_ = 0;
    height_ = 1;
  }

  /**
   * Fill one sparse vector to argument.
   * @note obj is a timestep of one sample.
   */
  virtual void fill(Argument& argument, PyObject* obj) {
    py::SequenceHelper s(obj);
    auto sz = s.size();
780
    auto smat = (CpuSparseMatrix*)(argument.value.get());
Z
zhangjinchao01 已提交
781 782 783
    int* row = smat->getRows();
    int* col = smat->getCols();
    real* dat = smat->getData();
784
    row[height_] = row[height_ - 1] + (int)sz;
Z
zhangjinchao01 已提交
785 786

    for (decltype(sz) i = 0; i < sz; ++i) {
787
      setData(col + nnz_, dat + nnz_, s[i]);
Z
zhangjinchao01 已提交
788 789 790 791 792
      ++nnz_;
    }
    ++height_;
  }

W
Wu Yi 已提交
793
 protected:
Z
zhangjinchao01 已提交
794 795 796 797 798 799 800
  /**
   * Set a single sparse index and value.
   * @param [out] col sparse index
   * @param [out] dat sparse value
   * @param [in] obj Python Object. For sparse_non_value is a PyInt or PyLong.
   *                 For sparse_value is a Tuple (int, float).
   */
801
  virtual void setData(int* col, real* dat, PyObject* obj) {
Z
zhangjinchao01 已提交
802 803 804 805 806 807 808 809 810 811
    bool ok;
    *col = py::castInt<int>(obj, &ok);
    CHECK(ok);
  }

  size_t nnz_;
  size_t height_;
};

class SparseValueScanner : public SparseNonValueScanner {
W
Wu Yi 已提交
812
 public:
813
  explicit SparseValueScanner(SlotHeader* ptr) : SparseNonValueScanner(ptr) {}
Z
zhangjinchao01 已提交
814

815 816 817
  virtual void finishPrepare(Argument& argument) {
    Matrix::resizeOrCreateSparseMatrix(
        argument.value, height_, headerPtr_->dim, nnz_, FLOAT_VALUE);
Z
zhangjinchao01 已提交
818 819
  }

W
Wu Yi 已提交
820
 protected:
821
  virtual void setData(int* col, real* dat, PyObject* obj) {
Z
zhangjinchao01 已提交
822 823
    py::SequenceHelper s(obj);
    SparseNonValueScanner::setData(col, dat, s[0]);
824
    *dat = (real)s.getDouble(1);
Z
zhangjinchao01 已提交
825 826 827 828 829 830
  }
};

/**
 * Sequence Scanner. Scanner for sequence or sub-sequence.
 */
831
class SequenceScanner : public IFieldScanner {
W
Wu Yi 已提交
832
 public:
Z
zhangjinchao01 已提交
833 834 835 836 837 838 839
  /**
   * Ctor
   * @param innerScanner inner scanner for each timestep or sub-sequence.
   * @param getSeqStartPos A callback, (Argument) => ICpuGpuVectorPtr.
   *                       return a sequence start position or a sub-sequence
   *                       start position.
   */
840 841 842 843 844 845 846
  SequenceScanner(
      std::unique_ptr<IFieldScanner>&& innerScanner,
      const std::function<ICpuGpuVectorPtr&(Argument&)>& getSeqStartPos)
      : IFieldScanner(nullptr),
        inner_(std::move(innerScanner)),
        cnt_(0),
        getSeqStartPos_(getSeqStartPos) {}
Z
zhangjinchao01 已提交
847 848 849 850

  /**
   * Start prepare. Invoke inner->startPrepare too.
   */
851
  virtual void startPrepare(Argument& argument) {
Z
zhangjinchao01 已提交
852 853 854 855 856 857 858
    inner_->startPrepare(argument);
  }

  /**
   * Prepare. obj is a list or tuple. it will invoke inner_->prepare for each
   * element of sequence obj.
   */
859
  virtual void prepare(Argument& argument, PyObject* obj) {
Z
zhangjinchao01 已提交
860 861
    py::SequenceHelper s(obj);
    ++cnt_;
862
    for (size_t i = 0; i < s.size(); ++i) {
Z
zhangjinchao01 已提交
863 864 865 866 867 868 869
      inner_->prepare(argument, s[i]);
    }
  }

  /**
   * Finish prepare. invoke inner_->finishPrepare too.
   */
870
  virtual void finishPrepare(Argument& argument) {
Z
zhangjinchao01 已提交
871 872 873 874 875 876 877
    ICpuGpuVector::resizeOrCreate(getSeqStartPos_(argument), cnt_ + 1, false);
    inner_->finishPrepare(argument);
  }

  /**
   * Start fill. invoke inner->startFill too.
   */
878
  virtual void startFill(Argument& argument) {
Z
zhangjinchao01 已提交
879 880 881 882 883 884 885 886 887 888
    getSeqStartPos_(argument)->getMutableData(false)[0] = 0;
    cnt_ = 1;
    inner_->startFill(argument);
  }

  /**
   * Fill. Obj is a tuple or list. invoke inner->fill for each element of
   * sequence obj. And set seqStartPos at same time. The seqStartPos will be
   * calculated by getSeqStartPos callback passed in ctor.
   */
889
  virtual void fill(Argument& argument, PyObject* obj) {
Z
zhangjinchao01 已提交
890
    getSeqStartPos_(argument)->getMutableData(false)[cnt_] =
891 892
        getSeqStartPos_(argument)->getMutableData(false)[cnt_ - 1] +
        (int)getSize(obj);
Z
zhangjinchao01 已提交
893 894
    py::SequenceHelper s(obj);
    ++cnt_;
895
    for (size_t i = 0; i < s.size(); ++i) {
Z
zhangjinchao01 已提交
896 897 898 899 900 901 902
      inner_->fill(argument, s[i]);
    }
  }

  /**
   * Finish fill. will invoke inner->finishFill too.
   */
903
  virtual void finishFill(Argument& argument) { inner_->finishFill(argument); }
Z
zhangjinchao01 已提交
904

W
Wu Yi 已提交
905
 protected:
Z
zhangjinchao01 已提交
906 907 908 909 910
  size_t getSize(PyObject* obj) {
    py::SequenceHelper s(obj);
    auto sc = dynamic_cast<SequenceScanner*>(inner_.get());
    if (sc) {
      size_t sum = 0;
911
      for (size_t i = 0; i < s.size(); ++i) {
Z
zhangjinchao01 已提交
912 913 914 915 916 917 918 919
        sum += sc->getSize(s[i]);
      }
      return sum;
    } else {
      return s.size();
    }
  }

W
Wu Yi 已提交
920
 private:
Z
zhangjinchao01 已提交
921 922 923 924 925
  std::unique_ptr<IFieldScanner> inner_;
  size_t cnt_;
  std::function<ICpuGpuVectorPtr&(Argument&)> getSeqStartPos_;
};

926
IFieldScanner* IFieldScanner::create(SlotHeader* header) {
Z
zhangjinchao01 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  IFieldScanner* retv = nullptr;
  switch (header->slotType) {
    case ST_DENSE:
      retv = new DenseScanner(header);
      break;
    case ST_INDEX:
      retv = new IndexScanner(header);
      break;
    case ST_NON_SPARSE_VALUE:
      retv = new SparseNonValueScanner(header);
      break;
    case ST_SPARSE_VALUE:
      retv = new SparseValueScanner(header);
      break;
    default:
      LOG(FATAL) << "Not implemented " << header->slotType;
  }

  switch (header->seqType) {
    case SQT_NONE:
      break;
    case SQT_SUBSEQ:
      retv = new SequenceScanner(std::unique_ptr<IFieldScanner>(retv),
950 951 952 953
                                 [](Argument& arg) -> ICpuGpuVectorPtr& {
                                   return arg.subSequenceStartPositions;
                                 });
    // fall through, not break;
Z
zhangjinchao01 已提交
954 955
    case SQT_SEQ:
      retv = new SequenceScanner(std::unique_ptr<IFieldScanner>(retv),
956 957 958
                                 [](Argument& arg) -> ICpuGpuVectorPtr& {
                                   return arg.sequenceStartPositions;
                                 });
Z
zhangjinchao01 已提交
959 960 961 962 963 964 965 966 967 968 969 970
      break;
    default:
      LOG(FATAL) << "Not implemented";
  }

  return retv;
}

/**
 * No Cache Strategy. Will destruct old data immediately and load data from
 * python every pass.
 */
971
class NoCacheStrategy : public IPyDataProviderCache {
W
Wu Yi 已提交
972
 public:
973
  virtual bool reset() { return true; }
Z
zhangjinchao01 已提交
974

975
  virtual void drop(std::deque<PyObjectPtr>* data) { data->clear(); }
Z
zhangjinchao01 已提交
976

977
  virtual std::deque<PyObjectPtr>* load() { return nullptr; }
Z
zhangjinchao01 已提交
978 979 980 981 982 983 984 985 986
};

/**
 * Cache One Pass In Memory strategy.
 *
 * In first pass, will load data from python and store them in memory.
 * The rest passes, will load data from memory.
 */
class CacheOnePassInMemory : public IPyDataProviderCache {
W
Wu Yi 已提交
987
 public:
988 989 990
  CacheOnePassInMemory()
      : objPool_(new std::deque<PyObjectPtr>()),
        droppedPool_(new std::deque<PyObjectPtr>()) {}
Z
zhangjinchao01 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002

  virtual bool reset() {
    if (objPool_->empty() && droppedPool_->empty()) {
      return true;
    } else if (objPool_->empty()) {
      std::swap(objPool_, droppedPool_);
      return false;
    } else {
      LOG(FATAL) << "Unexpected branch";
    }
  }

1003
  virtual void drop(std::deque<PyObjectPtr>* data) {
Z
zhangjinchao01 已提交
1004 1005
    size_t orgSize = droppedPool_->size();
    droppedPool_->resize(orgSize + data->size());
1006
    for (size_t i = 0; i < data->size(); ++i) {
Z
zhangjinchao01 已提交
1007 1008 1009 1010 1011
      std::swap((*droppedPool_)[orgSize + i], (*data)[i]);
    }
    data->clear();
  }

1012
  virtual std::deque<PyObjectPtr>* load() { return objPool_.get(); }
Z
zhangjinchao01 已提交
1013

W
Wu Yi 已提交
1014
 private:
1015 1016
  std::unique_ptr<std::deque<PyObjectPtr>> objPool_;
  std::unique_ptr<std::deque<PyObjectPtr>> droppedPool_;
Z
zhangjinchao01 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
};

IPyDataProviderCache* IPyDataProviderCache::create(CacheType ct) {
  switch (ct) {
    case NO_CACHE:
      return new NoCacheStrategy();
    case CACHE_PASS_IN_MEM:
      return new CacheOnePassInMemory();
    default:
      LOG(FATAL) << "Not implemented";
  }
}
}  // namespace paddle

#endif