data_feed.cc 105.0 KB
Newer Older
W
Wang Guibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

D
dongdaxiang 已提交
15 16 17 18 19
#if defined _WIN32 || defined __APPLE__
#else
#define _LINUX
#endif

20
#include "paddle/fluid/framework/data_feed.h"
21

T
Thunderbrook 已提交
22
#include "paddle/fluid/framework/fleet/ps_gpu_wrapper.h"
D
dongdaxiang 已提交
23
#ifdef _LINUX
D
dongdaxiang 已提交
24
#include <stdio_ext.h>
H
hutuxian 已提交
25 26
#include <sys/mman.h>
#include <sys/stat.h>
D
dongdaxiang 已提交
27
#endif
28
#include "io/fs.h"
H
hutuxian 已提交
29
#include "paddle/fluid/platform/monitor.h"
30
#include "paddle/fluid/platform/timer.h"
W
Wang Guibao 已提交
31

H
hutuxian 已提交
32
USE_INT_STAT(STAT_total_feasign_num_in_mem);
33
PHI_DECLARE_bool(enable_ins_parser_file);
W
Wang Guibao 已提交
34 35 36
namespace paddle {
namespace framework {

T
Thunderbrook 已提交
37 38 39 40 41
DLManager& global_dlmanager_pool() {
  static DLManager manager;
  return manager;
}

Y
yaoxuefeng 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
class BufferedLineFileReader {
  typedef std::function<bool()> SampleFunc;
  static const int MAX_FILE_BUFF_SIZE = 4 * 1024 * 1024;
  class FILEReader {
   public:
    explicit FILEReader(FILE* fp) : fp_(fp) {}
    int read(char* buf, int len) { return fread(buf, sizeof(char), len, fp_); }

   private:
    FILE* fp_;
  };

 public:
  typedef std::function<bool(const std::string&)> LineFunc;

 private:
  template <typename T>
  int read_lines(T* reader, LineFunc func, int skip_lines) {
    int lines = 0;
    size_t ret = 0;
    char* ptr = NULL;
    char* eol = NULL;
    total_len_ = 0;
    error_line_ = 0;

    SampleFunc spfunc = get_sample_func();
    std::string x;
    while (!is_error() && (ret = reader->read(buff_, MAX_FILE_BUFF_SIZE)) > 0) {
      total_len_ += ret;
      ptr = buff_;
      eol = reinterpret_cast<char*>(memchr(ptr, '\n', ret));
      while (eol != NULL) {
        int size = static_cast<int>((eol - ptr) + 1);
        x.append(ptr, size - 1);
        ++lines;
        if (lines > skip_lines && spfunc()) {
          if (!func(x)) {
            ++error_line_;
          }
        }

        x.clear();
        ptr += size;
        ret -= size;
        eol = reinterpret_cast<char*>(memchr(ptr, '\n', ret));
      }
      if (ret > 0) {
        x.append(ptr, ret);
      }
    }
    if (!is_error() && !x.empty()) {
      ++lines;
      if (lines > skip_lines && spfunc()) {
        if (!func(x)) {
          ++error_line_;
        }
      }
    }
    return lines;
  }

 public:
  BufferedLineFileReader()
      : random_engine_(std::random_device()()),
        uniform_distribution_(0.0f, 1.0f) {
    total_len_ = 0;
    sample_line_ = 0;
    buff_ =
        reinterpret_cast<char*>(calloc(MAX_FILE_BUFF_SIZE + 1, sizeof(char)));
  }
  ~BufferedLineFileReader() { free(buff_); }

  int read_file(FILE* fp, LineFunc func, int skip_lines) {
    FILEReader reader(fp);
    return read_lines<FILEReader>(&reader, func, skip_lines);
  }
118
  uint64_t file_size() { return total_len_; }
Y
yaoxuefeng 已提交
119 120
  void set_sample_rate(float r) { sample_rate_ = r; }
  size_t get_sample_line() { return sample_line_; }
121
  bool is_error() { return (error_line_ > 10); }
Y
yaoxuefeng 已提交
122 123 124 125

 private:
  SampleFunc get_sample_func() {
    if (std::abs(sample_rate_ - 1.0f) < 1e-5f) {
126
      return []() { return true; };
Y
yaoxuefeng 已提交
127
    }
128
    return [this]() {
Y
yaoxuefeng 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142
      return (uniform_distribution_(random_engine_) < sample_rate_);
    };
  }

 private:
  char* buff_ = nullptr;
  uint64_t total_len_ = 0;

