heter_server.h 12.9 KB
Newer Older
T
tangwei12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2018 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
#include <atomic>
#include <ctime>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <unordered_map>
T
tangwei12 已提交
23
#include <unordered_set>
T
tangwei12 已提交
24 25 26 27 28 29
#include <vector>
#include "brpc/channel.h"
#include "brpc/controller.h"
#include "brpc/server.h"
#include "paddle/fluid/distributed/service/brpc_utils.h"
#include "paddle/fluid/distributed/service/sendrecv.pb.h"
30
#include "paddle/fluid/framework/blocking_queue.h"
T
tangwei12 已提交
31 32 33 34 35 36 37 38
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/framework/variable_helper.h"
#include "paddle/fluid/platform/macros.h"  // for DISABLE_COPY_AND_ASSIGN
#include "paddle/fluid/platform/profiler.h"

39 40 41 42 43 44 45 46 47 48
namespace google {
namespace protobuf {
class Closure;
class RpcController;
}  // namespace protobuf
}  // namespace google
namespace paddle {
namespace framework {
class Executor;
class ProgramDesc;
49
class Scope;
50 51 52 53 54 55
}  // namespace framework
namespace platform {
class DeviceContext;
}  // namespace platform
}  // namespace paddle

T
tangwei12 已提交
56
DECLARE_double(eager_delete_tensor_gb);
T
tangwei12 已提交
57 58 59
namespace paddle {
namespace distributed {

T
tangwei12 已提交
60 61
using MultiVarMsg = ::paddle::distributed::MultiVariableMessage;
using VarMsg = ::paddle::distributed::VariableMessage;
T
tangwei12 已提交
62 63

class HeterService;
64

T
tangwei12 已提交
65
typedef int32_t (HeterService::*serviceHandlerFunc)(
66
    const PsRequestMessage& request, PsResponseMessage& response,  // NOLINT
T
tangwei12 已提交
67 68 69 70 71 72
    brpc::Controller* cntl);

typedef std::function<void(void*)> HeterRpcCallbackFunc;
typedef std::function<int(const MultiVarMsg*, MultiVarMsg*, brpc::Controller*)>
    HeterServiceHandler;

T
tangwei12 已提交
73
class HeterService : public ::paddle::distributed::PsService {
T
tangwei12 已提交
74 75 76 77 78 79 80 81 82 83
 public:
  HeterService() {
    _service_handler_map[PS_STOP_SERVER] = &HeterService::stop_heter_worker;
    _service_handler_map[PS_START_PROFILER] = &HeterService::start_profiler;
    _service_handler_map[PS_STOP_PROFILER] = &HeterService::stop_profiler;
  }

  virtual ~HeterService() {}

  virtual void service(::google::protobuf::RpcController* controller,
T
tangwei12 已提交
84 85
                       const PsRequestMessage* request,
                       PsResponseMessage* response,
T
tangwei12 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
                       ::google::protobuf::Closure* done) {
    brpc::ClosureGuard done_guard(done);
    std::string log_label("ReceiveCmd-");

    response->set_err_code(0);
    response->set_err_msg("");
    brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
    auto itr = _service_handler_map.find(request->cmd_id());
    if (itr == _service_handler_map.end()) {
      std::string err_msg(
          "undefined cmd_id, should match PsCmdID in ps.proto, cmd_id:");
      err_msg.append(std::to_string(request->cmd_id()));
      return;
    }
    serviceHandlerFunc handler_func = itr->second;
    int service_ret = (this->*handler_func)(*request, *response, cntl);
    if (service_ret != 0) {
      response->set_err_code(service_ret);
      response->set_err_msg("server internal error");
    }
T
tangwei12 已提交
106
  }
T
tangwei12 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

  void SendAndRecvVariable(::google::protobuf::RpcController* controller,
                           const MultiVarMsg* request, MultiVarMsg* response,
                           ::google::protobuf::Closure* done) {
    brpc::ClosureGuard done_guard(done);
    std::string message_name = request->message_name();
    auto itr = handler_map_.find(message_name);
    brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
    PADDLE_ENFORCE_NE(
        itr, handler_map_.end(),
        platform::errors::InvalidArgument(
            "HeterService::SendAndRecvVariable Get illegal message_name: %s "
            "which is not in HeterService::handler_map_",
            message_name));
    itr->second(request, response, cntl);
  }

  void RegisterServiceHandler(std::string message_name,
                              HeterServiceHandler func) {
    handler_map_[message_name] = func;
  }

129 130 131 132 133 134
  int32_t ForceExit() {
    VLOG(3) << "heter service force exit";
    is_exit_ = true;
    return 0;
  }

T
tangwei12 已提交
135 136 137 138 139 140
  void SetEndpoint(const std::string& end_point) { endpoint_ = end_point; }
  void SetFanin(const int& fan_in) { fan_in_ = fan_in; }
  bool IsExit() { return is_exit_; }

 private:
  int32_t stop_profiler(const PsRequestMessage& request,
141 142
                        PsResponseMessage& response,  // NOLINT
                        brpc::Controller* cntl);
T
tangwei12 已提交
143 144

