downpour_worker.cc 37.4 KB
Newer Older
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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

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

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

#include "paddle/fluid/framework/device_worker.h"
16
#include "paddle/fluid/framework/fleet/metrics.h"
17
#include "paddle/fluid/operators/isfinite_op.h"
18
#include "paddle/fluid/platform/cpu_helper.h"
W
wanghuancoder 已提交
19

20
namespace phi {
21
class DenseTensor;
22
}  // namespace phi
23

W
wanghuancoder 已提交
24 25 26 27 28
namespace paddle {
namespace framework {
class Variable;
}  // namespace framework
}  // namespace paddle
29

30 31 32 33 34
#if defined _WIN32 || defined __APPLE__
#else
#define _LINUX
#endif

35 36
namespace paddle {
namespace framework {
37
void DownpourWorker::Initialize(const TrainerDesc& desc) {
38
  param_ = desc.downpour_param();
D
dongdaxiang 已提交
39
  for (int i = 0; i < param_.sparse_table_size(); ++i) {
40 41 42 43
    uint64_t table_id =
        static_cast<uint64_t>(param_.sparse_table(i).table_id());
    TableParameter table = param_.sparse_table(i);
    sparse_key_names_[table_id].resize(table.sparse_key_name_size());
D
dongdaxiang 已提交
44
    for (int j = 0; j < table.sparse_key_name_size(); ++j) {
45 46 47
      sparse_key_names_[table_id][j] = table.sparse_key_name(j);
    }
    sparse_value_names_[table_id].resize(table.sparse_value_name_size());
D
dongdaxiang 已提交
48
    for (int j = 0; j < table.sparse_value_name_size(); ++j) {
49 50 51
      sparse_value_names_[table_id][j] = table.sparse_value_name(j);
    }
    sparse_grad_names_[table_id].resize(table.sparse_grad_name_size());
D
dongdaxiang 已提交
52
    for (int j = 0; j < table.sparse_grad_name_size(); ++j) {
53 54
      sparse_grad_names_[table_id][j] = table.sparse_grad_name(j);
    }
55
    label_var_name_[table_id] = table.label_var_name();
56
    sparse_push_keys_[table_id] = std::vector<uint64_t>();
57 58
  }

D
dongdaxiang 已提交
59
  for (int i = 0; i < param_.dense_table_size(); ++i) {
60 61 62
    uint64_t table_id = static_cast<uint64_t>(param_.dense_table(i).table_id());
    auto table = param_.dense_table(i);
    dense_value_names_[table_id].resize(table.dense_value_name_size());
D
dongdaxiang 已提交
63
    for (int j = 0; j < table.dense_value_name_size(); ++j) {
64 65 66
      dense_value_names_[table_id][j] = table.dense_value_name(j);
    }
    dense_grad_names_[table_id].resize(table.dense_grad_name_size());
D
dongdaxiang 已提交
67
    for (int j = 0; j < table.dense_grad_name_size(); ++j) {
68 69 70 71
      dense_grad_names_[table_id][j] = table.dense_grad_name(j);
    }
  }

Z
zhang wenhui 已提交
72 73 74 75 76 77 78
  flag_partial_push_ = false;
  for (auto& m : param_.program_config(0).partial_pushdense_condtable_map()) {
    cond2table_map_[m.key()] = m.value();
    condvalue_set_.insert(m.value());
    flag_partial_push_ = true;
  }

79
  skip_ops_.resize(param_.skip_ops_size());
D
dongdaxiang 已提交
80
  for (int i = 0; i < param_.skip_ops_size(); ++i) {
81 82
    skip_ops_[i] = param_.skip_ops(i);
  }
83

84 85 86 87
  for (int i = 0; i < param_.stat_var_names_size(); ++i) {
    stat_var_name_map_[param_.stat_var_names(i)] = 1;
  }

88 89 90
  need_to_push_sparse_ = param_.push_sparse();
  need_to_push_dense_ = param_.push_dense();

91
  fleet_ptr_ = FleetWrapper::GetInstance();
D
dongdaxiang 已提交
92
  fetch_config_ = desc.fetch_config();
93
  use_cvm_ = desc.use_cvm();
94 95
  // for sparse value accessor, embedding only
  no_cvm_ = desc.no_cvm();
96 97
  scale_sparse_gradient_with_batch_size_ =
      desc.scale_sparse_gradient_with_batch_size();
98
  scale_datanorm_ = desc.scale_datanorm();
T
Thunderbrook 已提交
99
  dump_slot_ = desc.dump_slot();
100
  adjust_ins_weight_config_ = desc.adjust_ins_weight_config();
101 102 103
  for (int i = 0; i < desc.check_nan_var_names_size(); ++i) {
    check_nan_var_names_.push_back(desc.check_nan_var_names(i));
  }
X
xujiaqi01 已提交
104 105 106 107 108 109
  copy_table_config_ = desc.copy_table_config();
  for (int i = 0; i < copy_table_config_.src_sparse_tables_size(); ++i) {
    uint64_t src_table = copy_table_config_.src_sparse_tables(i);
    uint64_t dest_table = copy_table_config_.dest_sparse_tables(i);
    VLOG(3) << "copy_sparse_tables_ push back " << src_table << "->"
            << dest_table;
110
    copy_sparse_tables_.emplace_back(src_table, dest_table);
X
xujiaqi01 已提交
111 112 113 114 115 116
  }
  for (int i = 0; i < copy_table_config_.src_dense_tables_size(); ++i) {
    uint64_t src_table = copy_table_config_.src_dense_tables(i);
    uint64_t dest_table = copy_table_config_.dest_dense_tables(i);
    VLOG(3) << "copy_dense_tables_ push back " << src_table << "->"
            << dest_table;
117
    copy_dense_tables_.emplace_back(src_table, dest_table);
X
xujiaqi01 已提交
118 119 120 121 122 123 124 125 126
  }
  for (auto& m : copy_table_config_.table_denpendency_map()) {
    if (sparse_key_names_.find(m.key()) != sparse_key_names_.end()) {
      // currently only support one dependency
      for (auto& value : m.values()) {
        table_dependency_[m.key()] = value;
      }
    }
  }
127 128
}

129
void DownpourWorker::CollectLabelInfo(size_t table_idx) {
130 131 132
  if (no_cvm_) {
    return;
  }
H
heqiaozhi 已提交
133
  uint64_t table_id = static_cast<uint64_t>(
134
      param_.program_config(0).pull_sparse_table_id(table_idx));
135

H
heqiaozhi 已提交
136 137 138 139 140 141 142
  TableParameter table;
  for (auto i : param_.sparse_table()) {
    if (i.table_id() == table_id) {
      table = i;
      break;
    }
  }
143 144 145
  auto& feature = features_[table_id];
  auto& feature_label = feature_labels_[table_id];
  feature_label.resize(feature.size());
146
  Variable* var = thread_scope_->FindVar(label_var_name_[table_id]);
147
  phi::DenseTensor* tensor = var->GetMutable<phi::DenseTensor>();
148 149
  int64_t* label_ptr = tensor->data<int64_t>();

D
dongdaxiang 已提交
150
  size_t global_index = 0;
151
  for (size_t i = 0; i < sparse_key_names_[table_id].size(); ++i) {
152 153
    VLOG(3) << "sparse_key_names_[" << i
            << "]: " << sparse_key_names_[table_id][i];
154
    Variable* fea_var = thread_scope_->FindVar(sparse_key_names_[table_id][i]);
155 156 157
    if (fea_var == nullptr) {
      continue;
    }
158
    phi::DenseTensor* tensor = fea_var->GetMutable<phi::DenseTensor>();
159 160
    CHECK(tensor != nullptr)
        << "tensor of var " << sparse_key_names_[table_id][i] << " is null";
161 162 163 164 165 166 167 168

    // skip slots which do not have embedding
    Variable* emb_var =
        thread_scope_->FindVar(sparse_value_names_[table_id][i]);
    if (emb_var == nullptr) {
      continue;
    }

169
    int64_t* ids = tensor->data<int64_t>();
D
dongdaxiang 已提交
170
    size_t fea_idx = 0;
171
    // tensor->lod()[0].size() == batch_size + 1
172 173
    for (auto lod_idx = 1u; lod_idx < tensor->lod()[0].size(); ++lod_idx) {
      for (; fea_idx < tensor->lod()[0][lod_idx]; ++fea_idx) {
174 175 176 177
        // should be skipped feasign defined in protobuf
        if (ids[fea_idx] == 0u) {
          continue;
        }
178 179
        feature_label[global_index++] =
            static_cast<float>(label_ptr[lod_idx - 1]);
180 181 182 183 184 185 186 187
      }
    }
  }
  CHECK(global_index == feature.size())
      << "expect fea info size:" << feature.size() << " real:" << global_index;
}

void DownpourWorker::FillSparseValue(size_t table_idx) {
H
heqiaozhi 已提交
188
  uint64_t table_id = static_cast<uint64_t>(
189
      param_.program_config(0).pull_sparse_table_id(table_idx));
H
heqiaozhi 已提交
190 191 192 193 194 195 196 197

  TableParameter table;
  for (auto i : param_.sparse_table()) {
    if (i.table_id() == table_id) {
      table = i;
      break;
    }
  }
198 199 200 201

  auto& fea_value = feature_values_[table_id];
  auto fea_idx = 0u;

X
xjqbest 已提交
202
  std::vector<float> init_value(table.fea_dim());
203 204 205 206
  for (size_t i = 0; i < sparse_key_names_[table_id].size(); ++i) {
    std::string slot_name = sparse_key_names_[table_id][i];
    std::string emb_slot_name = sparse_value_names_[table_id][i];
    Variable* var = thread_scope_->FindVar(slot_name);
207 208 209
    if (var == nullptr) {
      continue;
    }
210
    phi::DenseTensor* tensor = var->GetMutable<phi::DenseTensor>();
211
    CHECK(tensor != nullptr) << "tensor of var " << slot_name << " is null";
212 213 214
    int64_t* ids = tensor->data<int64_t>();
    int len = tensor->numel();
    Variable* var_emb = thread_scope_->FindVar(emb_slot_name);
215 216 217
    if (var_emb == nullptr) {
      continue;
    }
218
    phi::DenseTensor* tensor_emb = var_emb->GetMutable<phi::DenseTensor>();
219 220 221 222 223 224
    float* ptr = tensor_emb->mutable_data<float>({len, table.emb_dim()},
                                                 platform::CPUPlace());
    memset(ptr, 0, sizeof(float) * len * table.emb_dim());
    auto& tensor_lod = tensor->lod()[0];
    LoD data_lod{tensor_lod};
    tensor_emb->set_lod(data_lod);
225 226 227 228 229 230 231 232

    bool is_nid = (adjust_ins_weight_config_.need_adjust() &&
                   adjust_ins_weight_config_.nid_slot() == emb_slot_name);
    if (is_nid) {
      nid_show_.clear();
    }
    int nid_ins_index = 0;

D
dongdaxiang 已提交
233
    for (int index = 0; index < len; ++index) {
234
      if (use_cvm_ || no_cvm_) {
235
        if (ids[index] == 0u) {
236 237
          memcpy(ptr + table.emb_dim() * index,
                 init_value.data(),
238
                 sizeof(float) * table.emb_dim());
239 240 241 242
          if (is_nid) {
            nid_show_.push_back(-1);
            ++nid_ins_index;
          }
243 244
          continue;
        }
245 246
        memcpy(ptr + table.emb_dim() * index,
               fea_value[fea_idx].data(),
247
               sizeof(float) * table.emb_dim());
248 249
        if (is_nid &&
            static_cast<size_t>(index) == tensor->lod()[0][nid_ins_index]) {
250 251 252
          nid_show_.push_back(fea_value[fea_idx][0]);
          ++nid_ins_index;
        }
253 254 255
        fea_idx++;
      } else {
        if (ids[index] == 0u) {
256 257
          memcpy(ptr + table.emb_dim() * index,
                 init_value.data() + 2,
258
                 sizeof(float) * table.emb_dim());
259 260 261 262
          if (is_nid) {
            nid_show_.push_back(-1);
            ++nid_ins_index;
          }
263 264
          continue;
        }
265 266
        memcpy(ptr + table.emb_dim() * index,
               fea_value[fea_idx].data() + 2,
267
               sizeof(float) * table.emb_dim());
268 269
        if (is_nid &&
            static_cast<size_t>(index) == tensor->lod()[0][nid_ins_index]) {
270 271 272
          nid_show_.push_back(fea_value[fea_idx][0]);
          ++nid_ins_index;
        }
273
        fea_idx++;
274 275 276 277 278
      }
    }
  }
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292
void DownpourWorker::AdjustInsWeight() {
#ifdef _LINUX
  // check var and tensor not null
  if (!adjust_ins_weight_config_.need_adjust()) {
    VLOG(0) << "need_adjust=false, skip adjust ins weight";
    return;
  }
  Variable* nid_var =
      thread_scope_->FindVar(adjust_ins_weight_config_.nid_slot());
  if (nid_var == nullptr) {
    VLOG(0) << "nid slot var " << adjust_ins_weight_config_.nid_slot()
            << " is nullptr, skip adjust ins weight";
    return;
  }
293
  phi::DenseTensor* nid_tensor = nid_var->GetMutable<phi::DenseTensor>();
294 295 296 297 298 299 300 301 302 303 304 305
  if (nid_tensor == nullptr) {
    VLOG(0) << "tensor of nid slot var " << adjust_ins_weight_config_.nid_slot()
            << " is nullptr, skip adjust ins weight";
    return;
  }
  Variable* ins_weight_var =
      thread_scope_->FindVar(adjust_ins_weight_config_.ins_weight_slot());
  if (ins_weight_var == nullptr) {
    VLOG(0) << "ins weight var " << adjust_ins_weight_config_.ins_weight_slot()
            << " is nullptr, skip adjust ins weight";
    return;
  }
306 307
  phi::DenseTensor* ins_weight_tensor =
      ins_weight_var->GetMutable<phi::DenseTensor>();
308 309 310 311 312 313 314 315 316 317
  if (ins_weight_tensor == nullptr) {
    VLOG(0) << "tensor of ins weight tensor "
            << adjust_ins_weight_config_.ins_weight_slot()
            << " is nullptr, skip adjust ins weight";
    return;
  }

  float* ins_weights = ins_weight_tensor->data<float>();
  size_t len = ins_weight_tensor->numel();  // len = batch size
  // here we assume nid_show slot only has one feasign in each instance
318 319 320
  CHECK(len == nid_show_.size())
      << "ins_weight size should be equal to "
      << "nid_show size, " << len << " vs " << nid_show_.size();
321 322 323 324 325
  float nid_adjw_threshold = adjust_ins_weight_config_.nid_adjw_threshold();
  float nid_adjw_ratio = adjust_ins_weight_config_.nid_adjw_ratio();
  int64_t nid_adjw_num = 0;
  double nid_adjw_weight = 0.0;
  size_t ins_index = 0;
326
  for (size_t i = 0; i < len; ++i) {
327 328 329 330 331 332 333 334
    float nid_show = nid_show_[i];
    VLOG(3) << "nid_show " << nid_show;
    if (nid_show < 0) {
      VLOG(3) << "nid_show < 0, continue";
      continue;
    }
    float ins_weight = 1.0;
    if (nid_show >= 0 && nid_show < nid_adjw_threshold) {
335 336
      ins_weight = log(M_E + (nid_adjw_threshold - nid_show) /
                                 nid_adjw_threshold * nid_adjw_ratio);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
      // count nid adjw insnum and weight
      ++nid_adjw_num;
      nid_adjw_weight += ins_weight;
      // choose large ins weight
      VLOG(3) << "ins weight new " << ins_weight << ", ins weight origin "
              << ins_weights[ins_index];
      if (ins_weight > ins_weights[ins_index]) {
        VLOG(3) << "ins " << ins_index << " weight changes to " << ins_weight;
        ins_weights[ins_index] = ins_weight;
      }
      ++ins_index;
    }
  }
  VLOG(3) << "nid adjw info: total_adjw_num: " << nid_adjw_num
          << ", avg_adjw_weight: " << nid_adjw_weight;
#endif
}

X
xujiaqi01 已提交
355
void DownpourWorker::CopySparseTable() {
356 357 358
  for (auto& copy_sparse_table : copy_sparse_tables_) {
    int64_t src_table = copy_sparse_table.first;
    int64_t dest_table = copy_sparse_table.second;
X
xujiaqi01 已提交
359 360 361 362 363 364
    int32_t feanum = 0;
    if (src_table == dest_table) {
      continue;
    } else if (!copy_table_config_.sparse_copy_by_feasign()) {
      if (feasign_set_.find(src_table) == feasign_set_.end()) {
        continue;
365
      } else if (feasign_set_[src_table].empty()) {
X
xujiaqi01 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        continue;
      }
      feanum = fleet_ptr_->CopyTable(src_table, dest_table);
    } else {
      std::vector<uint64_t> fea_vec(feasign_set_[src_table].begin(),
                                    feasign_set_[src_table].end());
      feanum = fleet_ptr_->CopyTableByFeasign(src_table, dest_table, fea_vec);
      fea_vec.clear();
      std::vector<uint64_t>().swap(fea_vec);
    }
    VLOG(3) << "copy feasign from table " << src_table << " to table "
            << dest_table << ", feasign num=" << feanum;
    feasign_set_[src_table].clear();
    std::unordered_set<uint64_t>().swap(feasign_set_[src_table]);
  }
  feasign_set_.clear();
}

void DownpourWorker::CopyDenseTable() {
  if (thread_id_ != 0) {
    return;
  }
  thread_local std::vector<std::future<int32_t>> pull_dense_status;
389 390 391
  for (auto& copy_dense_table : copy_dense_tables_) {
    uint64_t src_table = copy_dense_table.first;
    uint64_t dest_table = copy_dense_table.second;
X
xujiaqi01 已提交
392 393 394 395 396 397 398 399 400
    if (src_table == dest_table) {
      continue;
    }
    int32_t dim = fleet_ptr_->CopyTable(src_table, dest_table);
    VLOG(3) << "copy param from table " << src_table << " to table "
            << dest_table << ", dim=" << dim;
    if (copy_table_config_.dense_pull_after_copy()) {
      VLOG(3) << "dense pull after copy, table=" << dest_table;
      pull_dense_status.resize(0);
401 402
      fleet_ptr_->PullDenseVarsAsync(*root_scope_,
                                     dest_table,
X
xujiaqi01 已提交
403
                                     dense_value_names_[dest_table],
404 405
                                     &pull_dense_status,
                                     true);
X
xujiaqi01 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
      for (auto& t : pull_dense_status) {
        t.wait();
        auto status = t.get();
        if (status != 0) {
          LOG(WARNING) << "pull dense after copy table failed,"
                       << " table=" << dest_table;
        }
      }
    }
  }
}

void DownpourWorker::CopyDenseVars() {
  if (thread_id_ != 0) {
    return;
  }
  for (int i = 0; i < copy_table_config_.src_var_list_size(); ++i) {
    auto& src_var_name = copy_table_config_.src_var_list(i);
    auto& dest_var_name = copy_table_config_.dest_var_list(i);
    if (src_var_name == dest_var_name) {
      continue;
    }
    VLOG(3) << "copy dense var from " << src_var_name << " to "
            << dest_var_name;
    Variable* src_var = thread_scope_->FindVar(src_var_name);
    CHECK(src_var != nullptr) << src_var_name << " not found";  // NOLINT
432
    phi::DenseTensor* src_tensor = src_var->GetMutable<phi::DenseTensor>();
433 434
    CHECK(src_tensor != nullptr)
        << src_var_name << " tensor is null";  // NOLINT
X
xujiaqi01 已提交
435 436 437 438
    float* src_data = src_tensor->data<float>();

    Variable* dest_var = thread_scope_->FindVar(dest_var_name);
    CHECK(dest_var != nullptr) << dest_var_name << " not found";  // NOLINT
439
    phi::DenseTensor* dest_tensor = dest_var->GetMutable<phi::DenseTensor>();
440 441
    CHECK(dest_tensor != nullptr)
        << dest_var_name << " tensor is null";  // NOLINT
X
xujiaqi01 已提交
442 443 444 445 446 447 448 449 450 451 452
    float* dest_data = dest_tensor->data<float>();

    CHECK(src_tensor->numel() == dest_tensor->numel())
        << "tensor numel not equal," << src_tensor->numel() << " vs "
        << dest_tensor->numel();
    for (int i = 0; i < src_tensor->numel(); i++) {
      dest_data[i] = src_data[i];
    }
  }
}

453 454 455
void DownpourWorker::TrainFilesWithProfiler() {
  VLOG(3) << "Begin to train files with profiler";
  platform::SetNumThreads(1);
456 457 458 459 460
  device_reader_->Start();
  std::vector<double> op_total_time;
  std::vector<std::string> op_name;
  for (auto& op : ops_) {
    bool need_skip = false;
461 462
    for (auto& skip_op : skip_ops_) {
      if (op->Type().find(skip_op) != std::string::npos) {
463 464 465 466 467 468 469 470 471 472 473
        need_skip = true;
        break;
      }
    }
    if (!need_skip) {
      op_name.push_back(op->Type());
    }
  }

  VLOG(3) << "op name size: " << op_name.size();
  op_total_time.resize(op_name.size());
474 475
  for (double& op_time : op_total_time) {
    op_time = 0.0;
476 477 478 479 480
  }
  platform::Timer timeline;
  double total_time = 0.0;
  double read_time = 0.0;
  double pull_sparse_time = 0.0;
481
  double adjust_ins_weight_time = 0.0;
482 483 484 485
  double collect_label_time = 0.0;
  double fill_sparse_time = 0.0;
  double push_sparse_time = 0.0;
  double push_dense_time = 0.0;
X
xujiaqi01 已提交
486
  double copy_table_time = 0.0;
487 488
  int cur_batch;
  int batch_cnt = 0;
D
dongdaxiang 已提交
489
  uint64_t total_inst = 0;
490 491 492 493 494
  timeline.Start();
  while ((cur_batch = device_reader_->Next()) > 0) {
    timeline.Pause();
    read_time += timeline.ElapsedSec();
    total_time += timeline.ElapsedSec();
X
xujiaqi01 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508

    timeline.Start();
    if (copy_table_config_.need_copy()) {
      VLOG(3) << "copy_sparse_tables_.size " << copy_sparse_tables_.size();
      if (batch_cnt % copy_table_config_.batch_num() == 0) {
        CopySparseTable();
        CopyDenseTable();
        CopyDenseVars();
      }
    }
    timeline.Pause();
    copy_table_time += timeline.ElapsedSec();
    total_time += timeline.ElapsedSec();

509
    VLOG(3) << "program config size: " << param_.program_config_size();
D
dongdaxiang 已提交
510
    for (int i = 0; i < param_.program_config(0).pull_sparse_table_id_size();
511 512 513 514
         ++i) {
      uint64_t tid = static_cast<uint64_t>(
          param_.program_config(0).pull_sparse_table_id(i));
      TableParameter table;
515 516 517
      for (auto j : param_.sparse_table()) {
        if (j.table_id() == tid) {
          table = j;
518 519 520 521
          break;
        }
      }
      timeline.Start();
522 523 524 525 526 527 528
      fleet_ptr_->PullSparseVarsSync(*thread_scope_,
                                     tid,
                                     sparse_key_names_[tid],
                                     &features_[tid],
                                     &feature_values_[tid],
                                     table.fea_dim(),
                                     sparse_value_names_[tid]);
529 530
      timeline.Pause();
      pull_sparse_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
531
      total_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
532
      timeline.Start();
533 534 535
      CollectLabelInfo(i);
      timeline.Pause();
      collect_label_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
536
      total_time += timeline.ElapsedSec();
537 538 539 540
      timeline.Start();
      FillSparseValue(i);
      timeline.Pause();
      fill_sparse_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
541
      total_time += timeline.ElapsedSec();
542 543 544 545 546 547 548 549 550 551
      timeline.Start();
      auto nid_iter = std::find(sparse_value_names_[tid].begin(),
                                sparse_value_names_[tid].end(),
                                adjust_ins_weight_config_.nid_slot());
      if (nid_iter != sparse_value_names_[tid].end()) {
        AdjustInsWeight();
      }
      timeline.Pause();
      adjust_ins_weight_time += timeline.ElapsedSec();
      total_time += timeline.ElapsedSec();
552 553 554 555 556 557
    }
    VLOG(3) << "Fill sparse value for all sparse table done.";

    int run_op_idx = 0;
    for (auto& op : ops_) {
      bool need_skip = false;
558 559
      for (auto& skip_op : skip_ops_) {
        if (op->Type().find(skip_op) != std::string::npos) {
560 561 562 563 564 565
          need_skip = true;
          break;
        }
      }
      if (!need_skip) {
        timeline.Start();
566
        VLOG(3) << "Going to run op " << op_name[run_op_idx];
567
        op->Run(*thread_scope_, place_);
568
        VLOG(3) << "Op " << op_name[run_op_idx] << " Finished";
569 570 571 572 573 574
        timeline.Pause();
        op_total_time[run_op_idx++] += timeline.ElapsedSec();
        total_time += timeline.ElapsedSec();
      }
    }

575 576 577 578 579 580
    // check inf and nan
    for (std::string& var_name : check_nan_var_names_) {
      Variable* var = thread_scope_->FindVar(var_name);
      if (var == nullptr) {
        continue;
      }
581
      phi::DenseTensor* tensor = var->GetMutable<phi::DenseTensor>();
582 583 584
      if (tensor == nullptr) {
        continue;
      }
585 586
      PADDLE_ENFORCE_EQ(framework::TensorContainsInf(*tensor),
                        false,
587
                        platform::errors::InvalidArgument(
588
                            "phi::DenseTensor %s contains Inf.", var_name));
589 590
      PADDLE_ENFORCE_EQ(framework::TensorContainsNAN(*tensor),
                        false,
591
                        platform::errors::InvalidArgument(
592
                            "phi::DenseTensor %s contains NAN.", var_name));
593 594
    }

595
    if (need_to_push_sparse_) {
D
dongdaxiang 已提交
596 597
      for (int i = 0; i < param_.program_config(0).push_sparse_table_id_size();
           ++i) {
598 599 600 601 602 603 604 605
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_sparse_table_id(i));
        TableParameter table;
        for (auto i : param_.sparse_table()) {
          if (i.table_id() == tid) {
            table = i;
            break;
          }
606
        }
607 608
        timeline.Start();
        fleet_ptr_->PushSparseVarsWithLabelAsync(
609 610 611 612 613 614 615 616 617 618 619 620 621 622
            *thread_scope_,
            tid,
            features_[tid],
            feature_labels_[tid],
            sparse_key_names_[tid],
            sparse_grad_names_[tid],
            table.emb_dim(),
            &feature_grads_[tid],
            &push_sparse_status_,
            cur_batch,
            use_cvm_,
            dump_slot_,
            &sparse_push_keys_[tid],
            no_cvm_,
623
            scale_sparse_gradient_with_batch_size_);
624 625 626
        timeline.Pause();
        push_sparse_time += timeline.ElapsedSec();
        total_time += timeline.ElapsedSec();
627
      }
628 629
    }

X
xujiaqi01 已提交
630 631 632 633 634 635 636 637 638 639 640 641
#ifdef PADDLE_WITH_PSLIB
    if (copy_table_config_.need_copy()) {
      if (copy_table_config_.sparse_copy_by_feasign()) {
        for (size_t i = 0; i < copy_sparse_tables_.size(); ++i) {
          uint64_t tid = copy_sparse_tables_[i].first;
          feasign_set_[tid].insert(sparse_push_keys_[tid].begin(),
                                   sparse_push_keys_[tid].end());
        }
      }
    }
#endif

642
    if (need_to_push_dense_) {
643
      timeline.Start();
D
dongdaxiang 已提交
644 645
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
646 647
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
648 649 650 651 652 653
        fleet_ptr_->PushDenseVarsAsync(*thread_scope_,
                                       tid,
                                       dense_grad_names_[tid],
                                       &push_sparse_status_,
                                       scale_datanorm_,
                                       cur_batch);
654
      }
655
      timeline.Pause();
656
      push_dense_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
657
      total_time += timeline.ElapsedSec();
658 659 660 661 662 663 664 665 666
      VLOG(3) << "push sparse and dense gradient done.";
      int32_t tmp_push_dense_wait_times = -1;
      static uint32_t push_dense_wait_times =
          static_cast<uint32_t>(tmp_push_dense_wait_times);
      if (push_dense_status_.size() >= push_dense_wait_times) {
        for (auto& t : push_dense_status_) {
          t.wait();
        }
        push_dense_status_.resize(0);
667 668
      }

669 670
      if (tmp_push_dense_wait_times == -1) {
        push_dense_status_.resize(0);
671 672 673
      }
    }

674
    if (need_to_push_sparse_) {
675 676 677
      int32_t tmp_push_sparse_wait_times = -1;
      static uint32_t push_sparse_wait_times =
          static_cast<uint32_t>(tmp_push_sparse_wait_times);
678 679 680 681 682 683
      if (push_sparse_status_.size() >= push_sparse_wait_times) {
        for (auto& t : push_sparse_status_) {
          t.wait();
        }
        push_sparse_status_.resize(0);
      }
684

685 686 687
      if (tmp_push_sparse_wait_times == -1) {
        push_sparse_status_.resize(0);
      }
688

689 690 691
      VLOG(3) << "going to increase thread version";
      VLOG(3) << "push dense table id size: "
              << param_.program_config(0).push_dense_table_id_size();
692 693 694
    }

    if (need_to_push_dense_) {
D
dongdaxiang 已提交
695 696
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
697 698 699 700
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        pull_dense_worker_->IncreaseThreadVersion(thread_id_, tid);
      }
701 702
    }

D
dongdaxiang 已提交
703
    PrintFetchVars();
704
    thread_scope_->DropKids();
D
dongdaxiang 已提交
705
    total_inst += cur_batch;
706 707 708 709 710
    ++batch_cnt;