  std::default_random_engine random_engine_;
  std::uniform_real_distribution<float> uniform_distribution_;
  float sample_rate_ = 1.0f;
  size_t sample_line_ = 0;
  size_t error_line_ = 0;
};
143
void RecordCandidateList::ReSize(size_t length) {
144 145 146 147 148 149 150 151 152
  mutex_.lock();
  capacity_ = length;
  CHECK(capacity_ > 0);  // NOLINT
  candidate_list_.clear();
  candidate_list_.resize(capacity_);
  full_ = false;
  cur_size_ = 0;
  total_size_ = 0;
  mutex_.unlock();
153 154 155
}

void RecordCandidateList::ReInit() {
156 157 158 159 160
  mutex_.lock();
  full_ = false;
  cur_size_ = 0;
  total_size_ = 0;
  mutex_.unlock();
161 162 163 164
}

void RecordCandidateList::AddAndGet(const Record& record,
                                    RecordCandidate* result) {
165
  mutex_.lock();
166
  size_t index = 0;
167
  ++total_size_;
168
  auto fleet_ptr = FleetWrapper::GetInstance();
169 170 171
  if (!full_) {
    candidate_list_[cur_size_++] = record;
    full_ = (cur_size_ == capacity_);
172
  } else {
173 174 175 176
    CHECK(cur_size_ == capacity_);
    index = fleet_ptr->LocalRandomEngine()() % total_size_;
    if (index < capacity_) {
      candidate_list_[index] = record;
177 178
    }
  }
179 180 181
  index = fleet_ptr->LocalRandomEngine()() % cur_size_;
  *result = candidate_list_[index];
  mutex_.unlock();
182 183
}

W
Wang Guibao 已提交
184 185 186 187
void DataFeed::AddFeedVar(Variable* var, const std::string& name) {
  CheckInit();
  for (size_t i = 0; i < use_slots_.size(); ++i) {
    if (name == use_slots_[i]) {
188 189 190
      if (var == nullptr) {
        feed_vec_[i] = nullptr;
      } else {
191
        feed_vec_[i] = var->GetMutable<phi::DenseTensor>();
192
      }
W
Wang Guibao 已提交
193 194 195 196 197
    }
  }
}

bool DataFeed::SetFileList(const std::vector<std::string>& files) {
198
  std::unique_lock<std::mutex> lock(*mutex_for_pick_file_);
W
Wang Guibao 已提交
199
  CheckInit();
200 201
  // Do not set finish_set_filelist_ flag,
  // since a user may set file many times after init reader
W
Wang Guibao 已提交
202 203 204 205 206 207 208
  filelist_.assign(files.begin(), files.end());

  finish_set_filelist_ = true;
  return true;
}

void DataFeed::SetBatchSize(int batch_size) {
209 210
  PADDLE_ENFORCE_GT(batch_size,
                    0,
211 212
                    platform::errors::InvalidArgument(
                        "Batch size %d is illegal.", batch_size));
W
Wang Guibao 已提交
213 214 215 216
  default_batch_size_ = batch_size;
}

bool DataFeed::PickOneFile(std::string* filename) {
217 218 219 220 221
  PADDLE_ENFORCE_NOT_NULL(
      mutex_for_pick_file_,
      platform::errors::PreconditionNotMet(
          "You should call SetFileListMutex before PickOneFile"));
  PADDLE_ENFORCE_NOT_NULL(
222 223 224
      file_idx_,
      platform::errors::PreconditionNotMet(
          "You should call SetFileListIndex before PickOneFile"));
225
  std::unique_lock<std::mutex> lock(*mutex_for_pick_file_);
226
  VLOG(4) << "filelist_ size: " << filelist_.size();
227
  if (*file_idx_ == filelist_.size()) {
228
    VLOG(3) << "DataFeed::PickOneFile no more file to pick";
W
Wang Guibao 已提交
229 230
    return false;
  }
231 232
  VLOG(3) << "file_idx_=" << *file_idx_;
  *filename = filelist_[(*file_idx_)++];
W
Wang Guibao 已提交
233 234 235 236
  return true;
}

void DataFeed::CheckInit() {
237
  PADDLE_ENFORCE_EQ(
238 239
      finish_init_,
      true,
240
      platform::errors::PreconditionNotMet("DataFeed initialization failed."));
W
Wang Guibao 已提交
241 242 243
}

void DataFeed::CheckSetFileList() {
244
  PADDLE_ENFORCE_EQ(
245 246
      finish_set_filelist_,
      true,
247
      platform::errors::PreconditionNotMet("DataFeed set filelist failed."));
W
Wang Guibao 已提交
248 249 250
}

void DataFeed::CheckStart() {
251 252
  PADDLE_ENFORCE_EQ(finish_start_,
                    true,
253 254
                    platform::errors::PreconditionNotMet(
                        "Datafeed has not started running yet."));
W
Wang Guibao 已提交
255 256
}

H
hutuxian 已提交
257 258 259
void DataFeed::AssignFeedVar(const Scope& scope) {
  CheckInit();
  for (size_t i = 0; i < use_slots_.size(); ++i) {
260
    feed_vec_[i] = scope.FindVar(use_slots_[i])->GetMutable<phi::DenseTensor>();
H
hutuxian 已提交
261 262 263
  }
}

264 265 266 267 268 269
void DataFeed::CopyToFeedTensor(void* dst, const void* src, size_t size) {
  if (platform::is_cpu_place(this->place_)) {
    memcpy(dst, src, size);
  } else {
#ifdef PADDLE_WITH_CUDA
    cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice);
270 271
#elif defined(PADDLE_WITH_HIP)
    hipMemcpy(dst, src, size, hipMemcpyHostToDevice);
272 273
#elif defined(PADDLE_WITH_XPU_KP)
    xpu_memcpy(dst, src, size, XPUMemcpyKind::XPU_HOST_TO_DEVICE);
274
#else
275
    PADDLE_THROW(platform::errors::Unimplemented(
276 277
        "Not supported GPU/ROCM, please compile with option WITH_GPU=ON or "
        "WITH_ROCM=ON."));
278 279 280 281
#endif
  }
}

W
Wang Guibao 已提交
282 283
template <typename T>
void PrivateQueueDataFeed<T>::SetQueueSize(int queue_size) {
284
  PADDLE_ENFORCE_GT(
285 286
      queue_size,
      0,
287 288
      platform::errors::InvalidArgument(
          "Queue size %d is illegal in PrivateQueueDataFeed.", queue_size));
W
Wang Guibao 已提交
289
  queue_size_ = queue_size;
290
  queue_ = paddle::framework::MakeChannel<T>();
J
jiaqi 已提交
291
  queue_->SetCapacity(queue_size);
W
Wang Guibao 已提交
292 293 294 295
}

template <typename T>
bool PrivateQueueDataFeed<T>::Start() {
296
  VLOG(4) << "entering PrivateQueueDataFeed<T>::Start()";
W
Wang Guibao 已提交
297
  CheckSetFileList();
298 299
  read_thread_ = std::thread(&PrivateQueueDataFeed::ReadThread, this);
  read_thread_.detach();
W
Wang Guibao 已提交
300 301 302 303 304 305 306

  finish_start_ = true;
  return true;
}

template <typename T>
void PrivateQueueDataFeed<T>::ReadThread() {
D
dongdaxiang 已提交
307
#ifdef _LINUX
308
  VLOG(4) << "entering PrivateQueueDataFeed<T>::ReadThread()";
309 310 311
  std::string filename;
  while (PickOneFile(&filename)) {
    int err_no = 0;
312
    fp_ = fs_open_read(filename, &err_no, pipe_command_, true);
313 314 315
    __fsetlocking(&*fp_, FSETLOCKING_BYCALLER);
    T instance;
    while (ParseOneInstanceFromPipe(&instance)) {
316
      queue_->Put(instance);
317
    }
W
Wang Guibao 已提交
318
  }
319
  queue_->Close();
D
dongdaxiang 已提交
320
#endif
W
Wang Guibao 已提交
321 322 323 324
}

template <typename T>
int PrivateQueueDataFeed<T>::Next() {
X
xjqbest 已提交
325
#ifdef _LINUX
W
Wang Guibao 已提交
326 327 328 329
  CheckStart();
  int index = 0;
  T ins_vec;
  while (index < default_batch_size_) {
330 331
    T instance;
    if (!queue_->Get(instance)) {
W
Wang Guibao 已提交
332 333 334 335 336 337 338 339 340
      break;
    }
    AddInstanceToInsVec(&ins_vec, instance, index++);
  }
  batch_size_ = index;
  if (batch_size_ != 0) {
    PutToFeedVec(ins_vec);
  }
  return batch_size_;
X
xjqbest 已提交
341 342 343
#else
  return 0;
#endif
W
Wang Guibao 已提交
344 345
}

346
// explicit instantiation
W
Wang Guibao 已提交
347 348
template class PrivateQueueDataFeed<std::vector<MultiSlotType>>;

349 350
template <typename T>
InMemoryDataFeed<T>::InMemoryDataFeed() {
351 352
  this->file_idx_ = nullptr;
  this->mutex_for_pick_file_ = nullptr;
J
jiaqi 已提交
353 354 355
  this->fp_ = nullptr;
  this->thread_id_ = 0;
  this->thread_num_ = 1;
356
  this->parse_ins_id_ = false;
357
  this->parse_uid_ = false;
358
  this->parse_content_ = false;
359 360 361
  this->parse_logkey_ = false;
  this->enable_pv_merge_ = false;
  this->current_phase_ = 1;  // 1:join ;0:update
J
jiaqi 已提交
362 363 364
  this->input_channel_ = nullptr;
  this->output_channel_ = nullptr;
  this->consume_channel_ = nullptr;
365 366 367 368
}

template <typename T>
bool InMemoryDataFeed<T>::Start() {
X
xjqbest 已提交
369
#ifdef _LINUX
370
  VLOG(4) << "entering InMemoryDataFeed<T>::Start()";
J
jiaqi 已提交
371 372 373 374 375
  this->CheckSetFileList();
  if (output_channel_->Size() == 0 && input_channel_->Size() != 0) {
    std::vector<T> data;
    input_channel_->Read(data);
    output_channel_->Write(std::move(data));
376
  }
X
xjqbest 已提交
377
#endif
378
  if (!batch_offsets_.empty()) {
Y
yaoxuefeng 已提交
379 380 381 382
    VLOG(3) << "batch_size offsets: " << batch_offsets_.size();
    enable_heterps_ = true;
    this->offset_index_ = 0;
  }
J
jiaqi 已提交
383
  this->finish_start_ = true;
384 385 386 387 388
  return true;
}

template <typename T>
int InMemoryDataFeed<T>::Next() {
X
xjqbest 已提交
389
#ifdef _LINUX
J
jiaqi 已提交
390
  this->CheckStart();
Y
yaoxuefeng 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  if (!enable_heterps_) {
    CHECK(output_channel_ != nullptr);
    CHECK(consume_channel_ != nullptr);
    VLOG(3) << "output_channel_ size=" << output_channel_->Size()
            << ", consume_channel_ size=" << consume_channel_->Size()
            << ", thread_id=" << thread_id_;
    int index = 0;
    T instance;
    std::vector<T> ins_vec;
    ins_vec.reserve(this->default_batch_size_);
    while (index < this->default_batch_size_) {
      if (output_channel_->Size() == 0) {
        break;
      }
      output_channel_->Get(instance);
      ins_vec.push_back(instance);
      ++index;
      consume_channel_->Put(std::move(instance));
    }
    this->batch_size_ = index;
    VLOG(3) << "batch_size_=" << this->batch_size_
            << ", thread_id=" << thread_id_;
    if (this->batch_size_ != 0) {
      PutToFeedVec(ins_vec);
    } else {
      VLOG(3) << "finish reading, output_channel_ size="
              << output_channel_->Size()
              << ", consume_channel_ size=" << consume_channel_->Size()
              << ", thread_id=" << thread_id_;
420
    }
D
dongdaxiang 已提交
421
  } else {
Y
yaoxuefeng 已提交
422
    VLOG(3) << "enable heter next: " << offset_index_
Y
yaoxuefeng 已提交
423 424 425 426 427 428 429 430 431
            << " batch_offsets: " << batch_offsets_.size();
    if (offset_index_ >= batch_offsets_.size()) {
      VLOG(3) << "offset_index: " << offset_index_
              << " batch_offsets: " << batch_offsets_.size();
      return 0;
    }
    auto& batch = batch_offsets_[offset_index_++];
    this->batch_size_ = batch.second;
    VLOG(3) << "batch_size_=" << this->batch_size_
J
jiaqi 已提交
432
            << ", thread_id=" << thread_id_;
Y
yaoxuefeng 已提交
433 434 435 436 437 438
    if (this->batch_size_ != 0) {
      PutToFeedVec(&records_[batch.first], this->batch_size_);
    } else {
      VLOG(3) << "finish reading for heterps, batch size zero, thread_id="
              << thread_id_;
    }
Y
yaoxuefeng 已提交
439
    VLOG(3) << "enable heter next: " << offset_index_
Y
yaoxuefeng 已提交
440 441
            << " batch_offsets: " << batch_offsets_.size()
            << " baych_size: " << this->batch_size_;
D
dongdaxiang 已提交
442
  }
J
jiaqi 已提交
443
  return this->batch_size_;
X
xjqbest 已提交
444 445 446
#else
  return 0;
#endif
447 448
}

449
template <typename T>
J
jiaqi 已提交
450 451 452 453 454 455 456
void InMemoryDataFeed<T>::SetInputChannel(void* channel) {
  input_channel_ = static_cast<paddle::framework::ChannelObject<T>*>(channel);
}

template <typename T>
void InMemoryDataFeed<T>::SetOutputChannel(void* channel) {
  output_channel_ = static_cast<paddle::framework::ChannelObject<T>*>(channel);
457 458 459
}

template <typename T>
J
jiaqi 已提交
460 461
void InMemoryDataFeed<T>::SetConsumeChannel(void* channel) {
  consume_channel_ = static_cast<paddle::framework::ChannelObject<T>*>(channel);
462 463
}

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
template <typename T>
void InMemoryDataFeed<T>::SetInputPvChannel(void* channel) {
  input_pv_channel_ =
      static_cast<paddle::framework::ChannelObject<PvInstance>*>(channel);
}

template <typename T>
void InMemoryDataFeed<T>::SetOutputPvChannel(void* channel) {
  output_pv_channel_ =
      static_cast<paddle::framework::ChannelObject<PvInstance>*>(channel);
}

template <typename T>
void InMemoryDataFeed<T>::SetConsumePvChannel(void* channel) {
  consume_pv_channel_ =
      static_cast<paddle::framework::ChannelObject<PvInstance>*>(channel);
}

482 483 484 485 486 487 488 489 490 491
template <typename T>
void InMemoryDataFeed<T>::SetThreadId(int thread_id) {
  thread_id_ = thread_id;
}

template <typename T>
void InMemoryDataFeed<T>::SetThreadNum(int thread_num) {
  thread_num_ = thread_num;
}

492 493 494 495 496
template <typename T>
void InMemoryDataFeed<T>::SetParseContent(bool parse_content) {
  parse_content_ = parse_content;
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
template <typename T>
void InMemoryDataFeed<T>::SetParseLogKey(bool parse_logkey) {
  parse_logkey_ = parse_logkey;
}

template <typename T>
void InMemoryDataFeed<T>::SetEnablePvMerge(bool enable_pv_merge) {
  enable_pv_merge_ = enable_pv_merge;
}

template <typename T>
void InMemoryDataFeed<T>::SetCurrentPhase(int current_phase) {
  current_phase_ = current_phase;
}

512 513 514 515 516
template <typename T>
void InMemoryDataFeed<T>::SetParseInsId(bool parse_ins_id) {
  parse_ins_id_ = parse_ins_id;
}

517 518 519 520 521
template <typename T>
void InMemoryDataFeed<T>::SetParseUid(bool parse_uid) {
  parse_uid_ = parse_uid;
}

522 523
template <typename T>
void InMemoryDataFeed<T>::LoadIntoMemory() {
D
dongdaxiang 已提交
524
#ifdef _LINUX
T
Thunderbrook 已提交
525 526 527 528
  if (!so_parser_name_.empty()) {
    LoadIntoMemoryFromSo();
    return;
  }
X
xujiaqi01 已提交
529
  VLOG(3) << "LoadIntoMemory() begin, thread_id=" << thread_id_;
530
  std::string filename;
J
jiaqi 已提交
531
  while (this->PickOneFile(&filename)) {
X
xujiaqi01 已提交
532 533
    VLOG(3) << "PickOneFile, filename=" << filename
            << ", thread_id=" << thread_id_;
H
hutuxian 已提交
534 535 536 537 538 539 540
#ifdef PADDLE_WITH_BOX_PS
    if (BoxWrapper::GetInstance()->UseAfsApi()) {
      this->fp_ = BoxWrapper::GetInstance()->afs_manager->GetFile(
          filename, this->pipe_command_);
    } else {
#endif
      int err_no = 0;
541
      this->fp_ = fs_open_read(filename, &err_no, this->pipe_command_, true);
H
hutuxian 已提交
542 543 544
#ifdef PADDLE_WITH_BOX_PS
    }
#endif
J
jiaqi 已提交
545 546 547
    CHECK(this->fp_ != nullptr);
    __fsetlocking(&*(this->fp_), FSETLOCKING_BYCALLER);
    paddle::framework::ChannelWriter<T> writer(input_channel_);
548
    T instance;
549 550
    platform::Timer timeline;
    timeline.Start();
D
dongdaxiang 已提交
551
    while (ParseOneInstanceFromPipe(&instance)) {
J
jiaqi 已提交
552 553
      writer << std::move(instance);
      instance = T();
554
    }
H
hutuxian 已提交
555 556 557 558 559 560
    STAT_ADD(STAT_total_feasign_num_in_mem, fea_num_);
    {
      std::lock_guard<std::mutex> flock(*mutex_for_fea_num_);
      *total_fea_num_ += fea_num_;
      fea_num_ = 0;
    }
J
jiaqi 已提交
561
    writer.Flush();
562
    timeline.Pause();
563 564
    VLOG(3) << "LoadIntoMemory() read all lines, file=" << filename
            << ", cost time=" << timeline.ElapsedSec()
565
            << " seconds, thread_id=" << thread_id_;
566
  }
X
xujiaqi01 已提交
567
  VLOG(3) << "LoadIntoMemory() end, thread_id=" << thread_id_;
D
dongdaxiang 已提交
568
#endif
569 570
}

T
Thunderbrook 已提交
571 572
template <typename T>
void InMemoryDataFeed<T>::LoadIntoMemoryFromSo() {
T
Thunderbrook 已提交
573 574
#if (defined _LINUX) && (defined PADDLE_WITH_HETERPS) && \
    (defined PADDLE_WITH_PSLIB)
T
Thunderbrook 已提交
575
  VLOG(3) << "LoadIntoMemoryFromSo() begin, thread_id=" << thread_id_;
T
Thunderbrook 已提交
576
  int buf_len = 1024 * 1024 * 10;
577
  char* buf = reinterpret_cast<char*>(malloc(buf_len + 10));
T
Thunderbrook 已提交
578
  auto ps_gpu_ptr = PSGPUWrapper::GetInstance();
T
Thunderbrook 已提交
579 580 581 582 583 584 585 586 587 588

  paddle::framework::CustomParser* parser =
      global_dlmanager_pool().Load(so_parser_name_, slot_conf_);

  std::string filename;
  while (this->PickOneFile(&filename)) {
    VLOG(3) << "PickOneFile, filename=" << filename
            << ", thread_id=" << thread_id_;
    platform::Timer timeline;
    timeline.Start();
T
Thunderbrook 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    if (ps_gpu_ptr->UseAfsApi()) {
      auto afs_reader = ps_gpu_ptr->OpenReader(filename);
      int read_len = 0;
      char* cursor = buf;
      int remain = 0;
      while ((read_len = afs_reader->read(cursor, buf_len - remain)) > 0) {
        std::vector<T> instances;
        read_len += remain;
        remain = ParseInstanceFromSo(read_len, buf, &instances, parser);
        input_channel_->Write(std::move(instances));
        instances = std::vector<T>();
        if (remain) {
          memmove(buf, buf + read_len - remain, remain);
        }
        cursor = buf + remain;
T
Thunderbrook 已提交
604
      }
T
Thunderbrook 已提交
605 606
    } else {
      VLOG(0) << "Should Call InitAfsApi First";
T
Thunderbrook 已提交
607 608 609 610 611 612 613
    }

    timeline.Pause();
    VLOG(3) << "LoadIntoMemoryFromSo() read all lines, file=" << filename
            << ", cost time=" << timeline.ElapsedSec()
            << " seconds, thread_id=" << thread_id_;
  }
T
Thunderbrook 已提交
614
  free(buf);
T
Thunderbrook 已提交
615 616 617 618
  VLOG(3) << "LoadIntoMemoryFromSo() end, thread_id=" << thread_id_;
#endif
}

619
// explicit instantiation
J
jiaqi 已提交
620
template class InMemoryDataFeed<Record>;
621

W
Wang Guibao 已提交
622 623 624 625 626 627
void MultiSlotDataFeed::Init(
    const paddle::framework::DataFeedDesc& data_feed_desc) {
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;

628
  PADDLE_ENFORCE_EQ(
629 630
      data_feed_desc.has_multi_slot_desc(),
      true,
631 632
      platform::errors::PreconditionNotMet(
          "Multi_slot_desc has not been set in MultiSlotDataFeed."));
W
Wang Guibao 已提交
633 634 635
  paddle::framework::MultiSlotDesc multi_slot_desc =
      data_feed_desc.multi_slot_desc();
  SetBatchSize(data_feed_desc.batch_size());
J
jiaqi 已提交
636 637
  // temporarily set queue size = batch size * 100
  SetQueueSize(data_feed_desc.batch_size() * 100);
W
Wang Guibao 已提交
638 639 640 641
  size_t all_slot_num = multi_slot_desc.slots_size();
  all_slots_.resize(all_slot_num);
  all_slots_type_.resize(all_slot_num);
  use_slots_index_.resize(all_slot_num);
642 643
  total_dims_without_inductive_.resize(all_slot_num);
  inductive_shape_index_.resize(all_slot_num);
W
Wang Guibao 已提交
644 645 646 647 648 649 650
  use_slots_.clear();
  use_slots_is_dense_.clear();
  for (size_t i = 0; i < all_slot_num; ++i) {
    const auto& slot = multi_slot_desc.slots(i);
    all_slots_[i] = slot.name();
    all_slots_type_[i] = slot.type();
    use_slots_index_[i] = slot.is_used() ? use_slots_.size() : -1;
651 652
    total_dims_without_inductive_[i] = 1;
    inductive_shape_index_[i] = -1;
W
Wang Guibao 已提交
653 654 655
    if (slot.is_used()) {
      use_slots_.push_back(all_slots_[i]);
      use_slots_is_dense_.push_back(slot.is_dense());
656 657
      std::vector<int> local_shape;
      if (slot.is_dense()) {
658
        for (int j = 0; j < slot.shape_size(); ++j) {
659 660
          if (slot.shape(j) > 0) {
            total_dims_without_inductive_[i] *= slot.shape(j);
661
          }
662 663
          if (slot.shape(j) == -1) {
            inductive_shape_index_[i] = j;
664
          }
665 666
        }
      }
667
      for (int j = 0; j < slot.shape_size(); ++j) {
668
        local_shape.push_back(slot.shape(j));
669 670
      }
      use_slots_shape_.push_back(local_shape);
W
Wang Guibao 已提交
671 672 673
    }
  }
  feed_vec_.resize(use_slots_.size());
674
  pipe_command_ = data_feed_desc.pipe_command();
W
Wang Guibao 已提交
675 676 677
  finish_init_ = true;
}

D
dongdaxiang 已提交
678
void MultiSlotDataFeed::ReadThread() {
679
#ifdef _LINUX
680
  VLOG(4) << "entering MultiSlotDataFeed::ReadThread()";
681 682 683
  std::string filename;
  while (PickOneFile(&filename)) {
    int err_no = 0;
684
    fp_ = fs_open_read(filename, &err_no, pipe_command_, true);
D
dongdaxiang 已提交
685
    CHECK(fp_ != nullptr);
686 687 688 689 690
    __fsetlocking(&*fp_, FSETLOCKING_BYCALLER);
    std::vector<MultiSlotType> instance;
    int ins_num = 0;
    while (ParseOneInstanceFromPipe(&instance)) {
      ins_num++;
691
      queue_->Put(instance);
692
    }
D
dongdaxiang 已提交
693
    VLOG(3) << "filename: " << filename << " inst num: " << ins_num;
D
dongdaxiang 已提交
694
  }
695
  queue_->Close();
696
#endif
D
dongdaxiang 已提交
697 698
}

W
Wang Guibao 已提交
699
bool MultiSlotDataFeed::CheckFile(const char* filename) {
700
#ifdef _LINUX
W
Wang Guibao 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
  CheckInit();  // get info of slots
  std::ifstream fin(filename);
  if (!fin.good()) {
    VLOG(1) << "error: open file<" << filename << "> fail";
    return false;
  }
  std::string line;
  int instance_cout = 0;
  std::string all_slots_alias = "";
  for (const auto& alias : all_slots_) {
    all_slots_alias += alias + " ";
  }
  std::string use_slots_alias = "";
  for (const auto& alias : use_slots_) {
    use_slots_alias += alias + " ";
  }
  VLOG(3) << "total slots num: " << all_slots_.size();
  VLOG(3) << "total slots alias: " << all_slots_alias;
  VLOG(3) << "used slots num: " << use_slots_.size();
  VLOG(3) << "used slots alias: " << use_slots_alias;
  while (getline(fin, line)) {
    ++instance_cout;
    const char* str = line.c_str();
    char* endptr = const_cast<char*>(str);
    int len = line.length();
    for (size_t i = 0; i < all_slots_.size(); ++i) {
X
xjqbest 已提交
727
      auto num = strtol(endptr, &endptr, 10);
W
Wang Guibao 已提交
728
      if (num < 0) {
729 730
        VLOG(0) << "error: the number of ids is a negative number: " << num;
        VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
731
                << filename << ">";
732
        VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
733
                << " th slot with total slots number: " << all_slots_.size();
W
Wang Guibao 已提交
734 735
        return false;
      } else if (num == 0) {
736
        VLOG(0)
W
Wang Guibao 已提交
737 738 739 740
            << "error: the number of ids can not be zero, you need "
               "padding it in data generator; or if there is something wrong"
               " with the data, please check if the data contains unresolvable "
               "characters.";
741
        VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
742
                << filename << ">";
743
        VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
744
                << " th slot with total slots number: " << all_slots_.size();
W
Wang Guibao 已提交
745
        return false;
X
xjqbest 已提交
746
      } else if (errno == ERANGE || num > INT_MAX) {
747 748
        VLOG(0) << "error: the number of ids greater than INT_MAX";
        VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
749
                << filename << ">";
750
        VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
751
                << " th slot with total slots number: " << all_slots_.size();
W
Wang Guibao 已提交
752 753 754
        return false;
      }
      if (all_slots_type_[i] == "float") {
Y
yaoxuefeng 已提交
755
        for (int j = 0; j < num; ++j) {
W
Wang Guibao 已提交
756 757
          strtof(endptr, &endptr);
          if (errno == ERANGE) {
758
            VLOG(0) << "error: the value is out of the range of "
W
Wang Guibao 已提交
759
                       "representable values for float";
760
            VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
761
                    << filename << ">";
762
            VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
763 764 765 766
                    << " th slot with total slots number: "
                    << all_slots_.size();
            VLOG(0) << "and in this slot: " << j
                    << " th id with total id number: " << num;
W
Wang Guibao 已提交
767 768
            return false;
          }
Y
yaoxuefeng 已提交
769
          if (j + 1 != num && endptr - str == len) {
770
            VLOG(0) << "error: there is a wrong with the number of ids.";
771
            VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
772 773 774 775
                    << " th slot with total slots number: "
                    << all_slots_.size();
            VLOG(0) << "and in this slot: " << j
                    << " th id with total id number: " << num;
776
            VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
777 778 779 780 781
                    << filename << ">";
            return false;
          }
        }
      } else if (all_slots_type_[i] == "uint64") {
Y
yaoxuefeng 已提交
782
        for (int j = 0; j < num; ++j) {
W
Wang Guibao 已提交
783 784
          strtoull(endptr, &endptr, 10);
          if (errno == ERANGE) {
785
            VLOG(0) << "error: the value is out of the range of "
W
Wang Guibao 已提交
786
                       "representable values for uint64_t";
787
            VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
788 789 790 791
                    << " th slot with total slots number: "
                    << all_slots_.size();
            VLOG(0) << "and in this slot: " << j
                    << " th id with total id number: " << num;
792
            VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
793 794 795
                    << filename << ">";
            return false;
          }
Y
yaoxuefeng 已提交
796
          if (j + 1 != num && endptr - str == len) {
797
            VLOG(0) << "error: there is a wrong with the number of ids.";
798
            VLOG(0) << "Error occurred when parsing " << i
Y
yaoxuefeng 已提交
799 800 801 802
                    << " th slot with total slots number: "
                    << all_slots_.size();
            VLOG(0) << "and in this slot: " << j
                    << " th id with total id number: " << num;
803
            VLOG(0) << "please check line<" << instance_cout << "> in file<"
W
Wang Guibao 已提交
804 805 806 807 808
                    << filename << ">";
            return false;
          }
        }
      } else {
809
        VLOG(0) << "error: this type<" << all_slots_type_[i]
W
Wang Guibao 已提交
810 811 812 813
                << "> is not supported";
        return false;
      }
    }
814 815 816
    // It may be added '\t' character to the end of the output of reduce
    // task when processes data by Hadoop(when the output of the reduce
    // task of Hadoop has only one field, it will add a '\t' at the end
817 818 819 820 821
    // of the line by default, and you can use this option to avoid it:
    // `-D mapred.textoutputformat.ignoreseparator=true`), which does
    // not affect the correctness of the data. Therefore, it should be
    // judged that the data is not normal when the end of each line of
    // data contains characters which are not spaces.
822 823 824 825 826 827 828 829
    while (endptr - str != len) {
      if (!isspace(*(endptr++))) {
        VLOG(0)
            << "error: there is some extra characters at the end of the line.";
        VLOG(0) << "please check line<" << instance_cout << "> in file<"
                << filename << ">";
        return false;
      }
W
Wang Guibao 已提交
830 831 832 833
    }
  }
  VLOG(3) << "instances cout: " << instance_cout;
  VLOG(3) << "The file format is correct";
834
#endif
W
Wang Guibao 已提交
835 836 837
  return true;
}

D
dongdaxiang 已提交
838 839
bool MultiSlotDataFeed::ParseOneInstanceFromPipe(
    std::vector<MultiSlotType>* instance) {
840
#ifdef _LINUX
841 842 843
  thread_local string::LineFileReader reader;

  if (!reader.getline(&*(fp_.get()))) {
D
dongdaxiang 已提交
844 845
    return false;
  } else {
846 847
    int use_slots_num = use_slots_.size();
    instance->resize(use_slots_num);
D
dongdaxiang 已提交
848 849
    const char* str = reader.get();
    std::string line = std::string(str);
T
tangwei12 已提交
850

D
dongdaxiang 已提交
851 852 853 854 855
    char* endptr = const_cast<char*>(str);
    int pos = 0;
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      int num = strtol(&str[pos], &endptr, 10);
T
tangwei12 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

      if (num <= 0) {
        std::stringstream ss;
        ss << "\n\nGot unexpected input, maybe something wrong with it.\n";
        ss << "\n----------------------\n";
        ss << "The Origin Input Data:\n";
        ss << "----------------------\n";

        ss << line << "\n";

        ss << "\n----------------------\n";
        ss << "Some Possible Errors:\n";
        ss << "----------------------\n";
        ss << "1. The number of ids can not be zero, you need padding.\n";
        ss << "2. The input data contains unresolvable characters.\n";
        ss << "3. We detect the slot " << i << "'s feasign number is " << num
           << " which is illegal.\n";
        ss << "\n";

        PADDLE_THROW(platform::errors::InvalidArgument(ss.str()));
      }

D
dongdaxiang 已提交
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
      if (idx != -1) {
        (*instance)[idx].Init(all_slots_type_[i]);
        if ((*instance)[idx].GetType()[0] == 'f') {  // float
          for (int j = 0; j < num; ++j) {
            float feasign = strtof(endptr, &endptr);
            (*instance)[idx].AddValue(feasign);
          }
        } else if ((*instance)[idx].GetType()[0] == 'u') {  // uint64
          for (int j = 0; j < num; ++j) {
            uint64_t feasign = (uint64_t)strtoull(endptr, &endptr, 10);
            (*instance)[idx].AddValue(feasign);
          }
        }
        pos = endptr - str;
      } else {
        for (int j = 0; j <= num; ++j) {
D
dongdaxiang 已提交
894 895 896 897
          // pos = line.find_first_of(' ', pos + 1);
          while (line[pos + 1] != ' ') {
            pos++;
          }
D
dongdaxiang 已提交
898 899 900 901 902
        }
      }
    }
    return true;
  }
903 904 905
#else
  return true;
#endif
D
dongdaxiang 已提交
906 907
}

W
Wang Guibao 已提交
908
bool MultiSlotDataFeed::ParseOneInstance(std::vector<MultiSlotType>* instance) {
X
xjqbest 已提交
909
#ifdef _LINUX
W
Wang Guibao 已提交
910 911 912 913 914 915 916 917 918 919 920
  std::string line;
  if (getline(file_, line)) {
    int use_slots_num = use_slots_.size();
    instance->resize(use_slots_num);
    // parse line
    const char* str = line.c_str();
    char* endptr = const_cast<char*>(str);
    int pos = 0;
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      int num = strtol(&str[pos], &endptr, 10);
921
      PADDLE_ENFORCE_NE(
922 923
          num,
          0,
924 925 926 927
          platform::errors::InvalidArgument(
              "The number of ids can not be zero, you need padding "
              "it in data generator; or if there is something wrong with "
              "the data, please check if the data contains unresolvable "
Y
yaoxuefeng 已提交
928 929 930
              "characters.\nplease check this error line: %s, \n Specifically, "
              "something wrong happened(the length of this slot's feasign is 0)"
              "when we parse the %d th slots."
Y
yaoxuefeng 已提交
931
              "Maybe something wrong around this slot"
Y
yaoxuefeng 已提交
932 933
              "\nWe detect the feasign number of this slot is %d, "
              "which is illegal.",
934 935 936
              str,
              i,
              num));
937

W
Wang Guibao 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
      if (idx != -1) {
        (*instance)[idx].Init(all_slots_type_[i]);
        if ((*instance)[idx].GetType()[0] == 'f') {  // float
          for (int j = 0; j < num; ++j) {
            float feasign = strtof(endptr, &endptr);
            (*instance)[idx].AddValue(feasign);
          }
        } else if ((*instance)[idx].GetType()[0] == 'u') {  // uint64
          for (int j = 0; j < num; ++j) {
            uint64_t feasign = (uint64_t)strtoull(endptr, &endptr, 10);
            (*instance)[idx].AddValue(feasign);
          }
        }
        pos = endptr - str;
      } else {
        for (int j = 0; j <= num; ++j) {
          pos = line.find_first_of(' ', pos + 1);
        }
      }
    }
  } else {
    return false;
  }
X
xjqbest 已提交
961 962
#endif
  return false;
W
Wang Guibao 已提交
963 964 965 966
}

