heterxpu_trainer.cc 20.9 KB
Newer Older
T
Thunderbrook 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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

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

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

15 16 17 18 19 20 21 22 23
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
#include "io/fs.h"
#include "paddle/fluid/framework/data_feed_factory.h"
#include "paddle/fluid/framework/data_set.h"
#include "paddle/fluid/framework/device_worker_factory.h"
#include "paddle/fluid/framework/fleet/fleet_wrapper.h"
T
Thunderbrook 已提交
24
#include "paddle/fluid/framework/fleet/heter_wrapper.h"
25
#include "paddle/fluid/framework/trainer.h"
T
Thunderbrook 已提交
26 27 28
#if (defined PADDLE_WITH_CUDA || defined PADDLE_WITH_XPU) && \
    (defined PADDLE_WITH_PSLIB)
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
29
#include "paddle/fluid/platform/cuda_device_guard.h"
T
Thunderbrook 已提交
30
#endif
T
Thunderbrook 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
namespace paddle {
namespace framework {

void HeterXpuTrainer::Initialize(const TrainerDesc& trainer_desc,
                                 Dataset* dataset) {
  srand((unsigned)time(NULL));
  param_ = trainer_desc.downpour_param();
  for (int i = 0; i < param_.dense_table_size(); ++i) {
    uint64_t table_id = static_cast<uint64_t>(param_.dense_table(i).table_id());
    auto table = param_.dense_table(i);
    dense_grad_names_[table_id].resize(table.dense_grad_name_size());
    for (int j = 0; j < table.dense_grad_name_size(); ++j) {
      dense_grad_names_[table_id][j] = table.dense_grad_name(j);
    }
  }
  scale_datanorm_ = trainer_desc.scale_datanorm();
  int place_num = trainer_desc.worker_places_size();
  for (int i = 0; i < place_num; ++i) {
    int num = trainer_desc.worker_places(i);
T
Thunderbrook 已提交
50
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
51 52 53
    platform::CUDAPlace place = platform::CUDAPlace(num);
    platform::CUDADeviceGuard guard(place.device);
    cudaStream_t stream;
54
    PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamCreate(&stream));
T
Thunderbrook 已提交
55 56 57
    copy_streams_.push_back(stream);
    places_.push_back(place);
    cudaEvent_t event;
58
    PADDLE_ENFORCE_GPU_SUCCESS(
T
Thunderbrook 已提交
59 60
        cudaEventCreateWithFlags(&event, cudaEventDisableTiming));
    events_.push_back(event);
T
Thunderbrook 已提交
61 62 63 64 65
#endif
#ifdef PADDLE_WITH_XPU
    platform::XPUPlace place = platform::XPUPlace(num);
    places_.push_back(place);
#endif
T
Thunderbrook 已提交
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
  }
  // thread_num_ = trainer_desc.thread_num();
  // SetDataset(dataset);

