box_wrapper.h 38.9 KB
Newer Older
H
hutuxian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2019 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. */

#pragma once

H
hutuxian 已提交
17
#ifdef PADDLE_WITH_BOX_PS
H
hutuxian 已提交
18
#include <afs_filesystem.h>
H
hutuxian 已提交
19
#include <boxps_public.h>
H
hutuxian 已提交
20 21 22 23 24
#include <dirent.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
H
hutuxian 已提交
25
#endif
H
hutuxian 已提交
26
#include <glog/logging.h>
H
hutuxian 已提交
27 28 29 30 31
#include <algorithm>
#include <atomic>
#include <ctime>
#include <deque>
#include <map>
H
hutuxian 已提交
32 33
#include <memory>
#include <mutex>  // NOLINT
34
#include <set>
H
hutuxian 已提交
35
#include <string>
H
hutuxian 已提交
36
#include <unordered_set>
H
hutuxian 已提交
37
#include <utility>
H
hutuxian 已提交
38
#include <vector>
39
#include "paddle/fluid/framework/data_feed.h"
H
hutuxian 已提交
40
#include "paddle/fluid/framework/data_set.h"
H
hutuxian 已提交
41
#include "paddle/fluid/framework/lod_tensor.h"
H
hutuxian 已提交
42
#include "paddle/fluid/framework/scope.h"
H
hutuxian 已提交
43 44
#include "paddle/fluid/platform/gpu_info.h"
#include "paddle/fluid/platform/place.h"
H
hutuxian 已提交
45
#include "paddle/fluid/platform/timer.h"
H
hutuxian 已提交
46
#include "paddle/fluid/string/string_helper.h"
H
hutuxian 已提交
47
#define BUF_SIZE 1024 * 1024
H
hutuxian 已提交
48

49 50
extern void comlog_set_log_level(int log_level);
extern int com_logstatus();
H
hutuxian 已提交
51 52 53
namespace paddle {
namespace framework {

H
hutuxian 已提交
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
#ifdef PADDLE_WITH_BOX_PS
class BasicAucCalculator {
 public:
  BasicAucCalculator() {}
  void init(int table_size) { set_table_size(table_size); }
  void reset() {
    for (int i = 0; i < 2; i++) {
      _table[i].assign(_table_size, 0.0);
    }
    _local_abserr = 0;
    _local_sqrerr = 0;
    _local_pred = 0;
  }
  void add_data(double pred, int label) {
    PADDLE_ENFORCE_GE(pred, 0.0, platform::errors::PreconditionNotMet(
                                     "pred should be greater than 0"));
    PADDLE_ENFORCE_LE(pred, 1.0, platform::errors::PreconditionNotMet(
                                     "pred should be lower than 1"));
    PADDLE_ENFORCE_EQ(
        label * label, label,
        platform::errors::PreconditionNotMet(
            "label must be equal to 0 or 1, but its value is: %d", label));
    int pos = std::min(static_cast<int>(pred * _table_size), _table_size - 1);
    PADDLE_ENFORCE_GE(
        pos, 0,
        platform::errors::PreconditionNotMet(
            "pos must be equal or greater than 0, but its value is: %d", pos));
    PADDLE_ENFORCE_LT(
        pos, _table_size,
        platform::errors::PreconditionNotMet(
            "pos must be less than table_size, but its value is: %d", pos));
    std::lock_guard<std::mutex> lock(_table_mutex);
    _local_abserr += fabs(pred - label);
    _local_sqrerr += (pred - label) * (pred - label);
    _local_pred += pred;
    _table[label][pos]++;
  }
  void compute();
  int table_size() const { return _table_size; }
  double bucket_error() const { return _bucket_error; }
  double auc() const { return _auc; }
  double mae() const { return _mae; }
  double actual_ctr() const { return _actual_ctr; }
  double predicted_ctr() const { return _predicted_ctr; }
  double size() const { return _size; }
  double rmse() const { return _rmse; }
  std::vector<double>& get_negative() { return _table[0]; }
  std::vector<double>& get_postive() { return _table[1]; }
  double& local_abserr() { return _local_abserr; }
  double& local_sqrerr() { return _local_sqrerr; }
  double& local_pred() { return _local_pred; }
  void calculate_bucket_error();

 protected:
  double _local_abserr = 0;
  double _local_sqrerr = 0;
  double _local_pred = 0;
  double _auc = 0;
  double _mae = 0;
  double _rmse = 0;
  double _actual_ctr = 0;
  double _predicted_ctr = 0;
  double _size;
  double _bucket_error = 0;

 private:
  void set_table_size(int table_size) {
    _table_size = table_size;
    for (int i = 0; i < 2; i++) {
      _table[i] = std::vector<double>();
    }
    reset();
  }
  int _table_size;
  std::vector<double> _table[2];
  static constexpr double kRelativeErrorBound = 0.05;
  static constexpr double kMaxSpan = 0.01;
  std::mutex _table_mutex;
};

H
hutuxian 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
class AfsStreamFile {
 public:
  explicit AfsStreamFile(afs::AfsFileSystem* afsfile)
      : afsfile_(afsfile), reader_(nullptr) {}
  virtual ~AfsStreamFile() {
    if (reader_ != NULL) {
      afsfile_->CloseReader(reader_);
      reader_ = NULL;
    }
  }
  virtual int Open(const char* path) {
    if (path == NULL) {
      return -1;
    }
    reader_ = afsfile_->OpenReader(path);
    PADDLE_ENFORCE_NE(reader_, nullptr,
                      platform::errors::PreconditionNotMet(
                          "OpenReader for file[%s] failed.", path));
    return 0;
  }
  virtual int Read(char* buf, int len) {
    int ret = reader_->Read(buf, len);
    return ret;
  }