void MultiSlotDataFeed::AddInstanceToInsVec(
    std::vector<MultiSlotType>* ins_vec,
967 968
    const std::vector<MultiSlotType>& instance,
    int index) {
X
xjqbest 已提交
969
#ifdef _LINUX
W
Wang Guibao 已提交
970 971 972 973 974 975 976
  if (index == 0) {
    ins_vec->resize(instance.size());
    for (size_t i = 0; i < instance.size(); ++i) {
      (*ins_vec)[i].Init(instance[i].GetType());
      (*ins_vec)[i].InitOffset();
    }
  }
977

W
Wang Guibao 已提交
978 979 980
  for (size_t i = 0; i < instance.size(); ++i) {
    (*ins_vec)[i].AddIns(instance[i]);
  }
X
xjqbest 已提交
981
#endif
W
Wang Guibao 已提交
982 983 984 985
}

void MultiSlotDataFeed::PutToFeedVec(
    const std::vector<MultiSlotType>& ins_vec) {
X
xjqbest 已提交
986
#ifdef _LINUX
W
Wang Guibao 已提交
987
  for (size_t i = 0; i < use_slots_.size(); ++i) {
988 989 990
    if (feed_vec_[i] == nullptr) {
      continue;
    }
991
    VLOG(4) << "MultiSlotDataFeed::PutToFeedVec i: " << i;
W
Wang Guibao 已提交
992 993 994
    const auto& type = ins_vec[i].GetType();
    const auto& offset = ins_vec[i].GetOffset();
    int total_instance = static_cast<int>(offset.back());
995 996 997
    VLOG(4) << "total_instance: " << total_instance;
    // platform::CPUPlace()
    VLOG(4) << "this->place_: " << this->place_;
W
Wang Guibao 已提交
998 999
    if (type[0] == 'f') {  // float
      const auto& feasign = ins_vec[i].GetFloatData();
1000 1001 1002
      float* tensor_ptr =
          feed_vec_[i]->mutable_data<float>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, &feasign[0], total_instance * sizeof(float));
W
Wang Guibao 已提交
1003 1004 1005
    } else if (type[0] == 'u') {  // uint64
      // no uint64_t type in paddlepaddle
      const auto& feasign = ins_vec[i].GetUint64Data();
1006
      int64_t* tensor_ptr = feed_vec_[i]->mutable_data<int64_t>(
1007
          {total_instance, 1}, this->place_);
1008 1009
      CopyToFeedTensor(
          tensor_ptr, &feasign[0], total_instance * sizeof(int64_t));
1010
    }
1011

W
wangguanqun 已提交
1012 1013 1014 1015
    if (!use_slots_is_dense_[i]) {
      LoD data_lod{offset};
      feed_vec_[i]->set_lod(data_lod);
    }
1016
    if (use_slots_is_dense_[i]) {
1017 1018 1019 1020
      if (inductive_shape_index_[i] != -1) {
        use_slots_shape_[i][inductive_shape_index_[i]] =
            total_instance / total_dims_without_inductive_[i];
      }
1021
      feed_vec_[i]->Resize(phi::make_ddim(use_slots_shape_[i]));
W
Wang Guibao 已提交
1022 1023
    }
  }
X
xjqbest 已提交
1024
#endif
W
Wang Guibao 已提交
1025 1026
}

1027 1028 1029 1030 1031 1032
void MultiSlotInMemoryDataFeed::Init(
    const paddle::framework::DataFeedDesc& data_feed_desc) {
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;

1033
  PADDLE_ENFORCE_EQ(
1034 1035
      data_feed_desc.has_multi_slot_desc(),
      true,
1036 1037
      platform::errors::PreconditionNotMet(
          "Multi_slot_desc has not been set in MultiSlotInMemoryDataFeed."));
1038 1039 1040 1041 1042 1043 1044
  paddle::framework::MultiSlotDesc multi_slot_desc =
      data_feed_desc.multi_slot_desc();
  SetBatchSize(data_feed_desc.batch_size());
  size_t all_slot_num = multi_slot_desc.slots_size();
  all_slots_.resize(all_slot_num);
  all_slots_type_.resize(all_slot_num);
  use_slots_index_.resize(all_slot_num);
1045 1046
  total_dims_without_inductive_.resize(all_slot_num);
  inductive_shape_index_.resize(all_slot_num);
1047 1048
  use_slots_.clear();
  use_slots_is_dense_.clear();
T
Thunderbrook 已提交
1049
  slot_conf_.resize(all_slot_num);
1050 1051 1052 1053 1054
  for (size_t i = 0; i < all_slot_num; ++i) {
    const auto& slot = multi_slot_desc.slots(i);
    all_slots_[i] = slot.name();
    all_slots_type_[i] = slot.type();
    use_slots_index_[i] = slot.is_used() ? use_slots_.size() : -1;
T
Thunderbrook 已提交
1055 1056 1057 1058 1059

    slot_conf_[i].name = slot.name();
    slot_conf_[i].type = slot.type();
    slot_conf_[i].use_slots_index = use_slots_index_[i];

1060 1061
    total_dims_without_inductive_[i] = 1;
    inductive_shape_index_[i] = -1;
1062 1063 1064
    if (slot.is_used()) {
      use_slots_.push_back(all_slots_[i]);
      use_slots_is_dense_.push_back(slot.is_dense());
T
Thunderbrook 已提交
1065
      slot_conf_[i].use_slots_is_dense = slot.is_dense();
1066 1067
      std::vector<int> local_shape;
      if (slot.is_dense()) {
1068
        for (int j = 0; j < slot.shape_size(); ++j) {
1069 1070
          if (slot.shape(j) > 0) {
            total_dims_without_inductive_[i] *= slot.shape(j);
1071
          }
1072 1073
          if (slot.shape(j) == -1) {
            inductive_shape_index_[i] = j;
1074
          }
1075 1076
        }
      }
1077
      for (int j = 0; j < slot.shape_size(); ++j) {
1078
        local_shape.push_back(slot.shape(j));
1079 1080
      }
      use_slots_shape_.push_back(local_shape);
1081 1082
    }
  }
1083
  uid_slot_ = multi_slot_desc.uid_slot();
1084
  feed_vec_.resize(use_slots_.size());
H
hutuxian 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  const int kEstimatedFeasignNumPerSlot = 5;  // Magic Number
  for (size_t i = 0; i < all_slot_num; i++) {
    batch_float_feasigns_.push_back(std::vector<float>());
    batch_uint64_feasigns_.push_back(std::vector<uint64_t>());
    batch_float_feasigns_[i].reserve(default_batch_size_ *
                                     kEstimatedFeasignNumPerSlot);
    batch_uint64_feasigns_[i].reserve(default_batch_size_ *
                                      kEstimatedFeasignNumPerSlot);
    offset_.push_back(std::vector<size_t>());
    offset_[i].reserve(default_batch_size_ +
                       1);  // Each lod info will prepend a zero
  }
  visit_.resize(all_slot_num, false);
1098
  pipe_command_ = data_feed_desc.pipe_command();
T
Thunderbrook 已提交
1099
  so_parser_name_ = data_feed_desc.so_parser_name();
1100
  finish_init_ = true;
1101
  input_type_ = data_feed_desc.input_type();
1102 1103
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
void MultiSlotInMemoryDataFeed::GetMsgFromLogKey(const std::string& log_key,
                                                 uint64_t* search_id,
                                                 uint32_t* cmatch,
                                                 uint32_t* rank) {
  std::string searchid_str = log_key.substr(16, 16);
  *search_id = (uint64_t)strtoull(searchid_str.c_str(), NULL, 16);

  std::string cmatch_str = log_key.substr(11, 3);
  *cmatch = (uint32_t)strtoul(cmatch_str.c_str(), NULL, 16);

  std::string rank_str = log_key.substr(14, 2);
  *rank = (uint32_t)strtoul(rank_str.c_str(), NULL, 16);
}

T
Thunderbrook 已提交
1118
int MultiSlotInMemoryDataFeed::ParseInstanceFromSo(
1119 1120 1121
    int len,
    const char* str,
    std::vector<Record>* instances,
T
Thunderbrook 已提交
1122 1123 1124
    CustomParser* parser) {
  // VLOG(0) << "parser: " << parser;
  return parser->ParseInstance(len, str, instances);
T
Thunderbrook 已提交
1125 1126
}

J
jiaqi 已提交
1127
bool MultiSlotInMemoryDataFeed::ParseOneInstanceFromPipe(Record* instance) {
X
xjqbest 已提交
1128
#ifdef _LINUX
1129 1130 1131 1132 1133 1134 1135
  thread_local string::LineFileReader reader;

  if (!reader.getline(&*(fp_.get()))) {
    return false;
  } else {
    const char* str = reader.get();
    std::string line = std::string(str);
1136
    // VLOG(3) << line;
1137 1138
    char* endptr = const_cast<char*>(str);
    int pos = 0;
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    if (parse_ins_id_) {
      int num = strtol(&str[pos], &endptr, 10);
      CHECK(num == 1);  // NOLINT
      pos = endptr - str + 1;
      size_t len = 0;
      while (str[pos + len] != ' ') {
        ++len;
      }
      instance->ins_id_ = std::string(str + pos, len);
      pos += len + 1;
      VLOG(3) << "ins_id " << instance->ins_id_;
    }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    if (parse_content_) {
      int num = strtol(&str[pos], &endptr, 10);
      CHECK(num == 1);  // NOLINT
      pos = endptr - str + 1;
      size_t len = 0;
      while (str[pos + len] != ' ') {
        ++len;
      }
      instance->content_ = std::string(str + pos, len);
      pos += len + 1;
      VLOG(3) << "content " << instance->content_;
    }
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
    if (parse_logkey_) {
      int num = strtol(&str[pos], &endptr, 10);
      CHECK(num == 1);  // NOLINT
      pos = endptr - str + 1;
      size_t len = 0;
      while (str[pos + len] != ' ') {
        ++len;
      }
      // parse_logkey
      std::string log_key = std::string(str + pos, len);
      uint64_t search_id;
      uint32_t cmatch;
      uint32_t rank;
      GetMsgFromLogKey(log_key, &search_id, &cmatch, &rank);

H
hutuxian 已提交
1178
      instance->ins_id_ = log_key;
1179 1180 1181 1182 1183
      instance->search_id = search_id;
      instance->cmatch = cmatch;
      instance->rank = rank;
      pos += len + 1;
    }
1184 1185 1186
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      int num = strtol(&str[pos], &endptr, 10);
1187
      PADDLE_ENFORCE_NE(
1188 1189
          num,
          0,
1190 1191 1192 1193
          platform::errors::InvalidArgument(
              "The number of ids can not be zero, you need padding "
              "it in data generator; or if there is something wrong with "
              "the data, please check if the data contains unresolvable "
Y
yaoxuefeng 已提交
1194 1195 1196
              "characters.\nplease check this error line: %s, \n Specifically, "
              "something wrong happened(the length of this slot's feasign is 0)"
              "when we parse the %d th slots."
Y
yaoxuefeng 已提交
1197
              "Maybe something wrong around this slot"
Y
yaoxuefeng 已提交
1198 1199
              "\nWe detect the feasign number of this slot is %d, "
              "which is illegal.",
1200 1201 1202
              str,
              i,
              num));
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
#ifdef PADDLE_WITH_PSLIB
      if (parse_uid_ && all_slots_[i] == uid_slot_) {
        PADDLE_ENFORCE(num == 1 && all_slots_type_[i][0] == 'u',
                       platform::errors::PreconditionNotMet(
                           "The uid has to be uint64 and single.\n"
                           "please check this error line: %s",
                           str));

        char* uidptr = endptr;
        uint64_t feasign = (uint64_t)strtoull(uidptr, &uidptr, 10);
        instance->uid_ = feasign;
      }
#endif
1216
      if (idx != -1) {
J
jiaqi 已提交
1217
        if (all_slots_type_[i][0] == 'f') {  // float
1218 1219
          for (int j = 0; j < num; ++j) {
            float feasign = strtof(endptr, &endptr);
J
jiaqi 已提交
1220
            // if float feasign is equal to zero, ignore it
1221 1222
            // except when slot is dense
            if (fabs(feasign) < 1e-6 && !use_slots_is_dense_[i]) {
J
jiaqi 已提交
1223 1224
              continue;
            }
T
Thunderbrook 已提交
1225
            FeatureFeasign f;
J
jiaqi 已提交
1226 1227
            f.float_feasign_ = feasign;
            instance->float_feasigns_.push_back(FeatureItem(f, idx));
1228
          }
J
jiaqi 已提交
1229
        } else if (all_slots_type_[i][0] == 'u') {  // uint64
1230 1231
          for (int j = 0; j < num; ++j) {
            uint64_t feasign = (uint64_t)strtoull(endptr, &endptr, 10);
J
jiaqi 已提交
1232
            // if uint64 feasign is equal to zero, ignore it
1233 1234
            // except when slot is dense
            if (feasign == 0 && !use_slots_is_dense_[i]) {
J
jiaqi 已提交
1235 1236
              continue;
            }
T
Thunderbrook 已提交
1237
            FeatureFeasign f;
J
jiaqi 已提交
1238 1239
            f.uint64_feasign_ = feasign;
            instance->uint64_feasigns_.push_back(FeatureItem(f, idx));
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
          }
        }
        pos = endptr - str;
      } else {
        for (int j = 0; j <= num; ++j) {
          // pos = line.find_first_of(' ', pos + 1);
          while (line[pos + 1] != ' ') {
            pos++;
          }
        }
      }
    }
J
jiaqi 已提交
1252 1253
    instance->float_feasigns_.shrink_to_fit();
    instance->uint64_feasigns_.shrink_to_fit();
H
hutuxian 已提交
1254
    fea_num_ += instance->uint64_feasigns_.size();
1255 1256
    return true;
  }
X
xjqbest 已提交
1257 1258 1259
#else
  return false;
#endif
1260 1261
}

