PyDataProvider.cpp 18.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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. */

#include "PyDataProvider.h"
#include <fenv.h>
L
liaogang 已提交
17
#include "paddle/utils/Excepts.h"
Y
Yu Yang 已提交
18 19
#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Util.h"
L
liaogang 已提交
20

Z
zhangjinchao01 已提交
21 22 23 24 25 26
namespace paddle {

#ifndef PADDLE_NO_PYTHON
REGISTER_DATA_PROVIDER(py, PyDataProvider);
#endif

27 28
PyDataProvider::PyDataProvider(const DataConfig& config,
                               bool useGpu,
Z
zhangjinchao01 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
                               bool loadDataAll)
    : DataProvider(config, useGpu), batchSize_(0) {
  PyGuard guard;
  pyModuleName_ = config_.load_data_module();
  pyClassName_ = config_.load_data_object();
  if (config_.load_data_args() != "") {
    pyUserArgs_["load_data_args"] = config_.load_data_args();
  }

  if (loadDataAll) {
    std::vector<std::string> fileList;
    if (!config_.files().empty()) {
      loadFileList(config_.files(), fileList);
    }
    loadData(fileList);
  }
}

void PyDataProvider::loadData(const std::vector<std::string>& fileList) {
  VLOG(1) << "module:" << pyModuleName_ << " class:" << pyClassName_;
  classInstance_ =
      createPythonClass(pyModuleName_, pyClassName_, fileList, pyUserArgs_);
  CHECK(classInstance_) << "Create class instance failed.";
52 53
  PyObjectPtr obj(PyObject_CallMethod(
      classInstance_.get(), const_cast<char*>("getHeader"), NULL));
Z
zhangjinchao01 已提交
54 55 56 57
  CHECK_PY(obj) << "Call function getHeader failed.";
  std::string headerInfo =
      std::string(PyString_AsString(obj.get()), PyString_Size(obj.get()));
  parseHeaderData(headerInfo);
L
liaogang 已提交
58
  feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
Z
zhangjinchao01 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
}

void PyDataProvider::parseHeaderData(const std::string& headerData) {
  char* pHeader = const_cast<char*>(headerData.c_str());
  char* pHeaderEnd = pHeader + headerData.size();
  slotNum_ = readT<unsigned int>(pHeader, pHeaderEnd);
  unsigned int useSequenceFlag = readT<unsigned int>(pHeader, pHeaderEnd);
  isIID_ = useSequenceFlag != 1;
  slots_.clear();
  slots_.reserve(slotNum_);
  for (size_t i = 0; i < slotNum_; ++i) {
    unsigned int slotType = readT<unsigned int>(pHeader, pHeaderEnd);
    unsigned int slotDim = readT<unsigned int>(pHeader, pHeaderEnd);
    slots_.emplace_back();
    slots_.back().dim = slotDim;
    slots_.back().type = static_cast<SlotDef_SlotType>(slotType);
  }
}

void PyDataProvider::resetSlots() {
  for (auto& slot : slots_) {
    slot.indexData.clear();
    slot.denseData.clear();
    slot.sparseNonValueData.clear();
    slot.sparseFloatValueData.clear();
    slot.indices.clear();
    slot.sequenceStartPositions.clear();
    slot.sampleSequenceIdVec.clear();
    slot.subSequenceStartPositions.clear();
    slot.strData.clear();
  }
}

92 93
void PyDataProvider::fillDenseSlot(ProtoSlot& slot,
                                   char*& data,
Z
zhangjinchao01 已提交
94 95 96 97 98 99 100 101 102 103 104
                                   const char* dataEnd) {
  unsigned int dim = slot.dim;
  slot.sampleNum = readT<unsigned int>(data, dataEnd);
  slot.denseData.resize(slot.sampleNum * dim);
#ifdef PADDLE_TYPE_DOUBLE
  CHECK_LE(data + sizeof(real) * dim * slot.sampleNum, dataEnd)
      << "std::copy data is out of range";
  // PyDataProvider always provide data in float
  float* dat = reinterpret_cast<float*>(data);
  std::copy(dat, dat + slot.sampleNum * dim, slot.denseData.begin());
#else
105 106 107 108
  memcpyWithCheck(slot.denseData.data(),
                  data,
                  sizeof(real) * dim * slot.sampleNum,
                  dataEnd);
Z
zhangjinchao01 已提交
109 110 111 112 113
#endif
  // PyDataProvider always provide data in float
  data += sizeof(float) * dim * slot.sampleNum;
}

114 115
void PyDataProvider::fillSparseNonValueSlot(ProtoSlot& slot,
                                            char*& data,
Z
zhangjinchao01 已提交
116 117 118 119 120 121 122 123 124 125 126
                                            const char* dataEnd) {
  slot.sampleNum = readT<unsigned int>(data, dataEnd);
  unsigned int* indexPtr = (unsigned int*)data;
  CHECK_LE(data + sizeof(unsigned int) * slot.sampleNum, dataEnd)
      << "Vector assign value is out of range";
  slot.indices.assign(indexPtr, indexPtr + slot.sampleNum);
  data += sizeof(unsigned int) * slot.sampleNum;
  unsigned int length = 0;
  length = readT<unsigned int>(data, dataEnd);
  slot.indices.push_back(length);
  slot.sparseNonValueData.resize(length);
127 128 129 130
  memcpyWithCheck(slot.sparseNonValueData.data(),
                  data,
                  sizeof(unsigned int) * length,
                  dataEnd);
Z
zhangjinchao01 已提交
131 132 133
  data += sizeof(unsigned int) * length;
}

134 135
void PyDataProvider::fillSparseValueSlot(ProtoSlot& slot,
                                         char*& data,
Z
zhangjinchao01 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
                                         const char* dataEnd) {
  slot.sampleNum = readT<unsigned int>(data, dataEnd);
  unsigned int* indexPtr = (unsigned int*)data;
  CHECK_LE(data + sizeof(unsigned int) * slot.sampleNum, dataEnd)
      << "Vector assign value is out of range";
  slot.indices.assign(indexPtr, indexPtr + slot.sampleNum);
  data += sizeof(unsigned int) * slot.sampleNum;
  unsigned int length = 0;
  length = readT<unsigned int>(data, dataEnd);
  unsigned int* colPtr = reinterpret_cast<unsigned int*>(data);
  CHECK_LE(data + sizeof(unsigned int) * length, dataEnd)
      << "Data is out of range";
  data += sizeof(unsigned int) * length;
  size_t colLen = readT<unsigned int>(data, dataEnd);
  CHECK_EQ(colLen, length);
  float* valuePtr = reinterpret_cast<float*>(data);
  CHECK_LE(data + sizeof(real) * length, dataEnd) << "Data is out of range";
  data += sizeof(real) * length;
  slot.indices.push_back(length);
  slot.sparseFloatValueData.resize(length);
  for (unsigned int ii = 0; ii < length; ++ii) {
    slot.sparseFloatValueData[ii].col = colPtr[ii];
    slot.sparseFloatValueData[ii].value = valuePtr[ii];
  }
}

162 163
void PyDataProvider::fillIndexSlot(ProtoSlot& slot,
                                   char*& data,
Z
zhangjinchao01 已提交
164 165 166 167 168 169 170 171 172
                                   const char* dataEnd) {
  slot.sampleNum = readT<unsigned int>(data, dataEnd);
  CHECK_LE(data + sizeof(unsigned int) * slot.sampleNum, dataEnd)
      << "Vector assign is out of range";
  slot.indexData.assign(reinterpret_cast<int*>(data),
                        reinterpret_cast<int*>(data) + slot.sampleNum);
  data += sizeof(unsigned int) * slot.sampleNum;
}

173 174
void PyDataProvider::fillStringSlot(ProtoSlot& slot,
                                    char*& data,
Z
zhangjinchao01 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 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
                                    const char* dataEnd) {
  slot.sampleNum = readT<unsigned int>(data, dataEnd);
  for (unsigned int i = 0; i < slot.sampleNum; ++i) {
    size_t len = readT<uint32_t>(data, dataEnd);
    auto str_begin = data;
    data += len;
    CHECK_LE(data, dataEnd) << "Data is out of range";
    slot.strData.emplace_back(str_begin, len);
  }
}

void PyDataProvider::fillSlotsByStr(const std::string& samples) {
  char* data = const_cast<char*>(samples.c_str());
  char* dataEnd = data + samples.size();
  batchSize_ = readT<unsigned int>(data, dataEnd);
  if (0 == batchSize_) {
    return;
  }

  for (size_t j = 0; j < slotNum_; ++j) {
    auto& slot = slots_[j];
    CHECK(SlotDef::INDEX >= slot.type || SlotDef::STRING == slot.type)
        << " Slot type:" << slot.type << " is out of range.";
    CHECK_GE(slot.type, SlotDef::VECTOR_DENSE) << " Slot type:" << slot.type
                                               << " is out of range.";
    switch (slot.type) {
      case SlotDef::VECTOR_DENSE:
        fillDenseSlot(slot, data, dataEnd);
        break;
      case SlotDef::VECTOR_SPARSE_NON_VALUE:
        fillSparseNonValueSlot(slot, data, dataEnd);
        break;
      case SlotDef::VECTOR_SPARSE_VALUE:
        fillSparseValueSlot(slot, data, dataEnd);
        break;
      case SlotDef::INDEX:
        fillIndexSlot(slot, data, dataEnd);
        break;
      case SlotDef::VAR_MDIM_DENSE:
        LOG(FATAL) << "Not implemented";
        break;
      case SlotDef::VAR_MDIM_INDEX:
        LOG(FATAL) << "Not implemented";
        break;
      case SlotDef::STRING:
        fillStringSlot(slot, data, dataEnd);
        break;
    }
  }
  // read sequenceStartPositions
  for (size_t j = 0; j < slotNum_; ++j) {
    auto& slot = slots_[j];
    if (!iidData()) {
      unsigned int sequenceNum = readT<unsigned int>(data, dataEnd);
      slot.sequenceNum = sequenceNum;
      for (size_t i = 0; i < sequenceNum; ++i) {
        slot.sequenceStartPositions.push_back(
            readT<unsigned int>(data, dataEnd));
      }
      for (size_t i = 0; i < sequenceNum; ++i) {
        size_t begin = slot.sequenceStartPositions[i];
236 237
        size_t end = (i < sequenceNum - 1) ? slot.sequenceStartPositions[i + 1]
                                           : slot.sampleNum;
Z
zhangjinchao01 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        for (size_t ii = begin; ii < end; ++ii) {
          slot.sampleSequenceIdVec.push_back(ii);
        }
      }
    } else {
      for (size_t i = 0; i < slot.sampleNum; ++i) {
        slot.sampleSequenceIdVec.push_back(i);
      }
    }
  }
  // read subSequenceStartPositions, not all slots have this infomation.
  for (size_t j = 0; j < slotNum_; ++j) {
    auto& slot = slots_[j];
    if (!iidData() && data != dataEnd) {
      unsigned int subSequenceNum = readT<unsigned int>(data, dataEnd);
      slot.subSequenceNum = subSequenceNum;
      for (size_t i = 0; i < subSequenceNum; ++i) {
        slot.subSequenceStartPositions.push_back(
            readT<unsigned int>(data, dataEnd));
      }
    }
  }
}

void PyDataProvider::reset() {
  {  // Invoke PyDataProvider Reset
    PyGuard guard;
265 266
    PyObjectPtr obj(PyObject_CallMethod(
        classInstance_.get(), const_cast<char*>("reset"), NULL));
Z
zhangjinchao01 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279
    CHECK_PY(obj) << "Call function reset failed.";
  }

  if (!skipShuffle_) {
    // Invoke PyDataProvider Shuffle
    shuffle();
  }
  DataProvider::reset();
}

void PyDataProvider::shuffle() {
  // py shuffle
  PyGuard guard;
280 281
  PyObjectPtr obj(PyObject_CallMethod(
      classInstance_.get(), const_cast<char*>("shuffle"), NULL));
Z
zhangjinchao01 已提交
282 283 284
  CHECK_PY(obj) << "Call function shuffle failed.";
}

285 286
void PyDataProvider::handleDenseSlot(ProtoSlot& slot,
                                     size_t slotIndex,
Z
zhangjinchao01 已提交
287 288
                                     std::vector<Argument>& cpuArguments) {
  unsigned int dim = slot.dim;
289 290 291
  Matrix::resizeOrCreate(cpuArguments[slotIndex].value,
                         slot.sampleNum,
                         dim,
Z
zhangjinchao01 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
                         false,   // trans = false
                         false);  // useGpu = false
  real* buf = cpuArguments[slotIndex].value->getData();
  for (size_t i = 0; i < slot.sampleNum; ++i) {
    memcpyWithCheck(buf + i * dim,
                    slot.denseData.data() + slot.sampleSequenceIdVec[i] * dim,
                    sizeof(real) * dim,
                    slot.denseData.data() + slot.denseData.size());
  }
}

void PyDataProvider::handleSparseNonValueSlot(
    ProtoSlot& slot, size_t slotIndex, std::vector<Argument>& cpuArguments) {
  unsigned int dim = slot.dim;
  if (!(cpuArguments[slotIndex].value)) {
307 308 309 310 311 312 313 314
    cpuArguments[slotIndex].value =
        Matrix::createSparseMatrix(slot.sampleNum,
                                   dim,
                                   slot.sampleNum /*DEFAULT_AVG_WIDTH = 1*/,
                                   NO_VALUE,
                                   SPARSE_CSR,
                                   false,
                                   useGpu_);
Z
zhangjinchao01 已提交
315 316 317 318
  }
  auto mat = cpuArguments[slotIndex].value;
  mat->resize(slot.sampleNum, dim, slot.sampleNum, NO_VALUE, SPARSE_CSR);
  if (std::dynamic_pointer_cast<GpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
319 320 321 322 323
    std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseNonValueData.data(),
        HPPL_STREAM_1);
Z
zhangjinchao01 已提交
324
  } else if (std::dynamic_pointer_cast<CpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
325 326 327 328
    std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseNonValueData.data());
Z
zhangjinchao01 已提交
329 330 331 332 333 334 335 336 337
  } else {
    LOG(FATAL) << "Not Supported";
  }
}

