hybrid_parallel_util.py 7.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#   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.
import os
import six
import numpy as np
import warnings

from paddle import framework
import paddle
from paddle.fluid import core
22
from paddle.fluid.dygraph.parallel import _split_tensors, sync_params_buffers, build_groups
23
from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph
24
from collections import OrderedDict
25
from .log_util import logger
26

27 28
__all__ = []

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

def _apply_collective_grads(parameters, comm_group):
    grad_var_set = set()
    grad_vars = []
    sparse_grad_vars = []

    for param in parameters:
        if param.trainable and (param._grad_ivar() is not None):
            g_var = param._grad_ivar()
            assert not g_var._is_sparse(
            ), "Now, it doesn't support sparse parameters"
            grad_vars.append(g_var)
            assert g_var not in grad_var_set
            grad_var_set.add(g_var)

44
    coalesced_grads_and_vars = build_groups(grad_vars, 128 * 1024 * 1024)
45

46 47
    nranks = paddle.distributed.get_world_size(
    ) if comm_group is None else comm_group.nranks
48 49
    for coalesced_grad, _, _ in coalesced_grads_and_vars:
        # need to div nranks
50
        div_factor = paddle.to_tensor(nranks, dtype=coalesced_grad.dtype)
51 52
        paddle.fluid.framework._dygraph_tracer().trace_op(
            type="elementwise_div",
53 54 55 56
            inputs={
                'X': coalesced_grad,
                'Y': div_factor
            },
57 58
            outputs={'Out': coalesced_grad},
            attrs={'axis': -1})
59
        paddle.distributed.all_reduce(coalesced_grad, group=comm_group)
60

61 62 63
    _split_tensors(coalesced_grads_and_vars)


64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
def _apply_collective_grads_eager(parameters, comm_group):
    grad_var_set = set()
    grad_vars = []

    for param in parameters:
        if param.trainable and (param._grad_ivar() is not None):
            g_var = param._grad_ivar()
            assert not g_var.is_sparse(
            ), "Now, it doesn't support sparse parameters"
            grad_vars.append(g_var)
            assert g_var not in grad_var_set
            grad_var_set.add(g_var)

    coalesced_grads_and_vars = build_groups(grad_vars, 128 * 1024 * 1024)

79 80
    nranks = paddle.distributed.get_world_size(
    ) if comm_group is None else comm_group.nranks
81
    for coalesced_grad, _, _ in coalesced_grads_and_vars:
82
        # need to div nranks
83
        coalesced_grad.scale_(1.0 / nranks)
84 85 86 87 88
        paddle.distributed.all_reduce(coalesced_grad, group=comm_group)

    _split_tensors(coalesced_grads_and_vars)


89
def _broadcast_data_help(data, shape, dtype, hcg):
90 91
    model_parallel_group = hcg.get_model_parallel_group()
    src_rank = hcg.get_model_parallel_group_src_rank()
92 93 94
    mp_rank = hcg.get_model_parallel_rank()

    shape_gpu = paddle.to_tensor(shape, dtype="int32")
95 96 97 98
    paddle.distributed.broadcast(shape_gpu,
                                 src=src_rank,
                                 group=model_parallel_group,
                                 use_calc_stream=True)
99 100 101 102 103 104

    if mp_rank != 0:
        input_data = paddle.zeros(shape_gpu, dtype=dtype)
    else:
        input_data = data

105 106 107 108
    paddle.distributed.broadcast(input_data,
                                 src=src_rank,
                                 group=model_parallel_group,
                                 use_calc_stream=True)
109

110 111 112 113

def broadcast_input_data(hcg, *inputs, **kwargs):
    for v in inputs:
        if isinstance(v, core.VarBase):
114
            with framework.no_grad():
115
                _broadcast_data_help(v, v.shape, v.dtype, hcg)
116
        else:
117
            logger.error("it doesn't support data type {}".format(type(v)))