 private:
  afs::AfsFileSystem* afsfile_;
  afs::Reader* reader_;
};

class AfsManager {
 public:
  AfsManager(const std::string& fs_name, const std::string& fs_ugi,
             const std::string& conf_path) {
    auto split = fs_ugi.find(",");
    std::string user = fs_ugi.substr(0, split);
    std::string pwd = fs_ugi.substr(split + 1);
    _afshandler = new afs::AfsFileSystem(fs_name.c_str(), user.c_str(),
                                         pwd.c_str(), conf_path.c_str());
    VLOG(0) << "AFSAPI Init: user: " << user << ", pwd: " << pwd;
174
    int ret = _afshandler->Init(true, (com_logstatus() == 0));
H
hutuxian 已提交
175 176
    PADDLE_ENFORCE_EQ(ret, 0, platform::errors::PreconditionNotMet(
                                  "Called AFSAPI Init Interface Failed."));
177 178
    // Too high level will hurt the performance
    comlog_set_log_level(4);
H
hutuxian 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    ret = _afshandler->Connect();
    PADDLE_ENFORCE_EQ(ret, 0, platform::errors::PreconditionNotMet(
                                  "Called AFSAPI Connect Interface Failed"));
  }
  virtual ~AfsManager() {
    if (_afshandler != NULL) {
      _afshandler->DisConnect();
      _afshandler->Destroy();
      delete _afshandler;
      _afshandler = nullptr;
    }
  }
  static void ReadFromAfs(const std::string& path, FILE* wfp,
                          afs::AfsFileSystem* _afshandler) {
    AfsStreamFile* read_stream = new AfsStreamFile(_afshandler);
    int ret = read_stream->Open(path.c_str());
    PADDLE_ENFORCE_EQ(ret, 0,
                      platform::errors::PreconditionNotMet(
                          "Called AFSAPI Open file %s Failed.", path.c_str()));
    char* _buff = static_cast<char*>(calloc(BUF_SIZE + 2, sizeof(char)));
    int size = 0;
    while ((size = read_stream->Read(_buff, BUF_SIZE)) > 0) {
      fwrite(_buff, 1, size, wfp);
    }
    fflush(wfp);
    fclose(wfp);
    delete _buff;
    delete read_stream;
  }
  int PopenBidirectionalInternal(const char* command,
                                 FILE*& fp_read,               // NOLINT
                                 FILE*& fp_write, pid_t& pid,  // NOLINT
                                 bool read,                    // NOLINT
                                 bool write) {
    std::lock_guard<std::mutex> g(g_flock);
    int fd_read[2];
    int fd_write[2];
    if (read) {
217 218 219
      PADDLE_ENFORCE_EQ(
          pipe(fd_read), 0,
          platform::errors::External("Create read pipe failed in AfsManager."));
H
hutuxian 已提交
220 221
    }
    if (write) {
222 223 224
      PADDLE_ENFORCE_EQ(pipe(fd_write), 0,
                        platform::errors::External(
                            "Create write pipe failed in AfsManager."));
H
hutuxian 已提交
225 226
    }
    pid = vfork();
227 228 229 230
    PADDLE_ENFORCE_GE(
        pid, 0,
        platform::errors::External(
            "Failed to create a child process via fork in AfsManager."));
H
hutuxian 已提交
231 232
    if (pid == 0) {
      if (read) {
233 234 235 236
        PADDLE_ENFORCE_NE(
            dup2(fd_read[1], STDOUT_FILENO), -1,
            platform::errors::External(
                "Failed to duplicate file descriptor via dup2 in AfsManager."));
H
hutuxian 已提交
237 238 239 240 241
        close(fd_read[1]);
        close(fd_read[0]);
      }

      if (write) {
242 243 244 245
        PADDLE_ENFORCE_NE(
            dup2(fd_write[0], STDIN_FILENO), -1,
            platform::errors::External(
                "Failed to duplicate file descriptor via dup2 in AfsManager."));
H
hutuxian 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        close(fd_write[0]);
        close(fd_write[1]);
      }

      struct dirent* item;
      DIR* dir = opendir("/proc/self/fd");
      while ((item = readdir(dir)) != NULL) {
        int fd = atoi(item->d_name);
        if (fd >= 3) {
          (void)close(fd);
        }
      }

      closedir(dir);

      execl("/bin/sh", "sh", "-c", command, NULL);
      exit(127);
    } else {
      if (read) {
        close(fd_read[1]);
        fcntl(fd_read[0], F_SETFD, FD_CLOEXEC);
        fp_read = fdopen(fd_read[0], "r");
268
        PADDLE_ENFORCE_NE(
269
            fp_read, nullptr,
270 271
            platform::errors::External(
                "Failed to open file descriptor via fdopen in AfsManager."));
H
hutuxian 已提交
272 273 274 275 276 277
      }

      if (write) {
        close(fd_write[0]);
        fcntl(fd_write[1], F_SETFD, FD_CLOEXEC);
        fp_write = fdopen(fd_write[1], "w");
278
        PADDLE_ENFORCE_NE(
279
            fp_write, nullptr,
280 281
            platform::errors::External(
                "Failed to open file descriptor via fdopen in AfsManager."));
H
hutuxian 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
      }
      return 0;
    }
  }
  std::shared_ptr<FILE> GetFile(const std::string& path,
                                const std::string& pipe_command) {
    pid_t pid = 0;
    FILE* wfp = NULL;
    FILE* rfp = NULL;

    // Always use set -eo pipefail. Fail fast and be aware of exit codes.
    std::string cmd = "set -eo pipefail; " + pipe_command;
    int ret =
        PopenBidirectionalInternal(cmd.c_str(), rfp, wfp, pid, true, true);

    PADDLE_ENFORCE_EQ(ret, 0, platform::errors::PreconditionNotMet(
                                  "Called PopenBidirectionalInternal Failed"));
    std::string filename(path);
    if (strncmp(filename.c_str(), "afs:", 4) == 0) {
      filename = filename.substr(4);
    }
    std::thread read_thread(&AfsManager::ReadFromAfs, filename, wfp,
                            _afshandler);
    read_thread.detach();
    return {rfp, [pid, cmd](FILE* rfp) {
              int wstatus = -1;
              int ret = -1;
              do {
                ret = waitpid(pid, &wstatus, 0);
              } while (ret == -1 && errno == EINTR);

              fclose(rfp);
              if (wstatus == 0 || wstatus == (128 + SIGPIPE) * 256 ||
                  (wstatus == -1 && errno == ECHILD)) {
                VLOG(3) << "pclose_bidirectional pid[" << pid << "], status["
                        << wstatus << "]";
              } else {
                LOG(WARNING) << "pclose_bidirectional pid[" << pid << "]"
                             << ", ret[" << ret << "] shell open fail";
              }
              if (wstatus == -1 && errno == ECHILD) {
                LOG(WARNING) << "errno is ECHILD";
              }
            }};
  }

