rpc_server_test.cc 11.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
T
tangwei12 已提交
2

3 4 5
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
T
tangwei12 已提交
6

7
    http://www.apache.org/licenses/LICENSE-2.0
T
tangwei12 已提交
8

9 10 11 12 13 14
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 <stdlib.h>
16
#include <unistd.h>
17
#include <chrono>  // NOLINT
18
#include <memory>
19
#include <string>
Y
Yancey1989 已提交
20
#include <thread>  // NOLINT
21
#include <unordered_map>
22 23

#include "gtest/gtest.h"
Y
Yancey1989 已提交
24
#include "paddle/fluid/framework/block_desc.h"
Y
Yancey1989 已提交
25 26 27
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"

W
Wu Yi 已提交
28
#include "paddle/fluid/operators/distributed/distributed.h"
29
#include "paddle/fluid/operators/distributed/heart_beat_monitor.h"
30
#include "paddle/fluid/operators/distributed/large_scale_kv.h"
31 32 33
#include "paddle/fluid/operators/distributed/request_handler_impl.h"
#include "paddle/fluid/operators/distributed/rpc_client.h"
#include "paddle/fluid/operators/distributed/rpc_server.h"
34

35 36
namespace framework = paddle::framework;
namespace platform = paddle::platform;
37
namespace distributed = paddle::operators::distributed;
38

39
USE_NO_KERNEL_OP(lookup_sparse_table_read);
40
USE_NO_KERNEL_OP(checkpoint_notify);
41
USE_OP(scale);
Y
Yancey1989 已提交
42

43 44
std::unique_ptr<distributed::RPCServer> g_rpc_service;
std::unique_ptr<distributed::RequestHandler> g_req_handler;
45

46
framework::BlockDesc* AppendSendAndRecvBlock(framework::ProgramDesc* program) {
Y
Yancey1989 已提交
47 48
  auto root_block = program->MutableBlock(0);
  auto* block = program->AppendBlock(*root_block);
Y
Yancey1989 已提交
49

50 51 52 53 54 55 56
  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");
57
  out.SetType(framework::proto::VarType::LOD_TENSOR);
58
  out.SetShape({1, 10});
Y
Yancey1989 已提交
59

Y
Yancey1989 已提交
60 61 62
  return block;
}

Y
Yancey1989 已提交
63 64
void CreateVarsOnScope(framework::Scope* scope, platform::CPUPlace* place) {
  auto w_var = scope->Var("w");
Y
Yancey1989 已提交
65
  w_var->GetMutable<framework::SelectedRows>();
Y
Yancey1989 已提交
66

Y
Yancey1989 已提交
67
  auto out_var = scope->Var("out");
68
  out_var->GetMutable<framework::LoDTensor>();
Y
Yancey1989 已提交
69

Y
Yancey1989 已提交
70
  auto ids_var = scope->Var("ids");
71
  ids_var->GetMutable<framework::LoDTensor>();
72 73 74 75 76 77

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

  auto res_var = scope->Var("res");
  res_var->GetMutable<framework::LoDTensor>();
Y
Yancey1989 已提交
78 79
}

Y
Yancey1989 已提交
80 81
void InitTensorsOnClient(framework::Scope* scope, platform::CPUPlace* place,
                         int64_t rows_numel) {
Y
Yancey1989 已提交
82
  CreateVarsOnScope(scope, place);
83 84 85 86
  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;
87 88 89 90 91

  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;
Y
Yancey1989 已提交
92 93
}

Y
Yancey1989 已提交
94 95
void InitTensorsOnServer(framework::Scope* scope, platform::CPUPlace* place,
                         int64_t rows_numel) {
Y
Yancey1989 已提交
96
  CreateVarsOnScope(scope, place);
Y
Yancey1989 已提交
97 98 99
  auto w = scope->Var("w")->GetMutable<framework::SelectedRows>();
  auto w_value = w->mutable_value();
  w_value->Resize({rows_numel, 10});
100
  for (int64_t i = 0; i < rows_numel; ++i) w->AutoGrownIndex(i, true);
Y
Yancey1989 已提交
101 102 103 104

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

  for (int64_t i = 0; i < w_value->numel(); ++i) {
Y
Yancey1989 已提交
105 106 107
    ptr[i] = static_cast<float>(i / 10);
  }
}
Y
Yancey1989 已提交
108

