heter_server_test.cc 10.6 KB
Newer Older
T
tangwei12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* 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. */

#include <stdlib.h>
#include <memory>
#include <string>
#include <thread>  // NOLINT

20 21 22
#include <random>
#include <sstream>

T
tangwei12 已提交
23
#include "gtest/gtest.h"
24 25
#include "paddle/fluid/distributed/ps/service/heter_client.h"
#include "paddle/fluid/distributed/ps/service/heter_server.h"
T
Thunderbrook 已提交
26 27
#include "paddle/fluid/framework/op_registry.h"

T
tangwei12 已提交
28 29 30 31
namespace framework = paddle::framework;
namespace platform = paddle::platform;
namespace distributed = paddle::distributed;

T
tangwei12 已提交
32 33
using MultiVarMsg = ::paddle::distributed::MultiVariableMessage;
using VarMsg = ::paddle::distributed::VariableMessage;
T
tangwei12 已提交
34

35
USE_OP_ITSELF(scale);
T
tangwei12 已提交
36 37 38

std::shared_ptr<distributed::HeterServer> b_rpc_service;

39 40 41 42 43 44 45 46 47 48 49 50 51
std::string get_ip_port() {
  std::mt19937 rng;
  rng.seed(std::random_device()());
  std::uniform_int_distribution<std::mt19937::result_type> dist(4444, 25000);
  int port = dist(rng);
  std::string ip_port;
  std::stringstream temp_str;
  temp_str << "127.0.0.1:";
  temp_str << port;
  temp_str >> ip_port;
  return ip_port;
}

T
tangwei12 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
framework::BlockDesc* AppendSendAndRecvBlock(framework::ProgramDesc* program) {
  auto root_block = program->MutableBlock(0);
  auto* block = program->AppendBlock(*root_block);

  framework::OpDesc* op = block->AppendOp();
  op->SetType("scale");
  op->SetInput("X", {"x"});
  op->SetOutput("Out", {"res"});
  op->SetAttr("scale", 0.5f);

  auto& out = *root_block->Var("res");
  out.SetType(framework::proto::VarType::LOD_TENSOR);
  out.SetShape({1, 10});

  return block;
}

void CreateVarsOnScope(framework::Scope* scope, platform::CPUPlace* place) {
  auto w_var = scope->Var("w");
71
  w_var->GetMutable<phi::SelectedRows>();
T
tangwei12 已提交
72 73 74 75

  auto out_var = scope->Var("out");
  out_var->GetMutable<framework::LoDTensor>();

76 77 78
  auto micro_var = scope->Var("microbatch_id");
  micro_var->GetMutable<framework::LoDTensor>();

T
tangwei12 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  auto ids_var = scope->Var("ids");
  ids_var->GetMutable<framework::LoDTensor>();

  auto x_var = scope->Var("x");
  x_var->GetMutable<framework::LoDTensor>();

  auto res_var = scope->Var("res");
  res_var->GetMutable<framework::LoDTensor>();
}

