common.py 6.8 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 ..dist_attribute import OperatorDistributedAttribute

17
_g_distributed_operator_impl_registries = {}
J
JZ-LIANG 已提交
18
BACKWARD_ONLY_DIST_OPS = {'check_finite_and_unscale'}
19 20


21
class DistributedOperatorImplContainer:
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    def __init__(self):
        self._impls = []
        self._name = None

    def register_impl(self, dist_impl):
        self._impls.append(dist_impl)

    def get_impl(self, impl_idx):
        return self._impls[impl_idx]

    def get_impls(self):
        return self._impls


class DistributedOperatorImpl:
    def __init__(self):
        self._name = None
39 40
        self._forward_implemented = False
        self._backward_implemented = False
41

42 43
    @staticmethod
    def forward(dist_ctx, *args, **kwargs):
44 45
        raise NotImplementedError("Please Implement this method in Subclass.")

46 47
    @staticmethod
    def backward(dist_ctx, *grad_outputs, **kwargs):
48 49 50 51 52
        raise NotImplementedError("Please Implement this method in Subclass.")

    def get_name(self):
        return self._name

53
    def is_input_compatible(self, dist_op):
54 55
        raise NotImplementedError("Please Implement this method in Subclass.")

56
    def is_output_compatible(self, dist_op):
57 58
        raise NotImplementedError("Please Implement this method in Subclass.")

59 60 61
    def is_compatible(self, dist_op):
        return self.is_input_compatible(dist_op) and \
            self.is_output_compatible(dist_op)
62

沉潜的鱼儿's avatar
沉潜的鱼儿 已提交
63 64 65
    def is_auto_compatible(self, dist_op):
        raise NotImplementedError("Please Implement this method in Subclass.")

66
    def update_dims_mapping(self, dist_op):
67 68 69
        raise NotImplementedError("Please Implement this method in Subclass.")


70 71 72
def register_distributed_operator_impl_container(name, dist_op_impl_container):
    global _g_distributed_operator_impl_registries
    _g_distributed_operator_impl_registries[name] = dist_op_impl_container
73 74


75 76 77
def get_distributed_operator_impl_container(name):
    global _g_distributed_operator_impl_registries
    return _g_distributed_operator_impl_registries.get(name, None)
78 79 80


def register_distributed_operator_impl(name, dist_impl):
81 82 83
    dist_op_impl_container = get_distributed_operator_impl_container(name)
    if dist_op_impl_container is not None:
        dist_op_impl_container.register_impl(dist_impl)
84
    else:
85
        assert False, "Must register distributed operator registry first."
86 87 88


def get_distributed_operator_impl(name, impl_idx):
89 90
    global _g_distributed_operator_impl_registries
    return _g_distributed_operator_impl_registries[name].get_impl(impl_idx)
91 92


93
def find_best_compatible_distributed_operator_impl(name, dist_op, fwd=True):
94 95 96 97
    """
    Here just return the first compatible implemention. 
    This will be improved by cost model in the future.
    """
98 99
    dist_op_impl_container = get_distributed_operator_impl_container(name)
    if dist_op_impl_container is None:
100 101
        return None, -1
    compatible_impls = []
102
    impls = dist_op_impl_container.get_impls()
103 104
    if fwd:
        for idx, impl in enumerate(impls):
105
            if impl.is_input_compatible(dist_op):
106 107 108
                compatible_impls.append((impl, idx))
    else:
        for idx, impl in enumerate(impls):
109
            if impl.is_output_compatible(dist_op):
110 111 112 113 114 115 116 117
                compatible_impls.append((impl, idx))

    if compatible_impls:
        best_compatible_impl, idx = compatible_impls[0]
    else:
        best_compatible_impl, idx = None, -1

    return best_compatible_impl, idx
118 119


J
JZ-LIANG 已提交
120 121 122 123 124 125 126 127
def is_parameter_related(varname, block):
    if ".cast_fp" in varname:
        varname = varname[:varname.index(".cast_fp")]
    assert block.has_var(varname)
    var = block.var(varname)
    return var.is_parameter


Z
zhaoyingli 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
def infer_shape(block, src_var, src_var_dist_attr, op_input_dist_attr):
    var_shape = block.var(src_var.name).shape
    var_topoloy = src_var_dist_attr.process_mesh.topology
    var_dims_mapping = src_var_dist_attr.dims_mapping

    complete_shape = []
    for idx, shape in enumerate(var_shape):
        if var_dims_mapping[idx] == -1:
            complete_shape.append(shape)
        else:
            new_shape = shape * var_topoloy[var_dims_mapping[idx]]
            complete_shape.append(new_shape)

    exact_shape = []
    input_topology = op_input_dist_attr.process_mesh.topology
    input_dims_mapping = op_input_dist_attr.dims_mapping
    for idx, shape in enumerate(complete_shape):
        if input_dims_mapping[idx] == -1:
            exact_shape.append(shape)
        else:
            new_shape = shape // input_topology[input_dims_mapping[idx]]
            exact_shape.append(new_shape)

    return exact_shape
152 153 154 155 156 157 158 159 160 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 186 187 188 189 190 191 192 193 194


def set_comm_op_dist_attr_for_program(new_op, process_mesh, tensor_dist_attr,
                                      ctx):
    assert process_mesh is not None
    assert tensor_dist_attr is not None

    new_op_dist_attr = OperatorDistributedAttribute()
    new_op_dist_attr.process_mesh = process_mesh
    for input_varname in new_op.desc.input_arg_names():
        new_op_dist_attr.set_input_dist_attr(input_varname, tensor_dist_attr)
    for output_varname in new_op.desc.output_arg_names():
        new_op_dist_attr.set_output_dist_attr(output_varname, tensor_dist_attr)
    ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr)


def naive_copy_op_dist_attr_for_program(new_op, ref_op, ctx):

    ref_dist_attr = ctx.get_op_dist_attr_for_program(ref_op)
    new_op_dist_attr = OperatorDistributedAttribute()
    new_op_dist_attr.process_mesh = ref_dist_attr.process_mesh

    for input_name in ref_op.input_names:
        assert input_name in new_op.input_names
        assert len(ref_op.input(input_name)) == 1
        assert len(new_op.input(input_name)) == 1

        ref_tensor_dist_attr = ref_dist_attr.get_input_dist_attr(
            ref_op.input(input_name)[0])
        new_op_dist_attr.set_input_dist_attr(
            new_op.input(input_name)[0], ref_tensor_dist_attr)

    for output_name in ref_op.output_names:
        assert output_name in new_op.output_names
        assert len(ref_op.output(output_name)) == 1
        assert len(new_op.output(output_name)) == 1

        ref_tensor_dist_attr = ref_dist_attr.get_output_dist_attr(
            ref_op.output(output_name)[0])
        new_op_dist_attr.set_output_dist_attr(
            new_op.output(output_name)[0], ref_tensor_dist_attr)

    ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr)