PyDataProvider.cpp 18.2 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

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"
X
Xin Pan 已提交
16 17 18
#include "paddle/legacy/utils/Common.h"
#include "paddle/legacy/utils/PythonUtil.h"
#include "paddle/legacy/utils/Util.h"
L
liaogang 已提交
19

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

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

26 27
PyDataProvider::PyDataProvider(const DataConfig& config,
                               bool useGpu,
Z
zhangjinchao01 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
                               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.";
51 52
  PyObjectPtr obj(PyObject_CallMethod(
      classInstance_.get(), const_cast<char*>("getHeader"), NULL));
Z
zhangjinchao01 已提交
53 54 55 56
  CHECK_PY(obj) << "Call function getHeader failed.";
  std::string headerInfo =
      std::string(PyString_AsString(obj.get()), PyString_Size(obj.get()));
  parseHeaderData(headerInfo);
L
liaogang 已提交
57
  feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
Z
zhangjinchao01 已提交
58 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
}

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();
  }
}

91 92
void PyDataProvider::fillDenseSlot(ProtoSlot& slot,
                                   char*& data,
Z
zhangjinchao01 已提交
93 94 95 96 97 98 99 100 101 102 103
                                   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
104 105 106 107
  memcpyWithCheck(slot.denseData.data(),
                  data,
                  sizeof(real) * dim * slot.sampleNum,
                  dataEnd);
Z
zhangjinchao01 已提交
108 109 110 111 112
#endif
  // PyDataProvider always provide data in float
  data += sizeof(float) * dim * slot.sampleNum;
}

113 114
void PyDataProvider::fillSparseNonValueSlot(ProtoSlot& slot,
                                            char*& data,
Z
zhangjinchao01 已提交
115 116 117 118 119 120 121 122 123 124 125
                                            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);
126 127 128 129
  memcpyWithCheck(slot.sparseNonValueData.data(),
                  data,
                  sizeof(unsigned int) * length,
                  dataEnd);
Z
zhangjinchao01 已提交
130 131 132
  data += sizeof(unsigned int) * length;
}

133 134
void PyDataProvider::fillSparseValueSlot(ProtoSlot& slot,
                                         char*& data,
Z
zhangjinchao01 已提交
135 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
                                         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];
  }
}

161 162
void PyDataProvider::fillIndexSlot(ProtoSlot& slot,
                                   char*& data,
Z
zhangjinchao01 已提交
163 164 165 166 167 168 169 170 171
                                   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;
}

172 173
void PyDataProvider::fillStringSlot(ProtoSlot& slot,
                                    char*& data,
Z
zhangjinchao01 已提交
174 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
                                    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];
235 236
        size_t end = (i < sequenceNum - 1) ? slot.sequenceStartPositions[i + 1]
                                           : slot.sampleNum;
Z
zhangjinchao01 已提交
237 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
        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;
264 265
    PyObjectPtr obj(PyObject_CallMethod(
        classInstance_.get(), const_cast<char*>("reset"), NULL));
Z
zhangjinchao01 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278
    CHECK_PY(obj) << "Call function reset failed.";
  }

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

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

284 285
void PyDataProvider::handleDenseSlot(ProtoSlot& slot,
                                     size_t slotIndex,
Z
zhangjinchao01 已提交
286 287
                                     std::vector<Argument>& cpuArguments) {
  unsigned int dim = slot.dim;
288 289 290
  Matrix::resizeOrCreate(cpuArguments[slotIndex].value,
                         slot.sampleNum,
                         dim,
Z
zhangjinchao01 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                         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)) {
306 307 308 309 310 311 312 313
    cpuArguments[slotIndex].value =
        Matrix::createSparseMatrix(slot.sampleNum,
                                   dim,
                                   slot.sampleNum /*DEFAULT_AVG_WIDTH = 1*/,
                                   NO_VALUE,
                                   SPARSE_CSR,
                                   false,
                                   useGpu_);
Z
zhangjinchao01 已提交
314 315 316 317
  }
  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 已提交
318 319 320 321 322
    std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseNonValueData.data(),
        HPPL_STREAM_1);
Z
zhangjinchao01 已提交
323
  } else if (std::dynamic_pointer_cast<CpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
324 325 326 327
    std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseNonValueData.data());
Z
zhangjinchao01 已提交
328 329 330 331 332 333 334 335 336
  } 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)) {
337 338 339 340 341 342 343 344
    cpuArguments[slotIndex].value =
        Matrix::createSparseMatrix(slot.sampleNum,
                                   dim,
                                   slot.sampleNum /*DEFAULT_AVG_WIDTH = 1*/,
                                   FLOAT_VALUE,
                                   SPARSE_CSR,
                                   false,
                                   useGpu_);
Z
zhangjinchao01 已提交
345 346 347 348
  }
  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 已提交
349 350 351 352 353
    std::dynamic_pointer_cast<GpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseFloatValueData.data(),
        HPPL_STREAM_DEFAULT);
Z
zhangjinchao01 已提交
354
  } else if (std::dynamic_pointer_cast<CpuSparseMatrix>(mat)) {
Y
Yu Yang 已提交
355 356 357 358
    std::dynamic_pointer_cast<CpuSparseMatrix>(mat)->copyFrom(
        slot.sampleSequenceIdVec.data(),
        slot.indices.data(),
        slot.sparseFloatValueData.data());
Z
zhangjinchao01 已提交
359 360 361 362 363
  } else {
    LOG(FATAL) << "Not Supported";
  }
}

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

376 377
void PyDataProvider::handleStringSlot(ProtoSlot& slot,
                                      size_t slotIndex,
Z
zhangjinchao01 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                                      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"),
395 396
                                      const_cast<char*>("i"),
                                      size));
Z
zhangjinchao01 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  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];
413 414 415
      ICpuGpuVector::resizeOrCreate(cpuArguments[j].sequenceStartPositions,
                                    slot.sequenceNum + 1,
                                    /* useGpu= */ false);
Z
zhangjinchao01 已提交
416 417
      int* buf = cpuArguments[j].sequenceStartPositions->getMutableData(false);
      std::copy(slot.sequenceStartPositions.begin(),
418 419
                slot.sequenceStartPositions.end(),
                buf);
Z
zhangjinchao01 已提交
420 421 422
      buf[slot.sequenceStartPositions.size()] = slot.sampleNum;

      if (slot.subSequenceStartPositions.size()) {
423 424 425
        ICpuGpuVector::resizeOrCreate(cpuArguments[j].subSequenceStartPositions,
                                      slot.subSequenceNum + 1,
                                      /*  useGpu= */ false);
Z
zhangjinchao01 已提交
426
        int* buf =
427
            cpuArguments[j].subSequenceStartPositions->getMutableData(false);
Z
zhangjinchao01 已提交
428
        std::copy(slot.subSequenceStartPositions.begin(),
429 430
                  slot.subSequenceStartPositions.end(),
                  buf);
Z
zhangjinchao01 已提交
431 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
        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 {
485 486
        gpuArguments[i].resizeAndCopyFrom(
            cpuArguments[i], useGpu_, HPPL_STREAM_1);
Z
zhangjinchao01 已提交
487 488 489 490 491 492 493 494 495 496 497 498
      }
    }
    hl_stream_synchronize(HPPL_STREAM_1);
    *batch = gpuBatch;
  } else {
    *batch = cpuBatch;
  }

  return batch->getSize();
}

}  // namespace paddle