void PyDataProvider::handleSparseValueSlot(
    ProtoSlot& slot, size_t slotIndex, std::vector<Argument>& cpuArguments) {
  unsigned int dim = slot.dim;
  if (!(cpuArguments[slotIndex].value)) {
338 339 340 341 342 343 344 345
    cpuArguments[slotIndex].value =
        Matrix::createSparseMatrix(slot.sampleNum,
                                   dim,
                                   slot.sampleNum /*DEFAULT_AVG_WIDTH = 1*/,
                                   FLOAT_VALUE,
                                   SPARSE_CSR,
                                   false,
                                   useGpu_);
Z
zhangjinchao01 已提交
346 347 348 349
  }
  auto mat = cpuArguments[slotIndex].value;
  mat->resize(slot.sampleNum, dim, slot.sampleNum, FLOAT_VALUE, SPARSE_CSR);
  if (std::dynamic_pointer_cast<GpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
350 351 352 353 354
    std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseFloatValueData.data(),
        HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
355
  } else if (std::dynamic_pointer_cast<CpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
356 357 358 359
    std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseFloatValueData.data());
Z
zhangjinchao01 已提交
360 361 362 363 364
  } else {
    LOG(FATAL) << "Not Supported";
  }
}

365 366
void PyDataProvider::handleIndexSlot(ProtoSlot& slot,
                                     size_t slotIndex,
Z
zhangjinchao01 已提交
367
                                     std::vector<Argument>& cpuArguments) {
368 369
  IVector::resizeOrCreate(cpuArguments[slotIndex].ids,
                          slot.sampleNum,
Z
zhangjinchao01 已提交
370 371 372 373 374 375 376
                          /*useGpu_*/ false);
  int* buf = cpuArguments[slotIndex].ids->getData();
  for (size_t i = 0; i < slot.sampleNum; ++i) {
    buf[i] = slot.indexData[slot.sampleSequenceIdVec[i]];
  }
}

