downpour_worker.cc 18.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/device_worker_factory.h"
17 18 19 20 21
#include "paddle/fluid/platform/cpu_helper.h"

namespace paddle {
namespace framework {

22
void DownpourWorker::Initialize(const TrainerDesc& desc) {
23
  param_ = desc.downpour_param();
D
dongdaxiang 已提交
24
  for (int i = 0; i < param_.sparse_table_size(); ++i) {
25 26 27 28
    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 已提交
29
    for (int j = 0; j < table.sparse_key_name_size(); ++j) {
30 31 32
      sparse_key_names_[table_id][j] = table.sparse_key_name(j);
    }
    sparse_value_names_[table_id].resize(table.sparse_value_name_size());
D
dongdaxiang 已提交
33
    for (int j = 0; j < table.sparse_value_name_size(); ++j) {
34 35 36
      sparse_value_names_[table_id][j] = table.sparse_value_name(j);
    }
    sparse_grad_names_[table_id].resize(table.sparse_grad_name_size());
D
dongdaxiang 已提交
37
    for (int j = 0; j < table.sparse_grad_name_size(); ++j) {
38 39
      sparse_grad_names_[table_id][j] = table.sparse_grad_name(j);
    }
40
    label_var_name_[table_id] = table.label_var_name();
41 42
  }

D
dongdaxiang 已提交
43
  for (int i = 0; i < param_.dense_table_size(); ++i) {
44 45 46
    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 已提交
47
    for (int j = 0; j < table.dense_value_name_size(); ++j) {
48 49 50
      dense_value_names_[table_id][j] = table.dense_value_name(j);
    }
    dense_grad_names_[table_id].resize(table.dense_grad_name_size());
D
dongdaxiang 已提交
51
    for (int j = 0; j < table.dense_grad_name_size(); ++j) {
52 53 54 55 56
      dense_grad_names_[table_id][j] = table.dense_grad_name(j);
    }
  }

  skip_ops_.resize(param_.skip_ops_size());
D
dongdaxiang 已提交
57
  for (int i = 0; i < param_.skip_ops_size(); ++i) {
58 59
    skip_ops_[i] = param_.skip_ops(i);
  }
60

61 62 63
  need_to_push_sparse_ = param_.push_sparse();
  need_to_push_dense_ = param_.push_dense();

64
  fleet_ptr_ = FleetWrapper::GetInstance();
D
dongdaxiang 已提交
65
  fetch_config_ = desc.fetch_config();
66
  use_cvm_ = desc.use_cvm();
67
  scale_datanorm_ = desc.scale_datanorm();
T
Thunderbrook 已提交
68
  dump_slot_ = desc.dump_slot();
69 70
}

71
void DownpourWorker::CollectLabelInfo(size_t table_idx) {
H
heqiaozhi 已提交
72
  uint64_t table_id = static_cast<uint64_t>(
73
      param_.program_config(0).pull_sparse_table_id(table_idx));
74

H
heqiaozhi 已提交
75 76 77 78 79 80 81
  TableParameter table;
  for (auto i : param_.sparse_table()) {
    if (i.table_id() == table_id) {
      table = i;
      break;
    }
  }
82 83 84
  auto& feature = features_[table_id];
  auto& feature_label = feature_labels_[table_id];
  feature_label.resize(feature.size());
85
  Variable* var = thread_scope_->FindVar(label_var_name_[table_id]);
86 87 88
  LoDTensor* tensor = var->GetMutable<LoDTensor>();
  int64_t* label_ptr = tensor->data<int64_t>();

D
dongdaxiang 已提交
89
  size_t global_index = 0;
90
  for (size_t i = 0; i < sparse_key_names_[table_id].size(); ++i) {
91 92
    VLOG(3) << "sparse_key_names_[" << i
            << "]: " << sparse_key_names_[table_id][i];
93
    Variable* fea_var = thread_scope_->FindVar(sparse_key_names_[table_id][i]);
94 95 96
    if (fea_var == nullptr) {
      continue;
    }
97
    LoDTensor* tensor = fea_var->GetMutable<LoDTensor>();
98 99
    CHECK(tensor != nullptr) << "tensor of var "
                             << sparse_key_names_[table_id][i] << " is null";
100
    int64_t* ids = tensor->data<int64_t>();
D
dongdaxiang 已提交
101
    size_t fea_idx = 0;
102
    // tensor->lod()[0].size() == batch_size + 1
103 104
    for (auto lod_idx = 1u; lod_idx < tensor->lod()[0].size(); ++lod_idx) {
      for (; fea_idx < tensor->lod()[0][lod_idx]; ++fea_idx) {
105 106 107 108
        // should be skipped feasign defined in protobuf
        if (ids[fea_idx] == 0u) {
          continue;
        }
109 110
        feature_label[global_index++] =
            static_cast<float>(label_ptr[lod_idx - 1]);
111 112 113 114 115 116 117 118
      }
    }
  }
  CHECK(global_index == feature.size())
      << "expect fea info size:" << feature.size() << " real:" << global_index;
}

void DownpourWorker::FillSparseValue(size_t table_idx) {
H
heqiaozhi 已提交
119
  uint64_t table_id = static_cast<uint64_t>(
120
      param_.program_config(0).pull_sparse_table_id(table_idx));
H
heqiaozhi 已提交
121 122 123 124 125 126 127 128

  TableParameter table;
  for (auto i : param_.sparse_table()) {
    if (i.table_id() == table_id) {
      table = i;
      break;
    }
  }
129 130 131 132

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

X
xjqbest 已提交
133
  std::vector<float> init_value(table.fea_dim());
134 135 136 137
  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);
138 139 140
    if (var == nullptr) {
      continue;
    }
141
    LoDTensor* tensor = var->GetMutable<LoDTensor>();
142
    CHECK(tensor != nullptr) << "tensor of var " << slot_name << " is null";
143 144 145 146 147 148 149 150 151 152
    int64_t* ids = tensor->data<int64_t>();
    int len = tensor->numel();
    Variable* var_emb = thread_scope_->FindVar(emb_slot_name);
    LoDTensor* tensor_emb = var_emb->GetMutable<LoDTensor>();
    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);
D
dongdaxiang 已提交
153
    for (int index = 0; index < len; ++index) {
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
      if (use_cvm_) {
        if (ids[index] == 0u) {
          memcpy(ptr + table.emb_dim() * index, init_value.data(),
                 sizeof(float) * table.emb_dim());
          continue;
        }
        memcpy(ptr + table.emb_dim() * index, fea_value[fea_idx].data(),
               sizeof(float) * table.emb_dim());
        fea_idx++;
      } else {
        if (ids[index] == 0u) {
          memcpy(ptr + table.emb_dim() * index, init_value.data() + 2,
                 sizeof(float) * table.emb_dim());
          continue;
        }
        memcpy(ptr + table.emb_dim() * index, fea_value[fea_idx].data() + 2,
170
               sizeof(float) * table.emb_dim());
171
        fea_idx++;
172 173 174 175 176
      }
    }
  }
}