J
jiaqi 已提交
1262
bool MultiSlotInMemoryDataFeed::ParseOneInstance(Record* instance) {
X
xjqbest 已提交
1263
#ifdef _LINUX
1264 1265
  std::string line;
  if (getline(file_, line)) {
1266
    VLOG(3) << line;
1267 1268 1269 1270 1271 1272 1273
    // parse line
    const char* str = line.c_str();
    char* endptr = const_cast<char*>(str);
    int pos = 0;
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      int num = strtol(&str[pos], &endptr, 10);
1274
      PADDLE_ENFORCE_NE(
1275 1276
          num,
          0,
1277 1278 1279 1280
          platform::errors::InvalidArgument(
              "The number of ids can not be zero, you need padding "
              "it in data generator; or if there is something wrong with "
              "the data, please check if the data contains unresolvable "
Y
yaoxuefeng 已提交
1281 1282 1283
              "characters.\nplease check this error line: %s, \n Specifically, "
              "something wrong happened(the length of this slot's feasign is 0)"
              "when we parse the %d th slots."
Y
yaoxuefeng 已提交
1284
              "Maybe something wrong around this slot"
Y
yaoxuefeng 已提交
1285 1286
              "\nWe detect the feasign number of this slot is %d, "
              "which is illegal.",
1287 1288 1289
              str,
              i,
              num));
1290 1291

      if (idx != -1) {
J
jiaqi 已提交
1292
        if (all_slots_type_[i][0] == 'f') {  // float
1293 1294
          for (int j = 0; j < num; ++j) {
            float feasign = strtof(endptr, &endptr);
J
jiaqi 已提交
1295 1296 1297
            if (fabs(feasign) < 1e-6) {
              continue;
            }
T
Thunderbrook 已提交
1298
            FeatureFeasign f;
J
jiaqi 已提交
1299 1300
            f.float_feasign_ = feasign;
            instance->float_feasigns_.push_back(FeatureItem(f, idx));
1301
          }
J
jiaqi 已提交
1302
        } else if (all_slots_type_[i][0] == 'u') {  // uint64
1303 1304
          for (int j = 0; j < num; ++j) {
            uint64_t feasign = (uint64_t)strtoull(endptr, &endptr, 10);
J
jiaqi 已提交
1305 1306 1307
            if (feasign == 0) {
              continue;
            }
T
Thunderbrook 已提交
1308
            FeatureFeasign f;
J
jiaqi 已提交
1309 1310
            f.uint64_feasign_ = feasign;
            instance->uint64_feasigns_.push_back(FeatureItem(f, idx));
1311 1312 1313 1314 1315 1316 1317 1318 1319
          }
        }
        pos = endptr - str;
      } else {
        for (int j = 0; j <= num; ++j) {
          pos = line.find_first_of(' ', pos + 1);
        }
      }
    }
J
jiaqi 已提交
1320 1321 1322
    instance->float_feasigns_.shrink_to_fit();
    instance->uint64_feasigns_.shrink_to_fit();
    return true;
1323 1324 1325
  } else {
    return false;
  }
X
xjqbest 已提交
1326 1327
#endif
  return false;
1328 1329
}

Y
yaoxuefeng 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
void MultiSlotInMemoryDataFeed::PutToFeedVec(const Record* ins_vec, int num) {
#ifdef _LINUX
  for (size_t i = 0; i < batch_float_feasigns_.size(); ++i) {
    batch_float_feasigns_[i].clear();
    batch_uint64_feasigns_[i].clear();
    offset_[i].clear();
    offset_[i].push_back(0);
  }
  ins_content_vec_.clear();
  ins_content_vec_.reserve(num);
  ins_id_vec_.clear();
  ins_id_vec_.reserve(num);
  for (int i = 0; i < num; ++i) {
    auto& r = ins_vec[i];
    ins_id_vec_.push_back(r.ins_id_);
    ins_content_vec_.push_back(r.content_);
    for (auto& item : r.float_feasigns_) {
      batch_float_feasigns_[item.slot()].push_back(item.sign().float_feasign_);
      visit_[item.slot()] = true;
    }
    for (auto& item : r.uint64_feasigns_) {
      batch_uint64_feasigns_[item.slot()].push_back(
          item.sign().uint64_feasign_);
      visit_[item.slot()] = true;
    }
    for (size_t j = 0; j < use_slots_.size(); ++j) {
      const auto& type = all_slots_type_[j];
      if (visit_[j]) {
        visit_[j] = false;
      } else {
        // fill slot value with default value 0
        if (type[0] == 'f') {  // float
          batch_float_feasigns_[j].push_back(0.0);
        } else if (type[0] == 'u') {  // uint64
          batch_uint64_feasigns_[j].push_back(0);
        }
      }
      // get offset of this ins in this slot
      if (type[0] == 'f') {  // float
        offset_[j].push_back(batch_float_feasigns_[j].size());
      } else if (type[0] == 'u') {  // uint64
        offset_[j].push_back(batch_uint64_feasigns_[j].size());
      }
    }
  }

  for (size_t i = 0; i < use_slots_.size(); ++i) {
    if (feed_vec_[i] == nullptr) {
      continue;
    }
    int total_instance = offset_[i].back();
    const auto& type = all_slots_type_[i];
    if (type[0] == 'f') {  // float
      float* feasign = batch_float_feasigns_[i].data();
      float* tensor_ptr =
          feed_vec_[i]->mutable_data<float>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(float));
    } else if (type[0] == 'u') {  // uint64
      // no uint64_t type in paddlepaddle
      uint64_t* feasign = batch_uint64_feasigns_[i].data();
      int64_t* tensor_ptr = feed_vec_[i]->mutable_data<int64_t>(
          {total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(int64_t));
    }
    auto& slot_offset = offset_[i];
    if (this->input_type_ == 0) {
      LoD data_lod{slot_offset};
      feed_vec_[i]->set_lod(data_lod);
    } else if (this->input_type_ == 1) {
      if (!use_slots_is_dense_[i]) {
        std::vector<size_t> tmp_offset;
1401 1402
        PADDLE_ENFORCE_EQ(slot_offset.size(),
                          2,
Y
yaoxuefeng 已提交
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
                          platform::errors::InvalidArgument(
                              "In batch reader, the sparse tensor lod size "
                              "must be 2, but received %d.",
                              slot_offset.size()));
        const auto& max_size = slot_offset[1];
        tmp_offset.reserve(max_size + 1);
        for (unsigned int k = 0; k <= max_size; k++) {
          tmp_offset.emplace_back(k);
        }
        slot_offset = tmp_offset;
        LoD data_lod{slot_offset};
        feed_vec_[i]->set_lod(data_lod);
      }
    }
    if (use_slots_is_dense_[i]) {
      if (inductive_shape_index_[i] != -1) {
        use_slots_shape_[i][inductive_shape_index_[i]] =
            total_instance / total_dims_without_inductive_[i];
      }
1422
      feed_vec_[i]->Resize(phi::make_ddim(use_slots_shape_[i]));
Y
yaoxuefeng 已提交
1423 1424 1425 1426 1427
    }
  }
#endif
}

J
jiaqi 已提交
1428 1429
void MultiSlotInMemoryDataFeed::PutToFeedVec(
    const std::vector<Record>& ins_vec) {
X
xjqbest 已提交
1430
#ifdef _LINUX
H
hutuxian 已提交
1431 1432 1433 1434 1435 1436
  for (size_t i = 0; i < batch_float_feasigns_.size(); ++i) {
    batch_float_feasigns_[i].clear();
    batch_uint64_feasigns_[i].clear();
    offset_[i].clear();
    offset_[i].push_back(0);
  }
1437 1438 1439 1440
  ins_content_vec_.clear();
  ins_content_vec_.reserve(ins_vec.size());
  ins_id_vec_.clear();
  ins_id_vec_.reserve(ins_vec.size());
1441
  for (const auto& r : ins_vec) {
1442 1443
    ins_id_vec_.push_back(r.ins_id_);
    ins_content_vec_.push_back(r.content_);
J
jiaqi 已提交
1444
    for (auto& item : r.float_feasigns_) {
H
hutuxian 已提交
1445 1446
      batch_float_feasigns_[item.slot()].push_back(item.sign().float_feasign_);
      visit_[item.slot()] = true;
J
jiaqi 已提交
1447 1448
    }
    for (auto& item : r.uint64_feasigns_) {
H
hutuxian 已提交
1449 1450 1451
      batch_uint64_feasigns_[item.slot()].push_back(
          item.sign().uint64_feasign_);
      visit_[item.slot()] = true;
J
jiaqi 已提交
1452 1453 1454
    }
    for (size_t j = 0; j < use_slots_.size(); ++j) {
      const auto& type = all_slots_type_[j];
H
hutuxian 已提交
1455 1456
      if (visit_[j]) {
        visit_[j] = false;
J
jiaqi 已提交
1457 1458 1459
      } else {
        // fill slot value with default value 0
        if (type[0] == 'f') {  // float
H
hutuxian 已提交
1460
          batch_float_feasigns_[j].push_back(0.0);
J
jiaqi 已提交
1461
        } else if (type[0] == 'u') {  // uint64
H
hutuxian 已提交
1462
          batch_uint64_feasigns_[j].push_back(0);
J
jiaqi 已提交
1463 1464 1465 1466
        }
      }
      // get offset of this ins in this slot
      if (type[0] == 'f') {  // float
H
hutuxian 已提交
1467
        offset_[j].push_back(batch_float_feasigns_[j].size());
J
jiaqi 已提交
1468
      } else if (type[0] == 'u') {  // uint64
H
hutuxian 已提交
1469
        offset_[j].push_back(batch_uint64_feasigns_[j].size());
J
jiaqi 已提交
1470
      }
1471 1472 1473 1474
    }
  }

  for (size_t i = 0; i < use_slots_.size(); ++i) {
1475 1476 1477
    if (feed_vec_[i] == nullptr) {
      continue;
    }
H
hutuxian 已提交
1478
    int total_instance = offset_[i].back();
J
jiaqi 已提交
1479
    const auto& type = all_slots_type_[i];
1480
    if (type[0] == 'f') {  // float
H
hutuxian 已提交
1481
      float* feasign = batch_float_feasigns_[i].data();
1482 1483 1484
      float* tensor_ptr =
          feed_vec_[i]->mutable_data<float>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(float));
1485 1486
    } else if (type[0] == 'u') {  // uint64
      // no uint64_t type in paddlepaddle
H
hutuxian 已提交
1487
      uint64_t* feasign = batch_uint64_feasigns_[i].data();
1488
      int64_t* tensor_ptr = feed_vec_[i]->mutable_data<int64_t>(
1489 1490
          {total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(int64_t));
1491
    }
H
hutuxian 已提交
1492
    auto& slot_offset = offset_[i];
1493
    if (this->input_type_ == 0) {
W
wangguanqun 已提交
1494 1495 1496 1497
      if (!use_slots_is_dense_[i]) {
        LoD data_lod{slot_offset};
        feed_vec_[i]->set_lod(data_lod);
      }
1498 1499 1500
    } else if (this->input_type_ == 1) {
      if (!use_slots_is_dense_[i]) {
        std::vector<size_t> tmp_offset;
1501 1502
        PADDLE_ENFORCE_EQ(slot_offset.size(),
                          2,
1503 1504
                          platform::errors::InvalidArgument(
                              "In batch reader, the sparse tensor lod size "
1505
                              "must be 2, but received %d.",
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
                              slot_offset.size()));
        const auto& max_size = slot_offset[1];
        tmp_offset.reserve(max_size + 1);
        for (unsigned int k = 0; k <= max_size; k++) {
          tmp_offset.emplace_back(k);
        }
        slot_offset = tmp_offset;
        LoD data_lod{slot_offset};
        feed_vec_[i]->set_lod(data_lod);
      }
    }
1517
    if (use_slots_is_dense_[i]) {
1518 1519 1520 1521
      if (inductive_shape_index_[i] != -1) {
        use_slots_shape_[i][inductive_shape_index_[i]] =
            total_instance / total_dims_without_inductive_[i];
      }
1522
      feed_vec_[i]->Resize(phi::make_ddim(use_slots_shape_[i]));
1523 1524
    }
  }
X
xjqbest 已提交
1525
#endif
1526 1527
}

1528
#if (defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)) && !defined(_WIN32)
H
hutuxian 已提交
1529 1530 1531 1532 1533 1534 1535 1536 1537
template <typename T>
void PrivateInstantDataFeed<T>::PutToFeedVec() {
  for (size_t i = 0; i < use_slots_.size(); ++i) {
    const auto& type = ins_vec_[i].GetType();
    const auto& offset = ins_vec_[i].GetOffset();
    int total_instance = static_cast<int>(offset.back());

    if (type[0] == 'f') {  // float
      const auto& feasign = ins_vec_[i].GetFloatData();
1538 1539
      float* tensor_ptr = feed_vec_[i]->template mutable_data<float>(
          {total_instance, 1}, this->place_);
1540
      CopyToFeedTensor(tensor_ptr, &feasign[0], total_instance * sizeof(float));
H
hutuxian 已提交
1541 1542 1543
    } else if (type[0] == 'u') {  // uint64
      // no uint64_t type in paddlepaddle
      const auto& feasign = ins_vec_[i].GetUint64Data();
1544
      int64_t* tensor_ptr = feed_vec_[i]->template mutable_data<int64_t>(
1545
          {total_instance, 1}, this->place_);
1546 1547
      CopyToFeedTensor(
          tensor_ptr, &feasign[0], total_instance * sizeof(int64_t));
H
hutuxian 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556
    }

    LoD data_lod{offset};
    feed_vec_[i]->set_lod(data_lod);
    if (use_slots_is_dense_[i]) {
      int64_t total_dims = 1;
      for (const auto e : use_slots_shape_[i]) {
        total_dims *= e;
      }
1557
      PADDLE_ENFORCE_EQ(
1558 1559
          total_dims,
          total_instance,
1560 1561 1562 1563
          platform::errors::InvalidArgument(
              "The actual data size of slot[%s] doesn't match its declaration. "
              "The actual data size of slot is %lld"
              ", and its declaration is %lld.",
1564 1565 1566
              use_slots_[i].c_str(),
              total_dims,
              total_instance));
1567
      feed_vec_[i]->Resize(phi::make_ddim(use_slots_shape_[i]));
H
hutuxian 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
    }
  }
}