  int32_t start_profiler(const PsRequestMessage& request,
145 146
                         PsResponseMessage& response,  // NOLINT
                         brpc::Controller* cntl);
T
tangwei12 已提交
147 148

  int32_t stop_heter_worker(const PsRequestMessage& request,
149
                            PsResponseMessage& response,  // NOLINT
T
tangwei12 已提交
150 151 152 153 154 155 156 157 158 159 160
                            brpc::Controller* cntl);

 private:
  std::string endpoint_;
  std::unordered_map<std::string, HeterServiceHandler> handler_map_;
  std::unordered_map<int32_t, serviceHandlerFunc> _service_handler_map;
  std::unordered_set<int> stop_cpu_worker_set_;
  int fan_in_;
  bool is_exit_ = false;
};

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
using SharedMiniScope =
    std::shared_ptr<std::unordered_map<int, ::paddle::framework::Scope*>>;
using SharedMicroScope = std::shared_ptr<std::unordered_map<
    int, std::shared_ptr<std::vector<::paddle::framework::Scope*>>>>;
using SharedTaskQueue = std::shared_ptr<
    std::unordered_map<int, std::shared_ptr<::paddle::framework::BlockingQueue<
                                std::pair<std::string, int>>>>>;

class HeterRequestHandler {
 public:
  HeterRequestHandler() : dev_ctx_(nullptr), scope_(nullptr) {}

  virtual ~HeterRequestHandler() {}

  void SetScope(const framework::Scope* scope) { scope_ = scope; }
  void SetDevCtx(const platform::DeviceContext* dev_ctx) { dev_ctx_ = dev_ctx; }

  virtual int Handle(const MultiVarMsg* request, MultiVarMsg* response,
                     brpc::Controller* cntl) = 0;

 protected:
  const platform::DeviceContext* dev_ctx_;
  const framework::Scope* scope_;
};

class RequestSendAndRecvHandler final : public HeterRequestHandler {
 public:
  RequestSendAndRecvHandler() {
    this->num_microbatch_ = 0;
    this->num_minibatch_ = 0;
  }

  virtual ~RequestSendAndRecvHandler() {}

195 196 197 198 199
  void SetMiniScopes(SharedMiniScope mini_scopes) {
    mini_scopes_ = mini_scopes;
    num_minibatch_ = mini_scopes_->size();
  }

200 201
  void SetMicroScopes(SharedMicroScope micro_scopes) {
    micro_scopes_ = micro_scopes;
202 203 204 205 206 207 208 209 210 211 212
    for (auto& scope_pair : (*micro_scopes_)) {
      // auto mini_idx = scope_pair.first;
      auto& micro_scopes = scope_pair.second;
      num_microbatch_ = micro_scopes->size();
      break;
    }
  }

  int GetThreadNum() {
    std::unique_lock<std::mutex> lk(scope_mutex_);
    return (*task_queue_).size();
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  }

  void SetTaskQueue(SharedTaskQueue task_queue) { task_queue_ = task_queue; }

  int Handle(const MultiVarMsg* request, MultiVarMsg* response,
             brpc::Controller* cntl) override {
    platform::RecordEvent record_event("RequestSendAndRecvHandler->Handle");
    FLAGS_eager_delete_tensor_gb = -1;

    // get microID from request
    // deserialize variable to micro scope
    // Push to heter worker's task_queue
    std::unique_ptr<paddle::framework::Scope> local_scope_ptr(
        new paddle::framework::Scope());
    auto& local_scope = *(local_scope_ptr.get());
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    platform::CPUPlace cpu_place;
    auto& cpu_dev_ctx = *pool.Get(cpu_place);

    auto message_name = request->message_name();
    auto& request_io_buffer = cntl->request_attachment();

    distributed::DeserializeFromMultiVarMsgAndIOBuf(
        *request, &request_io_buffer, cpu_dev_ctx, &local_scope);

    auto* var = local_scope.FindVar("microbatch_id");
    PADDLE_ENFORCE_NE(var, nullptr,
                      platform::errors::InvalidArgument(
                          "Not find variable microbatch_id in scope."));
    auto* tensor = var->GetMutable<framework::LoDTensor>();
    auto data = reinterpret_cast<const float*>(tensor->data<void>());
    auto micro_id = static_cast<int>(data[0]);

    int minibatch_index = micro_id / 10;
    int microbatch_index = micro_id % 10;

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
    // check minibatch_index is in mini_scopes_
    std::unique_lock<std::mutex> lk(scope_mutex_);
    if ((*mini_scopes_).find(minibatch_index) != (*mini_scopes_).end()) {
      lk.unlock();
      // PADDLE_ENFORCE_EQ(
      //    (*mini_scopes_).find(minibatch_index) != (*mini_scopes_).end(), 1,
      //    platform::errors::InvalidArgument(
      //        "minibatch index should in current trainer"));
      PADDLE_ENFORCE_EQ(
          (*micro_scopes_).find(minibatch_index) != (*micro_scopes_).end(), 1,
          platform::errors::InvalidArgument(
              "minibatch index should in current trainer"));

    } else {
      // create mini scope & micro scopes
      auto* minibatch_scope = &(scope_->NewScope());
      (*mini_scopes_)[minibatch_index] = minibatch_scope;
      (*micro_scopes_)[minibatch_index].reset(
          new std::vector<paddle::framework::Scope*>{});
      for (int i = 0; i < num_microbatch_; i++) {
        auto* micro_scope = &(minibatch_scope->NewScope());
        (*((*micro_scopes_)[minibatch_index])).push_back(micro_scope);
      }
      (*task_queue_)[minibatch_index].reset(
          new ::paddle::framework::BlockingQueue<
              std::pair<std::string, int>>());
      lk.unlock();
    }
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

    auto* micro_scope =
        (*((*micro_scopes_)[minibatch_index]))[microbatch_index];

    distributed::DeserializeFromMultiVarMsgAndIOBuf(
        *request, &request_io_buffer, *dev_ctx_, micro_scope);
    // blocking queue handles multi thread
    (*task_queue_)[minibatch_index]->Push(
        std::make_pair(message_name, microbatch_index));
    auto response_var_nums = request->recv_var_names_size();
    std::vector<std::string> response_var_names(response_var_nums),
        empty_var_names{};
    for (int var_idx = 0; var_idx < response_var_nums; ++var_idx) {
      response_var_names[var_idx] = request->recv_var_names(var_idx);
    }
    auto& response_io_buffer = cntl->response_attachment();
    distributed::SerializeToMultiVarMsgAndIOBuf(
        message_name, response_var_names, empty_var_names, *dev_ctx_,
        &local_scope, response, &response_io_buffer);
    return 0;
  }