  // dump_fields_path_ = trainer_desc.dump_fields_path();
  // dump_converter_ = trainer_desc.dump_converter();
  // need_dump_field_ = false;
  // if (trainer_desc.dump_fields_size() != 0 && dump_fields_path_ != "") {
  //   need_dump_field_ = true;
  // }
  // if (need_dump_field_) {
  //   auto &file_list = dataset->GetFileList();
  //   if (file_list.size() == 0) {
  //     need_dump_field_ = false;
  //   }
  // }
  // mpi_rank_ = trainer_desc.mpi_rank();
  // mpi_size_ = trainer_desc.mpi_size();
  // dump_file_num_ = trainer_desc.dump_file_num();
  // const std::vector<paddle::framework::DataFeed *> readers =
  //     dataset->GetReaders();
  // thread_num_ = readers.size();
  for (int i = 0; i < trainer_desc.downpour_param().stat_var_names_size();
       i++) {
    need_merge_var_names_.push_back(
        trainer_desc.downpour_param().stat_var_names(i));
  }
  running_ = true;
  VLOG(3) << "going to initialize pull dense worker";
  pull_dense_worker_ = PullDenseWorker::GetInstance();
  pull_dense_worker_->Initialize(trainer_desc);
  VLOG(3) << "initialize pull dense worker";
  SetDebug(trainer_desc.debug());
  fleet_ptr_ = FleetWrapper::GetInstance();
  heter_ptr_ = HeterWrapper::GetInstance();
  RegisterServiceHandler();
  // for (int i = 0; i < trainer_desc.worker_places_size(); ++i) {
  //   int num = trainer_desc.worker_places(i);
  //   platform::CUDAPlace place = platform::CUDAPlace(num);
  //   platform::CUDADeviceGuard guard(place.device);
  //   cudaStream_t stream;
107
  //   PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamCreate(&stream));
T
Thunderbrook 已提交
108 109 110 111 112 113 114 115 116
  //   copy_streams_.push_back(stream);
  //   places_.push_back(place);
  // }
  trainer_desc_ = trainer_desc;
}

void HeterXpuTrainer::CreateThreadParam(const ProgramDesc& program, int num) {
  auto place = places_[num];
  Scope* scope = place_scopes_[num];
T
Thunderbrook 已提交
117
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
118 119
  auto stream = copy_streams_[num];
  auto event = events_[num];
120
  auto dev_id = place.device;
T
Thunderbrook 已提交
121
  platform::CUDADeviceGuard guard(dev_id);
T
Thunderbrook 已提交
122 123 124
#endif

#ifdef PADDLE_WITH_XPU
125
  auto dev_id = place.device;
126
  platform::XPUDeviceGuard guard(dev_id);
T
Thunderbrook 已提交
127 128
#endif

T
Thunderbrook 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  auto& block = program.Block(0);
  for (auto& var : block.AllVars()) {
    if (var->Persistable()) {
      auto name = var->Name();
      Variable* root_var = root_scope_->FindVar(name);
      LoDTensor* root_tensor = root_var->GetMutable<LoDTensor>();
      auto* ptr = scope->Var(name);
      InitializeVariable(ptr, proto::VarType::LOD_TENSOR);
      LoDTensor* thread_tensor = ptr->GetMutable<LoDTensor>();

#define HeterMemcpyFunc(cpp_type, proto_type)                           \
  do {                                                                  \
    if (root_tensor->type() == proto_type) {                            \
      HeterMemCpy<cpp_type>(thread_tensor, root_tensor, place, stream); \
    }                                                                   \
  } while (0)
T
Thunderbrook 已提交
145 146 147 148 149 150 151 152

#define HeterMemcpyXpuFunc(cpp_type, proto_type)                \
  do {                                                          \
    if (root_tensor->type() == proto_type) {                    \
      HeterMemCpy<cpp_type>(thread_tensor, root_tensor, place); \
    }                                                           \
  } while (0)
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
153
      _ForEachDataType_(HeterMemcpyFunc);
T
Thunderbrook 已提交
154 155 156 157
#endif
#ifdef PADDLE_WITH_XPU
      _ForEachDataType_(HeterMemcpyXpuFunc);
#endif
T
Thunderbrook 已提交
158 159
    }
  }
T
Thunderbrook 已提交
160
#ifdef PADDLE_WITH_CUDA
161
  PADDLE_ENFORCE_GPU_SUCCESS(cudaEventRecord(event, stream));
T
Thunderbrook 已提交
162
  cudaEventSynchronize(event);
T
Thunderbrook 已提交
163
#endif
T
Thunderbrook 已提交
164 165
}

T
Thunderbrook 已提交
166
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
167 168 169 170 171 172 173 174 175
template <typename T>
void HeterXpuTrainer::HeterMemCpy(LoDTensor* thread_tensor,
                                  LoDTensor* root_tensor,
                                  const paddle::platform::Place& thread_place,
                                  cudaStream_t stream) {
  T* thread_ptr =
      thread_tensor->mutable_data<T>(root_tensor->dims(), thread_place);
  T* root_ptr = root_tensor->data<T>();
  if (platform::is_cpu_place(root_tensor->place())) {
176
    memory::Copy(thread_place, thread_ptr, platform::CPUPlace(), root_ptr,
T
Thunderbrook 已提交
177 178
                 sizeof(T) * root_tensor->numel(), stream);
  } else {
179 180
    memory::Copy(thread_place, thread_ptr, root_tensor->place(), root_ptr,
                 sizeof(T) * root_tensor->numel(), stream);
T
Thunderbrook 已提交
181 182
  }
}
T
Thunderbrook 已提交
183 184 185 186 187 188 189 190 191 192 193
#endif

#ifdef PADDLE_WITH_XPU
template <typename T>
void HeterXpuTrainer::HeterMemCpy(LoDTensor* thread_tensor,
                                  LoDTensor* root_tensor,
                                  const paddle::platform::Place& thread_place) {
  T* thread_ptr =
      thread_tensor->mutable_data<T>(root_tensor->dims(), thread_place);
  T* root_ptr = root_tensor->data<T>();
  if (platform::is_cpu_place(root_tensor->place())) {
194
    memory::Copy(thread_place, thread_ptr, platform::CPUPlace(), root_ptr,
T
Thunderbrook 已提交
195 196
                 sizeof(T) * root_tensor->numel());
  } else {
197 198
    memory::Copy(thread_place, thread_ptr, root_tensor->place(), root_ptr,
                 sizeof(T) * root_tensor->numel());
T
Thunderbrook 已提交
199 200 201
  }
}
#endif
T
Thunderbrook 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

void HeterXpuTrainer::DumpWork(int tid) {}

void HeterXpuTrainer::InitTrainerEnv(const ProgramDesc& main_program,
                                     const platform::Place& place) {
  CacheProgram(main_program);
  place_ = place;
  auto& profiler = paddle::ps::CostProfiler::instance();
  profiler.register_profiler("xpu_service_run_task");
  profiler.register_profiler("xpu_service_deserial");
  profiler.register_profiler("xpu_service_launch_kernel");
  profiler.register_profiler("xpu_service_wait");
}

void HeterXpuTrainer::InitOtherEnv(const ProgramDesc& main_program) {
  auto& block = main_program.Block(0);
  pull_dense_worker_->SetRootScope(root_scope_);
  pull_dense_worker_->CreatePinVar();
  for (size_t i = 0; i < places_.size(); ++i) {
    Scope* scope = &(root_scope_->NewScope());
    // for (auto &var : block.AllVars()) {
    //   if (var->Persistable()) {
    //     auto *ptr = scope->Var(var->Name());
    //     InitializeVariable(ptr, var->GetType());
    //   }
    // }
    place_scopes_.push_back(scope);
    CreateThreadParam(main_program, i);
    pull_dense_worker_->AddThreadScope(scope);
    pull_dense_worker_->AddPlace(places_[i]);
T
Thunderbrook 已提交
232
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
233
    pull_dense_worker_->AddStream(copy_streams_[i]);
T
Thunderbrook 已提交
234
#endif
T
Thunderbrook 已提交
235 236
  }
  pull_dense_worker_->Start();
T
Thunderbrook 已提交
237
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
238 239 240
  for (auto& stream : copy_streams_) {
    cudaStreamSynchronize(stream);
  }
T
Thunderbrook 已提交
241
#endif
T
Thunderbrook 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  op_names_.clear();
  for (auto& op_desc : block.AllOps()) {
    std::unique_ptr<OperatorBase> local_op = OpRegistry::CreateOp(*op_desc);
    op_names_.push_back(op_desc->Type());
    OperatorBase* local_op_ptr = local_op.release();
    ops_.push_back(local_op_ptr);
    continue;
  }
  xpu_begin_op_index_ = xpu_end_op_index_ = -1;
  xpu_begin_op_index_ = trainer_desc_.xpu_start_idx();
  xpu_end_op_index_ = trainer_desc_.xpu_end_idx();
  VLOG(0) << "xpu begin: " << xpu_begin_op_index_
          << " xpu end: " << xpu_end_op_index_;
  // CHECK(xpu_begin_op_index_ == 0);
  // CHECK(xpu_end_op_index_ = ops_.size() - 1);
  //// init pool
  for (size_t i = 0; i < 6; ++i) {
    for (size_t j = 0; j < places_.size(); ++j) {
      int num = j;
      std::shared_ptr<HeterServiceContext> context =
          std::make_shared<HeterServiceContext>();
      context->place_num_ = num;
      auto place = places_[num];
      context->scope_ = &(place_scopes_[num]->NewScope());
      auto& block = program_.Block(0);
      for (auto& var : block.AllVars()) {
        if (!var->Persistable()) {
          auto* ptr = context->scope_->Var(var->Name());
          InitializeVariable(ptr, var->GetType());
        }
      }
      for (auto& v : dense_grad_names_) {
        for (auto& name : v.second) {
          auto* ptr = context->scope_->Var(name + "pin");
          InitializeVariable(ptr, proto::VarType::LOD_TENSOR);
        }
      }
      for (auto& op_desc : block.AllOps()) {
        std::unique_ptr<OperatorBase> local_op = OpRegistry::CreateOp(*op_desc);
        OperatorBase* local_op_ptr = local_op.release();
        (context->ops_).push_back(local_op_ptr);
      }
T
Thunderbrook 已提交
284
#ifdef PADDLE_WITH_CUDA
285
      auto dev_id = place.device;
T
Thunderbrook 已提交
286
      platform::CUDADeviceGuard guard(dev_id);
287
      PADDLE_ENFORCE_GPU_SUCCESS(
T
Thunderbrook 已提交
288
          cudaEventCreateWithFlags(&context->event_, cudaEventDisableTiming));
T
Thunderbrook 已提交
289
#endif
T
Thunderbrook 已提交
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
      object_pool_.Push(context);
    }
  }
  VLOG(3) << "init other env done.";
}

void HeterXpuTrainer::Run() {}

int HeterXpuTrainer::EndPass(const HeterRequest* request,
                             HeterResponse* response) {
  // int scope_num = object_pool_.Size();
  for (size_t i = 0; i < need_merge_var_names_.size(); i++) {
    Variable* root_var = root_scope_->FindVar(need_merge_var_names_[i]);
    if (root_var == nullptr) {
      continue;
    }
    LoDTensor* root_tensor = root_var->GetMutable<LoDTensor>();

    for (size_t j = 0; j < place_scopes_.size(); j++) {
      Scope* cur_thread_scope = place_scopes_[j];
      Variable* thread_var =
          cur_thread_scope->FindVar(need_merge_var_names_[i]);
      if (thread_var == nullptr) {
        continue;
      }
      LoDTensor* thread_tensor = thread_var->GetMutable<LoDTensor>();
//      if (root_tensor->numel() != thread_tensor->numel()) {
//        continue;
//      }
#define MergeCallback(cpp_type, proto_type)                                    \
  do {                                                                         \
    if (root_tensor->type() == proto_type) {                                   \
      if (thread_tensor->type() != proto_type) {                               \
        VLOG(0) << "Error: thread id=" << j << ", need_merge_var_names_[" << i \
                << "] " << need_merge_var_names_[i]                            \
                << ", root tensor type=" << root_tensor->type()                \
                << ", thread tensor type=" << thread_tensor->type();           \
        exit(-1);                                                              \
      }                                                                        \
      MergeToRootScope<cpp_type>(root_tensor, thread_tensor);                  \
    }                                                                          \
  } while (0)
      _ForEachDataType_(MergeCallback);
T
Thunderbrook 已提交
333 334
      if (!platform::is_cpu_place(thread_tensor->place())) {
#ifdef PADDLE_WITH_CUDA
335
        auto dev_id = thread_tensor->place().device;
T
Thunderbrook 已提交
336
        platform::CUDADeviceGuard guard(dev_id);
337
        cudaMemset(thread_tensor->data(), 0,
T
Thunderbrook 已提交
338
                   thread_tensor->numel() * SizeOfType(thread_tensor->type()));
T
Thunderbrook 已提交
339 340 341
#endif
#ifdef PADDLE_WITH_XPU
        auto place = thread_tensor->place();
342
        auto dev_id = place.device;
343
        platform::XPUDeviceGuard guard(dev_id);
T
Thunderbrook 已提交
344 345 346 347 348
        platform::DeviceContextPool& pool =
            platform::DeviceContextPool::Instance();
        platform::DeviceContext* dev_ctx = pool.Get(place);
        const platform::XPUDeviceContext* xpu_ctx =
            reinterpret_cast<const platform::XPUDeviceContext*>(dev_ctx);
349
        xpu::memset(xpu_ctx->x_context(), thread_tensor->data(), 0,
T
Thunderbrook 已提交
350 351
                    thread_tensor->numel() * SizeOfType(thread_tensor->type()));
#endif
T
Thunderbrook 已提交
352
      } else {
353
        memset(thread_tensor->data(), 0,
T
Thunderbrook 已提交
354 355 356 357 358 359
               thread_tensor->numel() * SizeOfType(thread_tensor->type()));
      }
    }
    auto* merge_var = response->add_vars();
    heter_ptr_->SerializeToReq(need_merge_var_names_[i], root_scope_,
                               merge_var);
T
Thunderbrook 已提交
360 361
    if (!platform::is_cpu_place(root_tensor->place())) {
#ifdef PADDLE_WITH_CUDA
362
      auto dev_id = root_tensor->place().device;
T
Thunderbrook 已提交
363
      platform::CUDADeviceGuard guard(dev_id);
364
      cudaMemset(root_tensor->data(), 0,
T
Thunderbrook 已提交
365
                 root_tensor->numel() * SizeOfType(root_tensor->type()));
T
Thunderbrook 已提交
366 367 368
#endif
#ifdef PADDLE_WITH_XPU
      auto place = root_tensor->place();
369
      auto dev_id = place.device;
370
      platform::XPUDeviceGuard guard(dev_id);
T
Thunderbrook 已提交
371 372 373 374 375
      platform::DeviceContextPool& pool =
          platform::DeviceContextPool::Instance();
      platform::DeviceContext* dev_ctx = pool.Get(place);
      const platform::XPUDeviceContext* xpu_ctx =
          reinterpret_cast<const platform::XPUDeviceContext*>(dev_ctx);
376
      xpu::memset(xpu_ctx->x_context(), root_tensor->data(), 0,
T
Thunderbrook 已提交
377 378
                  root_tensor->numel() * SizeOfType(root_tensor->type()));
#endif
T
Thunderbrook 已提交
379
    } else {
380
      memset(root_tensor->data(), 0,
T
Thunderbrook 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
             root_tensor->numel() * SizeOfType(root_tensor->type()));
    }
  }
  return 0;
}

template <typename T>
void HeterXpuTrainer::MergeToRootScope(LoDTensor* root_tensor,
                                       LoDTensor* tensor) {
  LoDTensor tmp_root;
  TensorCopy(*root_tensor, platform::CPUPlace(), &tmp_root);
  T* tmp_root_data = tmp_root.data<T>();
  LoDTensor tmp_tensor;
  TensorCopy(*tensor, platform::CPUPlace(), &tmp_tensor);
  T* data = tmp_tensor.data<T>();
  for (int i = 0; i < tmp_tensor.numel(); i++) {
    tmp_root_data[i] += data[i];
  }
  TensorCopy(tmp_root, root_tensor->place(), root_tensor);
}

int HeterXpuTrainer::StopService(const HeterRequest* request,
                                 HeterResponse* response) {
  std::unique_lock<std::mutex> lock(mutex_);
  running_ = false;
  cond_.notify_one();
  return 0;
}

int HeterXpuTrainer::RunTask(const HeterRequest* request,
                             HeterResponse* response) {
  auto timer = std::make_shared<paddle::ps::CostTimer>("xpu_service_run_task");
  std::shared_ptr<HeterServiceContext> context = object_pool_.Get();

  if (!context->scope_) {
416
    int num = rand_r() % places_.size();
T
Thunderbrook 已提交
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    context->place_num_ = num;
    auto place = places_[num];
    context->scope_ = &(place_scopes_[num]->NewScope());
    auto& block = program_.Block(0);
    for (auto& var : block.AllVars()) {
      if (!var->Persistable()) {
        auto* ptr = context->scope_->Var(var->Name());
        InitializeVariable(ptr, var->GetType());
      }
    }
    for (auto& v : dense_grad_names_) {
      for (auto& name : v.second) {
        auto* ptr = context->scope_->Var(name + "pin");
        InitializeVariable(ptr, proto::VarType::LOD_TENSOR);
      }
    }
    for (auto& op_desc : block.AllOps()) {
      std::unique_ptr<OperatorBase> local_op = OpRegistry::CreateOp(*op_desc);
      OperatorBase* local_op_ptr = local_op.release();
      (context->ops_).push_back(local_op_ptr);
    }
T
Thunderbrook 已提交
438
#ifdef PADDLE_WITH_CUDA
439
    auto dev_id = place.device;
T
Thunderbrook 已提交
440
    platform::CUDADeviceGuard guard(dev_id);
441
    PADDLE_ENFORCE_GPU_SUCCESS(
T
Thunderbrook 已提交
442
        cudaEventCreateWithFlags(&context->event_, cudaEventDisableTiming));
T
Thunderbrook 已提交
443
#endif
T
Thunderbrook 已提交
444 445 446 447 448 449 450 451
  }

  context->Reset();
  auto place = places_[context->place_num_];
  {
    auto deserial_timer =
        std::make_shared<paddle::ps::CostTimer>("xpu_service_deserial");
    for (int i = 0; i < request->vars_size(); ++i) {
T
Thunderbrook 已提交
452
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
453 454
      heter_ptr_->DeSerializeToTensor(context->scope_, request->vars(i), place,
                                      copy_streams_[context->place_num_]);
T
Thunderbrook 已提交
455 456 457 458
#endif
#ifdef PADDLE_WITH_XPU
      heter_ptr_->DeSerializeToTensor(context->scope_, request->vars(i), place);
#endif
T
Thunderbrook 已提交
459
    }
T
Thunderbrook 已提交
460
#ifdef PADDLE_WITH_CUDA
461
    PADDLE_ENFORCE_GPU_SUCCESS(
T
Thunderbrook 已提交
462 463 464 465 466
        cudaEventRecord(context->event_, copy_streams_[context->place_num_]));
    while (cudaEventQuery(context->event_) != cudaSuccess) {
      VLOG(3) << "wait for kernel";
      bthread_yield();
    }
T
Thunderbrook 已提交
467
#endif
T
Thunderbrook 已提交
468 469 470 471 472 473 474 475 476 477
  }

  {
    auto launch_timer =
        std::make_shared<paddle::ps::CostTimer>("xpu_service_launch_kernel");
    for (int i = xpu_begin_op_index_; i <= xpu_end_op_index_; ++i) {
      auto& op = (context->ops_)[i];
      op->Run(*(context->scope_), place);
    }
  }
T
Thunderbrook 已提交
478
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
479 480
  auto* dev_ctx = static_cast<platform::CUDADeviceContext*>(
      platform::DeviceContextPool::Instance().Get(place));
481
  PADDLE_ENFORCE_GPU_SUCCESS(
T
Thunderbrook 已提交
482 483 484 485 486 487 488 489 490 491
      cudaEventRecord(context->event_, dev_ctx->stream()));
  // cudaEventSynchronize(context->event_);
  {
    auto wait_timer =
        std::make_shared<paddle::ps::CostTimer>("xpu_service_wait");
    while (cudaEventQuery(context->event_) != cudaSuccess) {
      VLOG(3) << "wait for kernel";
      bthread_yield();
    }
  }
T
Thunderbrook 已提交
492 493 494 495
#endif
#ifdef PADDLE_WITH_XPU
  xpu_wait();
#endif
T
Thunderbrook 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

  for (int i = 0; i < trainer_desc_.xpu_send_list_size(); ++i) {
    const std::string& varname = trainer_desc_.xpu_send_list(i);
    // CHECK(varname == "concat_1.tmp_0@GRAD");
    auto* res_var = response->add_vars();
    heter_ptr_->SerializeToReq(varname, context->scope_, res_var);
  }

  // std::string varname = "concat_1.tmp_0@GRAD";
  //
  // auto* res_var = response->add_vars();
  // heter_ptr_->SerializeToReq(varname, context->scope_, res_var);
  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));
