grpc_serde.cc 7.4 KB
Newer Older
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
#ifdef PADDLE_WITH_NCCL
16 17
#include <nccl.h>
#endif
18 19 20
#ifdef PADDLE_WITH_RCCL
#include <rccl.h>
#endif
G
gongweibao 已提交
21
#include <limits>
G
gongweibao 已提交
22
#include <memory>
W
wanghuancoder 已提交
23 24
#include "grpcpp/impl/codegen/byte_buffer.h"
#include "grpcpp/impl/codegen/slice.h"
W
Wu Yi 已提交
25 26
#include "paddle/fluid/operators/distributed/grpc/grpc_serde.h"
#include "paddle/fluid/operators/distributed/grpc/grpc_variable_response.h"
27
#include "paddle/fluid/operators/distributed/proto_encoder_helper.h"
W
wanghuancoder 已提交
28
#include "paddle/fluid/operators/distributed/send_recv.pb.h"
29
#include "paddle/fluid/operators/distributed/sendrecvop_utils.h"
W
wanghuancoder 已提交
30
#include "paddle/fluid/platform/enforce.h"
31 32
#include "paddle/fluid/platform/profiler.h"

W
wanghuancoder 已提交
33 34 35 36 37 38 39 40 41 42
namespace paddle {
namespace framework {
class Scope;
class Variable;
}  // namespace framework
namespace platform {
class DeviceContext;
}  // namespace platform
}  // namespace paddle

43 44 45 46 47 48
namespace paddle {
namespace operators {
namespace distributed {

void SerializeToByteBuffer(const std::string& name, framework::Variable* var,
                           const platform::DeviceContext& ctx,
W
Wu Yi 已提交
49
                           ::grpc::ByteBuffer* msg, const std::string& out_name,
Q
Qiao Longfei 已提交
50 51
                           const int trainer_id,
                           const std::string& table_name) {
52
  platform::RecordRPCEvent record_event("serial");
53
  VarMsg request;
Y
Yu Yang 已提交
54
  TensorPayload* payload = nullptr;
55 56

  request.set_varname(name);
W
Wu Yi 已提交
57
  request.set_trainer_id(trainer_id);
58 59 60 61 62 63 64 65 66 67 68 69 70 71
  // Note: normally the profiler is enabled in 1 trainer, hence only
  // 1 trainer returns true for ShouldSendProfileState(). It tells PS
  // servers the trainer's profiling state so that PS can follow the
  // trainer.
  if (platform::ShouldSendProfileState()) {
    if (platform::IsProfileEnabled()) {
      request.set_profile(platform::kEnableProfiler);
    } else {
      request.set_profile(platform::kDisableProfiler);
    }
  }
  if (!out_name.empty()) {
    request.set_out_varname(out_name);
  }
Q
Qiao Longfei 已提交
72 73 74
  if (!table_name.empty()) {
    request.set_table_name(table_name);
  }
75 76
  if (var->IsType<framework::LoDTensor>()) {
    request.set_type(::sendrecv::LOD_TENSOR);
Y
Yu Yang 已提交
77
    payload = new TensorPayload(GetTensorPayload(var, ctx, &request));
78 79
  } else if (var->IsType<framework::SelectedRows>()) {
    request.set_type(::sendrecv::SELECTED_ROWS);
Y
Yu Yang 已提交
80
    payload = new TensorPayload(GetSelectedRowsPayload(var, ctx, &request));
81
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
82 83 84 85
  } else if (var->IsType<ncclUniqueId>()) {
    request.set_type(::sendrecv::NCCL_ID);
#endif
  } else {
M
MRXLT 已提交
86 87
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Serialize does not support type: %s", typeid(var->Type()).name()));
88 89 90 91 92 93 94 95 96
  }
  std::string header;
  request.AppendToString(&header);
  auto buffer = std::unique_ptr<char[]>(new char[1024]);
  void* buf = buffer.get();
  ProtoEncodeHelper e(static_cast<char*>(buf), 1024);
  e.WriteRawBytes(std::string(header.data(), header.size()));
// NCCLID is copied directly to the message, return bytebuffer
// with only one slice if serializing NCCLID.
97
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
98 99 100 101 102 103 104 105 106 107 108 109 110 111
  if (var->IsType<ncclUniqueId>()) {
    e.WriteVarlengthBeginning(VarMsg::kSerializedFieldNumber,
                              NCCL_UNIQUE_ID_BYTES);
    const ncclUniqueId& uid = var->Get<ncclUniqueId>();
    e.WriteRawBytes(std::string(uid.internal, NCCL_UNIQUE_ID_BYTES));

    // for serialize NCCL_ID
    ::grpc::Slice slices(e.size());
    memcpy(const_cast<uint8_t*>(slices.begin()), e.data(), e.size());
    ::grpc::ByteBuffer tmp(&slices, 1);
    msg->Swap(&tmp);
    return;
  }
#endif
M
MRXLT 已提交
112 113 114 115 116
  PADDLE_ENFORCE_NOT_NULL(
      payload,
      platform::errors::InvalidArgument(
          "Not support type: %s, need to be LOD_TENSOR or SELECTED_ROWS",
          var->Type()));
Y
Yu Yang 已提交
117
  e.WriteVarlengthBeginning(VarMsg::kSerializedFieldNumber,
Y
Yu Yang 已提交
118
                            payload->memory_size());
G
gongweibao 已提交
119
  if (payload->memory_size() >= std::numeric_limits<int>::max()) {
120 121 122
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Variable %s length %d should less than %d.", name,
        payload->memory_size(), std::numeric_limits<int>::max()));
G
gongweibao 已提交
123
  }
124 125 126 127 128
  // steal reference of tensor data
  ::grpc::Slice slices[4];  // metadata, tensor, rows meta, rows
  int num_slices = 2;       // only SelectedRows have rows buffer
  slices[0] = ::grpc::Slice(e.size());
  memcpy(const_cast<uint8_t*>(slices[0].begin()), e.data(), e.size());
Y
Yu Yang 已提交
129 130 131 132
  slices[1] = ::grpc::Slice(
      grpc_slice_new_with_user_data(payload->ptr(), payload->memory_size(),
                                    SerializeDestroyCallback, payload),
      ::grpc::Slice::STEAL_REF);
133 134 135 136