177 178 179
void DownpourWorker::TrainFilesWithProfiler() {
  VLOG(3) << "Begin to train files with profiler";
  platform::SetNumThreads(1);
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
  device_reader_->Start();
  std::vector<double> op_total_time;
  std::vector<std::string> op_name;
  for (auto& op : ops_) {
    bool need_skip = false;
    for (auto t = 0u; t < skip_ops_.size(); ++t) {
      if (op->Type().find(skip_ops_[t]) != std::string::npos) {
        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());
  for (size_t i = 0; i < op_total_time.size(); ++i) {
    op_total_time[i] = 0.0;
  }
  platform::Timer timeline;
  double total_time = 0.0;
  double read_time = 0.0;
  double pull_sparse_time = 0.0;
  double collect_label_time = 0.0;
  double fill_sparse_time = 0.0;
  double push_sparse_time = 0.0;
  double push_dense_time = 0.0;
  int cur_batch;
  int batch_cnt = 0;
D
dongdaxiang 已提交
211
  uint64_t total_inst = 0;
212 213
  double op_sum_time = 0;
  std::unordered_map<std::string, double> op_to_time;
214 215 216 217 218 219
  timeline.Start();
  while ((cur_batch = device_reader_->Next()) > 0) {
    timeline.Pause();
    read_time += timeline.ElapsedSec();
    total_time += timeline.ElapsedSec();
    VLOG(3) << "program config size: " << param_.program_config_size();
D
dongdaxiang 已提交
220
    for (int i = 0; i < param_.program_config(0).pull_sparse_table_id_size();
221 222 223 224
         ++i) {
      uint64_t tid = static_cast<uint64_t>(
          param_.program_config(0).pull_sparse_table_id(i));
      TableParameter table;
225 226 227
      for (auto j : param_.sparse_table()) {
        if (j.table_id() == tid) {
          table = j;
228 229 230 231 232 233 234 235 236
          break;
        }
      }
      timeline.Start();
      fleet_ptr_->PullSparseVarsSync(*thread_scope_, tid,
                                     sparse_key_names_[tid], &features_[tid],
                                     &feature_values_[tid], table.fea_dim());
      timeline.Pause();
      pull_sparse_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
237
      total_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
238
      timeline.Start();
239 240 241
      CollectLabelInfo(i);
      timeline.Pause();
      collect_label_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
242
      total_time += timeline.ElapsedSec();
243 244 245 246
      timeline.Start();
      FillSparseValue(i);
      timeline.Pause();
      fill_sparse_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
247
      total_time += timeline.ElapsedSec();
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    }
    VLOG(3) << "Fill sparse value for all sparse table done.";

    int run_op_idx = 0;
    for (auto& op : ops_) {
      bool need_skip = false;
      for (auto t = 0u; t < skip_ops_.size(); ++t) {
        if (op->Type().find(skip_ops_[t]) != std::string::npos) {
          need_skip = true;
          break;
        }
      }
      if (!need_skip) {
        timeline.Start();
262
        VLOG(3) << "Going to run op " << op_name[run_op_idx];
263
        op->Run(*thread_scope_, place_);
264
        VLOG(3) << "Op " << op_name[run_op_idx] << " Finished";
265 266 267 268 269 270
        timeline.Pause();
        op_total_time[run_op_idx++] += timeline.ElapsedSec();
        total_time += timeline.ElapsedSec();
      }
    }

271
    if (need_to_push_sparse_) {
D
dongdaxiang 已提交
272 273
      for (int i = 0; i < param_.program_config(0).push_sparse_table_id_size();
           ++i) {
274 275 276 277 278 279 280 281
        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;
          }
282
        }
283 284 285 286
        timeline.Start();
        fleet_ptr_->PushSparseVarsWithLabelAsync(
            *thread_scope_, tid, features_[tid], feature_labels_[tid],
            sparse_key_names_[tid], sparse_grad_names_[tid], table.emb_dim(),
T
Thunderbrook 已提交
287 288
            &feature_grads_[tid], &push_sparse_status_, cur_batch, use_cvm_,
            dump_slot_);
289 290 291
        timeline.Pause();
        push_sparse_time += timeline.ElapsedSec();
        total_time += timeline.ElapsedSec();
292
      }
293 294 295
    }

    if (need_to_push_dense_) {
296
      timeline.Start();
D
dongdaxiang 已提交
297 298
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
299 300 301
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        fleet_ptr_->PushDenseVarsAsync(
302 303
            *thread_scope_, tid, dense_grad_names_[tid], &push_sparse_status_,
            scale_datanorm_, cur_batch);
304
      }
305
      timeline.Pause();
306
      push_dense_time += timeline.ElapsedSec();
D
dongdaxiang 已提交
307
      total_time += timeline.ElapsedSec();
308 309 310 311 312 313 314 315 316
      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);
317 318
      }

