role_maker.py 8.6 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2019 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.

T
tangwei12 已提交
15
from __future__ import print_function
16 17
from enum import Enum

T
tangwei12 已提交
18 19 20 21
__all__ = [
    'Role', 'RoleMakerBase', 'MPISymetricRoleMaker', 'UserDefinedRoleMaker'
]

22 23 24 25 26

class Role(Enum):
    WORKER = 1,
    SERVER = 2

D
dongdaxiang 已提交
27 28

class RoleMakerBase(object):
29 30 31 32 33 34 35
    """
    RoleMakerBase is a base class for assigning a role to current process
    in distributed training.
    A paddle developer can implement RoleMakerBase to design a role maker
    for worker or pserver assignment.
    """

D
dongdaxiang 已提交
36
    def __init__(self):
T
tangwei12 已提交
37 38
        self._worker_endpoints = []
        self._server_endpoints = []
D
dongdaxiang 已提交
39
        self._role_is_generated = False
T
tangwei12 已提交
40 41
        self._role = None
        self._current_id = -1
D
dongdaxiang 已提交
42

T
tangwei12 已提交
43
    def is_worker(self):
44 45 46
        """
        return is_worker() of current process
        """
D
dongdaxiang 已提交
47 48
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
49
    def is_server(self):
50 51 52
        """
        return is_server() of current process
        """
D
dongdaxiang 已提交
53 54
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
55
    def is_first_worker(self):
56
        """
T
tangwei12 已提交
57 58 59 60
        Check whether the node is the first instance of worker.
        Returns:
            bool: True if this is the first node of worker,
                  False if not.
61
        """
T
tangwei12 已提交
62
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
63

T
tangwei12 已提交
64
    def worker_index(self):
65
        """
T
tangwei12 已提交
66 67 68 69
        Get current worker id.

        Returns:
            int: node id
70
        """
T
tangwei12 已提交
71
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
72

T
tangwei12 已提交
73
    def server_index(self):
74
        """
T
tangwei12 已提交
75 76 77 78
        Get current server id.

        Returns:
            int: node id
79
        """
T
tangwei12 已提交
80
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
81

T
tangwei12 已提交
82
    def get_trainer_endpoints(self):
83
        """
T
tangwei12 已提交
84
        return trainer endpoints
85
        """
T
tangwei12 已提交
86 87 88 89 90 91 92
        return self._worker_endpoints

    def get_pserver_endpoints(self):
        """
        return pserver endpoints
        """
        return self._server_endpoints
D
dongdaxiang 已提交
93 94 95


class MPIRoleMaker(RoleMakerBase):
96 97 98 99 100
    """
    MPIRoleMaker is a MPI-API based role maker which is a counter-part of K8SRoleMaker
    mpi4py will be used if a developer inherits MPIRoleMaker
    """

D
dongdaxiang 已提交
101
    def __init__(self):
X
xujiaqi01 已提交
102
        super(MPIRoleMaker, self).__init__()
D
dongdaxiang 已提交
103 104
        from mpi4py import MPI
        self.MPI = MPI
T
tangwei12 已提交
105 106
        self._comm = MPI.COMM_WORLD
        self._node_type_comm = None
D
dongdaxiang 已提交
107
        self._ips = None
T
tangwei12 已提交
108
        self._ip = None
D
dongdaxiang 已提交
109

110
    def _get_rank(self):
111 112 113
        """
        return rank
        """
D
dongdaxiang 已提交
114 115
        self._rank = self._comm.Get_rank()
        return self._rank
D
dongdaxiang 已提交
116

117
    def _get_size(self):
118 119 120
        """
        return size
        """
D
dongdaxiang 已提交
121 122
        self._size = self._comm.Get_size()
        return self._size
D
dongdaxiang 已提交
123

124
    def _all_gather(self, obj):
125 126 127
        """
        all_gather(obj) will call MPI's allgather function
        """
X
xjqbest 已提交
128
        self._barrier_all()
D
dongdaxiang 已提交
129
        return self._comm.allgather(obj)
D
dongdaxiang 已提交
130

X
xjqbest 已提交
131 132 133 134
    def _worker_gather(self, obj):
        """
        worker_gather(obj) will call MPI's allgather function
        """
T
tangwei12 已提交
135
        if self.is_worker():
D
dongdaxiang 已提交
136 137
            self._node_type_comm.barrier()
            return self._node_type_comm.allgather(obj)
X
xjqbest 已提交
138 139
        return None

140
    def _barrier_all(self):
141 142 143
        """
        barrier_all() will call MPI's barrier_all function
        """
D
dongdaxiang 已提交
144
        self._comm.barrier()
D
dongdaxiang 已提交
145

T
tangwei12 已提交
146 147 148 149 150 151
    def _finalize(self):
        """
        finalize the current MPI instance.
        """
        pass

152
    def _get_ips(self):
153 154 155
        """
        collect current distributed job's ip list
        """
T
tangwei12 已提交
156 157
        if not self._ips:
            self._ips = self._comm.allgather(self.get_local_ip())
D
dongdaxiang 已提交
158
        return self._ips
D
dongdaxiang 已提交
159

T
tangwei12 已提交
160
    def get_local_ip(self):