 private:
  afs::AfsFileSystem* _afshandler;
  std::mutex g_flock;
};

H
hutuxian 已提交
333 334 335 336 337
class BoxWrapper {
 public:
  virtual ~BoxWrapper() {}
  BoxWrapper() {}

H
hutuxian 已提交
338 339 340
  void FeedPass(int date, const std::vector<uint64_t>& feasgin_to_box) const;
  void BeginFeedPass(int date, boxps::PSAgentBase** agent) const;
  void EndFeedPass(boxps::PSAgentBase* agent) const;
H
hutuxian 已提交
341
  void BeginPass() const;
342
  void EndPass(bool need_save_delta) const;
343
  void SetTestMode(bool is_test) const;
S
ShenLiang 已提交
344 345 346 347 348 349 350 351

  template <size_t EMBEDX_DIM, size_t EXPAND_EMBED_DIM = 0>
  void PullSparseCase(const paddle::platform::Place& place,
                      const std::vector<const uint64_t*>& keys,
                      const std::vector<float*>& values,
                      const std::vector<int64_t>& slot_lengths,
                      const int hidden_size, const int expand_embed_dim);

H
hutuxian 已提交
352 353 354 355
  void PullSparse(const paddle::platform::Place& place,
                  const std::vector<const uint64_t*>& keys,
                  const std::vector<float*>& values,
                  const std::vector<int64_t>& slot_lengths,
S
ShenLiang 已提交
356 357 358 359 360 361 362 363 364 365
                  const int hidden_size, const int expand_embed_dim);

  template <size_t EMBEDX_DIM, size_t EXPAND_EMBED_DIM = 0>
  void PushSparseGradCase(const paddle::platform::Place& place,
                          const std::vector<const uint64_t*>& keys,
                          const std::vector<const float*>& grad_values,
                          const std::vector<int64_t>& slot_lengths,
                          const int hidden_size, const int expand_embed_dim,
                          const int batch_size);

H
hutuxian 已提交
366 367 368 369
  void PushSparseGrad(const paddle::platform::Place& place,
                      const std::vector<const uint64_t*>& keys,
                      const std::vector<const float*>& grad_values,
                      const std::vector<int64_t>& slot_lengths,
S
ShenLiang 已提交
370 371 372
                      const int hidden_size, const int expand_embed_dim,
                      const int batch_size);

H
hutuxian 已提交
373
  void CopyForPull(const paddle::platform::Place& place, uint64_t** gpu_keys,
S
ShenLiang 已提交
374
                   const std::vector<float*>& values, void* total_values_gpu,
H
hutuxian 已提交
375
                   const int64_t* gpu_len, const int slot_num,
S
ShenLiang 已提交
376 377 378
                   const int hidden_size, const int expand_embed_dim,
                   const int64_t total_length);

H
hutuxian 已提交
379 380
  void CopyForPush(const paddle::platform::Place& place,
                   const std::vector<const float*>& grad_values,
S
ShenLiang 已提交
381
                   void* total_grad_values_gpu,
H
hutuxian 已提交
382
                   const std::vector<int64_t>& slot_lengths,
S
ShenLiang 已提交
383 384 385
                   const int hidden_size, const int expand_embed_dim,
                   const int64_t total_length, const int batch_size);

H
hutuxian 已提交
386 387 388
  void CopyKeys(const paddle::platform::Place& place, uint64_t** origin_keys,
                uint64_t* total_keys, const int64_t* gpu_len, int slot_num,
                int total_len);
S
ShenLiang 已提交
389 390 391

  void CheckEmbedSizeIsValid(int embedx_dim, int expand_embed_dim);

H
hutuxian 已提交
392
  boxps::PSAgentBase* GetAgent() { return p_agent_; }
393 394 395 396
  void InitializeGPUAndLoadModel(
      const char* conf_file, const std::vector<int>& slot_vector,
      const std::vector<std::string>& slot_omit_in_feedpass,
      const std::string& model_path) {
H
hutuxian 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410
    if (nullptr != s_instance_) {
      VLOG(3) << "Begin InitializeGPU";
      std::vector<cudaStream_t*> stream_list;
      for (int i = 0; i < platform::GetCUDADeviceCount(); ++i) {
        VLOG(3) << "before get context i[" << i << "]";
        platform::CUDADeviceContext* context =
            dynamic_cast<platform::CUDADeviceContext*>(
                platform::DeviceContextPool::Instance().Get(
                    platform::CUDAPlace(i)));
        stream_list_[i] = context->stream();
        stream_list.push_back(&stream_list_[i]);
      }
      VLOG(2) << "Begin call InitializeGPU in BoxPS";
      // the second parameter is useless
411 412
      s_instance_->boxps_ptr_->InitializeGPUAndLoadModel(
          conf_file, -1, stream_list, slot_vector, model_path);
H
hutuxian 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
      p_agent_ = boxps::PSAgentBase::GetIns(feedpass_thread_num_);
      p_agent_->Init();
      for (const auto& slot_name : slot_omit_in_feedpass) {
        slot_name_omited_in_feedpass_.insert(slot_name);
      }
      slot_vector_ = slot_vector;
      keys_tensor.resize(platform::GetCUDADeviceCount());
    }
  }

  int GetFeedpassThreadNum() const { return feedpass_thread_num_; }