Y
Yancey1989 已提交
109
void StartServer(const std::string& rpc_name) {
Y
Yancey1989 已提交
110 111 112 113 114 115
  framework::ProgramDesc program;
  framework::Scope scope;
  platform::CPUPlace place;
  framework::Executor exe(place);
  platform::CPUDeviceContext ctx(place);

116 117 118
  std::unordered_map<std::string,
                     std::shared_ptr<framework::ExecutorPrepareContext>>
      prefetch_var_name_to_prepared;
Y
Yancey1989 已提交
119

120
  g_req_handler->SetProgram(&program);
121
  g_req_handler->SetPrefetchPreparedCtx(&prefetch_var_name_to_prepared);
122 123 124 125
  g_req_handler->SetDevCtx(&ctx);
  g_req_handler->SetScope(&scope);
  g_req_handler->SetExecutor(&exe);

Y
Yancey1989 已提交
126
  g_rpc_service->RegisterRPC(rpc_name, g_req_handler.get());
127

128
  //  distributed::HeartBeatMonitor::Init(1, true, "w@grad");
129

130 131 132
  g_req_handler->SetRPCServer(g_rpc_service.get());

  std::thread server_thread(
133
      std::bind(&distributed::RPCServer::StartServer, g_rpc_service.get()));
Y
Yancey1989 已提交
134

135
  server_thread.join();
136 137
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
void StartSendAndRecvServer(const std::string& rpc_name) {
  framework::ProgramDesc program;
  framework::Scope scope;
  platform::CPUPlace place;
  framework::Executor exe(place);
  platform::CPUDeviceContext ctx(place);
  auto block = AppendSendAndRecvBlock(&program);
  std::string in_var_name("x");
  std::vector<int> prefetch_block_ids{block->ID()};
  auto prepared = exe.Prepare(program, prefetch_block_ids);
  InitTensorsOnServer(&scope, &place, 10);

  std::unordered_map<std::string,
                     std::shared_ptr<framework::ExecutorPrepareContext>>
      grad_to_prepared_ctx;
  grad_to_prepared_ctx[in_var_name] = prepared[0];

  g_req_handler->SetProgram(&program);
  g_req_handler->SetGradToPreparedCtx(&grad_to_prepared_ctx);
  g_req_handler->SetDevCtx(&ctx);
  g_req_handler->SetScope(&scope);
  g_req_handler->SetExecutor(&exe);

  g_rpc_service->RegisterRPC(rpc_name, g_req_handler.get());
  g_req_handler->SetRPCServer(g_rpc_service.get());

  std::thread server_thread(
      std::bind(&distributed::RPCServer::StartServer, g_rpc_service.get()));

  server_thread.join();
}

Y
Yancey1989 已提交
170
TEST(COMPLETE, CPU) {
171 172
  setenv("http_proxy", "", 1);
  setenv("https_proxy", "", 1);
T
tangwei12 已提交
173 174
  g_req_handler.reset(
      new distributed::RequestSendHandler(distributed::DistributedMode::kSync));
Y
Yancey1989 已提交
175 176
  g_rpc_service.reset(new RPCSERVER_T("127.0.0.1:0", 2));
  distributed::RPCClient* client =
W
Wu Yi 已提交
177
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(0);
M
MRXLT 已提交
178 179 180
  PADDLE_ENFORCE_NE(client, nullptr,
                    platform::errors::InvalidArgument(
                        "Client Start Fail, Check Your Code & Env"));
T
tangwei12 已提交
181
  std::thread server_thread(StartServer, distributed::kRequestSend);
Y
Yancey1989 已提交
182 183 184 185 186 187
  g_rpc_service->WaitServerReady();
  int port = g_rpc_service->GetSelectedPort();
  std::string ep = paddle::string::Sprintf("127.0.0.1:%d", port);
  client->AsyncSendComplete(ep);
  client->Wait();

T
tangwei12 已提交
188
  EXPECT_EQ(g_rpc_service->GetClientNum(), 1);
Y
Yancey1989 已提交
189 190 191 192 193 194

  g_rpc_service->ShutDown();
  server_thread.join();
  g_rpc_service.reset(nullptr);
  g_req_handler.reset(nullptr);
}
195 196 197 198 199 200 201 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 232 233 234 235 236 237

TEST(SENDANDRECV, CPU) {
  setenv("http_proxy", "", 1);
  setenv("https_proxy", "", 1);
  g_req_handler.reset(new distributed::RequestSendAndRecvHandler(
      distributed::DistributedMode::kAsync));
  g_rpc_service.reset(new RPCSERVER_T("127.0.0.1:0", 1));
  distributed::RPCClient* client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(0);
  PADDLE_ENFORCE_NE(client, nullptr,
                    platform::errors::InvalidArgument(
                        "Client Start Fail, Check Your Code & Env"));
  std::thread server_thread(StartSendAndRecvServer,
                            distributed::kRequestSendAndRecv);
  g_rpc_service->WaitServerReady();
  int port = g_rpc_service->GetSelectedPort();
  std::string ep = paddle::string::Sprintf("127.0.0.1:%d", port);

  framework::Scope scope;
  platform::CPUPlace place;
  platform::CPUDeviceContext ctx(place);

  // create var on local scope
  int64_t rows_numel = 10;
  InitTensorsOnClient(&scope, &place, rows_numel);
  std::string in_var_name("x");
  std::string out_var_name("res");

  client->AsyncSendAndRecv(ep, ctx, scope, in_var_name, out_var_name);
  client->Wait();
  auto var = scope.Var(out_var_name);
  auto value = var->GetMutable<framework::LoDTensor>();
  auto ptr = value->mutable_data<float>(place);

  for (int64_t i = 0; i < rows_numel; ++i) {
    EXPECT_EQ(ptr[i], 0.5);
  }
  g_rpc_service->ShutDown();
  server_thread.join();
  LOG(INFO) << "begin reset";
  g_rpc_service.reset(nullptr);
  g_req_handler.reset(nullptr);
}
238 239 240 241 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 284 285 286 287 288 289 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 333 334 335 336 337 338 339 340 341 342 343 344

void StartCheckpointServer(const std::string& rpc_name) {
  framework::ProgramDesc program;
  framework::Scope scope;
  platform::CPUPlace place;
  framework::Executor exe(place);
  platform::CPUDeviceContext ctx(place);

  std::vector<distributed::SparseMeta> metas;

  auto meta = distributed::SparseMeta();
  meta.name = "embedding.block0";
  meta.value_names = {"Param"};
  meta.value_dims = {64};
  meta.mode = distributed::Mode::training;
  meta.grad_name = "embedding@Grad";
  meta.cached_varnames = {"kSparseIds"};
  meta.initializer_attrs = {"fill_constant&1.0"};
  meta.entry = "none";

  metas.push_back(meta);
  distributed::LargeScaleKV::Init(metas);

  auto* ins = distributed::LargeScaleKV::GetInstance();
  ins->Get("embedding.block0")->Init({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});

  std::unordered_map<std::string,
                     std::shared_ptr<framework::ExecutorPrepareContext>>
      prefetch_var_name_to_prepared;

  g_req_handler->SetProgram(&program);
  g_req_handler->SetPrefetchPreparedCtx(&prefetch_var_name_to_prepared);
  g_req_handler->SetDevCtx(&ctx);
  g_req_handler->SetScope(&scope);
  g_req_handler->SetExecutor(&exe);

  g_rpc_service->RegisterRPC(rpc_name, g_req_handler.get());

  g_req_handler->SetRPCServer(g_rpc_service.get());

  std::thread server_thread(
      std::bind(&distributed::RPCServer::StartServer, g_rpc_service.get()));

  server_thread.join();
}

TEST(LARGE_SCALE_CHECKPOINT, CPU) {
  setenv("http_proxy", "", 1);
  setenv("https_proxy", "", 1);

  paddle::framework::Scope scope;
  paddle::platform::CPUPlace place;

  g_req_handler.reset(new distributed::RequestCheckpointHandler(
      distributed::DistributedMode::kAsync));
  g_rpc_service.reset(new RPCSERVER_T("127.0.0.1:0", 1));

  distributed::RPCClient* client =
      distributed::RPCClient::GetInstance<RPCCLIENT_T>(0);

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

  std::thread server_thread(StartCheckpointServer,
                            distributed::kRequestCheckpoint);
  g_rpc_service->WaitServerReady();

  int port = g_rpc_service->GetSelectedPort();
  std::string ep = paddle::string::Sprintf("127.0.0.1:%d", port);

  auto save_path =
      paddle::string::Sprintf("%s/%s/%s", "/tmp/large_scale_table/base",
                              "embedding", "embedding.block0");
  int mode = 0;
  client->AsyncCheckpointNotify(ep, save_path, "embedding.block0", mode);
  client->Wait();

  save_path =
      paddle::string::Sprintf("%s/%s/%s", "/tmp/large_scale_table/delta",
                              "embedding", "embedding.block0");
  mode = 1;
  client->AsyncCheckpointNotify(ep, save_path, "embedding.block0", mode);
  client->Wait();

  paddle::framework::AttributeMap attrs;

  std::vector<std::string> eps = {ep};
  attrs["endpoints"] = eps;
  attrs["dirname"] = std::string("/tmp/large_scale_table/delta1");
  attrs["varname"] = std::string("embedding");
  attrs["mode"] = 2;
  std::vector<std::string> slices = {"embedding.block0"};
  attrs["slice_varnames"] = slices;
  std::vector<std::string> remotes = {"embedding.block0"};
  attrs["remote_varnames"] = remotes;

  auto ops =
      framework::OpRegistry::CreateOp("checkpoint_notify", {}, {}, attrs, true);
  ops->Run(scope, place);

  g_rpc_service->ShutDown();
  server_thread.join();
  LOG(INFO) << "begin reset";
  g_rpc_service.reset(nullptr);
  g_req_handler.reset(nullptr);
}