hybrid_parallel_util.py 8.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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 paddle
16
from paddle import framework
Q
qizhaoaoe 已提交
17
from paddle.distributed.parallel import (
18 19
    _split_tensors,
    build_groups,
20
    in_dygraph_mode,
21
    sync_params_buffers,
22
)
23

Q
qizhaoaoe 已提交
24 25 26
# (TODO: GhostScreaming) It will be removed later.
from paddle.fluid import core

27
from .log_util import logger
28

29 30
__all__ = []

31

32
def _apply_collective_grads(parameters, comm_group, bucket_size, scale=None):
33 34 35 36 37 38 39
    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()
40 41
            assert (
                not g_var._is_sparse()
42 43 44 45 46
            ), "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)

47
    coalesced_grads_and_vars = build_groups(grad_vars, bucket_size)
48

49 50 51 52 53
    nranks = (
        paddle.distributed.get_world_size()
        if comm_group is None
        else comm_group.nranks
    )
54 55 56 57

    scale = nranks if scale is None else 1.0 / scale
    scale = None if scale == 1.0 else scale

58 59
    for coalesced_grad, _, _ in coalesced_grads_and_vars:
        # need to div nranks
60 61 62 63 64 65 66 67
        if scale is not None:
            div_factor = paddle.to_tensor(scale, dtype=coalesced_grad.dtype)
            paddle.fluid.framework._dygraph_tracer().trace_op(
                type="elementwise_div",
                inputs={'X': coalesced_grad, 'Y': div_factor},
                outputs={'Out': coalesced_grad},
                attrs={'axis': -1},
            )
68
        paddle.distributed.all_reduce(coalesced_grad, group=comm_group)
69

70 71 72
    _split_tensors(coalesced_grads_and_vars)


73 74 75
def _apply_collective_grads_eager(
    parameters, comm_group, bucket_size, scale=None
):
76 77 78 79
    grad_var_set = set()
    grad_vars = []

    for param in parameters:
80
        g_var = None
81 82
        if param.trainable and (param._grad_ivar() is not None):
            g_var = param._grad_ivar()
83 84 85 86
        if param.trainable and hasattr(param, "main_grad"):
            assert param._grad_ivar() is None, "param.grad is not None"
            g_var = param.main_grad
        if g_var is not None:
87 88
            assert (
                not g_var.is_sparse()
89 90 91 92 93
            ), "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)

94
    coalesced_grads_and_vars = build_groups(grad_vars, bucket_size)
95

96 97 98 99 100
    nranks = (
        paddle.distributed.get_world_size()
        if comm_group is None
        else comm_group.nranks
    )
101 102 103 104

    scale = 1.0 / nranks if scale is None else scale
    scale = None if scale == 1.0 else scale

105
    for coalesced_grad, _, _ in coalesced_grads_and_vars:
106
        # need to div nranks
107 108
        if scale is not None:
            coalesced_grad.scale_(scale)
109 110 111 112 113
        paddle.distributed.all_reduce(coalesced_grad, group=comm_group)

    _split_tensors(coalesced_grads_and_vars)


114
def _broadcast_data_help(data, shape, dtype, hcg):
115 116
    model_parallel_group = hcg.get_model_parallel_group()
    src_rank = hcg.get_model_parallel_group_src_rank()
117 118 119
    mp_rank = hcg.get_model_parallel_rank()

    shape_gpu = paddle.to_tensor(shape, dtype="int32")
120 121 122
    paddle.distributed.broadcast(
        shape_gpu, src=src_rank, group=model_parallel_group, sync_op=True
    )
123 124 125 126 127 128

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

129 130 131
    paddle.distributed.broadcast(
        input_data, src=src_rank, group=model_parallel_group, sync_op=True
    )
132

133 134 135 136 137 138 139
    if mp_rank != 0:
        if in_dygraph_mode():
            data._clear_data()
            input_data._share_buffer_to(data)
        else:
            data.value().get_tensor()._clear()
            data.value().get_tensor()._share_data_with(
140 141
                input_data.value().get_tensor()
            )
142

143