377 378
void PyDataProvider::handleStringSlot(ProtoSlot& slot,
                                      size_t slotIndex,
Z
zhangjinchao01 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
                                      std::vector<Argument>& cpuArguments) {
  if (cpuArguments[slotIndex].strs) {
    cpuArguments[slotIndex].strs->resize(slot.sampleNum);
  } else {
    cpuArguments[slotIndex].strs =
        std::make_shared<std::vector<std::string>>(slot.sampleNum);
  }
  for (size_t i = 0; i < slot.sampleNum; ++i) {
    (*cpuArguments[slotIndex].strs)[i] =
        slot.strData[slot.sampleSequenceIdVec[i]];
  }
}

int64_t PyDataProvider::getNextBatchInternal(int64_t size, DataBatch* batch) {
  PyGuard guard;
  PyObjectPtr obj(PyObject_CallMethod(classInstance_.get(),
                                      const_cast<char*>("getNextBatch"),
396 397
                                      const_cast<char*>("i"),
                                      size));
Z
zhangjinchao01 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
  CHECK_PY(obj) << "Call function getNextBatch failed.";
  const std::string& samples =
      std::string(PyString_AsString(obj.get()), PyString_Size(obj.get()));
  resetSlots();
  fillSlotsByStr(samples);
  size = batchSize_;
  if (size <= 0) return 0;

  DataBatch& cpuBatch = *cpuBatch_;
  std::vector<Argument>& cpuArguments = cpuBatch.getStreams();
  cpuBatch.setSize(size);
  cpuArguments.resize(slotNum_);

  if (!iidData()) {
    for (size_t j = 0; j < slotNum_; ++j) {
      auto& slot = slots_[j];
414 415 416
      ICpuGpuVector::resizeOrCreate(cpuArguments[j].sequenceStartPositions,
                                    slot.sequenceNum + 1,
                                    /* useGpu= */ false);
Z
zhangjinchao01 已提交
417 418
      int* buf = cpuArguments[j].sequenceStartPositions->getMutableData(false);
      std::copy(slot.sequenceStartPositions.begin(),
419 420
                slot.sequenceStartPositions.end(),
                buf);
Z
zhangjinchao01 已提交
421 422 423
      buf[slot.sequenceStartPositions.size()] = slot.sampleNum;

      if (slot.subSequenceStartPositions.size()) {
424 425 426
        ICpuGpuVector::resizeOrCreate(cpuArguments[j].subSequenceStartPositions,
                                      slot.subSequenceNum + 1,
                                      /*  useGpu= */ false);
Z
zhangjinchao01 已提交
427
        int* buf =
428
            cpuArguments[j].subSequenceStartPositions->getMutableData(false);
Z
zhangjinchao01 已提交
429
        std::copy(slot.subSequenceStartPositions.begin(),
430 431
                  slot.subSequenceStartPositions.end(),
                  buf);
Z
zhangjinchao01 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        buf[slot.subSequenceNum] = slot.sampleNum;
        // check subSequenceStartPositions and sequenceStartPositions
        cpuArguments[j].checkSubset();
      }
    }
  }

  for (size_t slotIndex = 0; slotIndex < slotNum_; ++slotIndex) {
    auto& slot = slots_[slotIndex];
    SlotDef::SlotType slotType = slot.type;
    switch (slotType) {
      case SlotDef::VECTOR_DENSE:
        handleDenseSlot(slot, slotIndex, cpuArguments);
        break;
      case SlotDef::VECTOR_SPARSE_NON_VALUE:
        handleSparseNonValueSlot(slot, slotIndex, cpuArguments);
        break;
      case SlotDef::VECTOR_SPARSE_VALUE:
        handleSparseValueSlot(slot, slotIndex, cpuArguments);
        break;
      case SlotDef::INDEX:
        handleIndexSlot(slot, slotIndex, cpuArguments);
        break;
      case SlotDef::VAR_MDIM_DENSE:
        LOG(FATAL) << "Not implemented";
        break;
      case SlotDef::VAR_MDIM_INDEX:
        LOG(FATAL) << "Not implemented";
        break;
      case SlotDef::STRING:
        handleStringSlot(slot, slotIndex, cpuArguments);
        break;
    }
  }

  if (useGpu_) {
    std::vector<Argument>& cpuArguments = cpuBatch.getStreams();
    DataBatch& gpuBatch = *gpuBatch_;
    std::vector<Argument>& gpuArguments = gpuBatch.getStreams();
    gpuArguments.resize(cpuArguments.size());
    gpuBatch.setSize(size);
    for (size_t i = 0; i < slotNum_; ++i) {
      SlotDef::SlotType slotType = slots_[i].type;
      if (SlotDef::VECTOR_SPARSE_VALUE == slotType ||
          SlotDef::VECTOR_SPARSE_NON_VALUE == slotType) {
        gpuArguments[i] = cpuArguments[i];
        gpuArguments[i].sequenceStartPositions =
            cpuArguments[i].sequenceStartPositions;

        if (slots_[i].subSequenceStartPositions.size()) {
          gpuArguments[i].subSequenceStartPositions =
              cpuArguments[i].subSequenceStartPositions;
        }
      } else {
486 487
        gpuArguments[i].resizeAndCopyFrom(
            cpuArguments[i], useGpu_, HPPL_STREAM_1);
Z
zhangjinchao01 已提交
488 489 490 491 492 493 494 495 496 497 498 499
      }
    }
    hl_stream_synchronize(HPPL_STREAM_1);
    *batch = gpuBatch;
  } else {
    *batch = cpuBatch;
  }

  return batch->getSize();
}

}  // namespace paddle