template <typename T>
int PrivateInstantDataFeed<T>::Next() {
  if (ParseOneMiniBatch()) {
    PutToFeedVec();
    return ins_vec_[0].GetBatchSize();
  }
  Postprocess();

  std::string filename;
  if (!PickOneFile(&filename)) {
    return -1;
  }
  if (!Preprocess(filename)) {
    return -1;
  }

1588
  PADDLE_ENFORCE_EQ(
1589 1590
      true,
      ParseOneMiniBatch(),
1591
      platform::errors::InvalidArgument("Fail to parse mini-batch data."));
H
hutuxian 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
  PutToFeedVec();
  return ins_vec_[0].GetBatchSize();
}

template <typename T>
void PrivateInstantDataFeed<T>::Init(const DataFeedDesc& data_feed_desc) {
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;

1602
  PADDLE_ENFORCE_EQ(
1603 1604
      data_feed_desc.has_multi_slot_desc(),
      true,
1605 1606
      platform::errors::PreconditionNotMet(
          "Multi_slot_desc has not been set in PrivateInstantDataFeed."));
H
hutuxian 已提交
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
  paddle::framework::MultiSlotDesc multi_slot_desc =
      data_feed_desc.multi_slot_desc();
  SetBatchSize(data_feed_desc.batch_size());
  size_t all_slot_num = multi_slot_desc.slots_size();
  all_slots_.resize(all_slot_num);
  all_slots_type_.resize(all_slot_num);
  use_slots_index_.resize(all_slot_num);
  multi_inductive_shape_index_.resize(all_slot_num);
  use_slots_.clear();
  use_slots_is_dense_.clear();
  for (size_t i = 0; i < all_slot_num; ++i) {
    const auto& slot = multi_slot_desc.slots(i);
    all_slots_[i] = slot.name();
    all_slots_type_[i] = slot.type();
    use_slots_index_[i] = slot.is_used() ? use_slots_.size() : -1;
    if (slot.is_used()) {
      use_slots_.push_back(all_slots_[i]);
      use_slots_is_dense_.push_back(slot.is_dense());
      std::vector<int> local_shape;
      if (slot.is_dense()) {
1627
        for (int j = 0; j < slot.shape_size(); ++j) {
H
hutuxian 已提交
1628 1629 1630 1631 1632
          if (slot.shape(j) == -1) {
            multi_inductive_shape_index_[i].push_back(j);
          }
        }
      }
1633
      for (int j = 0; j < slot.shape_size(); ++j) {
H
hutuxian 已提交
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
        local_shape.push_back(slot.shape(j));
      }
      use_slots_shape_.push_back(local_shape);
    }
  }
  feed_vec_.resize(use_slots_.size());
  ins_vec_.resize(use_slots_.size());

  finish_init_ = true;
}

template class PrivateInstantDataFeed<std::vector<MultiSlotType>>;

bool MultiSlotFileInstantDataFeed::Preprocess(const std::string& filename) {
  fd_ = open(filename.c_str(), O_RDONLY);
1649
  PADDLE_ENFORCE_NE(
1650 1651
      fd_,
      -1,
1652 1653 1654
      platform::errors::Unavailable(
          "Fail to open file: %s in MultiSlotFileInstantDataFeed.",
          filename.c_str()));
H
hutuxian 已提交
1655 1656 1657 1658 1659 1660 1661

  struct stat sb;
  fstat(fd_, &sb);
  end_ = static_cast<size_t>(sb.st_size);

  buffer_ =
      reinterpret_cast<char*>(mmap(NULL, end_, PROT_READ, MAP_PRIVATE, fd_, 0));
1662
  PADDLE_ENFORCE_NE(
1663 1664
      buffer_,
      MAP_FAILED,
1665 1666 1667
      platform::errors::Unavailable(
          "Memory map failed when create shared memory, error number is %s.",
          strerror(errno)));
H
hutuxian 已提交
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698

  offset_ = 0;
  return true;
}

bool MultiSlotFileInstantDataFeed::Postprocess() {
  if (buffer_ != nullptr) {
    munmap(buffer_, end_);
    buffer_ = nullptr;
  }
  if (fd_ != -1) {
    close(fd_);
    fd_ = -1;
    end_ = 0;
    offset_ = 0;
  }
  return true;
}

bool MultiSlotFileInstantDataFeed::ParseOneMiniBatch() {
  if (offset_ == end_) {
    return false;
  }

  batch_size_ = 0;
  while (batch_size_ < default_batch_size_ && offset_ < end_) {
    for (size_t i = 0; i < use_slots_index_.size(); ++i) {
      int idx = use_slots_index_[i];
      char type = all_slots_type_[i][0];

      uint16_t num = *reinterpret_cast<uint16_t*>(buffer_ + offset_);
1699
      PADDLE_ENFORCE_NE(
1700 1701
          num,
          0,
1702 1703 1704 1705 1706
          platform::errors::InvalidArgument(
              "The number of ids can not be zero, you need padding "
              "it in data generator; or if there is something wrong with "
              "the data, please check if the data contains unresolvable "
              "characters."));
H
hutuxian 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
      offset_ += sizeof(uint16_t);

      if (idx != -1) {
        int inductive_size = multi_inductive_shape_index_[i].size();
        if (UNLIKELY(batch_size_ == 0)) {
          ins_vec_[idx].Init(all_slots_type_[i], default_batch_size_ * num);
          ins_vec_[idx].InitOffset(default_batch_size_);
          uint64_t* inductive_shape =
              reinterpret_cast<uint64_t*>(buffer_ + offset_);
          for (int inductive_id = 0; inductive_id < inductive_size;
               ++inductive_id) {
            use_slots_shape_[i][multi_inductive_shape_index_[i][inductive_id]] =
                static_cast<int>(*(inductive_shape + inductive_id));
          }
        }
        num -= inductive_size;
        offset_ += sizeof(uint64_t) * inductive_size;

        if (type == 'f') {
          ins_vec_[idx].AppendValues(
              reinterpret_cast<float*>(buffer_ + offset_), num);
          offset_ += num * sizeof(float);
        } else if (type == 'u') {
          ins_vec_[idx].AppendValues(
              reinterpret_cast<uint64_t*>(buffer_ + offset_), num);
          offset_ += num * sizeof(uint64_t);
        }
      } else {
        if (type == 'f') {
          offset_ += num * sizeof(float);
        } else if (type == 'u') {
          offset_ += num * sizeof(uint64_t);
        }
      }
    }
    ++batch_size_;
    // OPTIMIZE: It is better to insert check codes between instances for format
    // checking
  }

  PADDLE_ENFORCE(batch_size_ == default_batch_size_ || offset_ == end_,
1748 1749 1750 1751 1752
                 platform::errors::InvalidArgument(
                     "The batch size id not equal to default batch size, or "
                     "the offset is not equal to end index."
                     "The batch size is %d, default batcch size is %d, offset "
                     "is %d, end index is %d.",
1753 1754 1755 1756
                     batch_size_,
                     default_batch_size_,
                     offset_,
                     end_));
H
hutuxian 已提交
1757 1758 1759 1760
  return true;
}
#endif

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
bool PaddleBoxDataFeed::Start() {
#ifdef _LINUX
  int phase = GetCurrentPhase();  // join: 1, update: 0
  this->CheckSetFileList();
  if (enable_pv_merge_ && phase == 1) {
    // join phase : input_pv_channel to output_pv_channel
    if (output_pv_channel_->Size() == 0 && input_pv_channel_->Size() != 0) {
      std::vector<PvInstance> data;
      input_pv_channel_->Read(data);
      output_pv_channel_->Write(std::move(data));
    }
  } else {
    // input_channel to output
    if (output_channel_->Size() == 0 && input_channel_->Size() != 0) {
      std::vector<Record> data;
      input_channel_->Read(data);
      output_channel_->Write(std::move(data));
    }
  }
#endif
  this->finish_start_ = true;
  return true;
}

int PaddleBoxDataFeed::Next() {
#ifdef _LINUX
  int phase = GetCurrentPhase();  // join: 1, update: 0
  this->CheckStart();
  if (enable_pv_merge_ && phase == 1) {
    // join phase : output_pv_channel to consume_pv_channel
    CHECK(output_pv_channel_ != nullptr);
    CHECK(consume_pv_channel_ != nullptr);
    VLOG(3) << "output_pv_channel_ size=" << output_pv_channel_->Size()
            << ", consume_pv_channel_ size=" << consume_pv_channel_->Size()
            << ", thread_id=" << thread_id_;
    int index = 0;
    PvInstance pv_instance;
    std::vector<PvInstance> pv_vec;
    pv_vec.reserve(this->pv_batch_size_);
    while (index < this->pv_batch_size_) {
      if (output_pv_channel_->Size() == 0) {
        break;
      }
      output_pv_channel_->Get(pv_instance);
      pv_vec.push_back(pv_instance);
      ++index;
      consume_pv_channel_->Put(std::move(pv_instance));
    }
    this->batch_size_ = index;
    VLOG(3) << "pv_batch_size_=" << this->batch_size_
            << ", thread_id=" << thread_id_;
    if (this->batch_size_ != 0) {
      PutToFeedVec(pv_vec);
    } else {
      VLOG(3) << "finish reading, output_pv_channel_ size="
              << output_pv_channel_->Size()
              << ", consume_pv_channel_ size=" << consume_pv_channel_->Size()
              << ", thread_id=" << thread_id_;
    }
    return this->batch_size_;
  } else {
    this->batch_size_ = MultiSlotInMemoryDataFeed::Next();
    return this->batch_size_;
  }
#else
  return 0;
#endif
}

void PaddleBoxDataFeed::Init(const DataFeedDesc& data_feed_desc) {
  MultiSlotInMemoryDataFeed::Init(data_feed_desc);
  rank_offset_name_ = data_feed_desc.rank_offset();
  pv_batch_size_ = data_feed_desc.pv_batch_size();
}

void PaddleBoxDataFeed::GetRankOffset(const std::vector<PvInstance>& pv_vec,
                                      int ins_number) {
  int index = 0;
  int max_rank = 3;  // the value is setting
  int row = ins_number;
  int col = max_rank * 2 + 1;
  int pv_num = pv_vec.size();

  std::vector<int> rank_offset_mat(row * col, -1);
  rank_offset_mat.shrink_to_fit();

  for (int i = 0; i < pv_num; i++) {
    auto pv_ins = pv_vec[i];
    int ad_num = pv_ins->ads.size();
    int index_start = index;
    for (int j = 0; j < ad_num; ++j) {
      auto ins = pv_ins->ads[j];
      int rank = -1;
      if ((ins->cmatch == 222 || ins->cmatch == 223) &&
          ins->rank <= static_cast<uint32_t>(max_rank) && ins->rank != 0) {
        rank = ins->rank;
      }

      rank_offset_mat[index * col] = rank;
      if (rank > 0) {
        for (int k = 0; k < ad_num; ++k) {
          auto cur_ins = pv_ins->ads[k];
          int fast_rank = -1;
          if ((cur_ins->cmatch == 222 || cur_ins->cmatch == 223) &&
              cur_ins->rank <= static_cast<uint32_t>(max_rank) &&
              cur_ins->rank != 0) {
            fast_rank = cur_ins->rank;
          }

          if (fast_rank > 0) {
            int m = fast_rank - 1;
            rank_offset_mat[index * col + 2 * m + 1] = cur_ins->rank;
            rank_offset_mat[index * col + 2 * m + 2] = index_start + k;
          }
        }
      }
      index += 1;
    }
  }

  int* rank_offset = rank_offset_mat.data();
  int* tensor_ptr = rank_offset_->mutable_data<int>({row, col}, this->place_);
  CopyToFeedTensor(tensor_ptr, rank_offset, row * col * sizeof(int));
}

void PaddleBoxDataFeed::AssignFeedVar(const Scope& scope) {
  MultiSlotInMemoryDataFeed::AssignFeedVar(scope);
  // set rank offset memory
  int phase = GetCurrentPhase();  // join: 1, update: 0
  if (enable_pv_merge_ && phase == 1) {
1891 1892
    rank_offset_ =
        scope.FindVar(rank_offset_name_)->GetMutable<phi::DenseTensor>();
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
  }
}

void PaddleBoxDataFeed::PutToFeedVec(const std::vector<PvInstance>& pv_vec) {
#ifdef _LINUX
  int ins_number = 0;
  std::vector<Record*> ins_vec;
  for (auto& pv : pv_vec) {
    ins_number += pv->ads.size();
    for (auto ins : pv->ads) {
      ins_vec.push_back(ins);
    }
  }
  GetRankOffset(pv_vec, ins_number);
  PutToFeedVec(ins_vec);
#endif
}

int PaddleBoxDataFeed::GetCurrentPhase() {
#ifdef PADDLE_WITH_BOX_PS
  auto box_ptr = paddle::framework::BoxWrapper::GetInstance();
1914 1915 1916 1917 1918
  if (box_ptr->Mode() == 1) {  // For AucRunner
    return 1;
  } else {
    return box_ptr->Phase();
  }
1919 1920 1921 1922 1923 1924 1925 1926
#else
  LOG(WARNING) << "It should be complied with BOX_PS...";
  return current_phase_;
#endif
}

void PaddleBoxDataFeed::PutToFeedVec(const std::vector<Record*>& ins_vec) {
#ifdef _LINUX
H
hutuxian 已提交
1927 1928 1929 1930 1931 1932
  for (size_t i = 0; i < batch_float_feasigns_.size(); ++i) {
    batch_float_feasigns_[i].clear();
    batch_uint64_feasigns_[i].clear();
    offset_[i].clear();
    offset_[i].push_back(0);
  }
1933 1934 1935 1936
  ins_content_vec_.clear();
  ins_content_vec_.reserve(ins_vec.size());
  ins_id_vec_.clear();
  ins_id_vec_.reserve(ins_vec.size());
1937
  for (auto r : ins_vec) {
1938 1939 1940
    ins_id_vec_.push_back(r->ins_id_);
    ins_content_vec_.push_back(r->content_);
    for (auto& item : r->float_feasigns_) {
H
hutuxian 已提交
1941 1942
      batch_float_feasigns_[item.slot()].push_back(item.sign().float_feasign_);
      visit_[item.slot()] = true;
1943 1944
    }
    for (auto& item : r->uint64_feasigns_) {
H
hutuxian 已提交
1945 1946 1947
      batch_uint64_feasigns_[item.slot()].push_back(
          item.sign().uint64_feasign_);
      visit_[item.slot()] = true;
1948 1949 1950
    }
    for (size_t j = 0; j < use_slots_.size(); ++j) {
      const auto& type = all_slots_type_[j];
H
hutuxian 已提交
1951 1952
      if (visit_[j]) {
        visit_[j] = false;
1953 1954 1955
      } else {
        // fill slot value with default value 0
        if (type[0] == 'f') {  // float
H
hutuxian 已提交
1956
          batch_float_feasigns_[j].push_back(0.0);
1957
        } else if (type[0] == 'u') {  // uint64
H
hutuxian 已提交
1958
          batch_uint64_feasigns_[j].push_back(0);
1959 1960 1961 1962
        }
      }
      // get offset of this ins in this slot
      if (type[0] == 'f') {  // float
H
hutuxian 已提交
1963
        offset_[j].push_back(batch_float_feasigns_[j].size());
1964
      } else if (type[0] == 'u') {  // uint64
H
hutuxian 已提交
1965
        offset_[j].push_back(batch_uint64_feasigns_[j].size());
1966 1967 1968 1969 1970 1971 1972 1973
      }
    }
  }

  for (size_t i = 0; i < use_slots_.size(); ++i) {
    if (feed_vec_[i] == nullptr) {
      continue;
    }
H
hutuxian 已提交
1974
    int total_instance = offset_[i].back();
1975 1976
    const auto& type = all_slots_type_[i];
    if (type[0] == 'f') {  // float
H
hutuxian 已提交
1977
      float* feasign = batch_float_feasigns_[i].data();
1978 1979 1980 1981 1982
      float* tensor_ptr =
          feed_vec_[i]->mutable_data<float>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(float));
    } else if (type[0] == 'u') {  // uint64
      // no uint64_t type in paddlepaddle
H
hutuxian 已提交
1983
      uint64_t* feasign = batch_uint64_feasigns_[i].data();
1984 1985 1986 1987
      int64_t* tensor_ptr = feed_vec_[i]->mutable_data<int64_t>(
          {total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(int64_t));
    }
H
hutuxian 已提交
1988
    auto& slot_offset = offset_[i];
1989 1990 1991 1992 1993 1994 1995
    LoD data_lod{slot_offset};
    feed_vec_[i]->set_lod(data_lod);
    if (use_slots_is_dense_[i]) {
      if (inductive_shape_index_[i] != -1) {
        use_slots_shape_[i][inductive_shape_index_[i]] =
            total_instance / total_dims_without_inductive_[i];
      }
1996
      feed_vec_[i]->Resize(phi::make_ddim(use_slots_shape_[i]));
1997 1998 1999 2000 2001
    }
  }
#endif
}