118 119 120 121

    for k, v in kwargs.items():
        if isinstance(v, core.VarBase):
            with framework.no_grad():
122
                _broadcast_data_help(v, v.shape, v.dtype, hcg)
123 124
            kwargs[k] = v
        else:
125
            logger.error("it doesn't support data type {}".format(type(v)))
126 127 128 129 130 131
    return inputs, kwargs


def broadcast_mp_parameters(model, hcg):
    model_parallel_group = hcg.get_model_parallel_group()
    src_rank = hcg.get_model_parallel_group_src_rank()
132 133 134 135
    sync_params_buffers(model,
                        model_parallel_group,
                        src_rank,
                        is_model_parallel=True)
136 137 138 139 140


def broadcast_dp_parameters(model, hcg):
    data_parallel_group = hcg.get_data_parallel_group()
    src_rank = hcg.get_data_parallel_group_src_rank()
141 142 143 144
    sync_params_buffers(model,
                        data_parallel_group,
                        src_rank,
                        is_model_parallel=False)
145 146 147


def fused_allreduce_gradients(parameter_list, hcg):
H
Haohongxiang 已提交
148 149 150 151 152 153
    data_parallel_group = None if hcg is None else hcg.get_data_parallel_group()
    logger.debug("dp start fuse allreduce gradients")
    apply_func = _apply_collective_grads_eager if in_dygraph_mode(
    ) else _apply_collective_grads
    with framework.no_grad():
        apply_func(parameter_list, data_parallel_group)
J
JZ-LIANG 已提交
154 155 156 157


def sharding_reduce_gradients(parameter_list, hcg):
    # TODO allreduce --> reduce
158
    # TODO merge grad / nrank with dp
J
JZ-LIANG 已提交
159 160 161 162 163 164
    logger.debug("sharding start gradients sync")
    with framework.no_grad():

        sharding_nrank = hcg.get_sharding_parallel_group().nranks
        for param in parameter_list:
            if param.trainable and (param._grad_ivar() is not None):
165 166 167 168 169 170 171 172 173
                if in_dygraph_mode():
                    param.grad.scale_(1.0 / sharding_nrank)
                    paddle.distributed.all_reduce(
                        param.grad,
                        group=hcg.get_sharding_parallel_group(),
                        use_calc_stream=True)

                elif _in_legacy_dygraph():
                    g_var = param._grad_ivar()
174
                    # need use trace_op to allreduce
175 176 177 178 179 180 181 182 183 184 185 186
                    # paddle.distributed.all_reduce(
                    #     g_var, group=hcg.get_sharding_parallel_group(), use_calc_stream=True)
                    paddle.fluid.framework._dygraph_tracer().trace_op(
                        type="c_allreduce_sum",
                        inputs={'X': g_var},
                        outputs={'Out': g_var},
                        attrs={
                            'ring_id': hcg.get_sharding_parallel_group().id,
                            'use_calc_stream': True
                        })

                    # grad / sharding_rank
187 188
                    div_factor = paddle.to_tensor(sharding_nrank,
                                                  dtype=g_var.dtype)
189 190
                    paddle.fluid.framework._dygraph_tracer().trace_op(
                        type="elementwise_div",
191 192 193 194
                        inputs={
                            'X': g_var,
                            'Y': div_factor
                        },
195 196
                        outputs={'Out': g_var},
                        attrs={'axis': -1})
J
JZ-LIANG 已提交
197 198 199 200 201 202 203


def broadcast_sharding_parameters(model, hcg):
    # TODO TO save memory, use un-fused broadcast to avoid potentional OOM
    logger.debug("sharding start init parameters sync")
    sharding_parallel_group = hcg.get_sharding_parallel_group()
    src_rank = hcg.get_sharding_parallel_group_src_rank()
204 205 206 207
    sync_params_buffers(model,
                        sharding_parallel_group,
                        src_rank,
                        is_model_parallel=False)