  void Finalize() {
    VLOG(3) << "Begin Finalize";
    if (nullptr != s_instance_) {
      s_instance_->boxps_ptr_->Finalize();
    }
  }

H
hutuxian 已提交
432
  const std::string SaveBase(const char* batch_model_path,
433 434
                             const char* xbox_model_path,
                             const std::string& date) {
H
hutuxian 已提交
435
    VLOG(3) << "Begin SaveBase";
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    PADDLE_ENFORCE_EQ(
        date.length(), 8,
        platform::errors::PreconditionNotMet(
            "date[%s] is invalid, correct example is 20190817", date.c_str()));
    int year = std::stoi(date.substr(0, 4));
    int month = std::stoi(date.substr(4, 2));
    int day = std::stoi(date.substr(6, 2));

    struct std::tm b;
    b.tm_year = year - 1900;
    b.tm_mon = month - 1;
    b.tm_mday = day;
    b.tm_min = b.tm_hour = b.tm_sec = 0;
    std::time_t seconds_from_1970 = std::mktime(&b);

H
hutuxian 已提交
451
    std::string ret_str;
452 453
    int ret = boxps_ptr_->SaveBase(batch_model_path, xbox_model_path, ret_str,
                                   seconds_from_1970 / 86400);
H
hutuxian 已提交
454 455 456
    PADDLE_ENFORCE_EQ(ret, 0, platform::errors::PreconditionNotMet(
                                  "SaveBase failed in BoxPS."));
    return ret_str;
H
hutuxian 已提交
457 458
  }

H
hutuxian 已提交
459
  const std::string SaveDelta(const char* xbox_model_path) {
H
hutuxian 已提交
460
    VLOG(3) << "Begin SaveDelta";
H
hutuxian 已提交
461 462 463 464 465
    std::string ret_str;
    int ret = boxps_ptr_->SaveDelta(xbox_model_path, ret_str);
    PADDLE_ENFORCE_EQ(ret, 0, platform::errors::PreconditionNotMet(
                                  "SaveDelta failed in BoxPS."));
    return ret_str;
H
hutuxian 已提交
466
  }
H
hutuxian 已提交
467 468

  static std::shared_ptr<BoxWrapper> GetInstance() {
S
ShenLiang 已提交
469 470 471 472 473 474 475 476 477
    PADDLE_ENFORCE_EQ(
        s_instance_ == nullptr, false,
        platform::errors::PreconditionNotMet(
            "GetInstance failed in BoxPs, you should use SetInstance firstly"));
    return s_instance_;
  }

  static std::shared_ptr<BoxWrapper> SetInstance(int embedx_dim = 8,
                                                 int expand_embed_dim = 0) {
H
hutuxian 已提交
478 479 480 481 482
    if (nullptr == s_instance_) {
      // If main thread is guaranteed to init this, this lock can be removed
      static std::mutex mutex;
      std::lock_guard<std::mutex> lock(mutex);
      if (nullptr == s_instance_) {
H
hutuxian 已提交
483
        VLOG(3) << "s_instance_ is null";
H
hutuxian 已提交
484
        s_instance_.reset(new paddle::framework::BoxWrapper());
S
ShenLiang 已提交
485 486 487 488
        s_instance_->boxps_ptr_.reset(
            boxps::BoxPSBase::GetIns(embedx_dim, expand_embed_dim));
        embedx_dim_ = embedx_dim;
        expand_embed_dim_ = expand_embed_dim;
H
hutuxian 已提交
489
      }
S
ShenLiang 已提交
490 491
    } else {
      LOG(WARNING) << "You have already used SetInstance() before";
H
hutuxian 已提交
492 493 494 495
    }
    return s_instance_;
  }

H
hutuxian 已提交
496 497 498 499 500 501 502 503
  void InitAfsAPI(const std::string& fs_name, const std::string& fs_ugi,
                  const std::string& conf_path) {
    afs_manager = new AfsManager(fs_name, fs_ugi, conf_path);
    use_afs_api_ = true;
  }