 private:
  // share with HeterPipelineTrainer
301
  SharedMiniScope mini_scopes_{nullptr};
302 303 304 305
  SharedMicroScope micro_scopes_{nullptr};

  int num_microbatch_;
  int num_minibatch_;
306
  std::mutex scope_mutex_;
307 308 309 310 311 312 313

  bool is_first_stage_ = false;
  bool is_last_stage_ = false;

  SharedTaskQueue task_queue_;
};

T
tangwei12 已提交
314 315 316 317 318
class HeterServer {
 public:
  virtual ~HeterServer() {}

  void Stop() {
T
tangwei12 已提交
319
    std::unique_lock<std::mutex> lock(mutex_);
320 321 322
    if (stoped_ == true) return;
    if (!IsExit()) service_.ForceExit();
    VLOG(3) << "HeterServer Stop()";
T
tangwei12 已提交
323 324
    stoped_ = true;
    cv_.notify_all();
T
tangwei12 已提交
325 326 327 328
    server_.Stop(1000);
    server_.Join();
  }

329 330 331 332 333 334 335 336
  bool IsStop() {
    std::unique_lock<std::mutex> lock(mutex_);
    if (stoped_ == true)
      return true;
    else
      return false;
  }

T
tangwei12 已提交
337 338
  bool IsExit() { return service_.IsExit(); }

Z
zmxdream 已提交
339
  HeterServer() : service_(), ready_(0) {}
T
tangwei12 已提交
340 341 342 343 344 345

  void RegisterServiceHandler(std::string message_name,
                              HeterServiceHandler func);

  void StartHeterService();

346 347 348 349 350 351 352 353
  void SetEndPoint(const std::string& endpoint);
  void SetFanin(const int& fan_in);

  void SetRequestHandler(
      std::shared_ptr<RequestSendAndRecvHandler> request_handler) {
    request_handler_ = request_handler;
  }

354 355 356
  void SetMiniBatchScopes(SharedMiniScope mini_scopes) {
    request_handler_->SetMiniScopes(mini_scopes);
  }
357 358 359 360 361

  void SetMicroBatchScopes(SharedMicroScope micro_scopes) {
    request_handler_->SetMicroScopes(micro_scopes);
  }

362 363
  int GetThreadNum() { return request_handler_->GetThreadNum(); }

364 365 366
  void SetTaskQueue(SharedTaskQueue task_queue) {
    request_handler_->SetTaskQueue(task_queue);
  }
T
tangwei12 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379

  // HeterWrapper singleton
  static std::shared_ptr<HeterServer> GetInstance() {
    if (NULL == s_instance_) {
      s_instance_.reset(new HeterServer());
    }
    return s_instance_;
  }

  void WaitServerReady();

 private:
  static std::shared_ptr<HeterServer> s_instance_;
T
tangwei12 已提交
380 381 382
  mutable std::mutex mutex_;
  std::condition_variable cv_;
  std::condition_variable condition_ready_;
383
  bool stoped_ = true;
T
tangwei12 已提交
384 385 386 387 388
  std::string endpoint_;

 protected:
  brpc::Server server_;
  HeterService service_;
389 390
  std::shared_ptr<RequestSendAndRecvHandler> request_handler_;

T
tangwei12 已提交
391 392
  DISABLE_COPY_AND_ASSIGN(HeterServer);
  std::mutex mutex_ready_;
T
tangwei12 已提交
393

Z
zmxdream 已提交
394
  int ready_;
T
tangwei12 已提交
395 396 397 398
};

}  // end namespace distributed
}  // end namespace paddle