    if (thread_id_ == 0) {
      // should be configured here
      if (batch_cnt > 0 && batch_cnt % 100 == 0) {
711 712
        double op_sum_time = 0;
        std::unordered_map<std::string, double> op_to_time;
713
        for (size_t i = 0; i < op_total_time.size(); ++i) {
714 715 716 717 718
          fprintf(stderr,
                  "op_name:[%zu][%s], op_mean_time:[%fs]\n",
                  i,
                  op_name[i].c_str(),
                  op_total_time[i] / batch_cnt);
719 720 721 722 723 724 725
          if (op_to_time.find(op_name[i]) == op_to_time.end()) {
            op_to_time[op_name[i]] = 0.0;
          }
          op_to_time[op_name[i]] += op_total_time[i];
          op_sum_time += op_total_time[i];
        }
        for (auto& i : op_to_time) {
726 727 728
          fprintf(stderr,
                  "op [%s] run total time: [%f]ms\n",
                  i.first.c_str(),
729
                  i.second / batch_cnt);
730
        }
731 732
        fprintf(stderr, "op run total time: %fs\n", op_sum_time / batch_cnt);
        fprintf(stderr, "train total time: %fs\n", total_time / batch_cnt);
733 734 735 736 737 738
        fprintf(
            stderr, "pull sparse time: %fs\n", pull_sparse_time / batch_cnt);
        fprintf(
            stderr, "fill sparse time: %fs\n", fill_sparse_time / batch_cnt);
        fprintf(
            stderr, "push sparse time: %fs\n", push_sparse_time / batch_cnt);
739
        fprintf(stderr, "push dense time: %fs\n", push_dense_time / batch_cnt);
740 741
        fprintf(stderr,
                "collect label time: %fs\n",
742
                collect_label_time / batch_cnt);
743 744
        fprintf(stderr,
                "adjust ins weight time: %fs\n",
745
                adjust_ins_weight_time / batch_cnt);
X
xujiaqi01 已提交
746
        fprintf(stderr, "copy table time: %fs\n", copy_table_time / batch_cnt);
747 748
        fprintf(stderr, "mean read time: %fs\n", read_time / batch_cnt);
        fprintf(stderr, "IO percent: %f\n", read_time / total_time * 100);
749
        fprintf(stderr, "op run percent: %f\n", op_sum_time / total_time * 100);
750 751
        fprintf(stderr,
                "pull sparse time percent: %f\n",
D
dongdaxiang 已提交
752
                pull_sparse_time / total_time * 100);
753 754
        fprintf(stderr,
                "adjust ins weight time percent: %f\n",
755
                adjust_ins_weight_time / total_time * 100);
756 757
        fprintf(stderr,
                "copy table time percent: %f\n",
X
xujiaqi01 已提交
758
                copy_table_time / total_time * 100);
759 760
        fprintf(stderr,
                "collect label time percent: %f\n",
D
dongdaxiang 已提交
761
                collect_label_time / total_time * 100);
762 763
        fprintf(stderr,
                "fill sparse time percent: %f\n",
D
dongdaxiang 已提交
764
                fill_sparse_time / total_time * 100);
765 766
        fprintf(stderr,
                "push sparse time percent: %f\n",
D
dongdaxiang 已提交
767
                push_sparse_time / total_time * 100);
768 769
        fprintf(stderr,
                "push dense time percent: %f\n",
D
dongdaxiang 已提交
770
                push_dense_time / total_time * 100);
D
dongdaxiang 已提交
771
        fprintf(stderr, "%6.2f instances/s\n", total_inst / total_time);
772 773
      }
    }
D
dongdaxiang 已提交
774
    timeline.Start();
775
  }
X
xujiaqi01 已提交
776 777 778 779 780
  if (copy_table_config_.need_copy()) {
    CopySparseTable();
    CopyDenseTable();
    CopyDenseVars();
  }
781 782
}

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
#ifdef PADDLE_WITH_PSLIB
/**
 * @brief add auc monitor
 */
