heter_server.cc 10.2 KB
Newer Older
T
tangwei12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2020 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
#include "paddle/fluid/distributed/ps/service/heter_server.h"
16

17
#include "paddle/fluid/string/split.h"
T
tangwei12 已提交
18 19 20

namespace paddle {
namespace distributed {
21 22 23
// DEFINE_string(cert_path, "./cert.pem", "cert.pem path");
// DEFINE_string(key_path, "./key.pem", "key.pem path");
std::shared_ptr<HeterServer> HeterServer::s_instance_ = nullptr;
24
std::mutex HeterServer::mtx_;
T
tangwei12 已提交
25 26 27 28 29 30

void HeterServer::RegisterServiceHandler(std::string message_name,
                                         HeterServiceHandler func) {
  service_.RegisterServiceHandler(message_name, func);
}

31
void HeterServer::StartHeterService(bool neeed_encrypt) {
T
tangwei12 已提交
32 33
  server_.AddService(&service_, brpc::SERVER_DOESNT_OWN_SERVICE);
  brpc::ServerOptions options;
34
  if (neeed_encrypt) {
35 36 37 38
#ifdef PADDLE_WITH_ARM_BRPC
    options.mutable_ssl_options()->default_cert.certificate = "/cert.pem";
    options.mutable_ssl_options()->default_cert.private_key = "/key.pem";
#else
39 40
    options.ssl_options.default_cert.certificate = "/cert.pem";
    options.ssl_options.default_cert.private_key = "/key.pem";
41
#endif
42
  }
T
tangwei12 已提交
43
  if (server_.Start(endpoint_.c_str(), &options) != 0) {
44 45 46 47 48 49 50 51
    VLOG(0) << "HeterServer start fail. Try again.";
    auto ip_port = paddle::string::Split(endpoint_, ':');
    std::string ip = ip_port[0];
    int port = std::stoi(ip_port[1]);
    std::string int_ip_port = GetIntTypeEndpoint(ip, port);
    if (server_.Start(endpoint_.c_str(), &options) != 0) {
      LOG(ERROR) << "HeterServer start failed, ip_port= " << int_ip_port;
    }
T
tangwei12 已提交
52 53 54 55 56 57
  } else {
    VLOG(0) << "heter server start success! listen on " << endpoint_;
  }

  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
58
    stoped_ = false;
T
tangwei12 已提交
59 60 61
    ready_ = 1;
  }
  condition_ready_.notify_all();
62
  VLOG(4) << "stopped: " << stoped_ << ", ready_: " << ready_;
T
tangwei12 已提交
63 64
  std::unique_lock<std::mutex> running_lock(mutex_);
  cv_.wait(running_lock, [&] {
65
    VLOG(4) << "Heter Server is Stop? " << stoped_;
T
tangwei12 已提交
66 67
    return stoped_;
  });
68
  VLOG(4) << "start service done";
T
tangwei12 已提交
69 70
}

71 72 73 74
void HeterServer::StartHeterInterService(bool neeed_encrypt) {
  server_inter_.AddService(&service_, brpc::SERVER_DOESNT_OWN_SERVICE);
  brpc::ServerOptions options;
  if (neeed_encrypt) {
75 76 77 78
#ifdef PADDLE_WITH_ARM_BRPC
    options.mutable_ssl_options()->default_cert.certificate = "/cert.pem";
    options.mutable_ssl_options()->default_cert.private_key = "/key.pem";
#else
79 80
    options.ssl_options.default_cert.certificate = "/cert.pem";
    options.ssl_options.default_cert.private_key = "/key.pem";
81
#endif
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  }
  if (server_inter_.Start(endpoint_inter_.c_str(), &options) != 0) {
    VLOG(4) << "switch inter server start fail. Try again.";
    auto ip_port = paddle::string::Split(endpoint_inter_, ':');
    std::string ip = ip_port[0];
    int port = std::stoi(ip_port[1]);
    std::string int_ip_port = GetIntTypeEndpoint(ip, port);
    if (server_inter_.Start(endpoint_inter_.c_str(), &options) != 0) {
      LOG(ERROR) << "switch inter server start failed, ip_port= "
                 << int_ip_port;
    }
  } else {
    VLOG(4) << "switch inter server server start success! listen on "
            << endpoint_inter_;
  }
  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
    stoped_ = false;
    ready_ = 1;
  }
  condition_ready_.notify_all();
  VLOG(4) << "stopped: " << stoped_ << ", ready_: " << ready_;
  std::unique_lock<std::mutex> running_lock(mutex_);
  cv_.wait(running_lock, [&] {
    VLOG(4) << "Heter Server is Stop? " << stoped_;
    return stoped_;
  });
  VLOG(4) << "start service done";
T
tangwei12 已提交
110 111
}

