common.py 8.3 KB
Newer Older
Y
Yi Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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
import os
Y
Yi Liu 已提交
16 17 18 19 20

import paddle.fluid as fluid
from paddle.fluid import core, unique_name
from ..base.private_helper_function import wait_server_ready

21 22
__all__ = []

Y
Yi Liu 已提交
23 24 25 26 27 28 29
OpRole = core.op_proto_and_checker_maker.OpRole

OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName()
OP_ROLE_VAR_KEY = core.op_proto_and_checker_maker.kOpRoleVarAttrName()


def is_update_op(op):
30 31 32 33 34
    return (
        'Param' in op.input_names
        and 'Grad' in op.input_names
        and "LearningRate" in op.input_names
    )
Y
Yi Liu 已提交
35 36 37 38 39 40 41 42 43 44


def is_loss_grad_op(op):
    if OP_ROLE_KEY not in op.attr_names:
        return False
    op_role = int(op.all_attrs()[OP_ROLE_KEY])
    return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss)


def is_backward_op(op):
45 46 47
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) & int(OpRole.Backward)
Y
Yi Liu 已提交
48 49 50


def is_optimizer_op(op):
51 52 53
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) & int(OpRole.Optimize)
Y
Yi Liu 已提交
54 55 56


class CollectiveHelper(object):
57
    def __init__(self, role_maker, nrings=1, wait_port=True):
Y
Yi Liu 已提交
58 59 60 61 62 63 64 65 66
        self.nrings = nrings
        self.wait_port = wait_port
        self.role_maker = role_maker

    def update_startup_program(self, startup_program=None):
        self.startup_program = startup_program
        if startup_program is None:
            self.startup_program = fluid.default_startup_program()

67 68
        endpoints = self.role_maker._get_trainer_endpoints()
        current_endpoint = endpoints[self.role_maker._worker_index()]
Y
Yi Liu 已提交
69
        for ring_id in range(self.nrings):
70 71 72 73 74 75 76 77
            self._init_communicator(
                self.startup_program,
                current_endpoint,
                endpoints,
                self.role_maker._worker_index(),
                ring_id,
                self.wait_port,
            )
Y
Yi Liu 已提交
78 79
        self._broadcast_params()

80 81 82 83 84 85 86 87 88 89 90
    def _init_communicator(
        self,
        program,
        current_endpoint,
        endpoints,
        rank,
        ring_id,
        wait_port,
        global_ring_id=None,
        sync=True,
    ):
91 92 93 94 95 96
        # if current_endpoint is None, it means just for sync,
        # no group is created.
        if current_endpoint:
            nranks = len(endpoints)
            other_endpoints = endpoints[:]
            other_endpoints.remove(current_endpoint)
97

Y
Yi Liu 已提交
98 99 100
        if rank == 0 and wait_port:
            wait_server_ready(other_endpoints)

101
        def _add_sync_by_allreduce(block):
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            sync_var = block.create_var(
                name=unique_name.generate('sync_var'),
                dtype=core.VarDesc.VarType.INT32,
                persistable=False,
                stop_gradient=True,
            )
            block.append_op(
                type='fill_constant',
                inputs={},
                outputs={'Out': [sync_var]},
                attrs={
                    'shape': [1],
                    'dtype': sync_var.dtype,
                    'value': 1,
                    'force_cpu': False,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_allreduce_sum',
                inputs={'X': [sync_var]},
                outputs={'Out': [sync_var]},
                attrs={
                    'ring_id': global_ring_id,
                    'use_calc_stream': True,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_sync_calc_stream',
                inputs={'X': sync_var},
                outputs={'Out': sync_var},
                attrs={OP_ROLE_KEY: OpRole.Forward},
            )
136

Y
Yi Liu 已提交
137
        block = program.global_block()
138 139 140 141 142 143
        if current_endpoint is None:
            assert endpoints is None
            assert sync
            _add_sync_by_allreduce(block)
            return

144 145 146 147 148
        comm_id_var = block.create_var(
            name=unique_name.generate('comm_id'),
            persistable=True,
            type=core.VarDesc.VarType.RAW,
        )
149
        if core.is_compiled_with_cuda():
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            block.append_op(
                type='c_gen_nccl_id',
                inputs={},
                outputs={'Out': comm_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    'ring_id': ring_id,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_comm_init',
                inputs={'X': comm_id_var},
                outputs={},
                attrs={
                    'nranks': nranks,
                    'rank': rank,
                    'ring_id': ring_id,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
173
        elif core.is_compiled_with_xpu():
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            block.append_op(
                type='c_gen_bkcl_id',
                inputs={},
                outputs={'Out': comm_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    'ring_id': ring_id,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_comm_init',
                inputs={'X': comm_id_var},
                outputs={},
                attrs={
                    'nranks': nranks,
                    'rank': rank,
                    'ring_id': ring_id,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
197
        elif core.is_compiled_with_npu():
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            block.append_op(
                type='c_gen_hccl_id',
                inputs={},
                outputs={'Out': comm_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    'ring_id': ring_id,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_comm_init_hccl',
                inputs={'X': comm_id_var},
                outputs={},
                attrs={
                    'rank': rank,
                    'ring_id': ring_id,
                    'device_id': int(os.getenv("FLAGS_selected_npus")),
                    'rank_ids': nranks,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
222 223 224 225
        else:
            raise ValueError(
                "comm_id must be generated in paddlepaddle-xpu or paddlepaddle-xpu."
            )
226 227
        if sync:
            _add_sync_by_allreduce(block)
Y
Yi Liu 已提交
228

229
    def _wait(self, current_endpoint, endpoints):
230
        assert self.wait_port
231 232 233 234
        other_endpoints = endpoints[:]
        other_endpoints.remove(current_endpoint)
        wait_server_ready(other_endpoints)

Y
Yi Liu 已提交
235 236 237 238 239 240 241 242
    def _broadcast_params(self):
        block = self.startup_program.global_block()
        ring_id = -1
        for param in block.iter_parameters():
            if param.is_distributed:
                continue

            ring_id = (ring_id + 1) % self.nrings
243 244 245 246 247 248 249 250 251 252
            block.append_op(
                type='c_broadcast',
                inputs={'X': param},
                outputs={'Out': param},
                attrs={
                    'ring_id': ring_id,
                    'root': 0,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
Y
Yi Liu 已提交
253 254

        for ring_id in range(self.nrings):
255 256 257 258 259 260
            block.append_op(
                type='c_sync_comm_stream',
                inputs={'X': param},
                outputs={'Out': param},
                attrs={'ring_id': ring_id, OP_ROLE_KEY: OpRole.Forward},
            )