319 320
      if (tmp_push_dense_wait_times == -1) {
        push_dense_status_.resize(0);
321 322 323
      }
    }

324
    if (need_to_push_sparse_) {
325 326 327
      int32_t tmp_push_sparse_wait_times = -1;
      static uint32_t push_sparse_wait_times =
          static_cast<uint32_t>(tmp_push_sparse_wait_times);
328 329 330 331 332 333
      if (push_sparse_status_.size() >= push_sparse_wait_times) {
        for (auto& t : push_sparse_status_) {
          t.wait();
        }
        push_sparse_status_.resize(0);
      }
334

335 336 337
      if (tmp_push_sparse_wait_times == -1) {
        push_sparse_status_.resize(0);
      }
338

339 340 341
      VLOG(3) << "going to increase thread version";
      VLOG(3) << "push dense table id size: "
              << param_.program_config(0).push_dense_table_id_size();
342 343 344
    }

    if (need_to_push_dense_) {
D
dongdaxiang 已提交
345 346
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
347 348 349 350
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        pull_dense_worker_->IncreaseThreadVersion(thread_id_, tid);
      }
351 352
    }

D
dongdaxiang 已提交
353
    PrintFetchVars();
354
    thread_scope_->DropKids();
D
dongdaxiang 已提交
355
    total_inst += cur_batch;