112
void HeterServer::SetFanin(const int& fan_in) { service_.SetFanin(fan_in); }
T
tangwei12 已提交
113 114 115 116 117 118

void HeterServer::WaitServerReady() {
  std::unique_lock<std::mutex> lock(this->mutex_ready_);
  condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
}

119 120 121 122 123
int SendAndRecvVariableHandler::SaveInSwitchWithShard(
    const MultiVarMsg* request, PsResponseMessage* response,
    brpc::Controller* cntl) {
  VLOG(4) << "entering SaveInSwitchWithShard";
  int32_t group_id = request->group_id();
124 125 126
  if (group_id >= FLAGS_heter_world_size) {
    LOG(ERROR) << "group id exceed maxmium";
  }
127 128 129 130 131
  auto& local_shard = _local_shards[group_id];
  auto& request_io_buffer = cntl->request_attachment();
  butil::IOBufBytesIterator io_buffer_itr(request_io_buffer);
  for (int idx = 0; idx < request->send_var_names_size(); idx++) {
    const auto& var_name = request->send_var_names(idx);
132 133
    const auto& var_size = request->vars_len(idx);
    WaitForVarsConsumed(group_id, var_name);
134
    std::unique_lock<std::mutex> lk(scope_mutex_);
135
    auto& value = local_shard[var_name];
136
    value.resize(var_size);
137
    io_buffer_itr.copy_and_forward(reinterpret_cast<void*>(value.data()),
138 139 140
                                   var_size);
    vars_ready_flag[group_id][var_name] = 1;
    VLOG(4) << "saved var_name: " << var_name << "is saved ready!";
141 142
  }
  VLOG(4) << "SaveInSwitchWithShard success";
T
tangwei12 已提交
143 144 145
  return 0;
}

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
int SendAndRecvVariableHandler::QueryInSwitchWithShard(
    const MultiVarMsg* request, MultiVarMsg* response, brpc::Controller* cntl) {
  VLOG(4) << "entering QueryInSwitchWithShard";
  int32_t group_id = request->group_id();
  VLOG(4) << "group id: " << group_id;
  auto& local_shard = _local_shards[group_id];
  auto& response_io_buffer = cntl->response_attachment();
  auto req_var_nums = request->recv_var_names_size();
  std::vector<std::string> req_var_names(req_var_nums);
  for (int var_idx = 0; var_idx < req_var_nums; ++var_idx) {
    req_var_names[var_idx] = request->recv_var_names(var_idx);
  }
  auto msg_name = request->message_name();
  response->set_message_name(msg_name);
  for (auto& req_var_name : req_var_names) {
    VLOG(4) << "req var name: " << req_var_name;
    response->add_send_var_names(req_var_name);
163
    WaitForVarsProduced(group_id, req_var_name);
164
    std::unique_lock<std::mutex> lk(scope_mutex_);
165 166
    auto itr = local_shard.find(req_var_name);
    auto& value = itr.value();
167 168 169 170
    response_io_buffer.append(value.data(), value.size());
    value.resize(0);  // 清空内存
    vars_ready_flag[group_id][req_var_name] = 0;
    VLOG(4) << "query var_name: " << req_var_name << "is consumed ready!";
171 172
  }
  VLOG(4) << "heter server QueryInSwitchWithShard done";
T
tangwei12 已提交
173 174 175
  return 0;
}

