dist_embedding.py 9.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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

from .common import DistributedOperator
from .common import DistributedOperatorImpl
from .common import register_distributed_operator
from .common import register_distributed_operator_impl
19 20
from .common import copy_distributed_attr_for_var
from .common import copy_distributed_attr_for_dist_op
21 22 23 24 25 26
from ..utils import is_dim_shard
from ..utils import is_dim_replicate
from ..utils import is_valid_list_index
from ..utils import compute_compatible_dim_mapping
from ..utils import compute_compatible_dims_mapping
from ..utils import compute_compatible_and_update_dim_mapping
27 28 29 30 31 32
from paddle.fluid import core, unique_name
from paddle.fluid.framework import in_dygraph_mode
from paddle.fluid.framework import Program, Parameter, Variable, program_guard
from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype
from ..process import new_process_group
from ..utils import _get_comm_group
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49


class DistributedEmbedding(DistributedOperator):
    def __init__(self, name):
        super(DistributedEmbedding, self).__init__()
        self._name = name


register_distributed_operator("lookup_table_v2",
                              DistributedEmbedding("embedding"))


# RowParallel
class DistributedEmbeddingImpl(DistributedOperatorImpl):
    def __init__(self, name):
        super(DistributedEmbeddingImpl, self).__init__()
        self._name = name