161
        """
T
tangwei12 已提交
162
        return get local ip
163
        """
T
tangwei12 已提交
164 165 166 167 168 169 170 171 172
        import socket
        self._ip = socket.gethostbyname(socket.gethostname())
        return self._ip

    def generate_role(self):
        """
        generate_role() should be called to identify current process's role
        """
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
173 174 175


class MPISymetricRoleMaker(MPIRoleMaker):
176 177 178 179 180 181
    """
    MPISymetricRoleMaker is designed for worker and server assignment
    under MPI. Typically, a worker and a server node will be appointed
    on each physical node. This role maker can be only used under MPI.
    """

D
dongdaxiang 已提交
182 183
    def __init__(self):
        super(MPISymetricRoleMaker, self).__init__()
D
dongdaxiang 已提交
184 185
        self._node_type = None
        self._proc_per_node = 2
D
dongdaxiang 已提交
186

187
    def _check_role_generation(self):
D
dongdaxiang 已提交
188
        if not self._role_is_generated:
T
tangwei12 已提交
189
            raise NameError("generate_role() should be called first")
190 191
        return True

T
tangwei12 已提交
192
    def is_first_worker(self):
193 194 195 196
        """
        return whether current process is the first worker assigned by role maker
        """
        if self._check_role_generation():
T
tangwei12 已提交
197
            return self.is_worker() and 0 == self.worker_index()
198
        return False
D
dongdaxiang 已提交
199

T
tangwei12 已提交
200
    def is_worker(self):
201 202 203 204
        """
        return whether current process is worker assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
205
            return self._node_type == 1
206
        return False
D
dongdaxiang 已提交
207

T
tangwei12 已提交
208
    def is_server(self):
209 210 211 212
        """
        return whether current process is server assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
213
            return self._node_type == 0
214
        return False
D
dongdaxiang 已提交
215

216
    def _worker_num(self):
217 218 219 220
        """
        return the current number of worker
        """
        if self._check_role_generation():
T
tangwei12 已提交
221
            if self.is_worker():
X
xjqbest 已提交
222
                return self._get_size() / 2
223
        return 0
D
dongdaxiang 已提交
224

225
    def _server_num(self):
226 227 228 229
        """
        return the current number of server
        """
        if self._check_role_generation():
T
tangwei12 已提交
230
            if self.is_server():
X
xjqbest 已提交
231
                return self._get_size() / 2
232
        return 0
D
dongdaxiang 已提交
233

T
tangwei12 已提交
234
    def worker_index(self):
235 236 237 238
        """
        return the index of worker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
239
            return self._rank / self._proc_per_node
240
        return 0
D
dongdaxiang 已提交
241

T
tangwei12 已提交
242
    def server_index(self):
243 244 245 246
        """
        return the index of server
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
247
            return self._rank / self._proc_per_node
248
        return 0
D
dongdaxiang 已提交
249

250
    def _barrier_worker(self):
251 252 253 254
        """
        barrier all workers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
255
            if self.is_worker():
D
dongdaxiang 已提交
256
                self._node_type_comm.barrier()
D
dongdaxiang 已提交
257

258
    def _barrier_server(self):
259 260 261 262
        """
        barrier all servers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
263
            if self.is_server():
D
dongdaxiang 已提交
264
                self._node_type_comm.barrier()
D
dongdaxiang 已提交
265

T
tangwei12 已提交
266
    def generate_role(self):
267 268 269
        """
        generate currently process's role
        """
D
dongdaxiang 已提交
270
        if not self._role_is_generated:
271
            # TODO(guru4elephant): only allow to be called once
T
tangwei12 已提交
272 273
            self._worker_endpoints = self._get_ips()
            self._server_endpoints = self._get_ips()
274

D
dongdaxiang 已提交
275 276
            if 0 == self._get_rank() % self._proc_per_node % 2:
                self._node_type = 0
277
            else:
D
dongdaxiang 已提交
278 279 280
                self._node_type = 1
            self._node_type_comm = self._comm.Split(self._node_type)
            self._role_is_generated = True
281 282 283 284 285


class UserDefinedRoleMaker(RoleMakerBase):
    def __init__(self,
                 current_id=0,
T
tangwei12 已提交
286 287 288
                 role=Role.WORKER,
                 worker_num=0,
                 server_endpoints=None):
289 290 291 292 293 294 295
        """
        UserDefinedRoleMaker is designed for worker and server assignment
        under manual. Typically, a worker and a server node will be appointed
        on each physical node, It can be assign by user.
        """
        super(UserDefinedRoleMaker, self).__init__()

T
tangwei12 已提交
296 297 298 299 300 301 302 303 304 305
        self._current_id = current_id
        self._role = role
        self._worker_num = worker_num
        self._server_endpoints = server_endpoints

    def is_worker(self):
        return self._role == Role.WORKER

    def is_server(self):
        return self._role == Role.SERVER
306

T
tangwei12 已提交
307 308
    def is_first_worker(self):
        return self._role == Role.WORKER and self._current_id == 0
309

T
tangwei12 已提交
310 311
    def worker_index(self):
        return self._current_id
312

T
tangwei12 已提交
313 314
    def server_index(self):
        return self._current_id