176 177 178 179 180 181 182 183 184
int SendAndRecvVariableHandler::SaveInSwitchWithScope(
    const MultiVarMsg* request, PsResponseMessage* response,
    brpc::Controller* cntl) {
  VLOG(4) << "entering SaveInSwitchWithScope";
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  platform::CPUPlace cpu_place;
  auto& cpu_dev_ctx = *pool.Get(cpu_place);
  auto message_name = request->message_name();
  VLOG(4) << "message_name in heter server: " << message_name;
185 186 187 188 189 190

  auto send_var_nums = request->send_var_names_size();
  std::vector<std::string> send_var_names(send_var_nums);
  for (int idx = 0; idx < send_var_nums; idx++) {
    send_var_names[idx] = request->var_messages(idx).varname();
  }
191 192 193 194 195
  std::unique_lock<std::mutex> lk(scope_mutex_);
  auto local_scope = local_scope_ptr.get();
  if (!local_scope) {
    LOG(ERROR) << "local_scope_ptr is null in SaveInSwitchWithScope";
  }
196
  for (auto var_name : send_var_names) {
197 198 199 200
    auto* var_exist_ptr = local_scope->FindVar(var_name);
    if (!var_exist_ptr) {
      VLOG(4) << "not find var: " << var_name << " in local_scope";
    }
201
    WaitForVarsConsumed(0, var_name);
202 203 204 205 206
  }
  auto& request_io_buffer = cntl->request_attachment();
  distributed::DeserializeFromMultiVarMsgAndIOBuf(*request, &request_io_buffer,
                                                  cpu_dev_ctx, local_scope);
  lk.unlock();
207 208 209
  for (auto var_name : send_var_names) {
    std::unique_lock<std::mutex> lk(scope_mutex_);
    vars_ready_flag[0][var_name] = 1;
T
tangwei12 已提交
210
  }
211
  VLOG(4) << "SaveInSwitchWithScope success";
T
tangwei12 已提交
212 213 214
  return 0;
}

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
int SendAndRecvVariableHandler::QueryInSwitchWithScope(
    const MultiVarMsg* request, MultiVarMsg* response, brpc::Controller* cntl) {
  VLOG(4) << "entering QueryInSwitchWithScope";
  auto local_scope = local_scope_ptr.get();
  if (!local_scope) {
    LOG(INFO) << "local_scope is null";
  }
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  platform::CPUPlace cpu_place;
  auto& cpu_dev_ctx = *pool.Get(cpu_place);

  // get req message_name & req_var_names
  auto msg_name = request->message_name();
  auto req_var_nums = request->recv_var_names_size();
  std::vector<std::string> req_var_names(req_var_nums);
  for (int var_idx = 0; var_idx < req_var_nums; ++var_idx) {
    req_var_names[var_idx] = request->recv_var_names(var_idx);
  }
  auto& response_io_buffer = cntl->response_attachment();

  // 1. fill message_name(string)
  response->set_message_name(msg_name);

  // 2. fill var_names(string)
  for (auto& req_var_name : req_var_names) {
    response->add_send_var_names(req_var_name);
  }

  // 3. fill var_messages(VarMessage)
  for (auto& req_var_name : req_var_names) {
245
    WaitForVarsProduced(0, req_var_name);
246 247 248 249
    auto* send_var_msg = response->add_var_messages();
    send_var_msg->set_varname(req_var_name);

    framework::Variable* var_ptr;
250 251 252
    var_ptr = local_scope->FindVar(req_var_name);
    if (!var_ptr) {
      LOG(INFO) << "local_scope not find var: " << req_var_name;
253 254 255 256 257 258 259 260 261 262 263
    }
    butil::IOBuf temp_iobuf;
    if (var_ptr->IsType<framework::LoDTensor>()) {
      SerializeLodTensor(var_ptr, cpu_dev_ctx, send_var_msg, &temp_iobuf);
    } else if (var_ptr->IsType<phi::SelectedRows>()) {
      SerializeSelectedRows(var_ptr, cpu_dev_ctx, send_var_msg, &temp_iobuf);
    }
    response_io_buffer.append(temp_iobuf);
  }
  for (auto& req_var_name : req_var_names) {
    std::unique_lock<std::mutex> lk(scope_mutex_);
264
    vars_ready_flag[0][req_var_name] = 0;
265 266 267 268
  }
  VLOG(4) << "heter server QueryInSwitchWithScope done";
  return 0;
}
T
tangwei12 已提交
269
}  // end namespace distributed
270
}  // namespace paddle