356 357 358 359 360 361 362 363
    ++batch_cnt;

    if (thread_id_ == 0) {
      // should be configured here
      if (batch_cnt > 0 && batch_cnt % 100 == 0) {
        for (size_t i = 0; i < op_total_time.size(); ++i) {
          fprintf(stderr, "op_name:[%zu][%s], op_mean_time:[%fs]\n", i,
                  op_name[i].c_str(), op_total_time[i] / batch_cnt);
364 365 366 367 368 369 370 371 372
          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) {
          fprintf(stderr, "op [%s] run total time: [%f]ms\n", i.first.c_str(),
                  i.second / batch_cnt);
373
        }
374 375 376 377 378 379 380 381 382 383 384
        fprintf(stderr, "op run total time: %fs\n", op_sum_time / batch_cnt);
        fprintf(stderr, "train total time: %fs\n", total_time / batch_cnt);
        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);
        fprintf(stderr, "push dense time: %fs\n", push_dense_time / batch_cnt);
        fprintf(stderr, "collect label time: %fs\n",
                collect_label_time / batch_cnt);
385 386
        fprintf(stderr, "mean read time: %fs\n", read_time / batch_cnt);
        fprintf(stderr, "IO percent: %f\n", read_time / total_time * 100);
D
dongdaxiang 已提交
387 388 389 390 391 392 393 394 395 396
        fprintf(stderr, "pull sparse time percent: %f\n",
                pull_sparse_time / total_time * 100);
        fprintf(stderr, "collect label time percent: %f\n",
                collect_label_time / total_time * 100);
        fprintf(stderr, "fill sparse time percent: %f\n",
                fill_sparse_time / total_time * 100);
        fprintf(stderr, "push sparse time percent: %f\n",
                push_sparse_time / total_time * 100);
        fprintf(stderr, "push dense time percent: %f\n",
                push_dense_time / total_time * 100);
D
dongdaxiang 已提交
397
        fprintf(stderr, "%6.2f instances/s\n", total_inst / total_time);
398 399
      }
    }
D
dongdaxiang 已提交
400
    timeline.Start();
401
  }
402 403
}

