mm_handler.cpp 10.3 KB
Newer Older
1 2 3 4 5
/**
 * \file python_module/src/cpp/mm_handler.cpp
 *
 * This file is part of MegBrain, a deep learning framework developed by Megvii.
 *
6
 * \copyright Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
7 8 9
 *
 */

10
#include "megbrain/opr/mm_handler.h"
11 12

#include "megbrain/exception.h"
13
#include "megbrain_build_config.h"
14

15
#if MGB_ENABLE_OPR_MM
M
Megvii Engine Team 已提交
16
#include <future>
17 18
#include "megbrain/opr/zmq_rpc.h"
#include "mm_handler.pb.h"
19

20 21 22
using namespace mgb;
using namespace opr;

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/* ======================== GroupServerProxy ========================== */
/*!
 * A proxy that receives zmqrpc call, direct call to NCCL Manager
 */

#define RUNSERVER(rpc_name)                                   \
    if (std::strcmp(describe, #rpc_name) == 0) {              \
        std::string output;                                   \
        rpc_name(input_ptr, input_len, &output);              \
        reply.rebuild(output.length());                       \
        memcpy(reply.data(), output.data(), output.length()); \
        return;                                               \
    }

class GroupServerProxy final : public ZmqRpc::ZmqRpcServerImpl {
public:
M
Megvii Engine Team 已提交
39
    void solve_request(zmq::message_t& request, zmq::message_t& reply) override {
40 41 42 43 44 45
        char* describe = (char*)request.data();
        void* input_ptr = (char*)request.data() + strlen(describe) + 1;
        size_t input_len = request.size() - strlen(describe) - 1;
        RUNSERVER(opr_register);
        RUNSERVER(set_output_shape);
        RUNSERVER(get_output_shape);
46
        RUNSERVER(bcast_addr);
47
        RUNSERVER(group_barrier);
48
        RUNSERVER(bcast_nccluniqueid);
49 50
        mgb_assert(false, "invalid rpc request");
    }
M
Megvii Engine Team 已提交
51

52
private:
M
Megvii Engine Team 已提交
53 54 55 56
    void opr_register(void* input_ptr, size_t input_len, std::string* output);
    void set_output_shape(void* input_ptr, size_t input_len, std::string* output);
    void get_output_shape(void* input_ptr, size_t input_len, std::string* output);
    void bcast_addr(void* input_ptr, size_t input_len, std::string* output);
57
    void bcast_nccluniqueid(void* input_ptr, size_t input_len, std::string* output);
M
Megvii Engine Team 已提交
58
    void group_barrier(void* input_ptr, size_t input_len, std::string* output);
59 60 61 62 63 64 65

private:
    GroupManager m_mgr;
};

#undef RUNSERVER

M
Megvii Engine Team 已提交
66
#define INFO_INIT(space, name)              \
67 68
    using Request = space::name##Request;   \
    using Response = space::name##Response; \
M
Megvii Engine Team 已提交
69 70
    Request req;                            \
    Response rsp;                           \
71 72
    req.ParseFromArray(input_ptr, input_len);

M
Megvii Engine Team 已提交
73 74
void GroupServerProxy::opr_register(
        void* input_ptr, size_t input_len, std::string* output) {
75
    INFO_INIT(mm_handler, OprRegister);
M
Megvii Engine Team 已提交
76 77 78
    auto ret = m_mgr.opr_register(
            req.key(), req.nr_expected_devices(), req.is_root(), req.rank(),
            req.comp_node_hash());
79 80 81
    rsp.set_hash(ret.hash);
    rsp.set_rank(ret.rank);
    rsp.set_root_rank(ret.root_rank);
82 83 84
    rsp.SerializeToString(output);
}

M
Megvii Engine Team 已提交
85 86
void GroupServerProxy::set_output_shape(
        void* input_ptr, size_t input_len, std::string* output) {
87 88 89 90 91 92 93 94 95 96 97
    INFO_INIT(mm_handler, SetOutputShape);
    auto&& shape_proto = req.shape();
    TensorShape shape;
    shape.ndim = shape_proto.ndim();
    for (size_t i = 0; i < shape.ndim; ++i) {
        shape.shape[i] = shape_proto.shape(i);
    }
    m_mgr.set_output_shape(req.key(), shape);
    rsp.SerializeToString(output);
}

M
Megvii Engine Team 已提交
98 99
void GroupServerProxy::get_output_shape(
        void* input_ptr, size_t input_len, std::string* output) {
100 101 102 103 104 105 106 107 108 109
    INFO_INIT(mm_handler, GetOutputShape);
    auto shape = m_mgr.get_output_shape(req.key());
    auto&& shape_proto = *rsp.mutable_shape();
    shape_proto.set_ndim(shape.ndim);
    for (size_t i = 0; i < shape.ndim; ++i) {
        shape_proto.add_shape(shape[i]);
    }
    rsp.SerializeToString(output);
}

M
Megvii Engine Team 已提交
110 111
void GroupServerProxy::bcast_addr(
        void* input_ptr, size_t input_len, std::string* output) {
112 113 114 115 116 117
    INFO_INIT(mm_handler, BcastAddr);
    std::string master_ip = req.master_ip();
    int port = req.port();
    m_mgr.bcast_addr(master_ip, port, req.key(), req.size(), req.rank(), req.root());
    rsp.set_master_ip(master_ip);
    rsp.set_port(port);
118 119 120
    rsp.SerializeToString(output);
}

121 122 123 124 125 126 127 128 129
void GroupServerProxy::bcast_nccluniqueid(
        void* input_ptr, size_t input_len, std::string* output) {
    INFO_INIT(mm_handler, BcastNcclUniqueId);
    std::string id = req.id();
    m_mgr.bcast_nccluniqueid(req.key(), id, req.size(), req.rank(), req.root());
    rsp.set_id(id);
    rsp.SerializeToString(output);
}

M
Megvii Engine Team 已提交
130 131
void GroupServerProxy::group_barrier(
        void* input_ptr, size_t input_len, std::string* output) {
132 133 134 135 136 137 138 139 140
    INFO_INIT(mm_handler, GroupBarrier);
    uint32_t rsp_size = m_mgr.group_barrier(req.size(), req.rank());
    rsp.set_size(rsp_size);
    rsp.SerializeToString(output);
}
#undef INFO_INIT

/* ======================== GroupClientProxy ========================== */

141
#define INFO_INIT(space, f_name, name)      \
142 143
    using Request = space::name##Request;   \
    using Response = space::name##Response; \
144 145
    std::string func_name = #f_name;        \
    Request req;                            \
146 147
    Response rsp;

M
Megvii Engine Team 已提交
148 149 150 151 152 153 154 155
#define SOLVE_REQUEST(name, req, rsp)                                                 \
    std::string req_str;                                                              \
    mgb_assert(req.SerializeToString(&req_str));                                      \
    zmq::message_t send(req_str.length() + name.length() + 1);                        \
    zmq::message_t recv;                                                              \
    memcpy(send.data(), name.data(), name.length() + 1);                              \
    memcpy((char*)send.data() + name.length() + 1, req_str.data(), req_str.length()); \
    static_cast<ZmqRpc::ZmqRpcClient*>(m_stub)->request(send, recv);                  \
156 157
    mgb_assert(rsp.ParseFromArray(recv.data(), recv.size()));

158
GroupClientProxy::GroupClientProxy(const std::string& server_addr)
M
Megvii Engine Team 已提交
159 160
        : m_addr(server_addr),
          m_stub{ZmqRpc::ZmqRpcClient::get_client("tcp://" + server_addr)} {}
161

162 163 164
GroupManager::RegisterInfo GroupClientProxy::opr_register(
        const std::string& key, size_t nr_devices, bool is_root, int rank,
        uint64_t comp_node_hash) {
165 166
    INFO_INIT(mm_handler, opr_register, OprRegister)
    req.set_key(key);
167
    req.set_is_root(is_root);
168
    req.set_rank(rank);
169
    req.set_comp_node_hash(comp_node_hash);
170 171
    req.set_nr_expected_devices(nr_devices);
    SOLVE_REQUEST(func_name, req, rsp);
172 173
    GroupManager::RegisterInfo ret{rsp.hash(), rsp.rank(), rsp.root_rank()};
    return ret;
174 175
}

M
Megvii Engine Team 已提交
176 177
void GroupClientProxy::set_output_shape(
        const std::string& key, const TensorShape& shape) {
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    INFO_INIT(mm_handler, set_output_shape, SetOutputShape)
    req.set_key(key);
    auto&& shape_proto = *req.mutable_shape();
    shape_proto.set_ndim(shape.ndim);
    for (size_t i = 0; i < shape.ndim; ++i) {
        shape_proto.add_shape(shape[i]);
    }
    SOLVE_REQUEST(func_name, req, rsp);
}

TensorShape GroupClientProxy::get_output_shape(const std::string& key) {
    INFO_INIT(mm_handler, get_output_shape, GetOutputShape)
    req.set_key(key);
    SOLVE_REQUEST(func_name, req, rsp);
    TensorShape shape;
    shape.ndim = rsp.shape().ndim();
    for (size_t i = 0; i < shape.ndim; ++i) {
        shape[i] = rsp.shape().shape(i);
    }
    return shape;
}
199

M
Megvii Engine Team 已提交
200 201
void GroupClientProxy::bcast_addr(
        std::string& master_ip, int& port, const std::string& key, uint32_t size,
202 203 204 205
        uint32_t rank, uint32_t root) {
    INFO_INIT(mm_handler, bcast_addr, BcastAddr);
    req.set_master_ip(master_ip.data(), master_ip.size());
    req.set_port(port);
206 207 208
    req.set_key(key.data(), key.size());
    req.set_size(size);
    req.set_rank(rank);
209
    req.set_root(root);
210
    SOLVE_REQUEST(func_name, req, rsp);
211 212
    master_ip = rsp.master_ip();
    port = rsp.port();
213 214
}

215 216 217 218 219 220 221 222 223 224 225 226 227
void GroupClientProxy::bcast_nccluniqueid(
        const std::string& key, std::string& id, uint32_t size, uint32_t rank,
        uint32_t root) {
    INFO_INIT(mm_handler, bcast_nccluniqueid, BcastNcclUniqueId);
    req.set_id(id.data(), id.size());
    req.set_key(key.data(), key.size());
    req.set_size(size);
    req.set_rank(rank);
    req.set_root(root);
    SOLVE_REQUEST(func_name, req, rsp);
    id = rsp.id();
}

228 229 230 231 232 233 234 235
uint32_t GroupClientProxy::group_barrier(uint32_t size, uint32_t rank) {
    INFO_INIT(mm_handler, group_barrier, GroupBarrier);
    req.set_size(size);
    req.set_rank(rank);
    SOLVE_REQUEST(func_name, req, rsp);
    return rsp.size();
}

236 237 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
std::shared_ptr<MegRay::Communicator> BatchSendRecvHelper::get(std::string&& key) {
    auto ptr = megray_comm_cache.find(key);
    if (ptr != megray_comm_cache.end()) {
        return megray_comm_cache[key];
    } else {
        return nullptr;
    }
}

std::unordered_map<std::string, std::shared_ptr<MegRay::Communicator>>
        BatchSendRecvHelper::megray_comm_cache{};

bool BatchSendRecvHelper::init(
        int nranks, int rank, std::string ip, int port, int root) {
    auto megray_comm =
            MegRay::get_communicator(nranks, rank, MegRay::Backend::MEGRAY_NCCL);
    auto group_client =
            std::make_shared<opr::GroupClientProxy>(ssprintf("%s:%d", ip.data(), port));
    auto cb = [=](char* nccl_buffer, size_t len) {
        std::string id;
        id.resize(128);
        if (rank == root) {
            memcpy(id.data(), nccl_buffer, len);
        }
        group_client->bcast_nccluniqueid("init_all_cards", id, nranks, rank, root);
        if (rank != root) {
            memcpy(nccl_buffer, id.data(), len);
        }
    };
    megray_comm->init(cb);
    return megray_comm_cache.insert({std::string("init_all_cards"), megray_comm})
            .second;
}

270 271 272
#undef INFO_INIT
#undef SOLVE_REQUEST

273 274
struct ServerInfo {
    std::unique_ptr<ZmqRpc::ZmqRpcServer> server;
275 276
};

277
int mgb::opr::create_zmqrpc_server(const std::string& server_addr, int port) {
278 279 280 281
    static std::unordered_map<std::string, ServerInfo> addr2server;
    static std::mutex mtx;
    MGB_LOCK_GUARD(mtx);
    auto service = std::make_unique<GroupServerProxy>();
M
Megvii Engine Team 已提交
282 283
    auto server = std::make_unique<ZmqRpc::ZmqRpcServer>(
            "tcp://" + server_addr, port, std::move(service));
284 285 286
    port = server->port();
    auto full_srv_addr = ssprintf("%s:%d", server_addr.c_str(), port);
    server->run();
M
Megvii Engine Team 已提交
287
    auto ins = addr2server.emplace(full_srv_addr, ServerInfo{std::move(server)});
288 289 290
    mgb_assert(ins.second);

    return port;
291 292 293 294
}

#endif

295
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}