P
pangengzheng 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
SlotRecordInMemoryDataFeed::~SlotRecordInMemoryDataFeed() {
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
  stop_token_.store(true);
  for (auto& thread : pack_threads_) {
    if (thread.joinable()) {
      thread.join();
    }
  }
  for (auto* pack : pack_vec_) {
    pack->set_use_flag(false);
  }
#endif
}

Y
yaoxuefeng 已提交
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
template class InMemoryDataFeed<SlotRecord>;
void SlotRecordInMemoryDataFeed::Init(const DataFeedDesc& data_feed_desc) {
  finish_init_ = false;
  finish_set_filelist_ = false;
  finish_start_ = false;
  PADDLE_ENFORCE(data_feed_desc.has_multi_slot_desc(),
                 platform::errors::PreconditionNotMet(
                     "Multi_slot_desc has not been set in data_feed_desc"));
  paddle::framework::MultiSlotDesc multi_slot_desc =
      data_feed_desc.multi_slot_desc();
  SetBatchSize(data_feed_desc.batch_size());
  size_t all_slot_num = multi_slot_desc.slots_size();

  all_slots_.resize(all_slot_num);
  all_slots_info_.resize(all_slot_num);
  used_slots_info_.resize(all_slot_num);
  use_slot_size_ = 0;
  use_slots_.clear();

  float_total_dims_size_ = 0;
  float_total_dims_without_inductives_.clear();
  for (size_t i = 0; i < all_slot_num; ++i) {
    const auto& slot = multi_slot_desc.slots(i);
    all_slots_[i] = slot.name();

    AllSlotInfo& all_slot = all_slots_info_[i];
    all_slot.slot = slot.name();
    all_slot.type = slot.type();
    all_slot.used_idx = slot.is_used() ? use_slot_size_ : -1;
    all_slot.slot_value_idx = -1;

    if (slot.is_used()) {
      UsedSlotInfo& info = used_slots_info_[use_slot_size_];
      info.idx = i;
      info.slot = slot.name();
      info.type = slot.type();
      info.dense = slot.is_dense();
      info.total_dims_without_inductive = 1;
      info.inductive_shape_index = -1;

      // record float value and uint64_t value pos
      if (info.type[0] == 'u') {
        info.slot_value_idx = uint64_use_slot_size_;
        all_slot.slot_value_idx = uint64_use_slot_size_;
        ++uint64_use_slot_size_;
      } else if (info.type[0] == 'f') {
        info.slot_value_idx = float_use_slot_size_;
        all_slot.slot_value_idx = float_use_slot_size_;
        ++float_use_slot_size_;
      }

      use_slots_.push_back(slot.name());

      if (slot.is_dense()) {
        for (int j = 0; j < slot.shape_size(); ++j) {
          if (slot.shape(j) > 0) {
            info.total_dims_without_inductive *= slot.shape(j);
          }
          if (slot.shape(j) == -1) {
            info.inductive_shape_index = j;
          }
        }
      }
      if (info.type[0] == 'f') {
        float_total_dims_without_inductives_.push_back(
            info.total_dims_without_inductive);
        float_total_dims_size_ += info.total_dims_without_inductive;
      }
      info.local_shape.clear();
      for (int j = 0; j < slot.shape_size(); ++j) {
        info.local_shape.push_back(slot.shape(j));
      }
      ++use_slot_size_;
    }
  }
  used_slots_info_.resize(use_slot_size_);

  feed_vec_.resize(used_slots_info_.size());
  const int kEstimatedFeasignNumPerSlot = 5;  // Magic Number
  for (size_t i = 0; i < all_slot_num; i++) {
    batch_float_feasigns_.push_back(std::vector<float>());
    batch_uint64_feasigns_.push_back(std::vector<uint64_t>());
    batch_float_feasigns_[i].reserve(default_batch_size_ *
                                     kEstimatedFeasignNumPerSlot);
    batch_uint64_feasigns_[i].reserve(default_batch_size_ *
                                      kEstimatedFeasignNumPerSlot);
    offset_.push_back(std::vector<size_t>());
    offset_[i].reserve(default_batch_size_ +
                       1);  // Each lod info will prepend a zero
  }
  visit_.resize(all_slot_num, false);
  pipe_command_ = data_feed_desc.pipe_command();
  finish_init_ = true;
  input_type_ = data_feed_desc.input_type();
  size_t pos = pipe_command_.find(".so");
  if (pos != std::string::npos) {
    pos = pipe_command_.rfind('|');
    if (pos == std::string::npos) {
      so_parser_name_ = pipe_command_;
      pipe_command_.clear();
    } else {
      so_parser_name_ = pipe_command_.substr(pos + 1);
      pipe_command_ = pipe_command_.substr(0, pos);
    }
    so_parser_name_ = paddle::string::erase_spaces(so_parser_name_);
  } else {
    so_parser_name_.clear();
  }
D
danleifeng 已提交
2124 2125 2126
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
  gpu_graph_data_generator_.SetConfig(data_feed_desc);
#endif
2127 2128 2129 2130 2131
  if (gpu_graph_mode_) {
    train_mode_ = true;
  } else {
    train_mode_ = data_feed_desc.graph_config().gpu_graph_training();
  }
Y
yaoxuefeng 已提交
2132 2133
}

L
lxsbupt 已提交
2134 2135
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
void SlotRecordInMemoryDataFeed::InitGraphResource() {
2136
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
2137
  gpu_graph_data_generator_.AllocResource(thread_id_, feed_vec_);
2138
#endif
L
lxsbupt 已提交
2139 2140 2141
}

void SlotRecordInMemoryDataFeed::InitGraphTrainResource() {
2142
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
2143
  gpu_graph_data_generator_.AllocTrainResource(thread_id_);
2144
#endif
L
lxsbupt 已提交
2145 2146 2147
}
#endif

Y
yaoxuefeng 已提交
2148 2149 2150 2151 2152 2153 2154 2155
void SlotRecordInMemoryDataFeed::LoadIntoMemory() {
  VLOG(3) << "SlotRecord LoadIntoMemory() begin, thread_id=" << thread_id_;
  if (!so_parser_name_.empty()) {
    LoadIntoMemoryByLib();
  } else {
    LoadIntoMemoryByCommand();
  }
}
2156
void SlotRecordInMemoryDataFeed::LoadIntoMemoryByLib() {
Y
yaoxuefeng 已提交
2157 2158 2159 2160 2161 2162 2163 2164
  if (true) {
    // user defined file format analysis
    LoadIntoMemoryByFile();
  } else {
    LoadIntoMemoryByLine();
  }
}

2165
void SlotRecordInMemoryDataFeed::LoadIntoMemoryByFile() {
T
Thunderbrook 已提交
2166 2167
#if (defined _LINUX) && (defined PADDLE_WITH_HETERPS) && \
    (defined PADDLE_WITH_PSLIB)
Y
yaoxuefeng 已提交
2168 2169 2170 2171 2172
  paddle::framework::CustomParser* parser =
      global_dlmanager_pool().Load(so_parser_name_, all_slots_info_);
  CHECK(parser != nullptr);
  // get slotrecord object
  auto pull_record_func = [this](std::vector<SlotRecord>& record_vec,
2173 2174
                                 int max_fetch_num,
                                 int offset) {
Y
yaoxuefeng 已提交
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
    if (offset > 0) {
      input_channel_->WriteMove(offset, &record_vec[0]);
      if (max_fetch_num > 0) {
        SlotRecordPool().get(&record_vec[0], offset);
      } else {  // free all
        max_fetch_num = static_cast<int>(record_vec.size());
        if (max_fetch_num > offset) {
          SlotRecordPool().put(&record_vec[offset], (max_fetch_num - offset));
        }
      }
    } else if (max_fetch_num > 0) {
      SlotRecordPool().get(&record_vec, max_fetch_num);
    } else {
      SlotRecordPool().put(&record_vec);
    }
  };

  std::string filename;
  while (this->PickOneFile(&filename)) {
    VLOG(3) << "PickOneFile, filename=" << filename
            << ", thread_id=" << thread_id_;
    platform::Timer timeline;
    timeline.Start();

    int lines = 0;
    bool is_ok = true;
T
Thunderbrook 已提交
2201
    auto ps_gpu_ptr = PSGPUWrapper::GetInstance();
Y
yaoxuefeng 已提交
2202
    do {
T
Thunderbrook 已提交
2203 2204 2205 2206 2207 2208
      if (ps_gpu_ptr->UseAfsApi()) {
        auto afs_reader = ps_gpu_ptr->OpenReader(filename);
        is_ok = parser->ParseFileInstance(
            [this, afs_reader](char* buf, int len) {
              return afs_reader->read(buf, len);
            },
2209 2210
            pull_record_func,
            lines);
T
Thunderbrook 已提交
2211 2212
      } else {
        int err_no = 0;
2213
        this->fp_ = fs_open_read(filename, &err_no, this->pipe_command_, true);
T
Thunderbrook 已提交
2214 2215 2216 2217 2218 2219 2220

        CHECK(this->fp_ != nullptr);
        __fsetlocking(&*(this->fp_), FSETLOCKING_BYCALLER);
        is_ok = parser->ParseFileInstance(
            [this](char* buf, int len) {
              return fread(buf, sizeof(char), len, this->fp_.get());
            },
2221 2222
            pull_record_func,
            lines);
T
Thunderbrook 已提交
2223 2224 2225 2226 2227

        if (!is_ok) {
          LOG(WARNING) << "parser error, filename=" << filename
                       << ", lines=" << lines;
        }
Y
yaoxuefeng 已提交
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
      }
    } while (!is_ok);
    timeline.Pause();
    VLOG(3) << "LoadIntoMemoryByLib() read all file, file=" << filename
            << ", cost time=" << timeline.ElapsedSec()
            << " seconds, thread_id=" << thread_id_ << ", lines=" << lines;
  }
#endif
}

2238
void SlotRecordInMemoryDataFeed::LoadIntoMemoryByLine() {
Y
yaoxuefeng 已提交
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
#ifdef _LINUX
  paddle::framework::CustomParser* parser =
      global_dlmanager_pool().Load(so_parser_name_, all_slots_info_);
  std::string filename;
  BufferedLineFileReader line_reader;
  line_reader.set_sample_rate(sample_rate_);
  BufferedLineFileReader::LineFunc line_func = nullptr;

  while (this->PickOneFile(&filename)) {
    VLOG(3) << "PickOneFile, filename=" << filename
            << ", thread_id=" << thread_id_;
    std::vector<SlotRecord> record_vec;
    platform::Timer timeline;
    timeline.Start();
    int offset = 0;
    int old_offset = 0;

    SlotRecordPool().get(&record_vec, OBJPOOL_BLOCK_SIZE);
    // get slotrecord object function
    auto record_func = [this, &offset, &record_vec, &old_offset](
2259
                           std::vector<SlotRecord>& vec, int num) {
Y
yaoxuefeng 已提交
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
      vec.resize(num);
      if (offset + num > OBJPOOL_BLOCK_SIZE) {
        input_channel_->WriteMove(offset, &record_vec[0]);
        SlotRecordPool().get(&record_vec[0], offset);
        record_vec.resize(OBJPOOL_BLOCK_SIZE);
        offset = 0;
        old_offset = 0;
      }
      for (int i = 0; i < num; ++i) {
        auto& ins = record_vec[offset + i];
        ins->reset();
        vec[i] = ins;
      }
      offset = offset + num;
    };

2276 2277 2278 2279 2280 2281
    line_func = [this,
                 &parser,
                 &record_vec,
                 &offset,
                 &filename,
                 &record_func,
Y
yaoxuefeng 已提交
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
                 &old_offset](const std::string& line) {
      old_offset = offset;
      if (!parser->ParseOneInstance(line, record_func)) {
        offset = old_offset;
        LOG(WARNING) << "read file:[" << filename << "] item error, line:["
                     << line << "]";
        return false;
      }
      if (offset >= OBJPOOL_BLOCK_SIZE) {
        input_channel_->Write(std::move(record_vec));
        record_vec.clear();
        SlotRecordPool().get(&record_vec, OBJPOOL_BLOCK_SIZE);
        offset = 0;
      }
      return true;
    };

    int lines = 0;

    do {
      int err_no = 0;
2303
      this->fp_ = fs_open_read(filename, &err_no, this->pipe_command_, true);
Y
yaoxuefeng 已提交
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
      CHECK(this->fp_ != nullptr);
      __fsetlocking(&*(this->fp_), FSETLOCKING_BYCALLER);
      lines = line_reader.read_file(this->fp_.get(), line_func, lines);
    } while (line_reader.is_error());

    if (offset > 0) {
      input_channel_->WriteMove(offset, &record_vec[0]);
      if (offset < OBJPOOL_BLOCK_SIZE) {
        SlotRecordPool().put(&record_vec[offset],
                             (OBJPOOL_BLOCK_SIZE - offset));
      }
    } else {
      SlotRecordPool().put(&record_vec);
    }
    record_vec.clear();
    record_vec.shrink_to_fit();
    timeline.Pause();
    VLOG(3) << "LoadIntoMemoryByLib() read all lines, file=" << filename
            << ", cost time=" << timeline.ElapsedSec()
            << " seconds, thread_id=" << thread_id_ << ", lines=" << lines
            << ", sample lines=" << line_reader.get_sample_line()
            << ", filesize=" << line_reader.file_size() / 1024.0 / 1024.0
            << "MB";
  }

  VLOG(3) << "LoadIntoMemoryByLib() end, thread_id=" << thread_id_
          << ", total size: " << line_reader.file_size();
#endif
}

2334
void SlotRecordInMemoryDataFeed::LoadIntoMemoryByCommand() {
Y
yaoxuefeng 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
#ifdef _LINUX
  std::string filename;
  BufferedLineFileReader line_reader;
  line_reader.set_sample_rate(sample_rate_);

  while (this->PickOneFile(&filename)) {
    VLOG(3) << "PickOneFile, filename=" << filename
            << ", thread_id=" << thread_id_;
    int lines = 0;
    std::vector<SlotRecord> record_vec;
    platform::Timer timeline;
    timeline.Start();
    SlotRecordPool().get(&record_vec, OBJPOOL_BLOCK_SIZE);
    int offset = 0;

    do {
      int err_no = 0;
2352
      this->fp_ = fs_open_read(filename, &err_no, this->pipe_command_, true);
Y
yaoxuefeng 已提交
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
      CHECK(this->fp_ != nullptr);
      __fsetlocking(&*(this->fp_), FSETLOCKING_BYCALLER);

      lines = line_reader.read_file(
          this->fp_.get(),
          [this, &record_vec, &offset, &filename](const std::string& line) {
            if (ParseOneInstance(line, &record_vec[offset])) {
              ++offset;
            } else {
              LOG(WARNING) << "read file:[" << filename
                           << "] item error, line:[" << line << "]";
              return false;
            }
            if (offset >= OBJPOOL_BLOCK_SIZE) {
              input_channel_->Write(std::move(record_vec));
              record_vec.clear();
              SlotRecordPool().get(&record_vec, OBJPOOL_BLOCK_SIZE);
              offset = 0;
            }
            return true;
          },
          lines);
    } while (line_reader.is_error());
    if (offset > 0) {
      input_channel_->WriteMove(offset, &record_vec[0]);
      if (offset < OBJPOOL_BLOCK_SIZE) {
        SlotRecordPool().put(&record_vec[offset],
                             (OBJPOOL_BLOCK_SIZE - offset));
      }
    } else {
      SlotRecordPool().put(&record_vec);
    }
    record_vec.clear();
    record_vec.shrink_to_fit();
    timeline.Pause();
    VLOG(3) << "LoadIntoMemory() read all lines, file=" << filename
            << ", lines=" << lines
            << ", sample lines=" << line_reader.get_sample_line()
            << ", cost time=" << timeline.ElapsedSec()
            << " seconds, thread_id=" << thread_id_;
  }
  VLOG(3) << "LoadIntoMemory() end, thread_id=" << thread_id_
          << ", total size: " << line_reader.file_size();
#endif
}

2399 2400 2401 2402
static void parser_log_key(const std::string& log_key,
                           uint64_t* search_id,
                           uint32_t* cmatch,
                           uint32_t* rank) {
Y
yaoxuefeng 已提交
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
  std::string searchid_str = log_key.substr(16, 16);
  *search_id = static_cast<uint64_t>(strtoull(searchid_str.c_str(), NULL, 16));
  std::string cmatch_str = log_key.substr(11, 3);
  *cmatch = static_cast<uint32_t>(strtoul(cmatch_str.c_str(), NULL, 16));
  std::string rank_str = log_key.substr(14, 2);
  *rank = static_cast<uint32_t>(strtoul(rank_str.c_str(), NULL, 16));
}