50 51
        self._forward_implemented = True
        self._backward_implemented = False
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

    def is_process_mesh_compatible(self, op_dist_attr):
        """ No restriction for now. """
        return True

    def is_input_compatible(self, op_dist_attr):
        op_desc = op_dist_attr.get_owner_op().desc
        ids_name = op_desc.input('Ids')[0]
        w_name = op_desc.input('W')[0]
        ids_dims_mapping = op_dist_attr.get_input_dims_mapping(ids_name)
        w_dims_mapping = op_dist_attr.get_input_dims_mapping(w_name)
        if is_dim_replicate(w_dims_mapping[-2]) or is_dim_shard(w_dims_mapping[
                -1]):
            return False
        # Other dimensions must be replicate except the batch dimension
        for mapping in ids_dims_mapping[1:]:
            if is_dim_shard(mapping):
                return False
        return True

    def is_output_compatible(self, op_dist_attr):
        op_desc = op_dist_attr.get_owner_op().desc
        out_name = op_desc.output('Out')[0]
        out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name)
        # Other dimensions must be replicate except the batch dimension
        for mapping in out_dims_mapping[1:]:
            if is_dim_shard(mapping):
                return False
        return True

    def update_dims_mapping(self, op_dist_attr):
        changed = False
        op_desc = op_dist_attr.get_owner_op().desc
        ids_name = op_desc.input('Ids')[0]
        w_name = op_desc.input('W')[0]
        out_name = op_desc.output('Out')[0]
        ids_dims_mapping = op_dist_attr.get_input_dims_mapping(ids_name)
        w_dims_mapping = op_dist_attr.get_input_dims_mapping(w_name)
        out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name)

        for i in range(len(ids_dims_mapping)):
            dim_changed = compute_compatible_and_update_dim_mapping(
                [ids_dims_mapping, out_dims_mapping], [i, i])
            if dim_changed:
                changed = True

        dim_changed = compute_compatible_and_update_dim_mapping(
            [w_dims_mapping, out_dims_mapping], [-1, -1])
        if dim_changed:
            changed = True

        return changed

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 136 137 138 139 140 141 142 143 144 145 146 147 148
    def forward(self, serial_op):
        def static_handle(dst_block,
                          src_op,
                          op_dist_attr,
                          input_name_mapping,
                          output_name_mapping,
                          rank_id=0):
            assert len(
                input_name_mapping
            ) == 2, "row_parallel_embedding take 2 inputs variable but got {}".format(
                input_name_mapping)
            assert len(
                output_name_mapping
            ) == 1, "row_parallel_embedding take 2 inputs variable but got {}".format(
                output_name_mapping)
            assert len(
                input_name_mapping['Ids']
            ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format(
                input_name_mapping['Ids'])
            assert len(
                input_name_mapping['W']
            ) == 1, "row_parallel_embedding input W take 1 variable but got {}".format(
                input_name_mapping['W'])
            assert len(
                output_name_mapping['Out']
            ) == 1, "row_parallel_embedding input Out take 1 variable but got {}".format(
                input_name_mapping['Out'])

            Ids_var = dst_block.var(input_name_mapping['Ids'][0])
            Weight_var = dst_block.var(input_name_mapping['W'][0])
            Out_var = dst_block.var(output_name_mapping['Out'][0])

            # got dist attribute info
            embedding_row_dim_mapping = op_dist_attr.get_input_dims_mapping(
                Weight_var.name)[0]
            process_mesh_shape = op_dist_attr.get_process_mesh().topology
            process_mesh_group = op_dist_attr.get_process_mesh().process_group

            # caculate embedding offset
            # TODO generalize here, using cartisian product to allow any dimensional mesh shape
            mesh_shape = len(process_mesh_shape)
            assert mesh_shape <= 2, "row_parallel_embedding only support 1 or 2 dimensional process mesh, but got {}".format(
                process_mesh_shape)
            num_partition = process_mesh_shape[embedding_row_dim_mapping]
C
caozhou 已提交
149 150 151
            # TODO generalize here, support any mesh group
            model_parallel_axis, process_mesh = op_dist_attr.get_owner_context(
            )._get_model_parallel_info()
152
            if mesh_shape == 1:
C
caozhou 已提交
153 154 155 156 157 158 159 160
                if rank_id not in process_mesh_group:
                    assert len(
                        process_mesh.topology
                    ) == 2, " row_parallel_embedding process mapping only support 2 dimensional process mesh, \
                    but got {}".format(len(process_mesh.topology))
                    rank_id = process_mesh_group[
                        process_mesh.process_group.index(rank_id) %
                        process_mesh_shape[0]]
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
                relative_idx = process_mesh_group.index(rank_id)
            else:
                relative_idx = rank_id % num_partition

            per_part_size = Weight_var.shape[0]
            relative_idx = relative_idx * per_part_size

            # TODO caculate ring id 
            group_ranks = _get_comm_group(process_mesh.process_group,
                                          process_mesh.topology,
                                          model_parallel_axis, rank_id)
            group = new_process_group(group_ranks)

            # append op
            check_variable_and_dtype(Ids_var, 'input', ['int32', 'int64'],
                                     'c_embedding')

            intermediate_var_0 = dst_block.create_var(
                name=unique_name.generate_with_ignorable_key(".".join(
                    ["c_embedding", 'tmp'])),
                dtype=Weight_var.dtype,
                shape=Out_var.shape,
                type=core.VarDesc.VarType.LOD_TENSOR,
                persistable=False,
                stop_gradient=Out_var.stop_gradient)
186 187 188
            # copy Out_var's dist_attr to intermediate_var_0's dist_attr
            copy_distributed_attr_for_var(op_dist_attr, intermediate_var_0,
                                          Out_var)
189 190 191 192 193 194

            check_variable_and_dtype(
                Out_var, 'tensor',
                ['float16', 'float32', 'float64', 'int32', 'int64'],
                'c_allreduce_sum')

195
            c_embedding_op = dst_block.append_op(
196 197 198 199 200 201 202
                type='c_embedding',
                inputs={'Ids': [Ids_var],
                        'W': [Weight_var]},
                outputs={'Out': [intermediate_var_0]},
                attrs={"start_index": relative_idx})

            # use_model_parallel
203
            c_allreduce_sum_op = dst_block.append_op(
204 205 206 207 208 209 210 211 212
                type='c_allreduce_sum',
                inputs={'X': [intermediate_var_0]},
                outputs={'Out': [Out_var]},
                attrs={
                    'ring_id': group.id,
                    'use_calc_stream': True,
                    'use_model_parallel': True,
                })

213 214 215 216 217 218
            # copy serial op's dist_attr to dist op's dist_attr
            copy_distributed_attr_for_dist_op(c_embedding_op, dst_block,
                                              op_dist_attr)
            copy_distributed_attr_for_dist_op(c_allreduce_sum_op, dst_block,
                                              op_dist_attr)

219 220 221 222 223 224 225
        if in_dygraph_mode():
            raise NotImplementedError(
                "Dist op for [{}] with idx [{}] is NOT implemented yet.".format(
                    "matmul", 0))
        else:
            return static_handle

226 227 228

register_distributed_operator_impl("lookup_table_v2",
                                   DistributedEmbeddingImpl("row_parallel"))