  if (var->IsType<framework::SelectedRows>()) {
    auto* slr = var->GetMutable<framework::SelectedRows>();
    ProtoEncodeHelper e2(static_cast<char*>(buf), 128);
G
gongweibao 已提交
137

M
MRXLT 已提交
138 139 140 141
    PADDLE_ENFORCE_EQ(VectorElemName(slr->rows()), typeid(int64_t).name(),
                      platform::errors::InvalidArgument(
                          "Got wrong type %s, expect type: int64_t",
                          VectorElemName(slr->rows())));
Y
Yu Yang 已提交
142
    size_t rows_memory_size = slr->rows().size() * sizeof(int64_t);
G
gongweibao 已提交
143

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    e2.WriteVarlengthBeginning(VarMsg::kRowsFieldNumber, rows_memory_size);
    slices[2] = ::grpc::Slice(e2.size());
    memcpy(const_cast<uint8_t*>(slices[2].begin()), e2.data(), e2.size());

    slices[3] = ::grpc::Slice(
        grpc_slice_new_with_user_data(
            const_cast<void*>(
                reinterpret_cast<const void*>(slr->rows().data())),
            rows_memory_size, [](void* backing) {},
            const_cast<char*>(
                reinterpret_cast<const char*>(slr->rows().data()))),
        ::grpc::Slice::STEAL_REF);
    num_slices = 4;
  }
  ::grpc::ByteBuffer tmp(&slices[0], num_slices);
  msg->Swap(&tmp);
}

void DeserializeFromByteBuffer(const ::grpc::ByteBuffer& msg,
                               const platform::DeviceContext& ctx,
                               const framework::Scope* scope,
W
Wu Yi 已提交
165
                               framework::Variable** var, int* trainer_id) {
166
  platform::RecordRPCEvent record_event("deserial");
167
  operators::distributed::GRPCVariableResponse resp(scope, &ctx);
M
MRXLT 已提交
168 169 170
  PADDLE_ENFORCE_EQ(
      resp.Parse(msg), 0,
      platform::errors::InvalidArgument("parse bytebuffer to tensor error!"));
171
  *var = resp.GetVar();
W
Wu Yi 已提交
172
  *trainer_id = resp.GetTrainerId();
173 174
}

175 176 177 178 179 180 181 182 183 184 185 186 187
void DeserializeRecvFromByteBuffer(const ::grpc::ByteBuffer& msg,
                                   const platform::DeviceContext& ctx,
                                   const framework::Scope* scope,
                                   framework::Variable** var, int* trainer_id) {
  platform::RecordRPCEvent record_event("deserial");
  operators::distributed::GRPCVariableResponse resp(scope, &ctx);
  PADDLE_ENFORCE_EQ(
      resp.Parse(msg), 0,
      platform::errors::InvalidArgument("parse bytebuffer to tensor error!"));
  *var = resp.GetRecvVar();
  *trainer_id = resp.GetTrainerId();
}

188 189 190
}  // namespace distributed
}  // namespace operators
}  // namespace paddle