  bool UseAfsApi() const { return use_afs_api_; }

H
hutuxian 已提交
504 505 506 507
  const std::unordered_set<std::string>& GetOmitedSlot() const {
    return slot_name_omited_in_feedpass_;
  }

H
hutuxian 已提交
508
  class MetricMsg {
H
hutuxian 已提交
509 510 511
   public:
    MetricMsg() {}
    MetricMsg(const std::string& label_varname, const std::string& pred_varname,
512
              int metric_phase, int bucket_size = 1000000)
H
hutuxian 已提交
513 514
        : label_varname_(label_varname),
          pred_varname_(pred_varname),
515
          metric_phase_(metric_phase) {
H
hutuxian 已提交
516 517 518
      calculator = new BasicAucCalculator();
      calculator->init(bucket_size);
    }
H
hutuxian 已提交
519 520
    virtual ~MetricMsg() {}

521
    int MetricPhase() const { return metric_phase_; }
H
hutuxian 已提交
522
    BasicAucCalculator* GetCalculator() { return calculator; }
H
hutuxian 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    virtual void add_data(const Scope* exe_scope) {
      std::vector<int64_t> label_data;
      get_data<int64_t>(exe_scope, label_varname_, &label_data);
      std::vector<float> pred_data;
      get_data<float>(exe_scope, pred_varname_, &pred_data);
      auto cal = GetCalculator();
      auto batch_size = label_data.size();
      for (size_t i = 0; i < batch_size; ++i) {
        cal->add_data(pred_data[i], label_data[i]);
      }
    }
    template <class T = float>
    static void get_data(const Scope* exe_scope, const std::string& varname,
                         std::vector<T>* data) {
      auto* var = exe_scope->FindVar(varname.c_str());
      PADDLE_ENFORCE_NOT_NULL(
          var, platform::errors::NotFound(
                   "Error: var %s is not found in scope.", varname.c_str()));
      auto& gpu_tensor = var->Get<LoDTensor>();
      auto* gpu_data = gpu_tensor.data<T>();
      auto len = gpu_tensor.numel();
      data->resize(len);
      cudaMemcpy(data->data(), gpu_data, sizeof(T) * len,
                 cudaMemcpyDeviceToHost);
    }
    static inline std::pair<int, int> parse_cmatch_rank(uint64_t x) {
      // first 32 bit store cmatch and second 32 bit store rank
      return std::make_pair(static_cast<int>(x >> 32),
                            static_cast<int>(x & 0xff));
    }
H
hutuxian 已提交
553

H
hutuxian 已提交
554
   protected:
H
hutuxian 已提交
555 556
    std::string label_varname_;
    std::string pred_varname_;
557
    int metric_phase_;
H
hutuxian 已提交
558 559 560
    BasicAucCalculator* calculator;
  };

H
hutuxian 已提交
561 562 563
  class MultiTaskMetricMsg : public MetricMsg {
   public:
    MultiTaskMetricMsg(const std::string& label_varname,
564
                       const std::string& pred_varname_list, int metric_phase,
H
hutuxian 已提交
565 566 567 568 569
                       const std::string& cmatch_rank_group,
                       const std::string& cmatch_rank_varname,
                       int bucket_size = 1000000) {
      label_varname_ = label_varname;
      cmatch_rank_varname_ = cmatch_rank_varname;
570
      metric_phase_ = metric_phase;
H
hutuxian 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
      calculator = new BasicAucCalculator();
      calculator->init(bucket_size);
      for (auto& cmatch_rank : string::split_string(cmatch_rank_group)) {
        const std::vector<std::string>& cur_cmatch_rank =
            string::split_string(cmatch_rank, "_");
        PADDLE_ENFORCE_EQ(
            cur_cmatch_rank.size(), 2,
            platform::errors::PreconditionNotMet(
                "illegal multitask auc spec: %s", cmatch_rank.c_str()));
        cmatch_rank_v.emplace_back(atoi(cur_cmatch_rank[0].c_str()),
                                   atoi(cur_cmatch_rank[1].c_str()));
      }
      for (const auto& pred_varname : string::split_string(pred_varname_list)) {
        pred_v.emplace_back(pred_varname);
      }
      PADDLE_ENFORCE_EQ(cmatch_rank_v.size(), pred_v.size(),
                        platform::errors::PreconditionNotMet(
                            "cmatch_rank's size [%lu] should be equal to pred "
                            "list's size [%lu], but ther are not equal",
                            cmatch_rank_v.size(), pred_v.size()));
    }
    virtual ~MultiTaskMetricMsg() {}
    void add_data(const Scope* exe_scope) override {
      std::vector<int64_t> cmatch_rank_data;
      get_data<int64_t>(exe_scope, cmatch_rank_varname_, &cmatch_rank_data);
      std::vector<int64_t> label_data;
      get_data<int64_t>(exe_scope, label_varname_, &label_data);
      size_t batch_size = cmatch_rank_data.size();
      PADDLE_ENFORCE_EQ(
          batch_size, label_data.size(),
          platform::errors::PreconditionNotMet(
              "illegal batch size: batch_size[%lu] and label_data[%lu]",
              batch_size, label_data.size()));

      std::vector<std::vector<float>> pred_data_list(pred_v.size());
      for (size_t i = 0; i < pred_v.size(); ++i) {
        get_data<float>(exe_scope, pred_v[i], &pred_data_list[i]);
      }
      for (size_t i = 0; i < pred_data_list.size(); ++i) {
        PADDLE_ENFORCE_EQ(
            batch_size, pred_data_list[i].size(),
            platform::errors::PreconditionNotMet(
                "illegal batch size: batch_size[%lu] and pred_data[%lu]",
                batch_size, pred_data_list[i].size()));
      }
      auto cal = GetCalculator();
      for (size_t i = 0; i < batch_size; ++i) {
        auto cmatch_rank_it =
            std::find(cmatch_rank_v.begin(), cmatch_rank_v.end(),
                      parse_cmatch_rank(cmatch_rank_data[i]));
        if (cmatch_rank_it != cmatch_rank_v.end()) {
          cal->add_data(pred_data_list[std::distance(cmatch_rank_v.begin(),
                                                     cmatch_rank_it)][i],
                        label_data[i]);
        }
      }
    }

   protected:
    std::vector<std::pair<int, int>> cmatch_rank_v;
    std::vector<std::string> pred_v;
    std::string cmatch_rank_varname_;
  };
  class CmatchRankMetricMsg : public MetricMsg {
   public:
    CmatchRankMetricMsg(const std::string& label_varname,
637
                        const std::string& pred_varname, int metric_phase,
H
hutuxian 已提交
638 639 640 641 642 643
                        const std::string& cmatch_rank_group,
                        const std::string& cmatch_rank_varname,
                        int bucket_size = 1000000) {
      label_varname_ = label_varname;
      pred_varname_ = pred_varname;
      cmatch_rank_varname_ = cmatch_rank_varname;
644
      metric_phase_ = metric_phase;
H
hutuxian 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      calculator = new BasicAucCalculator();
      calculator->init(bucket_size);
      for (auto& cmatch_rank : string::split_string(cmatch_rank_group)) {
        const std::vector<std::string>& cur_cmatch_rank =
            string::split_string(cmatch_rank, "_");
        PADDLE_ENFORCE_EQ(
            cur_cmatch_rank.size(), 2,
            platform::errors::PreconditionNotMet(
                "illegal cmatch_rank auc spec: %s", cmatch_rank.c_str()));
        cmatch_rank_v.emplace_back(atoi(cur_cmatch_rank[0].c_str()),
                                   atoi(cur_cmatch_rank[1].c_str()));
      }
    }
    virtual ~CmatchRankMetricMsg() {}
    void add_data(const Scope* exe_scope) override {
      std::vector<int64_t> cmatch_rank_data;
      get_data<int64_t>(exe_scope, cmatch_rank_varname_, &cmatch_rank_data);
      std::vector<int64_t> label_data;
      get_data<int64_t>(exe_scope, label_varname_, &label_data);
      std::vector<float> pred_data;
      get_data<float>(exe_scope, pred_varname_, &pred_data);
      size_t batch_size = cmatch_rank_data.size();
      PADDLE_ENFORCE_EQ(
          batch_size, label_data.size(),
          platform::errors::PreconditionNotMet(
              "illegal batch size: cmatch_rank[%lu] and label_data[%lu]",
              batch_size, label_data.size()));
      PADDLE_ENFORCE_EQ(
          batch_size, pred_data.size(),
          platform::errors::PreconditionNotMet(
              "illegal batch size: cmatch_rank[%lu] and pred_data[%lu]",
              batch_size, pred_data.size()));
      auto cal = GetCalculator();
      for (size_t i = 0; i < batch_size; ++i) {
        const auto& cur_cmatch_rank = parse_cmatch_rank(cmatch_rank_data[i]);
        for (size_t j = 0; j < cmatch_rank_v.size(); ++j) {
          if (cmatch_rank_v[j] == cur_cmatch_rank) {
            cal->add_data(pred_data[i], label_data[i]);
            break;
          }
        }
      }
    }