T
Thunderbrook 已提交
512
#ifdef PADDLE_WITH_CUDA
T
Thunderbrook 已提交
513 514 515 516 517
    fleet_ptr_->PushDenseVarsAsync(
        *(context->scope_), tid, dense_grad_names_[tid],
        &(context->push_dense_status_), scale_datanorm_, request->cur_batch(),
        places_[context->place_num_], copy_streams_[context->place_num_],
        context->event_);
T
Thunderbrook 已提交
518 519 520 521 522 523 524
#endif
#ifdef PADDLE_WITH_XPU
    fleet_ptr_->PushDenseVarsAsync(
        *(context->scope_), tid, dense_grad_names_[tid],
        &(context->push_dense_status_), scale_datanorm_, request->cur_batch(),
        places_[context->place_num_]);
#endif
T
Thunderbrook 已提交
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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
  }
  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));
    pull_dense_worker_->IncreaseThreadVersion(0, tid);
  }
  VLOG(3) << "push dense gradient done.";
  context->scope_->DropKids();
  object_pool_.Push(context);
  VLOG(0) << "pool size " << object_pool_.Size();
  return 0;
}

void HeterXpuTrainer::RegisterServiceHandler() {
  heter_ptr_->RegisterServiceHandler(
      0, [this](const HeterRequest* request, HeterResponse* response) -> int {
        return this->RunTask(request, response);
      });
  heter_ptr_->RegisterServiceHandler(
      1, [this](const HeterRequest* request, HeterResponse* response) -> int {
        return this->EndPass(request, response);
      });
  heter_ptr_->RegisterServiceHandler(
      2, [this](const HeterRequest* request, HeterResponse* response) -> int {
        return this->StopService(request, response);
      });
}

Scope* HeterXpuTrainer::GetWorkerScope(int thread_id) { return nullptr; }

void HeterXpuTrainer::Finalize() {
  // for (auto &th : threads_) {
  //   th.join();
  // }
  std::unique_lock<std::mutex> lock(mutex_);
  cond_.wait(lock, [this] { return !running_; });
  sleep(3);
  pull_dense_worker_->Stop();
  root_scope_->DropKids();
}
}  // namespace framework
}  // namespace paddle
#endif