404
void DownpourWorker::TrainFiles() {
D
dongdaxiang 已提交
405
  VLOG(3) << "Begin to train files";
406
  platform::SetNumThreads(1);
407
  device_reader_->Start();
408 409
  int batch_cnt = 0;
  int cur_batch;
410
  while ((cur_batch = device_reader_->Next()) > 0) {
411
    // pull sparse here
D
dongdaxiang 已提交
412
    for (int i = 0; i < param_.program_config(0).pull_sparse_table_id_size();
H
heqiaozhi 已提交
413 414 415 416
         ++i) {
      uint64_t tid = static_cast<uint64_t>(
          param_.program_config(0).pull_sparse_table_id(i));
      TableParameter table;
417 418 419
      for (auto j : param_.sparse_table()) {
        if (j.table_id() == tid) {
          table = j;
H
heqiaozhi 已提交
420 421 422 423 424 425
          break;
        }
      }
      fleet_ptr_->PullSparseVarsSync(*thread_scope_, tid,
                                     sparse_key_names_[tid], &features_[tid],
                                     &feature_values_[tid], table.fea_dim());
426 427 428
      CollectLabelInfo(i);
      FillSparseValue(i);
    }
D
dongdaxiang 已提交
429
    VLOG(3) << "fill sparse value for all sparse table done.";
430 431 432

    // do computation here
    for (auto& op : ops_) {
433 434 435 436 437 438 439 440 441 442
      bool need_skip = false;
      for (auto t = 0u; t < skip_ops_.size(); ++t) {
        if (op->Type().find(skip_ops_[t]) != std::string::npos) {
          need_skip = true;
          break;
        }
      }
      if (!need_skip) {
        op->Run(*thread_scope_, place_);
      }
443 444
    }

445 446
    if (need_to_push_sparse_) {
      // push gradients here
D
dongdaxiang 已提交
447 448
      for (int i = 0; i < param_.program_config(0).push_sparse_table_id_size();
           ++i) {
449 450 451 452 453 454 455 456
        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 已提交
457
        }
458 459 460
        fleet_ptr_->PushSparseVarsWithLabelAsync(
            *thread_scope_, tid, features_[tid], feature_labels_[tid],
            sparse_key_names_[tid], sparse_grad_names_[tid], table.emb_dim(),
T
Thunderbrook 已提交
461 462
            &feature_grads_[tid], &push_sparse_status_, cur_batch, use_cvm_,
            dump_slot_);
H
heqiaozhi 已提交
463
      }
464 465
    }

466
    if (need_to_push_dense_) {
D
dongdaxiang 已提交
467 468
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
469 470 471
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        fleet_ptr_->PushDenseVarsAsync(
472 473
            *thread_scope_, tid, dense_grad_names_[tid], &push_sparse_status_,
            scale_datanorm_, cur_batch);
474 475 476
      }

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

478 479 480 481 482
      // 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);
483

484 485 486 487 488
      if (push_dense_status_.size() >= push_dense_wait_times) {
        for (auto& t : push_dense_status_) {
          t.wait();
        }
        push_dense_status_.resize(0);
489 490
      }

491 492 493
      if (tmp_push_dense_wait_times == -1) {
        push_dense_status_.resize(0);
      }
494 495
    }

496 497 498 499 500 501 502 503 504 505
    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);
506 507
      }

508 509 510
      if (tmp_push_sparse_wait_times == -1) {
        push_sparse_status_.resize(0);
      }
511 512
    }

513
    if (need_to_push_dense_) {
D
dongdaxiang 已提交
514 515
      for (int i = 0; i < param_.program_config(0).push_dense_table_id_size();
           ++i) {
516 517 518 519
        uint64_t tid = static_cast<uint64_t>(
            param_.program_config(0).push_dense_table_id(i));
        pull_dense_worker_->IncreaseThreadVersion(thread_id_, tid);
      }
520
    }
521

D
dongdaxiang 已提交
522
    PrintFetchVars();
523 524 525 526 527 528 529
    thread_scope_->DropKids();
    ++batch_cnt;
  }
}

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