bool SlotRecordInMemoryDataFeed::ParseOneInstance(const std::string& line,
                                                  SlotRecord* ins) {
  SlotRecord& rec = (*ins);
  // parse line
  const char* str = line.c_str();
  char* endptr = const_cast<char*>(str);
  int pos = 0;

  thread_local std::vector<std::vector<float>> slot_float_feasigns;
  thread_local std::vector<std::vector<uint64_t>> slot_uint64_feasigns;
  slot_float_feasigns.resize(float_use_slot_size_);
  slot_uint64_feasigns.resize(uint64_use_slot_size_);

  if (parse_ins_id_) {
    int num = strtol(&str[pos], &endptr, 10);
    CHECK(num == 1);  // NOLINT
    pos = endptr - str + 1;
    size_t len = 0;
    while (str[pos + len] != ' ') {
      ++len;
    }
    rec->ins_id_ = std::string(str + pos, len);
    pos += len + 1;
  }
  if (parse_logkey_) {
    int num = strtol(&str[pos], &endptr, 10);
    CHECK(num == 1);  // NOLINT
    pos = endptr - str + 1;
    size_t len = 0;
    while (str[pos + len] != ' ') {
      ++len;
    }
    // parse_logkey
    std::string log_key = std::string(str + pos, len);
    uint64_t search_id;
    uint32_t cmatch;
    uint32_t rank;
    parser_log_key(log_key, &search_id, &cmatch, &rank);

    rec->ins_id_ = log_key;
    rec->search_id = search_id;
    rec->cmatch = cmatch;
    rec->rank = rank;
    pos += len + 1;
  }

  int float_total_slot_num = 0;
  int uint64_total_slot_num = 0;

2460
  for (auto& info : all_slots_info_) {
Y
yaoxuefeng 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    int num = strtol(&str[pos], &endptr, 10);
    PADDLE_ENFORCE(num,
                   "The number of ids can not be zero, you need padding "
                   "it in data generator; or if there is something wrong with "
                   "the data, please check if the data contains unresolvable "
                   "characters.\nplease check this error line: %s",
                   str);
    if (info.used_idx != -1) {
      if (info.type[0] == 'f') {  // float
        auto& slot_fea = slot_float_feasigns[info.slot_value_idx];
        slot_fea.clear();
        for (int j = 0; j < num; ++j) {
          float feasign = strtof(endptr, &endptr);
          if (fabs(feasign) < 1e-6 && !used_slots_info_[info.used_idx].dense) {
            continue;
          }
          slot_fea.push_back(feasign);
          ++float_total_slot_num;
        }
      } else if (info.type[0] == 'u') {  // uint64
        auto& slot_fea = slot_uint64_feasigns[info.slot_value_idx];
        slot_fea.clear();
        for (int j = 0; j < num; ++j) {
          uint64_t feasign =
              static_cast<uint64_t>(strtoull(endptr, &endptr, 10));
          slot_fea.push_back(feasign);
          ++uint64_total_slot_num;
        }
      }
      pos = endptr - str;
    } else {
      for (int j = 0; j <= num; ++j) {
        // pos = line.find_first_of(' ', pos + 1);
        while (line[pos + 1] != ' ') {
          pos++;
        }
      }
    }
  }
  rec->slot_float_feasigns_.add_slot_feasigns(slot_float_feasigns,
                                              float_total_slot_num);
  rec->slot_uint64_feasigns_.add_slot_feasigns(slot_uint64_feasigns,
                                               uint64_total_slot_num);

  return (uint64_total_slot_num > 0);
}

2508 2509
void SlotRecordInMemoryDataFeed::AssignFeedVar(const Scope& scope) {
  CheckInit();
P
pangengzheng 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
  if (scpoe_feed_vec_.count(&scope) > 0) {
    return;
  }
  auto& feed_vec = scpoe_feed_vec_[&scope];
  feed_vec.resize(used_slots_info_.size());
  for (int i = 0; i < use_slot_size_; ++i) {
    feed_vec[i] =
        scope.FindVar(used_slots_info_[i].slot)->GetMutable<phi::DenseTensor>();
  }
#else
2521 2522
  for (int i = 0; i < use_slot_size_; ++i) {
    feed_vec_[i] =
2523
        scope.FindVar(used_slots_info_[i].slot)->GetMutable<phi::DenseTensor>();
2524
  }
P
pangengzheng 已提交
2525
#endif
2526 2527
}

Y
yaoxuefeng 已提交
2528 2529
void SlotRecordInMemoryDataFeed::PutToFeedVec(const SlotRecord* ins_vec,
                                              int num) {
P
pangengzheng 已提交
2530 2531 2532 2533 2534 2535 2536 2537
  // set ins id
  if (parse_ins_id_) {
    ins_id_vec_.clear();
    ins_id_vec_.resize(num);
    for (int i = 0; i < num; ++i) {
      ins_id_vec_[i] = ins_vec[i]->ins_id_;
    }
  }
2538
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
P
pangengzheng 已提交
2539
  // do nothing
2540
#else
Y
yaoxuefeng 已提交
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
  for (int j = 0; j < use_slot_size_; ++j) {
    auto& feed = feed_vec_[j];
    if (feed == nullptr) {
      continue;
    }

    auto& slot_offset = offset_[j];
    slot_offset.clear();
    slot_offset.reserve(num + 1);
    slot_offset.push_back(0);

    int total_instance = 0;
    auto& info = used_slots_info_[j];
    // fill slot value with default value 0
    if (info.type[0] == 'f') {  // float
      auto& batch_fea = batch_float_feasigns_[j];
      batch_fea.clear();

      for (int i = 0; i < num; ++i) {
        auto r = ins_vec[i];
        size_t fea_num = 0;
        float* slot_values =
            r->slot_float_feasigns_.get_values(info.slot_value_idx, &fea_num);
        batch_fea.resize(total_instance + fea_num);
2565 2566
        memcpy(
            &batch_fea[total_instance], slot_values, sizeof(float) * fea_num);
Y
yaoxuefeng 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
        total_instance += fea_num;
        slot_offset.push_back(total_instance);
      }

      float* feasign = batch_fea.data();
      float* tensor_ptr =
          feed->mutable_data<float>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(float));

    } else if (info.type[0] == 'u') {  // uint64
      auto& batch_fea = batch_uint64_feasigns_[j];
      batch_fea.clear();

      for (int i = 0; i < num; ++i) {
        auto r = ins_vec[i];
        size_t fea_num = 0;
        uint64_t* slot_values =
            r->slot_uint64_feasigns_.get_values(info.slot_value_idx, &fea_num);
        if (fea_num > 0) {
          batch_fea.resize(total_instance + fea_num);
2587 2588
          memcpy(&batch_fea[total_instance],
                 slot_values,
Y
yaoxuefeng 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
                 sizeof(uint64_t) * fea_num);
          total_instance += fea_num;
        }
        if (fea_num == 0) {
          batch_fea.resize(total_instance + fea_num);
          batch_fea[total_instance] = 0;
          total_instance += 1;
        }
        slot_offset.push_back(total_instance);
      }

      // no uint64_t type in paddlepaddle
      uint64_t* feasign = batch_fea.data();
      int64_t* tensor_ptr =
          feed->mutable_data<int64_t>({total_instance, 1}, this->place_);
      CopyToFeedTensor(tensor_ptr, feasign, total_instance * sizeof(int64_t));
    }

    if (info.dense) {
      if (info.inductive_shape_index != -1) {
        info.local_shape[info.inductive_shape_index] =
            total_instance / info.total_dims_without_inductive;
      }
2612
      feed->Resize(phi::make_ddim(info.local_shape));
Y
yaoxuefeng 已提交
2613 2614 2615 2616 2617
    } else {
      LoD data_lod{slot_offset};
      feed_vec_[j]->set_lod(data_lod);
    }
  }
2618
#endif
Y
yaoxuefeng 已提交
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
}

void SlotRecordInMemoryDataFeed::ExpandSlotRecord(SlotRecord* rec) {
  SlotRecord& ins = (*rec);
  if (ins->slot_float_feasigns_.slot_offsets.empty()) {
    return;
  }
  size_t total_value_size = ins->slot_float_feasigns_.slot_values.size();
  if (float_total_dims_size_ == total_value_size) {
    return;
  }
  int float_slot_num =
      static_cast<int>(float_total_dims_without_inductives_.size());
  CHECK(float_slot_num == float_use_slot_size_);
  std::vector<float> old_values;
  std::vector<uint32_t> old_offsets;
  old_values.swap(ins->slot_float_feasigns_.slot_values);
  old_offsets.swap(ins->slot_float_feasigns_.slot_offsets);

  ins->slot_float_feasigns_.slot_values.resize(float_total_dims_size_);
  ins->slot_float_feasigns_.slot_offsets.assign(float_slot_num + 1, 0);

  auto& slot_offsets = ins->slot_float_feasigns_.slot_offsets;
  auto& slot_values = ins->slot_float_feasigns_.slot_values;

  uint32_t offset = 0;
  int num = 0;
  uint32_t old_off = 0;
  int dim = 0;

  for (int i = 0; i < float_slot_num; ++i) {
    dim = float_total_dims_without_inductives_[i];
    old_off = old_offsets[i];
    num = static_cast<int>(old_offsets[i + 1] - old_off);
    if (num == 0) {
      // fill slot value with default value 0
      for (int k = 0; k < dim; ++k) {
        slot_values[k + offset] = 0.0;
      }
    } else {
      if (num == dim) {
        memcpy(&slot_values[offset], &old_values[old_off], dim * sizeof(float));
      } else {
        // position fea
        // record position index need fix values
        int pos_idx = static_cast<int>(old_values[old_off]);
        for (int k = 0; k < dim; ++k) {
          if (k == pos_idx) {
            slot_values[k + offset] = 1.0;
          } else {
            slot_values[k + offset] = 0.0;
          }
        }
      }
    }
    slot_offsets[i] = offset;
    offset += dim;
  }
  slot_offsets[float_slot_num] = offset;
  CHECK(float_total_dims_size_ == static_cast<size_t>(offset));
}

bool SlotRecordInMemoryDataFeed::Start() {
P
pangengzheng 已提交
2682
  VLOG(3) << "entering SlotRecordInMemoryDataFeed::Start";
Y
yaoxuefeng 已提交
2683 2684 2685 2686 2687 2688 2689
#ifdef _LINUX
  this->CheckSetFileList();
  if (input_channel_->Size() != 0) {
    std::vector<SlotRecord> data;
    input_channel_->Read(data);
  }
#endif
2690
  if (!batch_offsets_.empty()) {
Y
yaoxuefeng 已提交
2691 2692 2693 2694 2695
    VLOG(3) << "batch_size offsets: " << batch_offsets_.size();
    enable_heterps_ = true;
    this->offset_index_ = 0;
  }
  this->finish_start_ = true;
2696 2697
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
  CHECK(paddle::platform::is_gpu_place(this->place_));
P
pangengzheng 已提交
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
  for (int i = 0; i < pack_thread_num_ + 1; i++) {
    auto pack = BatchGpuPackMgr().get(this->GetPlace(), used_slots_info_);
    pack_vec_.push_back(pack);
    free_pack_queue_.Push(pack);
  }

  pack_offset_index_.store(0);
  pack_is_end_.store(false);
  thread_count_.store(pack_thread_num_);
  pack_threads_.reserve(pack_thread_num_);
  for (int i = 0; i < pack_thread_num_; i++) {
    pack_threads_.emplace_back(std::thread([this]() -> void {
      while (!stop_token_.load()) {
        uint64_t offset_index = pack_offset_index_.fetch_add(1);
        if (offset_index >= batch_offsets_.size()) {
          int thread_num = thread_count_.fetch_sub(1);
          if (thread_num == 1) {
            pack_is_end_.store(true);
          }
          return;
        }
        auto* pack = free_pack_queue_.Pop();

        auto& batch = batch_offsets_[offset_index];
        auto offset = batch.first;
        auto batch_size = batch.second;

        paddle::platform::SetDeviceId(place_.GetDeviceId());
        pack->pack_instance(&records_[offset], batch_size);
        this->BuildSlotBatchGPU(batch_size, pack);
        using_pack_queue_.Push(pack);
      }
    }));
  }
D
danleifeng 已提交
2732 2733
#endif
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
L
lxsbupt 已提交
2734
  gpu_graph_data_generator_.SetFeedVec(feed_vec_);
2735
#endif
Y
yaoxuefeng 已提交
2736 2737 2738 2739 2740 2741
  return true;
}

int SlotRecordInMemoryDataFeed::Next() {
#ifdef _LINUX
  this->CheckStart();
D
danleifeng 已提交
2742
  if (!gpu_graph_mode_) {
P
pangengzheng 已提交
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
    while (true) {
      if (last_pack_ != nullptr) {
        free_pack_queue_.Push(last_pack_);
        last_pack_ = nullptr;
      }
      if (using_pack_queue_.Size() != 0) {
        auto* pack = using_pack_queue_.Pop();
        PackToScope(pack);
        last_pack_ = pack;
        return pack->ins_num();
      }
      bool is_end = pack_is_end_.load();
      if (is_end) {
        if (using_pack_queue_.Size() == 0) {
          return 0;
        }
      }
      std::this_thread::sleep_for(std::chrono::microseconds(200));
    }
#else
D
danleifeng 已提交
2764
    VLOG(3) << "enable heter next: " << offset_index_
Y
yaoxuefeng 已提交
2765
            << " batch_offsets: " << batch_offsets_.size();
D
danleifeng 已提交
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
    if (offset_index_ >= batch_offsets_.size()) {
      VLOG(3) << "offset_index: " << offset_index_
              << " batch_offsets: " << batch_offsets_.size();
      return 0;
    }
    auto& batch = batch_offsets_[offset_index_++];
    this->batch_size_ = batch.second;
    VLOG(3) << "batch_size_=" << this->batch_size_
            << ", thread_id=" << thread_id_;
    if (this->batch_size_ != 0) {
      PutToFeedVec(&records_[batch.first], this->batch_size_);
    } else {
      VLOG(3) << "finish reading for heterps, batch size zero, thread_id="
              << thread_id_;
    }
P
pangengzheng 已提交
2781
#endif
Y
yaoxuefeng 已提交
2782
  } else {
D
danleifeng 已提交
2783 2784 2785 2786
    VLOG(3) << "datafeed in gpu graph mode";
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
    this->batch_size_ = gpu_graph_data_generator_.GenerateBatch();
#endif
Y
yaoxuefeng 已提交
2787 2788 2789 2790 2791 2792 2793 2794
  }

  return this->batch_size_;
#else
  return 0;
#endif
}

L
lxsbupt 已提交
2795 2796 2797 2798 2799 2800
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
void SlotRecordInMemoryDataFeed::DoWalkandSage() {
  gpu_graph_data_generator_.DoWalkandSage();
}
#endif

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
void SlotRecordInMemoryDataFeed::DumpWalkPath(std::string dump_path,
                                              size_t dump_rate) {
  VLOG(3) << "INTO SlotRecordInMemoryDataFeed::DumpWalkPath";
#if defined(PADDLE_WITH_GPU_GRAPH) && defined(PADDLE_WITH_HETERPS)
  std::string path =
      string::format_string("%s/part-%03d", dump_path.c_str(), thread_id_);
  gpu_graph_data_generator_.DumpWalkPath(path, dump_rate);
#endif
}