144 145 146 147 148 149 150 151 152 153
def _broadcast_object_list_help(object_list, hcg):
    model_parallel_group = hcg.get_model_parallel_group()
    src_rank = hcg.get_model_parallel_group_src_rank()
    mp_rank = hcg.get_model_parallel_rank()

    paddle.distributed.broadcast_object_list(
        object_list, src=src_rank, group=model_parallel_group
    )


154
def broadcast_input_data(hcg, *inputs, **kwargs):
155
    cur_device = paddle.get_device()
R
Roc 已提交
156 157 158 159 160 161 162 163 164 165 166 167
    dev = cur_device.split(":")[0]
    assert dev in [
        "xpu",
        "gpu",
        "npu",
    ], f"Only support xpu, gpu and npu now, but this is {dev}"
    dev_idx = int(cur_device.split(':')[1])
    if dev == "gpu":
        place = paddle.CUDAPlace(dev_idx)
    else:
        place = eval(f"paddle.{dev.upper()}Place")(dev_idx)

168
    for v in inputs:
W
wanghuancoder 已提交
169
        if isinstance(v, core.eager.Tensor):
170
            with framework.no_grad():
R
Roc 已提交
171 172
                if in_dygraph_mode() and not eval(f"v.place.is_{dev}_place")():
                    v_gpu = v._copy_to(place, True)
173 174
                    v._clear_data()
                    v_gpu._share_buffer_to(v)
175
                _broadcast_data_help(v, v.shape, v.dtype, hcg)
176
        else:
177
            _broadcast_object_list_help(v, hcg)
178 179

    for k, v in kwargs.items():
W
wanghuancoder 已提交
180
        if isinstance(v, core.eager.Tensor):
181
            with framework.no_grad():
R
Roc 已提交
182 183
                if in_dygraph_mode() and not eval(f"v.place.is_{dev}_place")():
                    v_gpu = v._copy_to(place, True)
184 185
                    v._clear_data()
                    v_gpu._share_buffer_to(v)
186
                _broadcast_data_help(v, v.shape, v.dtype, hcg)
187 188
            kwargs[k] = v
        else:
189
            kwargs[k] = _broadcast_object_list_help(v, hcg)
190 191 192 193 194 195
    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()
196 197 198
    sync_params_buffers(
        model, model_parallel_group, src_rank, is_model_parallel=True
    )
199 200 201 202 203


def broadcast_dp_parameters(model, hcg):
    data_parallel_group = hcg.get_data_parallel_group()
    src_rank = hcg.get_data_parallel_group_src_rank()
204 205 206
    sync_params_buffers(
        model, data_parallel_group, src_rank, is_model_parallel=False
    )
207 208


209 210 211
def fused_allreduce_gradients_with_group(
    parameter_list, group, bucket_size=128 * 1024 * 1024, scale=None
):
212 213 214 215 216
    apply_func = (
        _apply_collective_grads_eager
        if in_dygraph_mode()
        else _apply_collective_grads
    )
H
Haohongxiang 已提交
217
    with framework.no_grad():
S
sneaxiy 已提交
218
        apply_func(parameter_list, group, bucket_size, scale)
219 220 221 222 223 224


def fused_allreduce_gradients(parameter_list, hcg):
    data_parallel_group = None if hcg is None else hcg.get_data_parallel_group()
    logger.debug("dp start fuse allreduce gradients")
    fused_allreduce_gradients_with_group(parameter_list, data_parallel_group)
J
JZ-LIANG 已提交
225 226 227 228


def sharding_reduce_gradients(parameter_list, hcg):
    # TODO allreduce --> reduce
229
    # TODO merge grad / nrank with dp
J
JZ-LIANG 已提交
230 231 232 233 234 235
    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):
236 237 238 239 240 241
                param.grad.scale_(1.0 / sharding_nrank)
                paddle.distributed.all_reduce(
                    param.grad,
                    group=hcg.get_sharding_parallel_group(),
                    sync_op=True,
                )
J
JZ-LIANG 已提交
242 243 244 245 246 247 248


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()
249 250 251
    sync_params_buffers(
        model, sharding_parallel_group, src_rank, is_model_parallel=False
    )