void InitTensorsOnClient(framework::Scope* scope, platform::CPUPlace* place,
                         int64_t rows_numel) {
  CreateVarsOnScope(scope, place);
  auto ids_var = scope->Var("ids")->GetMutable<framework::LoDTensor>();
  int64_t* ids_ptr =
      ids_var->mutable_data<int64_t>(framework::DDim({rows_numel, 1}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) ids_ptr[i] = i * 2;

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  auto micro_id_var =
      scope->Var("microbatch_id")->GetMutable<framework::LoDTensor>();
  float* micro_id_ptr =
      micro_id_var->mutable_data<float>(framework::DDim({1}), *place);
  micro_id_ptr[0] = 0;

  auto x_var = scope->Var("x")->GetMutable<framework::LoDTensor>();
  float* x_ptr =
      x_var->mutable_data<float>(framework::DDim({1, rows_numel}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) x_ptr[i] = 1.0;

  auto res_var = scope->Var("res")->GetMutable<framework::LoDTensor>();
  float* res_ptr =
      res_var->mutable_data<float>(framework::DDim({1, rows_numel}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) res_ptr[i] = 1.0;
}

void InitTensorsOnClient2(framework::Scope* scope, platform::CPUPlace* place,
                          int64_t rows_numel) {
  CreateVarsOnScope(scope, place);
  auto ids_var = scope->Var("ids")->GetMutable<framework::LoDTensor>();
  int64_t* ids_ptr =
      ids_var->mutable_data<int64_t>(framework::DDim({rows_numel, 1}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) ids_ptr[i] = i * 2;

  auto micro_id_var =
      scope->Var("microbatch_id")->GetMutable<framework::LoDTensor>();
  float* micro_id_ptr =
      micro_id_var->mutable_data<float>(framework::DDim({1}), *place);
  micro_id_ptr[0] = 1;

T
tangwei12 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141
  auto x_var = scope->Var("x")->GetMutable<framework::LoDTensor>();
  float* x_ptr =
      x_var->mutable_data<float>(framework::DDim({1, rows_numel}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) x_ptr[i] = 1.0;

  auto res_var = scope->Var("res")->GetMutable<framework::LoDTensor>();
  float* res_ptr =
      res_var->mutable_data<float>(framework::DDim({1, rows_numel}), *place);
  for (int64_t i = 0; i < rows_numel; ++i) res_ptr[i] = 1.0;
}

void InitTensorsOnServer(framework::Scope* scope, platform::CPUPlace* place,
                         int64_t rows_numel) {
  CreateVarsOnScope(scope, place);
142
  auto w = scope->Var("w")->GetMutable<phi::SelectedRows>();
T
tangwei12 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  auto w_value = w->mutable_value();
  w_value->Resize({rows_numel, 10});
  for (int64_t i = 0; i < rows_numel; ++i) w->AutoGrownIndex(i, true);

  auto ptr = w_value->mutable_data<float>(*place);

  for (int64_t i = 0; i < w_value->numel(); ++i) {
    ptr[i] = static_cast<float>(i / 10);
  }
}

void RunServer(std::shared_ptr<paddle::distributed::HeterServer> service) {
  service->StartHeterService();
}

void StartSendAndRecvServer(std::string endpoint) {
  framework::ProgramDesc program;
  framework::Scope scope;
  platform::CPUPlace place;
  framework::Executor exe(place);
  platform::CPUDeviceContext ctx(place);
  LOG(INFO) << "before AppendSendAndRecvBlock";
  auto block = AppendSendAndRecvBlock(&program);
  std::string in_var_name("x");
167
  std::string in_var_name2("y");
T
tangwei12 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  std::vector<int> prefetch_block_ids{block->ID()};

  LOG(INFO) << "before InitTensorsOnServer";
  InitTensorsOnServer(&scope, &place, 10);
  LOG(INFO) << "end InitTensorsOnServer";

  std::shared_ptr<distributed::RequestSendAndRecvHandler> b_req_handler;
  b_req_handler.reset(new distributed::RequestSendAndRecvHandler());
  LOG(INFO) << "before SetDevCtx";
  b_req_handler->SetDevCtx(&ctx);
  LOG(INFO) << "before SetScope";
  b_req_handler->SetScope(&scope);
  LOG(INFO) << "before HeterServer::GetInstance";
  b_rpc_service = distributed::HeterServer::GetInstance();
  b_rpc_service->SetEndPoint(endpoint);
  LOG(INFO) << "before HeterServer::RegisterServiceHandler";
  b_rpc_service->RegisterServiceHandler(
      in_var_name, [&](const MultiVarMsg* request, MultiVarMsg* response,
                       brpc::Controller* cntl) -> int {
        return b_req_handler->Handle(request, response, cntl);
      });
189 190 191 192 193
  b_rpc_service->RegisterServiceHandler(
      in_var_name2, [&](const MultiVarMsg* request, MultiVarMsg* response,
                        brpc::Controller* cntl) -> int {
        return b_req_handler->Handle(request, response, cntl);
      });
T
tangwei12 已提交
194

195
  b_rpc_service->SetRequestHandler(b_req_handler);
T
tangwei12 已提交
196
  LOG(INFO) << "before HeterServer::RunServer";
197 198
  RunServer(b_rpc_service);
  // std::thread server_thread(std::bind(RunServer, b_rpc_service));
T
tangwei12 已提交
199

200
  // server_thread.join();
T
tangwei12 已提交
201 202 203 204 205
}

TEST(SENDANDRECV, CPU) {
  setenv("http_proxy", "", 1);
  setenv("https_proxy", "", 1);
206 207
  std::string endpoint = get_ip_port();
  std::string previous_endpoint = endpoint;
T
tangwei12 已提交
208 209 210 211
  LOG(INFO) << "before StartSendAndRecvServer";
  b_rpc_service = distributed::HeterServer::GetInstance();
  std::thread server_thread(StartSendAndRecvServer, endpoint);
  b_rpc_service->WaitServerReady();
212 213
  using MicroScope =
      std::unordered_map<int, std::shared_ptr<std::vector<framework::Scope*>>>;
214 215
  using MiniScope = std::unordered_map<int, framework::Scope*>;
  std::shared_ptr<MiniScope> mini_scopes(new MiniScope{});
216 217 218
  std::shared_ptr<MicroScope> micro_scopes(new MicroScope{});
  std::shared_ptr<std::vector<framework::Scope*>> micro_scope(
      new std::vector<framework::Scope*>{});
219 220 221 222 223 224
  auto* mini_scope = new framework::Scope();
  (*mini_scopes)[0] = mini_scope;
  auto* micro_scope_0 = &(mini_scope->NewScope());
  auto* micro_scope_1 = &(mini_scope->NewScope());
  (*micro_scope).push_back(micro_scope_0);
  (*micro_scope).push_back(micro_scope_1);
225 226
  (*micro_scopes)[0] = micro_scope;
  b_rpc_service->SetMicroBatchScopes(micro_scopes);
227
  b_rpc_service->SetMiniBatchScopes(mini_scopes);
228 229 230 231 232 233 234 235 236 237 238 239

  using TaskQueue =
      std::unordered_map<int,
                         std::shared_ptr<::paddle::framework::BlockingQueue<
                             std::pair<std::string, int>>>>;
  using SharedTaskQueue = std::shared_ptr<std::unordered_map<
      int, std::shared_ptr<::paddle::framework::BlockingQueue<
               std::pair<std::string, int>>>>>;
  SharedTaskQueue task_queue_(new TaskQueue{});
  (*task_queue_)[0] = std::make_shared<
      ::paddle::framework::BlockingQueue<std::pair<std::string, int>>>();
  b_rpc_service->SetTaskQueue(task_queue_);
T
tangwei12 已提交
240 241 242

  LOG(INFO) << "before HeterClient::GetInstance";
  distributed::HeterClient* rpc_client =
243 244
      distributed::HeterClient::GetInstance({endpoint}, {previous_endpoint}, 0)
          .get();
T
tangwei12 已提交
245 246 247 248 249

  PADDLE_ENFORCE_NE(rpc_client, nullptr,
                    platform::errors::InvalidArgument(
                        "Client Start Fail, Check Your Code & Env"));

250
  framework::Scope* scope = (*micro_scope)[0];
T
tangwei12 已提交
251 252 253 254 255 256
  platform::CPUPlace place;
  platform::CPUDeviceContext ctx(place);

  // create var on local scope
  int64_t rows_numel = 10;
  LOG(INFO) << "before InitTensorsOnClient";
257
  InitTensorsOnClient(scope, &place, rows_numel);
T
tangwei12 已提交
258
  std::string in_var_name("x");
259
  std::string micro_var_name("microbatch_id");
T
tangwei12 已提交
260
  std::string out_var_name("res");
261 262
  std::vector<std::string> send_var = {in_var_name, micro_var_name};
  std::vector<std::string> recv_var = {};
T
tangwei12 已提交
263 264

  LOG(INFO) << "before SendAndRecvAsync";
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  rpc_client->SendAndRecvAsync(ctx, *scope, in_var_name, send_var, recv_var,
                               "forward");

  LOG(INFO) << "client wait for Pop";
  auto task = (*task_queue_)[0]->Pop();
  LOG(INFO) << "client get from task queue";
  PADDLE_ENFORCE_EQ(
      task.first, "x",
      platform::errors::InvalidArgument(
          "Recv message and Send message name not match, Check your Code"));

  InitTensorsOnClient2((*micro_scope)[1], &place, rows_numel);
  LOG(INFO) << "before SendAndRecvAsync 2";
  std::string in_var_name2("y");
  rpc_client->SendAndRecvAsync(ctx, *((*micro_scope)[1]), in_var_name2,
                               send_var, recv_var, "backward");
  LOG(INFO) << "after SendAndRecvAsync 2";

  auto task2 = (*task_queue_)[0]->Pop();
  PADDLE_ENFORCE_EQ(
      task2.first, "y",
      platform::errors::InvalidArgument(
          "Recv message and Send message name not match, Check your Code"));

T
tangwei12 已提交
289 290 291 292 293 294
  rpc_client->FinalizeWorker();
  b_rpc_service->Stop();
  LOG(INFO) << "end server Stop";
  server_thread.join();
  LOG(INFO) << "end server thread join";
}