   protected:
    std::vector<std::pair<int, int>> cmatch_rank_v;
    std::string cmatch_rank_varname_;
  };
693 694 695
  class MaskMetricMsg : public MetricMsg {
   public:
    MaskMetricMsg(const std::string& label_varname,
696
                  const std::string& pred_varname, int metric_phase,
697 698 699 700
                  const std::string& mask_varname, int bucket_size = 1000000) {
      label_varname_ = label_varname;
      pred_varname_ = pred_varname;
      mask_varname_ = mask_varname;
701
      metric_phase_ = metric_phase;
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
      calculator = new BasicAucCalculator();
      calculator->init(bucket_size);
    }
    virtual ~MaskMetricMsg() {}
    void add_data(const Scope* exe_scope) override {
      std::vector<int64_t> label_data;
      get_data<int64_t>(exe_scope, label_varname_, &label_data);
      std::vector<float> pred_data;
      get_data<float>(exe_scope, pred_varname_, &pred_data);
      std::vector<int64_t> mask_data;
      get_data<int64_t>(exe_scope, mask_varname_, &mask_data);
      auto cal = GetCalculator();
      auto batch_size = label_data.size();
      for (size_t i = 0; i < batch_size; ++i) {
        if (mask_data[i] == 1) {
          cal->add_data(pred_data[i], label_data[i]);
        }
      }
    }

   protected:
    std::string mask_varname_;
  };
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
  const std::vector<std::string> GetMetricNameList(
      int metric_phase = -1) const {
    VLOG(0) << "Want to Get metric phase: " << metric_phase;
    if (metric_phase == -1) {
      return metric_name_list_;
    } else {
      std::vector<std::string> ret;
      for (const auto& name : metric_name_list_) {
        const auto iter = metric_lists_.find(name);
        PADDLE_ENFORCE_NE(
            iter, metric_lists_.end(),
            platform::errors::InvalidArgument(
                "The metric name you provided is not registered."));

        if (iter->second->MetricPhase() == metric_phase) {
          VLOG(0) << name << "'s phase is " << iter->second->MetricPhase()
                  << ", we want";
          ret.push_back(name);
        } else {
          VLOG(0) << name << "'s phase is " << iter->second->MetricPhase()
                  << ", not we want";
        }
      }
      return ret;
    }
H
hutuxian 已提交
750
  }
751 752
  int Phase() const { return phase_; }
  void FlipPhase() { phase_ = (phase_ + 1) % phase_num_; }
H
hutuxian 已提交
753
  std::map<std::string, MetricMsg*>& GetMetricList() { return metric_lists_; }
H
hutuxian 已提交
754

H
hutuxian 已提交
755 756 757
  void InitMetric(const std::string& method, const std::string& name,
                  const std::string& label_varname,
                  const std::string& pred_varname,
758
                  const std::string& cmatch_rank_varname,
759
                  const std::string& mask_varname, int metric_phase,
H
hutuxian 已提交
760
                  const std::string& cmatch_rank_group,
H
hutuxian 已提交
761
                  int bucket_size = 1000000) {
H
hutuxian 已提交
762 763
    if (method == "AucCalculator") {
      metric_lists_.emplace(name, new MetricMsg(label_varname, pred_varname,
764
                                                metric_phase, bucket_size));
H
hutuxian 已提交
765 766 767
    } else if (method == "MultiTaskAucCalculator") {
      metric_lists_.emplace(
          name, new MultiTaskMetricMsg(label_varname, pred_varname,
768
                                       metric_phase, cmatch_rank_group,
H
hutuxian 已提交
769 770 771 772
                                       cmatch_rank_varname, bucket_size));
    } else if (method == "CmatchRankAucCalculator") {
      metric_lists_.emplace(
          name, new CmatchRankMetricMsg(label_varname, pred_varname,
773
                                        metric_phase, cmatch_rank_group,
H
hutuxian 已提交
774
                                        cmatch_rank_varname, bucket_size));
775 776
    } else if (method == "MaskAucCalculator") {
      metric_lists_.emplace(
777
          name, new MaskMetricMsg(label_varname, pred_varname, metric_phase,
778
                                  mask_varname, bucket_size));
H
hutuxian 已提交
779 780
    } else {
      PADDLE_THROW(platform::errors::Unimplemented(
781 782
          "PaddleBox only support AucCalculator, MultiTaskAucCalculator "
          "CmatchRankAucCalculator and MaskAucCalculator"));
H
hutuxian 已提交
783 784
    }
    metric_name_list_.emplace_back(name);
H
hutuxian 已提交
785 786 787 788 789 790 791 792
  }

  const std::vector<float> GetMetricMsg(const std::string& name) {
    const auto iter = metric_lists_.find(name);
    PADDLE_ENFORCE_NE(iter, metric_lists_.end(),
                      platform::errors::InvalidArgument(
                          "The metric name you provided is not registered."));
    std::vector<float> metric_return_values_(8, 0.0);
H
hutuxian 已提交
793
    auto* auc_cal_ = iter->second->GetCalculator();
H
hutuxian 已提交
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
    auc_cal_->calculate_bucket_error();
    auc_cal_->compute();
    metric_return_values_[0] = auc_cal_->auc();
    metric_return_values_[1] = auc_cal_->bucket_error();
    metric_return_values_[2] = auc_cal_->mae();
    metric_return_values_[3] = auc_cal_->rmse();
    metric_return_values_[4] = auc_cal_->actual_ctr();
    metric_return_values_[5] = auc_cal_->predicted_ctr();
    metric_return_values_[6] =
        auc_cal_->actual_ctr() / auc_cal_->predicted_ctr();
    metric_return_values_[7] = auc_cal_->size();
    auc_cal_->reset();
    return metric_return_values_;
  }

H
hutuxian 已提交
809
 private:
H
hutuxian 已提交
810 811 812
  static cudaStream_t stream_list_[8];
  static std::shared_ptr<boxps::BoxPSBase> boxps_ptr_;
  boxps::PSAgentBase* p_agent_ = nullptr;
H
hutuxian 已提交
813
  // TODO(hutuxian): magic number, will add a config to specify
H
hutuxian 已提交
814
  const int feedpass_thread_num_ = 30;  // magic number
H
hutuxian 已提交
815
  static std::shared_ptr<BoxWrapper> s_instance_;
H
hutuxian 已提交
816
  std::unordered_set<std::string> slot_name_omited_in_feedpass_;
S
ShenLiang 已提交
817 818 819
  // EMBEDX_DIM and EXPAND_EMBED_DIM
  static int embedx_dim_;
  static int expand_embed_dim_;
H
hutuxian 已提交
820 821