inline void AddAucMonitor(const Scope* scope, const platform::Place& place) {
  auto metric_ptr = Metric::GetInstance();
  auto& metric_list = metric_ptr->GetMetricList();
  for (auto iter = metric_list.begin(); iter != metric_list.end(); iter++) {
    auto* metric_msg = iter->second;
    if (metric_ptr->Phase() != metric_msg->MetricPhase()) {
      continue;
    }
    metric_msg->add_data(scope, place);
  }
}
#endif

800
void DownpourWorker::TrainFiles() {
D
dongdaxiang 已提交
801
  VLOG(3) << "Begin to train files";
802
  platform::SetNumThreads(1);
803
  device_reader_->Start();
804 805
  int batch_cnt = 0;
  int cur_batch;
806
  while ((cur_batch = device_reader_->Next()) > 0) {
X
xujiaqi01 已提交
807 808 809 810 811 812 813
    if (copy_table_config_.need_copy()) {
      if (batch_cnt % copy_table_config_.batch_num() == 0) {
        CopySparseTable();
        CopyDenseTable();
        CopyDenseVars();
      }
    }
814
    // pull sparse here
D
dongdaxiang 已提交
815
    for (int i = 0; i < param_.program_config(0).pull_sparse_table_id_size();
H
heqiaozhi 已提交
816 817 818 819
         ++i) {
      uint64_t tid = static_cast<uint64_t>(
          param_.program_config(0).pull_sparse_table_id(i));
      TableParameter table;
820 821 822
      for (auto j : param_.sparse_table()) {
        if (j.table_id() == tid) {
          table = j;
H
heqiaozhi 已提交
823 824 825
          break;
        }
      }
826 827 828 829 830 831 832
      fleet_ptr_->PullSparseVarsSync(*thread_scope_,
                                     tid,
                                     sparse_key_names_[tid],
                                     &features_[tid],
                                     &feature_values_[tid],
                                     table.fea_dim(),
                                     sparse_value_names_[tid]);
833 834
      CollectLabelInfo(i);
      FillSparseValue(i);
835 836 837 838 839 840
      auto nid_iter = std::find(sparse_value_names_[tid].begin(),
                                sparse_value_names_[tid].end(),
                                adjust_ins_weight_config_.nid_slot());
      if (nid_iter != sparse_value_names_[tid].end()) {
        AdjustInsWeight();
      }
841
    }
D
dongdaxiang 已提交
842
    VLOG(3) << "fill sparse value for all sparse table done.";
843 844 845

    // do computation here
    for (auto& op : ops_) {
846
      bool need_skip = false;
847 848
      for (auto& skip_op : skip_ops_) {
        if (op->Type().find(skip_op) != std::string::npos) {
849 850 851 852 853
          need_skip = true;
          break;
        }
      }
      if (!need_skip) {
854 855 856 857 858 859 860 861 862 863 864 865
#ifdef PADDLE_WITH_PSLIB
        try {
          op->Run(*thread_scope_, place_);
        } catch (std::exception& e) {
          fprintf(stderr, "error message: %s\n", e.what());
          auto& ins_id_vec = device_reader_->GetInsIdVec();
          size_t batch_size = device_reader_->GetCurBatchSize();
          std::string s = "";
          for (auto& ins_id : ins_id_vec) {
            if (s != "") s += ",";
            s += ins_id;
          }
866 867 868
          fprintf(stderr,
                  "batch_size: %zu, ins_ids_vec: %s\n",
                  batch_size,
869 870 871 872 873 874 875
                  s.c_str());
          s = "";
          for (auto& param : all_param_) {
            Variable* var = thread_scope_->FindVar(param);
            if (var == nullptr) {
              continue;
            }
876
            phi::DenseTensor* tensor = nullptr;
877
            int64_t len = 0;
878
            if (var->IsType<phi::DenseTensor>()) {
879
              tensor = var->GetMutable<phi::DenseTensor>();
880
              len = tensor->numel();
881 882
            } else if (var->IsType<phi::SelectedRows>()) {
              auto selected_rows = var->GetMutable<phi::SelectedRows>();
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
              tensor = selected_rows->mutable_value();
              len = tensor->numel();
            }
            if (!tensor->IsInitialized()) {
              continue;
            }
            s += param + ":" + std::to_string(len) + ":";
            s += PrintLodTensor(tensor, 0, len);
            fprintf(stderr, "%s\n", s.c_str());
            fflush(stderr);
            s = "";
          }
          throw e;
        }
#else
898
        op->Run(*thread_scope_, place_);
899
#endif
900
      }
901 902
    }

903 904 905 906 907 908 909
#ifdef PADDLE_WITH_PSLIB
    // add data for MetricMsg
    if (Metric::GetInstance() != nullptr) {
      AddAucMonitor(thread_scope_, place_);
    }
#endif

910 911 912 913 914 915
    // check inf and nan
    for (std::string& var_name : check_nan_var_names_) {
      Variable* var = thread_scope_->FindVar(var_name);
      if (var == nullptr) {
        continue;
      }
916
      phi::DenseTensor* tensor = var->GetMutable<phi::DenseTensor>();
917 918 919
      if (tensor == nullptr) {
        continue;
      }
920 921
      PADDLE_ENFORCE_EQ(framework::TensorContainsInf(*tensor),
                        false,
922
                        platform::errors::InvalidArgument(
923
                            "phi::DenseTensor %s contains Inf.", var_name));
924 925
      PADDLE_ENFORCE_EQ(framework::TensorContainsNAN(*tensor),
                        false,
926
                        platform::errors::InvalidArgument(
927
                            "phi::DenseTensor %s contains NAN.", var_name));
928 929
    }

930 931
    if (need_to_push_sparse_) {
      // push gradients here
D
dongdaxiang 已提交
932 933
      for (int i = 0; i < param_.program_config(0).push_sparse_table_id_size();
           ++i) {
934 935 936 937 938 939 940 941
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_sparse_table_id(i));
        TableParameter table;
        for (auto i : param_.sparse_table()) {
          if (i.table_id() == tid) {
            table = i;
            break;
          }
H
heqiaozhi 已提交
942
        }
943
        fleet_ptr_->PushSparseVarsWithLabelAsync(
944 945 946 947 948 949 950 951 952 953 954 955 956 957
            *thread_scope_,
            tid,
            features_[tid],
            feature_labels_[tid],
            sparse_key_names_[tid],
            sparse_grad_names_[tid],
            table.emb_dim(),
            &feature_grads_[tid],
            &push_sparse_status_,
            cur_batch,
            use_cvm_,
            dump_slot_,
            &sparse_push_keys_[tid],
            no_cvm_,
958
            scale_sparse_gradient_with_batch_size_);
H
heqiaozhi 已提交
959
      }
960 961
    }

X
xujiaqi01 已提交
962 963 964 965 966 967 968 969 970 971 972 973
#ifdef PADDLE_WITH_PSLIB
    if (copy_table_config_.need_copy()) {
      if (copy_table_config_.sparse_copy_by_feasign()) {
        for (size_t i = 0; i < copy_sparse_tables_.size(); ++i) {
          uint64_t tid = copy_sparse_tables_[i].first;
          feasign_set_[tid].insert(sparse_push_keys_[tid].begin(),
                                   sparse_push_keys_[tid].end());
        }
      }
    }
#endif

974
    if (need_to_push_dense_) {
Z
zhang wenhui 已提交
975 976
      if (flag_partial_push_) {
        Variable* var = (*thread_scope_).FindVar("cond_tag");
977
        phi::DenseTensor* tensor = var->GetMutable<phi::DenseTensor>();
Z
zhang wenhui 已提交
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
        // check type in python code
        int64_t* cond_value_batch = tensor->data<int64_t>();

        for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
             ++i) {
          uint64_t tid = static_cast<uint64_t>(
              param_.program_config(0).push_dense_table_id(i));
          if (condvalue_set_.find(tid) != condvalue_set_.end()) {
            // common dense table must push dense
            if (cond2table_map_[cond_value_batch[0]] != tid) {
              // can't push dense
              continue;
            }
          }

          VLOG(3) << "push multitask dense gradient " << tid;
994 995 996 997 998 999
          fleet_ptr_->PushDenseVarsAsync(*thread_scope_,
                                         tid,
                                         dense_grad_names_[tid],
                                         &push_sparse_status_,
                                         scale_datanorm_,
                                         cur_batch);
Z
zhang wenhui 已提交
1000 1001 1002 1003 1004 1005 1006 1007
        }

      } else {
        for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
             ++i) {
          uint64_t tid = static_cast<uint64_t>(
              param_.program_config(0).push_dense_table_id(i));

1008 1009 1010 1011 1012 1013
          fleet_ptr_->PushDenseVarsAsync(*thread_scope_,
                                         tid,
                                         dense_grad_names_[tid],
                                         &push_sparse_status_,
                                         scale_datanorm_,
                                         cur_batch);
Z
zhang wenhui 已提交
1014
        }
1015
      }
