process_group.py 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2021 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 16
from collections import OrderedDict

17
import paddle
18
from paddle import _legacy_C_ops
19
from paddle.framework import core, in_dygraph_mode
20
from paddle.tensor import fill_constant
21

22
from ..collective import _get_global_env, _new_ring_id
23 24 25


def get_all_process_groups():
26 27
    global _g_process_group_map
    return _g_process_group_map.values()
28 29


30
def get_process_group(group_id, g_process_group_map=None):
31
    global _g_process_group_map
32 33 34 35 36
    return (
        _g_process_group_map.get(group_id, None)
        if g_process_group_map is None
        else g_process_group_map.get(group_id, None)
    )
37 38


J
JZ-LIANG 已提交
39
def get_world_process_group():
40 41 42 43
    global _g_process_group_map
    return _g_process_group_map[0]


44 45 46 47 48 49
def clear_all_process_groups():
    global _g_process_group_map
    _g_process_group_map = {}
    _g_process_group_map[0] = ProcessGroup(0, [])


50 51
def new_process_group(ranks, group_id=None, force_new_group=False):

52
    global _g_process_group_map
53 54 55 56 57 58 59
    if not force_new_group:
        # A key constructed from ranks is used for avoiding duplication
        new_key = ''.join(map(str, sorted(ranks)))
        for pg_id, pg in _g_process_group_map.items():
            cur_key = ''.join(map(str, sorted(pg.ranks)))
            if pg_id != 0 and new_key == cur_key:
                return pg
C
chenxujun 已提交
60
    # If not matching the existing one, construct a new process group
61 62 63
    num_groups = len(_g_process_group_map)
    # Note: our process group may interfere with the original implementation
    # so the created group id should start from the original _new_ring_id()
64
    if group_id is None:
65 66
        group_id = _new_ring_id() + num_groups + 1

67 68 69
    new_pg = ProcessGroup(group_id, ranks)
    _g_process_group_map[group_id] = new_pg
    return new_pg
70 71 72


# This implementation refers to lots of Paddle/python/paddle/distributed/collective.py,
73
# Fleet also has a collective helper which uses ops to initialize communication in
74
# Paddle/python/paddle/distributed/fleet/meta_optimizers/common.py. We use the first one
75 76
# because it seems simple. This should be enhanced to manage the process membership and
# the instantiation process in a more general way. In the future, the process group may
77 78 79
# handle the communication implementation choice.
class ProcessGroup:
    def __init__(self, group_id, ranks):
80
        if group_id == 0 and get_process_group(0) is not None:
81 82 83
            assert (
                group_id != 0
            ), "Process group id 0 is reserved for all ranks."
84 85
        self._group_id = group_id
        self._ranks = sorted(ranks)
86 87 88 89
        # Add the current ranks into group 0
        if group_id != 0:
            global _g_process_group_map
            _g_process_group_map[0].add_ranks(ranks)
90 91 92 93 94 95
        self._is_instantiate = False

    @property
    def id(self):
        return self._group_id

96 97 98 99 100 101 102 103 104 105 106 107
    @property
    def ranks(self):
        return self._ranks

    @property
    def nranks(self):
        return len(self._ranks)

    def add_ranks(self, new_ranks):
        if set(new_ranks) <= set(self.ranks):
            return
        else:
108
            assert (
109
                not self.is_instantiate()
110
            ), "Cannot add new ranks after instantiating the process group"
111
        self._ranks.extend(new_ranks)
112
        self._ranks = sorted(set(self.ranks))
113 114

    def local_rank(self, global_rank):
115 116
        if global_rank in self.ranks:
            return self.ranks.index(global_rank)
117
        else:
118
            raise AssertionError(
119
                f"Rank {global_rank} doesn't belong to this group"
120
            )
121 122 123 124 125 126 127 128 129 130 131

    def is_instantiate(self):
        return self._is_instantiate

    def instantiate(self):
        if self._is_instantiate:
            return
        ring_id = self.id
        genv = _get_global_env()
        global_rank = genv.rank

132
        if self.nranks >= 2:
133
            strategy = core.ParallelStrategy()
134
            strategy.nranks = self.nranks
135 136
            strategy.local_rank = self.local_rank(global_rank)
            strategy.trainer_endpoints = [
137
                genv.trainer_endpoints[i] for i in self.ranks
138 139 140 141 142
            ]
            strategy.current_endpoint = genv.current_endpoint
            strategy.nrings = 1
            if core.is_compiled_with_cuda():
                place = core.CUDAPlace(genv.device_id)
143 144 145
                core.NCCLParallelContext(strategy, place).init_with_ring_id(
                    ring_id
                )
146 147 148 149 150
            elif core.is_compiled_with_xpu():
                place = core.XPUPlace(genv.device_id)
                core.BKCLParallelContext(strategy, place).init_with_ring_id(
                    ring_id
                )
151
            else:
152
                raise AssertionError('No CUDA device found')
153

154 155
            # TODO(shenliang03): This is a temporary solution to solve the problem of
            # hang caused by cross-creation of new_group
156
            paddle.disable_static()
157 158 159 160 161 162 163 164
            if core.is_compiled_with_cuda():
                paddle.set_device(
                    'gpu:%d' % paddle.distributed.ParallelEnv().dev_id
                )
            elif core.is_compiled_with_xpu():
                paddle.set_device(
                    'xpu:%d' % paddle.distributed.ParallelEnv().dev_id
                )
165 166
            tmp = (
                paddle.to_tensor([1], dtype="int32")
167
                if in_dygraph_mode()
168 169
                else fill_constant([0], dtype="int32", value="1")
            )
170
            # use legacy ops
171 172 173
            _legacy_C_ops.c_allreduce_sum_(
                tmp, 'use_calc_stream', True, 'ring_id', self.id
            )
174
            _legacy_C_ops.c_sync_calc_stream(tmp, tmp)
175
            paddle.enable_static()
176 177 178

        self._is_instantiate = True

179 180 181
    def is_member(self):
        return True

182 183 184 185 186 187
    def __eq__(self, other):
        if not isinstance(other, ProcessGroup):
            return False
        if self.id != other.id:
            return False
        return True
188

189 190
    def __ne__(self, other):
        return not self.__eq__(other)
191

192 193
    def __str__(self):
        string = "id: {}, nranks: {}, ranks: {}.".format(
194 195
            self.id, self.nranks, ", ".join(map(str, self.ranks))
        )
196
        return string
197

198 199 200
    def __hash__(self):
        return hash(self.__str__())

201

202
# Note that Process group 0 is reserved for representing all ranks.
203
# At the beginning, group 0 is empty and new ranks will be added automatically.
204
_g_process_group_map = OrderedDict()
205
_g_process_group_map[0] = ProcessGroup(0, [])