2811
#if defined(PADDLE_WITH_CUDA) && defined(PADDLE_WITH_HETERPS)
P
pangengzheng 已提交
2812 2813
void SlotRecordInMemoryDataFeed::BuildSlotBatchGPU(const int ins_num,
                                                   MiniBatchGpuPack* pack) {
2814 2815
  int offset_cols_size = (ins_num + 1);
  size_t slot_total_num = (use_slot_size_ * offset_cols_size);
P
pangengzheng 已提交
2816
  pack->resize_gpu_slot_offsets(slot_total_num * sizeof(size_t));
2817

P
pangengzheng 已提交
2818
  auto& value = pack->value();
2819
  const UsedSlotGpuType* used_slot_gpu_types =
P
pangengzheng 已提交
2820
      static_cast<const UsedSlotGpuType*>(pack->get_gpu_slots());
2821 2822
  FillSlotValueOffset(ins_num,
                      use_slot_size_,
P
pangengzheng 已提交
2823
                      reinterpret_cast<size_t*>(pack->gpu_slot_offsets()),
2824 2825 2826 2827
                      value.d_uint64_offset.data(),
                      uint64_use_slot_size_,
                      value.d_float_offset.data(),
                      float_use_slot_size_,
P
pangengzheng 已提交
2828 2829 2830
                      used_slot_gpu_types,
                      pack->get_stream());
  size_t* d_slot_offsets = reinterpret_cast<size_t*>(pack->gpu_slot_offsets());
2831

P
pangengzheng 已提交
2832
  HostBuffer<size_t>& offsets = pack->offsets();
2833
  offsets.resize(slot_total_num);
P
pangengzheng 已提交
2834
  HostBuffer<void*>& h_tensor_ptrs = pack->h_tensor_ptrs();
2835 2836
  h_tensor_ptrs.resize(use_slot_size_);
  // alloc gpu memory
P
pangengzheng 已提交
2837
  pack->resize_tensor();
2838

P
pangengzheng 已提交
2839 2840
  phi::DenseTensor& float_tensor = pack->float_tensor();
  phi::DenseTensor& uint64_tensor = pack->uint64_tensor();
2841 2842 2843

  int64_t float_offset = 0;
  int64_t uint64_offset = 0;
P
pangengzheng 已提交
2844 2845
  size_t float_zero_slot_index = 0;
  size_t uint64_zero_slot_index = 0;
2846 2847

  // copy index
2848 2849
  CUDA_CHECK(cudaMemcpy(offsets.data(),
                        d_slot_offsets,
2850 2851
                        slot_total_num * sizeof(size_t),
                        cudaMemcpyDeviceToHost));
P
pangengzheng 已提交
2852 2853
  auto* dev_ctx = static_cast<phi::GPUContext*>(
      platform::DeviceContextPool::Instance().Get(this->place_));
2854
  for (int j = 0; j < use_slot_size_; ++j) {
P
pangengzheng 已提交
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
    if (scpoe_feed_vec_.size() > 0) {
      if (scpoe_feed_vec_.begin()->second[j] == nullptr) {
        h_tensor_ptrs[j] = nullptr;
        continue;
      }
    } else {
      if (feed_vec_[j] == nullptr) {
        h_tensor_ptrs[j] = nullptr;
        continue;
      }
2865 2866 2867 2868 2869
    }

    size_t* off_start_ptr = &offsets[j * offset_cols_size];

    int total_instance = static_cast<int>(off_start_ptr[offset_cols_size - 1]);
2870 2871
    CHECK(total_instance >= 0)
        << "slot idx:" << j << ", total instance:" << total_instance;
2872 2873
    auto& info = used_slots_info_[j];

P
pangengzheng 已提交
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
    // fill slot value with default value 0
    if (info.type[0] == 'f') {  // float
      if (total_instance > 0) {
        h_tensor_ptrs[j] = float_tensor.data<float>() + float_offset;
        float_offset += total_instance;
      } else {
        phi::DenseTensor& f_tensor =
            pack->float_tensor_vec()[float_zero_slot_index];
        f_tensor.Resize({total_instance, 1});
        dev_ctx->Alloc<float>(&f_tensor);
        h_tensor_ptrs[j] = f_tensor.data<float>();
        float_zero_slot_index++;
      }
    } else if (info.type[0] == 'u') {  // uint64
      if (total_instance > 0) {
        h_tensor_ptrs[j] = uint64_tensor.data<int64_t>() + uint64_offset;
        uint64_offset += total_instance;
      } else {
        phi::DenseTensor& i_tensor =
            pack->uint64_tensor_vec()[uint64_zero_slot_index];
        i_tensor.Resize({total_instance, 1});
        dev_ctx->Alloc<int64_t>(&i_tensor);
        h_tensor_ptrs[j] = i_tensor.data<int64_t>();
        uint64_zero_slot_index++;
      }
    }
  }
  void** dest_gpu_p = reinterpret_cast<void**>(pack->slot_buf_ptr());
  CUDA_CHECK(cudaMemcpyAsync(dest_gpu_p,
                             h_tensor_ptrs.data(),
                             use_slot_size_ * sizeof(void*),
                             cudaMemcpyHostToDevice,
                             pack->get_stream()));

  CopyForTensor(ins_num,
                use_slot_size_,
                dest_gpu_p,
                (const size_t*)pack->gpu_slot_offsets(),
                (const uint64_t*)value.d_uint64_keys.data(),
                (const int*)value.d_uint64_offset.data(),
                (const int*)value.d_uint64_lens.data(),
                uint64_use_slot_size_,
                (const float*)value.d_float_keys.data(),
                (const int*)value.d_float_offset.data(),
                (const int*)value.d_float_lens.data(),
                float_use_slot_size_,
                used_slot_gpu_types,
                pack->get_stream());
}

void SlotRecordInMemoryDataFeed::PackToScope(MiniBatchGpuPack* pack,
                                             const Scope* scope) {
  int64_t float_offset = 0;
  int64_t uint64_offset = 0;
  size_t float_zero_slot_index = 0;
  size_t uint64_zero_slot_index = 0;

  int offset_cols_size = (pack->ins_num() + 1);
  HostBuffer<size_t>& offsets = pack->offsets();
  phi::DenseTensor& float_tensor = pack->float_tensor();
  phi::DenseTensor& uint64_tensor = pack->uint64_tensor();

  auto* feed_vec = &feed_vec_;
  if (scope) {
    CHECK(scpoe_feed_vec_.count(scope) > 0) << "scope not found.";
    feed_vec = &scpoe_feed_vec_[scope];
  }

  CHECK(feed_vec != nullptr) << "feed_vec nullptr.";

  for (int j = 0; j < use_slot_size_; ++j) {
    auto& feed = (*feed_vec)[j];
    if (feed == nullptr) {
      continue;
    }
    size_t* off_start_ptr = &offsets[j * offset_cols_size];
    int total_instance = static_cast<int>(off_start_ptr[offset_cols_size - 1]);
    auto& info = used_slots_info_[j];

2953 2954 2955 2956 2957 2958 2959 2960 2961
    // fill slot value with default value 0
    if (info.type[0] == 'f') {  // float
      if (total_instance > 0) {
        feed->ShareDataWith(float_tensor.Slice(
            static_cast<int64_t>(float_offset),
            static_cast<int64_t>(float_offset + total_instance)));
        feed->Resize({total_instance, 1});
        float_offset += total_instance;
      } else {
P
pangengzheng 已提交
2962 2963
        feed->ShareDataWith(pack->float_tensor_vec()[float_zero_slot_index++]);
        feed->Resize({total_instance, 1});
2964 2965 2966 2967 2968 2969 2970 2971 2972
      }
    } else if (info.type[0] == 'u') {  // uint64
      if (total_instance > 0) {
        feed->ShareDataWith(uint64_tensor.Slice(
            static_cast<int64_t>(uint64_offset),
            static_cast<int64_t>(uint64_offset + total_instance)));
        feed->Resize({total_instance, 1});
        uint64_offset += total_instance;
      } else {
P
pangengzheng 已提交
2973 2974 2975
        feed->ShareDataWith(
            pack->uint64_tensor_vec()[uint64_zero_slot_index++]);
        feed->Resize({total_instance, 1});
2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
      }
    }

    if (info.dense) {
      if (info.inductive_shape_index != -1) {
        info.local_shape[info.inductive_shape_index] =
            total_instance / info.total_dims_without_inductive;
      }
      feed->Resize(phi::make_ddim(info.local_shape));
    } else {
      LoD& lod = (*feed->mutable_lod());
      lod.resize(1);
      lod[0].resize(offset_cols_size);
H
Huang Jiyi 已提交
2989
      phi::MixVector<size_t> mixv_lod(&lod[0]);
2990 2991
      memcpy(mixv_lod.MutableData(platform::CPUPlace()),
             off_start_ptr,
2992 2993 2994 2995 2996
             offset_cols_size * sizeof(size_t));
    }
  }
}

P
pangengzheng 已提交
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
MiniBatchGpuPack* SlotRecordInMemoryDataFeed::get_pack(
    MiniBatchGpuPack* last_pack) {
  if (last_pack != nullptr) {
    free_pack_queue_.Push(last_pack);
    return nullptr;
  }

  std::unique_lock<std::mutex> lock(pack_mutex_);
  while (true) {
    if (using_pack_queue_.Size() != 0) {
      auto* pack = using_pack_queue_.Pop();
      return pack;
    }
    bool is_end = pack_is_end_.load();
    if (is_end) {
      if (using_pack_queue_.Size() == 0) {
        return nullptr;
      }
    }
    std::this_thread::sleep_for(std::chrono::microseconds(200));
  }
}

3020
MiniBatchGpuPack::MiniBatchGpuPack(const paddle::platform::Place& place,
P
pangengzheng 已提交
3021 3022
                                   const std::vector<UsedSlotInfo>& infos,
                                   phi::StreamId stream_id) {
3023
  place_ = place;
P
pangengzheng 已提交
3024 3025
  stream_holder_.reset(new phi::CUDAStream(place));
  stream_ = stream_holder_->raw_stream();
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050

  ins_num_ = 0;
  pv_num_ = 0;
  used_float_num_ = 0;
  used_uint64_num_ = 0;

  used_slot_size_ = static_cast<int>(infos.size());
  for (int i = 0; i < used_slot_size_; ++i) {
    auto& info = infos[i];
    if (info.type[0] == 'u') {
      gpu_used_slots_.push_back({1, info.slot_value_idx});
      ++used_uint64_num_;
    } else {
      gpu_used_slots_.push_back({0, info.slot_value_idx});
      ++used_float_num_;
    }
  }
  copy_host2device(&gpu_slots_, gpu_used_slots_.data(), gpu_used_slots_.size());

  slot_buf_ptr_ = memory::AllocShared(place_, used_slot_size_ * sizeof(void*));

  int device_id = place_.GetDeviceId();
  VLOG(3) << "begin get batch pack device id: " << device_id;
  // sync
  CUDA_CHECK(cudaStreamSynchronize(stream_));
P
pangengzheng 已提交
3051 3052
  float_tensor_vec_.resize(used_slot_size_);
  uint64_tensor_vec_.resize(used_slot_size_);
3053 3054 3055 3056 3057 3058
}

MiniBatchGpuPack::~MiniBatchGpuPack() {}

void MiniBatchGpuPack::reset(const paddle::platform::Place& place) {
  place_ = place;
P
pangengzheng 已提交
3059 3060
  stream_holder_.reset(new phi::CUDAStream(place));
  stream_ = stream_holder_->raw_stream();
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
  ins_num_ = 0;
  pv_num_ = 0;
}

void MiniBatchGpuPack::pack_all_data(const SlotRecord* ins_vec, int num) {
  int uint64_total_num = 0;
  int float_total_num = 0;

  buf_.h_uint64_lens.resize(num + 1);
  buf_.h_uint64_lens[0] = 0;
  buf_.h_float_lens.resize(num + 1);
  buf_.h_float_lens[0] = 0;

  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    uint64_total_num += r->slot_uint64_feasigns_.slot_values.size();
    buf_.h_uint64_lens[i + 1] = uint64_total_num;
    float_total_num += r->slot_float_feasigns_.slot_values.size();
    buf_.h_float_lens[i + 1] = float_total_num;
  }

  int uint64_cols = (used_uint64_num_ + 1);
  buf_.h_uint64_offset.resize(uint64_cols * num);
  buf_.h_uint64_keys.resize(uint64_total_num);

  int float_cols = (used_float_num_ + 1);
  buf_.h_float_offset.resize(float_cols * num);
  buf_.h_float_keys.resize(float_total_num);

  size_t fea_num = 0;
  uint64_total_num = 0;
  float_total_num = 0;
  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    auto& uint64_feasigns = r->slot_uint64_feasigns_;
    fea_num = uint64_feasigns.slot_values.size();
    if (fea_num > 0) {
      memcpy(&buf_.h_uint64_keys[uint64_total_num],
3099 3100
             uint64_feasigns.slot_values.data(),
             fea_num * sizeof(uint64_t));
3101 3102 3103 3104
    }
    uint64_total_num += fea_num;
    // copy uint64 offset
    memcpy(&buf_.h_uint64_offset[i * uint64_cols],
3105 3106
           uint64_feasigns.slot_offsets.data(),
           sizeof(int) * uint64_cols);
3107 3108 3109 3110

    auto& float_feasigns = r->slot_float_feasigns_;
    fea_num = float_feasigns.slot_values.size();
    memcpy(&buf_.h_float_keys[float_total_num],
3111 3112
           float_feasigns.slot_values.data(),
           fea_num * sizeof(float));
3113 3114 3115 3116
    float_total_num += fea_num;

    // copy float offset
    memcpy(&buf_.h_float_offset[i * float_cols],
3117 3118
           float_feasigns.slot_offsets.data(),
           sizeof(int) * float_cols);
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
  }

  CHECK(uint64_total_num == static_cast<int>(buf_.h_uint64_lens.back()))
      << "uint64 value length error";
  CHECK(float_total_num == static_cast<int>(buf_.h_float_lens.back()))
      << "float value length error";
}
void MiniBatchGpuPack::pack_uint64_data(const SlotRecord* ins_vec, int num) {
  int uint64_total_num = 0;

  buf_.h_float_lens.clear();
  buf_.h_float_keys.clear();
  buf_.h_float_offset.clear();

  buf_.h_uint64_lens.resize(num + 1);
  buf_.h_uint64_lens[0] = 0;

  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    uint64_total_num += r->slot_uint64_feasigns_.slot_values.size();
    buf_.h_uint64_lens[i + 1] = uint64_total_num;
  }

  int uint64_cols = (used_uint64_num_ + 1);
  buf_.h_uint64_offset.resize(uint64_cols * num);
  buf_.h_uint64_keys.resize(uint64_total_num);

  size_t fea_num = 0;
  uint64_total_num = 0;
  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    auto& uint64_feasigns = r->slot_uint64_feasigns_;
    fea_num = uint64_feasigns.slot_values.size();
    if (fea_num > 0) {
      memcpy(&buf_.h_uint64_keys[uint64_total_num],
3154 3155
             uint64_feasigns.slot_values.data(),
             fea_num * sizeof(uint64_t));
3156 3157 3158 3159
    }
    uint64_total_num += fea_num;
    // copy uint64 offset
    memcpy(&buf_.h_uint64_offset[i * uint64_cols],
3160 3161
           uint64_feasigns.slot_offsets.data(),
           sizeof(int) * uint64_cols);
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
  }
  CHECK(uint64_total_num == static_cast<int>(buf_.h_uint64_lens.back()))
      << "uint64 value length error";
}
void MiniBatchGpuPack::pack_float_data(const SlotRecord* ins_vec, int num) {
  int float_total_num = 0;

  buf_.h_uint64_lens.clear();
  buf_.h_uint64_offset.clear();
  buf_.h_uint64_keys.clear();

  buf_.h_float_lens.resize(num + 1);
  buf_.h_float_lens[0] = 0;

  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    float_total_num += r->slot_float_feasigns_.slot_values.size();
    buf_.h_float_lens[i + 1] = float_total_num;
  }

  int float_cols = (used_float_num_ + 1);
  buf_.h_float_offset.resize(float_cols * num);
  buf_.h_float_keys.resize(float_total_num);

  size_t fea_num = 0;
  float_total_num = 0;
  for (int i = 0; i < num; ++i) {
    auto r = ins_vec[i];
    auto& float_feasigns = r->slot_float_feasigns_;
    fea_num = float_feasigns.slot_values.size();
    memcpy(&buf_.h_float_keys[float_total_num],
3193 3194
           float_feasigns.slot_values.data(),
           fea_num * sizeof(float));
3195 3196 3197 3198
    float_total_num += fea_num;

    // copy float offset
    memcpy(&buf_.h_float_offset[i * float_cols],
3199 3200
           float_feasigns.slot_offsets.data(),
           sizeof(int) * float_cols);
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
  }
  CHECK(float_total_num == static_cast<int>(buf_.h_float_lens.back()))
      << "float value length error";
}

void MiniBatchGpuPack::pack_instance(const SlotRecord* ins_vec, int num) {
  ins_num_ = num;
  batch_ins_ = ins_vec;
  CHECK(used_uint64_num_ > 0 || used_float_num_ > 0);
  // uint64 and float
  if (used_uint64_num_ > 0 && used_float_num_ > 0) {
    pack_all_data(ins_vec, num);
  } else if (used_uint64_num_ > 0) {  // uint64
    pack_uint64_data(ins_vec, num);
  } else {  // only float
    pack_float_data(ins_vec, num);
  }
  // to gpu
  transfer_to_gpu();
}

3222
void MiniBatchGpuPack::transfer_to_gpu() {
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
  copy_host2device(&value_.d_uint64_lens, buf_.h_uint64_lens);
  copy_host2device(&value_.d_uint64_keys, buf_.h_uint64_keys);
  copy_host2device(&value_.d_uint64_offset, buf_.h_uint64_offset);

  copy_host2device(&value_.d_float_lens, buf_.h_float_lens);
  copy_host2device(&value_.d_float_keys, buf_.h_float_keys);
  copy_host2device(&value_.d_float_offset, buf_.h_float_offset);
  CUDA_CHECK(cudaStreamSynchronize(stream_));
}
#endif

W
Wang Guibao 已提交
3234 3235
}  // namespace framework
}  // namespace paddle