Z
zhang wenhui 已提交
1016

1017
      VLOG(3) << "push dense gradient done.";
1018

1019 1020 1021 1022 1023
      // the following code should be more precise and clean
      // TODO(guru4elephant)
      int32_t tmp_push_dense_wait_times = -1;
      static uint32_t push_dense_wait_times =
          static_cast<uint32_t>(tmp_push_dense_wait_times);
1024

1025 1026 1027 1028 1029
      if (push_dense_status_.size() >= push_dense_wait_times) {
        for (auto& t : push_dense_status_) {
          t.wait();
        }
        push_dense_status_.resize(0);
1030 1031
      }

1032 1033 1034
      if (tmp_push_dense_wait_times == -1) {
        push_dense_status_.resize(0);
      }
1035 1036
    }

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    if (need_to_push_sparse_) {
      VLOG(3) << "push sparse gradient done.";
      int32_t tmp_push_sparse_wait_times = -1;
      static uint32_t push_sparse_wait_times =
          static_cast<uint32_t>(tmp_push_sparse_wait_times);
      if (push_sparse_status_.size() >= push_sparse_wait_times) {
        for (auto& t : push_sparse_status_) {
          t.wait();
        }
        push_sparse_status_.resize(0);
1047 1048
      }

1049 1050 1051
      if (tmp_push_sparse_wait_times == -1) {
        push_sparse_status_.resize(0);
      }
1052 1053
    }

1054
    if (need_to_push_dense_) {
D
dongdaxiang 已提交
1055 1056
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
1057 1058 1059 1060
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        pull_dense_worker_->IncreaseThreadVersion(thread_id_, tid);
      }
1061
    }
1062
    if (need_dump_field_) {
H
hutuxian 已提交
1063 1064 1065 1066
      DumpField(*thread_scope_, dump_mode_, dump_interval_);
    }
    if (need_dump_param_ && thread_id_ == 0) {
      DumpParam(*thread_scope_, batch_cnt);
1067
    }
1068

D
dongdaxiang 已提交
1069
    PrintFetchVars();
1070 1071 1072
    thread_scope_->DropKids();
    ++batch_cnt;
  }
H
hutuxian 已提交
1073
  if (need_dump_field_ || need_dump_param_) {
1074 1075
    writer_.Flush();
  }
X
xujiaqi01 已提交
1076 1077 1078 1079 1080
  if (copy_table_config_.need_copy()) {
    CopySparseTable();
    CopyDenseTable();
    CopyDenseVars();
  }
1081 1082 1083 1084
}

}  // end namespace framework
}  // end namespace paddle