send_op.cc 5.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
武毅 已提交
2

L
Luo Tao 已提交
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
武毅 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
武毅 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
武毅 已提交
14 15 16

#include <ostream>

Y
Yi Wang 已提交
17 18 19 20
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
武毅 已提交
21

G
gongweibao 已提交
22
#include <future>
Y
Yi Wang 已提交
23
#include "paddle/fluid/operators/detail/grpc_client.h"
24
#include "paddle/fluid/platform/profiler.h"
武毅 已提交
25 26 27

namespace paddle {
namespace operators {
28 29
static bool NeedSend(const framework::Scope& scope,
                     const std::string& varname) {
30 31 32 33 34 35
  auto* var = scope.FindVar(varname);
  PADDLE_ENFORCE_NOT_NULL(var, "Can not find variable '%s' in the send side.",
                          varname);
  if (var->IsType<framework::LoDTensor>()) {
    return var->Get<framework::LoDTensor>().IsInitialized();
  } else if (var->IsType<framework::SelectedRows>()) {
36
    return var->Get<framework::SelectedRows>().rows().size() > 0UL;
37 38 39 40 41 42 43
  } else {
    PADDLE_THROW(
        "Variable type in send side should be in "
        "[LodTensor, SelectedRows]");
  }
  return false;
}
武毅 已提交
44 45 46

class SendOp : public framework::OperatorBase {
 public:
G
gongweibao 已提交
47 48 49 50
  SendOp(const std::string& type, const framework::VariableNameMap& inputs,
         const framework::VariableNameMap& outputs,
         const framework::AttributeMap& attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}
T
typhoonzero 已提交
51

T
typhoonzero 已提交
52 53
  void RunImpl(const framework::Scope& scope,
               const platform::Place& place) const override {
T
typhoonzero 已提交
54
    auto ins = Inputs("X");
T
typhoonzero 已提交
55
    auto outs = Outputs("Out");
T
typhoonzero 已提交
56
    std::vector<std::string> epmap = Attr<std::vector<std::string>>("epmap");
Y
Yancey 已提交
57 58
    std::vector<std::string> endpoints =
        Attr<std::vector<std::string>>("endpoints");
G
gongweibao 已提交
59

Y
Yancey1989 已提交
60 61
    platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
    auto& ctx = *pool.Get(place);
T
typhoonzero 已提交
62

63 64 65
    // For profiling
    platform::RecordEvent record_event(Type(), &ctx);

T
typhoonzero 已提交
66 67 68 69 70 71 72
    auto client_var_name = Output("RPCClient");
    PADDLE_ENFORCE_NOT_NULL(scope.FindVar(client_var_name),
                            "Can not find variable '%s' in the scope.",
                            client_var_name);
    auto* client_var = scope.FindVar(client_var_name);
    detail::RPCClient* rpc_client = client_var->GetMutable<detail::RPCClient>();

G
gongweibao 已提交
73
    for (size_t i = 0; i < ins.size(); i++) {
74
      if (NeedSend(scope, ins[i])) {
T
typhoonzero 已提交
75
        VLOG(2) << "sending " << ins[i] << " to " << epmap[i];
76 77 78 79
        rpc_client->AsyncSendVariable(epmap[i], ctx, scope, ins[i]);
      } else {
        VLOG(3) << "don't send no-initialied variable: " << ins[i];
      }
武毅 已提交
80
    }
T
typhoonzero 已提交
81
    PADDLE_ENFORCE(rpc_client->Wait());
G
gongweibao 已提交
82

Y
Yancey 已提交
83
    for (auto& ep : endpoints) {
T
typhoonzero 已提交
84
      VLOG(2) << "batch barrier, ep: " << ep;
T
typhoonzero 已提交
85
      rpc_client->AsyncSendBatchBarrier(ep);
Y
Yancey 已提交
86
    }
T
typhoonzero 已提交
87
    PADDLE_ENFORCE(rpc_client->Wait());
Y
Yancey 已提交
88

T
typhoonzero 已提交
89
    if (outs.size() > 0) {
T
typhoonzero 已提交
90
      for (size_t i = 0; i < outs.size(); i++) {
T
typhoonzero 已提交
91
        VLOG(2) << "getting " << outs[i] << " from " << epmap[i];
Y
Yancey1989 已提交
92
        rpc_client->AsyncGetVariable(epmap[i], ctx, scope, outs[i]);
T
typhoonzero 已提交
93
      }
Y
Yancey1989 已提交
94
      PADDLE_ENFORCE(rpc_client->Wait());
95 96
      // tell pservers that current trainer have called fetch
      for (auto& ep : endpoints) {
T
typhoonzero 已提交
97
        VLOG(2) << "send fetch barrier, ep: " << ep;
98 99 100
        rpc_client->AsyncSendFetchBarrier(ep);
      }
      PADDLE_ENFORCE(rpc_client->Wait());
武毅 已提交
101 102 103 104 105 106
    }
  }
};

class SendOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
G
gongweibao 已提交
107
  SendOpMaker(OpProto* proto, OpAttrChecker* op_checker)
武毅 已提交
108
      : OpProtoAndCheckerMaker(proto, op_checker) {
109 110
    AddInput("X", "(Tensor) Input tensor to be sent").AsDuplicable();
    AddOutput("Out", "(Tensor) Output tensor to be received from server")
T
typhoonzero 已提交
111
        .AsDuplicable();
T
typhoonzero 已提交
112 113 114
    AddOutput("RPCClient",
              "(RPCClient) The RPC client object which is"
              "initialized at most once.");
武毅 已提交
115
    AddComment(R"DOC(
A
Abhinav Arora 已提交
116
Send operator
武毅 已提交
117

118
This operator will send tensor to recv_op at the parameter server.
武毅 已提交
119
)DOC");
T
typhoonzero 已提交
120 121
    // TODO(typhoonzero): remove this attr generate de-duplicated vector from
    // epmap when initializing.
T
typhoonzero 已提交
122 123
    AddAttr<std::vector<std::string>>("endpoints",
                                      "(string vector, default 127.0.0.1:6164)"
T
typhoonzero 已提交
124 125
                                      "Server endpoints to send variables to.")
        .SetDefault({});
T
typhoonzero 已提交
126 127 128
    AddAttr<std::vector<std::string>>("epmap",
                                      "(string vector, default 127.0.0.1:6164)"
                                      "Server endpoints in the order of input "
T
typhoonzero 已提交
129 130
                                      "variables for mapping")
        .SetDefault({});
武毅 已提交
131 132 133
  }
};

T
typhoonzero 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
class SendOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc& op_desc,
                  framework::BlockDesc* block) const override {
    auto out_var_name = op_desc.Output("RPCClient").front();
    auto& out_var = block->FindRecursiveOrCreateVar(out_var_name);
    auto var_type = framework::proto::VarType::RAW;
    out_var.SetType(var_type);
  }
};

class SendOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext* ctx) const override {}
};

武毅 已提交
150 151 152 153 154
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

T
typhoonzero 已提交
155 156 157
REGISTER_OPERATOR(send, ops::SendOp, paddle::framework::EmptyGradOpMaker,
                  ops::SendOpMaker, ops::SendOpVarTypeInference,
                  ops::SendOpShapeInference);