  // Metric Related
822 823
  int phase_ = 1;
  int phase_num_ = 2;
H
hutuxian 已提交
824 825
  std::map<std::string, MetricMsg*> metric_lists_;
  std::vector<std::string> metric_name_list_;
H
hutuxian 已提交
826 827
  std::vector<int> slot_vector_;
  std::vector<LoDTensor> keys_tensor;  // Cache for pull_sparse
H
hutuxian 已提交
828 829 830 831
  bool use_afs_api_ = false;

 public:
  static AfsManager* afs_manager;
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882

  // Auc Runner
 public:
  void InitializeAucRunner(std::vector<std::vector<std::string>> slot_eval,
                           int thread_num, int pool_size,
                           std::vector<std::string> slot_list) {
    mode_ = 1;
    phase_num_ = static_cast<int>(slot_eval.size());
    phase_ = phase_num_ - 1;
    auc_runner_thread_num_ = thread_num;
    pass_done_semi_ = paddle::framework::MakeChannel<int>();
    pass_done_semi_->Put(1);  // Note: At most 1 pipeline in AucRunner
    random_ins_pool_list.resize(thread_num);

    std::unordered_set<std::string> slot_set;
    for (size_t i = 0; i < slot_eval.size(); ++i) {
      for (const auto& slot : slot_eval[i]) {
        slot_set.insert(slot);
      }
    }
    for (size_t i = 0; i < slot_list.size(); ++i) {
      if (slot_set.find(slot_list[i]) != slot_set.end()) {
        slot_index_to_replace_.insert(static_cast<int16_t>(i));
      }
    }
    for (int i = 0; i < auc_runner_thread_num_; ++i) {
      random_ins_pool_list[i].SetSlotIndexToReplace(slot_index_to_replace_);
    }
    VLOG(0) << "AucRunner configuration: thread number[" << thread_num
            << "], pool size[" << pool_size << "], runner_group[" << phase_num_
            << "]";
    VLOG(0) << "Slots that need to be evaluated:";
    for (auto e : slot_index_to_replace_) {
      VLOG(0) << e << ": " << slot_list[e];
    }
  }
  void GetRandomReplace(const std::vector<Record>& pass_data);
  void AddReplaceFeasign(boxps::PSAgentBase* p_agent, int feed_pass_thread_num);
  void GetRandomData(const std::vector<Record>& pass_data,
                     const std::unordered_set<uint16_t>& slots_to_replace,
                     std::vector<Record>* result);
  int Mode() const { return mode_; }

 private:
  int mode_ = 0;  // 0 means train/test 1 means auc_runner
  int auc_runner_thread_num_ = 1;
  bool init_done_ = false;
  paddle::framework::Channel<int> pass_done_semi_;
  std::unordered_set<uint16_t> slot_index_to_replace_;
  std::vector<RecordCandidateList> random_ins_pool_list;
  std::vector<size_t> replace_idx_;
H
hutuxian 已提交
883
};
H
hutuxian 已提交
884
#endif
H
hutuxian 已提交
885 886 887 888 889 890

class BoxHelper {
 public:
  explicit BoxHelper(paddle::framework::Dataset* dataset) : dataset_(dataset) {}
  virtual ~BoxHelper() {}

H
hutuxian 已提交
891 892 893 894 895
  void SetDate(int year, int month, int day) {
    year_ = year;
    month_ = month;
    day_ = day;
  }
H
hutuxian 已提交
896
  void BeginPass() {
H
hutuxian 已提交
897
#ifdef PADDLE_WITH_BOX_PS
H
hutuxian 已提交
898 899
    auto box_ptr = BoxWrapper::GetInstance();
    box_ptr->BeginPass();
H
hutuxian 已提交
900
#endif
H
hutuxian 已提交
901
  }
902
  void EndPass(bool need_save_delta) {
H
hutuxian 已提交
903
#ifdef PADDLE_WITH_BOX_PS
H
hutuxian 已提交
904
    auto box_ptr = BoxWrapper::GetInstance();
905
    box_ptr->EndPass(need_save_delta);
H
hutuxian 已提交
906
#endif
H
hutuxian 已提交
907 908
  }
  void LoadIntoMemory() {
H
hutuxian 已提交
909 910 911
    platform::Timer timer;
    VLOG(3) << "Begin LoadIntoMemory(), dataset[" << dataset_ << "]";
    timer.Start();
H
hutuxian 已提交
912
    dataset_->LoadIntoMemory();
H
hutuxian 已提交
913 914 915 916
    timer.Pause();
    VLOG(0) << "download + parse cost: " << timer.ElapsedSec() << "s";

    timer.Start();
H
hutuxian 已提交
917
    FeedPass();
H
hutuxian 已提交
918 919 920
    timer.Pause();
    VLOG(0) << "FeedPass cost: " << timer.ElapsedSec() << " s";
    VLOG(3) << "End LoadIntoMemory(), dataset[" << dataset_ << "]";
H
hutuxian 已提交
921 922 923 924 925 926 927
  }
  void PreLoadIntoMemory() {
    dataset_->PreLoadIntoMemory();
    feed_data_thread_.reset(new std::thread([&]() {
      dataset_->WaitPreLoadDone();
      FeedPass();
    }));
H
hutuxian 已提交
928
    VLOG(3) << "After PreLoadIntoMemory()";
H
hutuxian 已提交
929 930
  }
  void WaitFeedPassDone() { feed_data_thread_->join(); }
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
  void SlotsShuffle(const std::set<std::string>& slots_to_replace) {
#ifdef PADDLE_WITH_BOX_PS
    auto box_ptr = BoxWrapper::GetInstance();
    PADDLE_ENFORCE_EQ(box_ptr->Mode(), 1,
                      platform::errors::PreconditionNotMet(
                          "Should call InitForAucRunner first."));
    box_ptr->FlipPhase();

    std::unordered_set<uint16_t> index_slots;
    dynamic_cast<MultiSlotDataset*>(dataset_)->PreprocessChannel(
        slots_to_replace, index_slots);
    const std::vector<Record>& pass_data =
        dynamic_cast<MultiSlotDataset*>(dataset_)->GetSlotsOriginalData();
    if (!get_random_replace_done_) {
      box_ptr->GetRandomReplace(pass_data);
      get_random_replace_done_ = true;
    }
    std::vector<Record> random_data;
    random_data.resize(pass_data.size());
    box_ptr->GetRandomData(pass_data, index_slots, &random_data);

    auto new_input_channel = paddle::framework::MakeChannel<Record>();
    new_input_channel->Open();
    new_input_channel->Write(std::move(random_data));
    new_input_channel->Close();
    dynamic_cast<MultiSlotDataset*>(dataset_)->SetInputChannel(
        new_input_channel);
    if (dataset_->EnablePvMerge()) {
      dataset_->PreprocessInstance();
    }
#endif
  }
H
hutuxian 已提交
963
#ifdef PADDLE_WITH_BOX_PS
H
hutuxian 已提交
964
  // notify boxps to feed this pass feasigns from SSD to memory
H
hutuxian 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
  static void FeedPassThread(const std::deque<Record>& t, int begin_index,
                             int end_index, boxps::PSAgentBase* p_agent,
                             const std::unordered_set<int>& index_map,
                             int thread_id) {
    p_agent->AddKey(0ul, thread_id);
    for (auto iter = t.begin() + begin_index; iter != t.begin() + end_index;
         iter++) {
      const auto& ins = *iter;
      const auto& feasign_v = ins.uint64_feasigns_;
      for (const auto feasign : feasign_v) {
        if (index_map.find(feasign.slot()) != index_map.end()) {
          continue;
        }
        p_agent->AddKey(feasign.sign().uint64_feasign_, thread_id);
      }
    }
  }
#endif
H
hutuxian 已提交
983
  void FeedPass() {
H
hutuxian 已提交
984
    VLOG(3) << "Begin FeedPass";
H
hutuxian 已提交
985
#ifdef PADDLE_WITH_BOX_PS
H
hutuxian 已提交
986 987 988 989 990 991 992
    struct std::tm b;
    b.tm_year = year_ - 1900;
    b.tm_mon = month_ - 1;
    b.tm_mday = day_;
    b.tm_min = b.tm_hour = b.tm_sec = 0;
    std::time_t x = std::mktime(&b);

H
hutuxian 已提交
993 994 995
    auto box_ptr = BoxWrapper::GetInstance();
    auto input_channel_ =
        dynamic_cast<MultiSlotDataset*>(dataset_)->GetInputChannel();
H
hutuxian 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    const std::deque<Record>& pass_data = input_channel_->GetData();

    // get feasigns that FeedPass doesn't need
    const std::unordered_set<std::string>& slot_name_omited_in_feedpass_ =
        box_ptr->GetOmitedSlot();
    std::unordered_set<int> slot_id_omited_in_feedpass_;
    const auto& all_readers = dataset_->GetReaders();
    PADDLE_ENFORCE_GT(all_readers.size(), 0,
                      platform::errors::PreconditionNotMet(
                          "Readers number must be greater than 0."));
    const auto& all_slots_name = all_readers[0]->GetAllSlotAlias();
    for (size_t i = 0; i < all_slots_name.size(); ++i) {
      if (slot_name_omited_in_feedpass_.find(all_slots_name[i]) !=
          slot_name_omited_in_feedpass_.end()) {
        slot_id_omited_in_feedpass_.insert(i);
H
hutuxian 已提交
1011 1012
      }
    }
H
hutuxian 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    const size_t tnum = box_ptr->GetFeedpassThreadNum();
    boxps::PSAgentBase* p_agent = box_ptr->GetAgent();
    VLOG(3) << "Begin call BeginFeedPass in BoxPS";
    box_ptr->BeginFeedPass(x / 86400, &p_agent);

    std::vector<std::thread> threads;
    size_t len = pass_data.size();
    size_t len_per_thread = len / tnum;
    auto remain = len % tnum;
    size_t begin = 0;
    for (size_t i = 0; i < tnum; i++) {
      threads.push_back(
          std::thread(FeedPassThread, std::ref(pass_data), begin,
                      begin + len_per_thread + (i < remain ? 1 : 0), p_agent,
                      std::ref(slot_id_omited_in_feedpass_), i));
      begin += len_per_thread + (i < remain ? 1 : 0);
    }
    for (size_t i = 0; i < tnum; ++i) {
      threads[i].join();
    }
1033 1034 1035 1036

    if (box_ptr->Mode() == 1) {
      box_ptr->AddReplaceFeasign(p_agent, tnum);
    }
H
hutuxian 已提交
1037 1038
    VLOG(3) << "Begin call EndFeedPass in BoxPS";
    box_ptr->EndFeedPass(p_agent);
H
hutuxian 已提交
1039
#endif
H
hutuxian 已提交
1040
  }
H
hutuxian 已提交
1041 1042 1043 1044 1045 1046 1047

 private:
  Dataset* dataset_;
  std::shared_ptr<std::thread> feed_data_thread_;
  int year_;
  int month_;
  int day_;
1048
  bool get_random_replace_done_ = false;
H
hutuxian 已提交
1049 1050 1051 1052
};

}  // end namespace framework
}  // end namespace paddle
S
ShenLiang 已提交
1053 1054

#include "paddle/fluid/framework/fleet/box_wrapper_impl.h"