completion.py 41.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 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 copy import deepcopy

from paddle.fluid import core
from paddle.fluid import framework

from .utils import compute_compatible_process_mesh
from .utils import compute_compatible_dim_mapping
from .utils import compute_compatible_dims_mapping
23
from .utils import print_program_with_dist_attr
24
from .operators import find_best_compatible_distributed_operator_impl
25 26 27 28 29
from .dist_context import get_default_distributed_context
from .dist_tensor import DistributedTensor
from .dist_op import DistributedOperator
from .dist_attribute import TensorDistributedAttribute
from .dist_attribute import OperatorDistributedAttribute
30
from paddle.distributed.fleet.meta_optimizers.common import OpRole
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

ELEMENTWISE_LIKE_OP_LIST = ["elementwise_add", "gelu", "dropout", "cast"]


def is_elementwise_like_op(op_type):
    if op_type in ELEMENTWISE_LIKE_OP_LIST:
        return True
    else:
        return False


def update_tensor_node_process_mesh(dist_context, tensor_node, fwd=True):
    """
    Update tensor's process mesh by using its predecessor's process mesh if in the forward direction, 
    and by using its successor's process mesh if in the backward direction. Note: only the equal 
    process meshes are compatible for now.
    """
    changed = False
49
    tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(tensor_node)
50 51
    if tensor_dist_attr.is_annotated("process_mesh"):
        return changed
52
    tensor_process_mesh = tensor_dist_attr.process_mesh
53 54 55 56
    if fwd:
        inputs_process_meshes = []
        for pred_op_node in tensor_node.inputs:
            if pred_op_node.op() is not None:
57
                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
58
                    pred_op_node)
59
                op_process_mesh = op_dist_attr.process_mesh
60 61 62 63
                inputs_process_meshes.append(op_process_mesh)
        compatible_process_mesh = compute_compatible_process_mesh(
            inputs_process_meshes)
        if compatible_process_mesh is not None and tensor_process_mesh is None:
64
            tensor_dist_attr.process_mesh = compatible_process_mesh
65 66 67 68 69
            changed = True
    else:
        outputs_process_meshes = []
        for succ_op_node in tensor_node.outputs:
            if succ_op_node.op() is not None:
70
                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
71
                    succ_op_node)
72
                op_process_mesh = op_dist_attr.process_mesh
73 74 75 76
                outputs_process_meshes.append(op_process_mesh)
        compatible_process_mesh = compute_compatible_process_mesh(
            outputs_process_meshes)
        if compatible_process_mesh is not None and tensor_process_mesh is None:
77
            tensor_dist_attr.process_mesh = compatible_process_mesh
78 79 80 81 82 83 84 85 86 87 88
            changed = True
    return changed


def update_op_node_process_mesh(dist_context, op_node, fwd=True):
    """
    Update op's process mesh by using its predecessor's process mesh if in the forward direction, 
    and by using its successor's process mesh if in the backward direction. Note: only the equal 
    process meshes are compatible for now.
    """
    changed = False
89
    op_dist_attr = dist_context.get_op_dist_attr_for_graph(op_node)
90 91
    if op_dist_attr.is_annotated("process_mesh"):
        return changed
92
    op_process_mesh = op_dist_attr.process_mesh
93 94 95 96
    if fwd:
        inputs_process_meshes = []
        for tensor_node in op_node.inputs:
            if tensor_node.var() is not None:
97
                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
98
                    tensor_node)
99
                tensor_process_mesh = tensor_dist_attr.process_mesh
100 101 102 103
                inputs_process_meshes.append(tensor_process_mesh)
        compatible_process_mesh = compute_compatible_process_mesh(
            inputs_process_meshes)
        if compatible_process_mesh is not None and op_process_mesh is None:
104
            op_dist_attr.process_mesh = compatible_process_mesh
105 106 107 108 109
            changed = True
    else:
        outputs_process_meshes = []
        for tensor_node in op_node.outputs:
            if tensor_node.var() is not None:
110
                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
111
                    tensor_node)
112
                tensor_process_mesh = tensor_dist_attr.process_mesh
113 114 115 116
                outputs_process_meshes.append(tensor_process_mesh)
        compatible_process_mesh = compute_compatible_process_mesh(
            outputs_process_meshes)
        if compatible_process_mesh is not None and op_process_mesh is None:
117
            op_dist_attr.process_mesh = compatible_process_mesh
118 119 120 121
            changed = True
    return changed


122
def update_op_dims_mapping_by_default_dist_impl(dist_context, op_node):
123 124
    """Each operator has a default distributed operator, only allowed to be sharded in batch dimension."""
    changed = False
125 126 127 128 129
    if (not op_node.is_op()) or (op_node.op() is None):
        return False
    op_desc = op_node.op()
    dist_op = dist_context.get_dist_op_for_graph(op_node)
    op_dist_attr = dist_op.dist_attr
130 131 132 133 134 135 136 137 138
    # The following statement will be replaced by a more elegent way
    if op_desc.type() == "shape" or op_desc.type() == "slice":
        return False
    output_names = op_desc.output_names()
    xshape_arg_names = []
    if "XShape" in output_names:
        xshape_arg_names = op_desc.output("XShape")
    batch_dim_mappings = []
    for arg_name in op_desc.input_arg_names():
139 140
        serial_tensor = dist_op.get_serial_input(arg_name)
        if serial_tensor.is_parameter:
141 142 143 144 145 146 147 148 149
            continue
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
        if len(dims_mapping) > 1:
            for idx, mapping in enumerate(dims_mapping[1:]):
                assert mapping == -1, \
                    "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part."\
                        .format(op_desc.type(), idx, mapping)
        batch_dim_mappings.append(dims_mapping[0])
    for arg_name in op_desc.output_arg_names():
150 151
        serial_tensor = dist_op.get_serial_output(arg_name)
        if serial_tensor.is_parameter:
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            continue
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if arg_name not in xshape_arg_names:
            if len(dims_mapping) > 1:
                for idx, mapping in enumerate(dims_mapping[1:]):
                    assert mapping == -1, \
                        "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part."\
                            .format(op_desc.type(), idx, mapping)
            batch_dim_mappings.append(dims_mapping[0])
        else:
            assert dims_mapping[0] == -1, \
                "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension 0 is sharded by {} part."\
                    .format(op_desc.type(), mapping)
            if len(dims_mapping) > 2:
                for idx, mapping in enumerate(dims_mapping[2:]):
                    assert mapping == -1, \
                        "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension {} is sharded by {} part."\
                            .format(op_desc.type(), idx, mapping)
            batch_dim_mappings.append(dims_mapping[1])

    compatible_dim_mapping = compute_compatible_dim_mapping(batch_dim_mappings)
    assert compatible_dim_mapping is not None, "There is no compatible dim mapping."
    for arg_name in op_desc.input_arg_names():
175 176
        serial_tensor = dist_op.get_serial_input(arg_name)
        if serial_tensor.is_parameter:
177 178 179 180 181 182
            continue
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
        if compatible_dim_mapping != dims_mapping[0]:
            dims_mapping[0] = compatible_dim_mapping
            changed = True
    for arg_name in op_desc.output_arg_names():
183 184
        serial_tensor = dist_op.get_serial_output(arg_name)
        if serial_tensor.is_parameter:
185 186 187 188 189 190 191 192 193 194 195 196 197 198
            continue
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if arg_name not in xshape_arg_names:
            if compatible_dim_mapping != dims_mapping[0]:
                dims_mapping[0] = compatible_dim_mapping
                changed = True
        else:
            if compatible_dim_mapping != dims_mapping[1]:
                dims_mapping[1] = compatible_dim_mapping
                changed = True

    return changed


199
def update_op_dims_mapping_by_elementwise_like_dist_impl(dist_context, op_node):
200 201
    """Element-wise operator can be sharded in any way (but should take care of broadcasting)."""
    changed = False
202 203 204 205
    if (not op_node.is_op()) or (op_node.op() is None):
        return False
    op_desc = op_node.op()
    op_dist_attr = dist_context.get_op_dist_attr_for_graph(op_node)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    input_arg_names = op_desc.input_arg_names()
    input_dims_mapping_dict = {}
    input_dims_mapping_lens = {}
    max_dims_mapping_len = -1
    for arg_name in input_arg_names:
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
        if max_dims_mapping_len < len(dims_mapping):
            max_dims_mapping_len = len(dims_mapping)
        input_dims_mapping_dict[arg_name] = dims_mapping
        input_dims_mapping_lens[arg_name] = len(dims_mapping)

    dims_mapping_list = []
    for arg_name in input_arg_names:
        if input_dims_mapping_lens[arg_name] < max_dims_mapping_len:
            new_dims_mapping = [-1 for _ in range(max_dims_mapping_len)]
            for i in range(input_dims_mapping_lens[arg_name]):
                new_idx = (max_dims_mapping_len -
                           input_dims_mapping_lens[arg_name]) + i
                new_dims_mapping[new_idx] = input_dims_mapping_dict[arg_name][i]
            dims_mapping_list.append(new_dims_mapping)
        else:
            dims_mapping_list.append(input_dims_mapping_dict[arg_name])
    output_arg_names = op_desc.output_arg_names()
    for arg_name in output_arg_names:
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        assert len(dims_mapping) == max_dims_mapping_len
        dims_mapping_list.append(dims_mapping)

    compatible_dims_mapping = compute_compatible_dims_mapping(dims_mapping_list)
    assert compatible_dims_mapping is not None, "There is no compatible dim mapping."

    for arg_name in input_arg_names:
        if input_dims_mapping_lens[arg_name] < max_dims_mapping_len:
            new_dims_mapping = [
                -1 for _ in range(input_dims_mapping_lens[arg_name])
            ]
            for i in range(input_dims_mapping_lens[arg_name]):
                new_idx = (max_dims_mapping_len -
                           input_dims_mapping_lens[arg_name]) + i
                new_dims_mapping[i] = compatible_dims_mapping[new_idx]
            if new_dims_mapping != input_dims_mapping_dict[arg_name]:
                op_dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping)
                changed = True
        else:
            if compatible_dims_mapping != input_dims_mapping_dict[arg_name]:
                op_dist_attr.set_input_dims_mapping(arg_name,
                                                    compatible_dims_mapping)
                changed = True

    for arg_name in output_arg_names:
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if compatible_dims_mapping != dims_mapping:
            op_dist_attr.set_output_dims_mapping(arg_name,
                                                 compatible_dims_mapping)
            changed = True

    return changed


def update_tensor_node_dims_mapping(dist_context, tensor_node, fwd=True):
    changed = False
    if (not tensor_node.is_var()) or (tensor_node.var() is None):
        return False
    tensor_desc = tensor_node.var()
271 272 273
    # Skip reader tensor
    if tensor_desc.type() == core.VarDesc.VarType.READER:
        return False
274
    tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(tensor_node)
275 276 277
    assert tensor_dist_attr is not None
    if tensor_dist_attr.is_annotated("dims_mapping"):
        return False
278
    tensor_dims_mapping = tensor_dist_attr.dims_mapping
279 280 281 282
    if fwd:
        dims_mapping_list = []
        for pred_op_node in tensor_node.inputs:
            if pred_op_node.op() is not None:
283 284 285 286
                if pred_op_node.op().type() == "create_py_reader" \
                    or pred_op_node.op().type() == "create_double_buffer_reader" \
                    or pred_op_node.op().type() == "read":
                    continue
287
                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
288 289 290 291 292 293 294 295 296
                    pred_op_node)
                op_dims_mapping = op_dist_attr.get_output_dims_mapping(
                    tensor_desc.name())
                dims_mapping_list.append(op_dims_mapping)
        dims_mapping_list.append(tensor_dims_mapping)
        compatible_dims_mapping = compute_compatible_dims_mapping(
            dims_mapping_list)
        if (compatible_dims_mapping is not None) and \
            (compatible_dims_mapping != tensor_dims_mapping):
297
            tensor_dist_attr.dims_mapping = compatible_dims_mapping
298 299 300 301 302
            changed = True
    else:
        dims_mapping_list = []
        for succ_op_node in tensor_node.outputs:
            if succ_op_node.op() is not None:
303 304 305 306
                if succ_op_node.op().type() == "create_py_reader" \
                    or succ_op_node.op().type() == "create_double_buffer_reader" \
                    or succ_op_node.op().type() == "read":
                    continue
307
                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
308 309 310 311 312 313 314 315 316
                    succ_op_node)
                op_dims_mapping = op_dist_attr.get_input_dims_mapping(
                    tensor_desc.name())
                dims_mapping_list.append(op_dims_mapping)
        dims_mapping_list.append(tensor_dims_mapping)
        compatible_dims_mapping = compute_compatible_dims_mapping(
            dims_mapping_list)
        if (compatible_dims_mapping is not None) and \
            (compatible_dims_mapping != tensor_dims_mapping):
317
            tensor_dist_attr.dims_mapping = compatible_dims_mapping
318 319 320 321 322 323 324 325
            changed = True
    return changed


def update_op_node_dims_mapping(dist_context, op_node, fwd=True):
    changed = False
    if (not op_node.is_op()) or (op_node.op() is None):
        return False
326
    # Skip reader op
327
    op_desc = op_node.op()
328 329 330 331
    if op_desc.type() == "create_py_reader" \
        or op_desc.type() == "create_double_buffer_reader" \
        or op_desc.type() == "read":
        return False
332 333
    dist_op = dist_context.get_dist_op_for_graph(op_node)
    op_dist_attr = dist_op.dist_attr
334 335 336
    if fwd:
        for tensor_node in op_node.inputs:
            if tensor_node.var() is not None:
337 338
                if tensor_node.var().type() == core.VarDesc.VarType.READER:
                    continue
339 340 341 342
                tensor_desc = tensor_node.var()
                if op_dist_attr.is_annotated_input_dims_mapping(
                        tensor_desc.name()):
                    continue
343
                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
344
                    tensor_node)
345
                tensor_dims_mapping = tensor_dist_attr.dims_mapping
346 347 348 349 350 351 352 353 354 355
                op_dims_mapping = op_dist_attr.get_input_dims_mapping(
                    tensor_desc.name())
                compatible_dims_mapping = compute_compatible_dims_mapping(
                    [op_dims_mapping, tensor_dims_mapping])
                if (compatible_dims_mapping is not None) and \
                    (compatible_dims_mapping != op_dims_mapping):
                    op_dist_attr.set_input_dims_mapping(tensor_desc.name(),
                                                        compatible_dims_mapping)
                    changed = True
        # Find the most compatible implemenetations from the distributed operator
356 357 358 359 360 361 362 363 364 365 366 367
        op_dist_impl = find_best_compatible_distributed_operator_impl(
            dist_op, fwd=True)
        assert op_dist_impl is not None, "Cannot find the dist op implementation."
        dim_changed = op_dist_impl.update_dims_mapping(dist_op)
        if dim_changed:
            changed = True
        if op_dist_impl.is_auto_compatible(dist_op):
            if op_dist_impl.type == "elementwise":
                op_dist_attr.impl_type = "default"
            else:
                op_dist_attr.impl_type = op_dist_impl.type
            op_dist_attr.impl_idx = op_dist_impl.idx
368 369 370
    else:
        for tensor_node in op_node.outputs:
            if tensor_node.var() is not None:
371 372
                if tensor_node.var().type() == core.VarDesc.VarType.READER:
                    continue
373 374 375 376
                tensor_desc = tensor_node.var()
                if op_dist_attr.is_annotated_output_dims_mapping(
                        tensor_desc.name()):
                    continue
377
                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
378
                    tensor_node)
379
                tensor_dims_mapping = tensor_dist_attr.dims_mapping
380 381 382 383 384 385 386 387 388 389
                op_dims_mapping = op_dist_attr.get_output_dims_mapping(
                    tensor_desc.name())
                compatible_dims_mapping = compute_compatible_dims_mapping(
                    [op_dims_mapping, tensor_dims_mapping])
                if (compatible_dims_mapping is not None) and \
                    (compatible_dims_mapping != op_dims_mapping):
                    op_dist_attr.set_output_dims_mapping(
                        tensor_desc.name(), compatible_dims_mapping)
                    changed = True
        # Find the most compatible implemenetations from the distributed operator
390 391 392 393 394 395 396 397 398 399 400 401
        op_dist_impl = find_best_compatible_distributed_operator_impl(
            dist_op, fwd=False)
        assert op_dist_impl is not None, "Cannot find the dist op implementation."
        dim_changed = op_dist_impl.update_dims_mapping(dist_op)
        if dim_changed:
            changed = True
        if op_dist_impl.is_auto_compatible(dist_op):
            if op_dist_impl.type == "elementwise":
                op_dist_attr.impl_type = "default"
            else:
                op_dist_attr.impl_type = op_dist_impl.type
            op_dist_attr.impl_idx = op_dist_impl.idx
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    return changed


def complete_annotation(program, dist_context=None):
    """ Complete annotation for the partial annotated program.

    Arguments:
        program: partial annotated program.
        dist_context: the distributed context is used to store distributed attributes for program.
            If not provided, the default one will be used.
    Returns:
        program: completed annotated program.
    """

    # Use the default distribted context for completeion if there is no one
    if dist_context is None:
        dist_context = get_default_distributed_context()
419 420 421
        dist_context.serial_program = program
    else:
        dist_context.serial_program = program
422

423
    # print_program_with_dist_attr(program, dist_context)
424

425 426
    # Initialize distributed attributes for all var and op node in program
    dist_context.init_dist_attr_for_program()
427 428

    # Initialize distributed attributes for all var and op node in graph
429
    dist_context.init_dist_attr_for_graph()
430

431
    # Complete process mesh for each node
432
    all_nodes = list(dist_context.serial_graph.all_nodes())
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

    def sort_key_fun(node):
        first = -1
        if node.is_op():
            first = 0
        else:
            first = 1
        second = -1
        if node.is_op() and node.op() is not None:
            second = node.op().id()
        if node.is_var() and node.var() is not None:
            second = node.var().id()
        return (first, second)

    all_nodes.sort(key=sort_key_fun)

449 450
    reach_fix_point = False
    while not reach_fix_point:
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        total_changed = False
        reach_fwd_fix_point = False
        reach_bwd_fix_point = False
        while not reach_fwd_fix_point:
            changed = False
            for node in all_nodes:
                if node.is_var() and node.var() is not None:
                    tensor_changed = update_tensor_node_process_mesh(
                        dist_context, node, fwd=True)
                    if tensor_changed:
                        changed = True
                if node.is_op() and node.op() is not None:
                    op_changed = update_op_node_process_mesh(
                        dist_context, node, fwd=True)
                    if op_changed:
                        changed = True
            if changed:
                reach_fwd_fix_point = False
                total_changed = True
            else:
                reach_fwd_fix_point = True
        while not reach_bwd_fix_point:
            changed = False
            for node in all_nodes:
                if node.is_var() and node.var() is not None:
                    tensor_changed = update_tensor_node_process_mesh(
                        dist_context, node, fwd=False)
                    if tensor_changed:
                        changed = True
                if node.is_op() and node.op() is not None:
                    op_changed = update_op_node_process_mesh(
                        dist_context, node, fwd=False)
                    if op_changed:
                        changed = True
            if changed:
                reach_bwd_fix_point = False
                total_changed = True
            else:
                reach_bwd_fix_point = True
        if total_changed:
491 492 493
            reach_fix_point = False
        else:
            reach_fix_point = True
494 495 496 497
            # Validation the completion of process meshes and should be moved to a proper location
            is_wrong = False
            for node in all_nodes:
                if node.is_var() and node.var() is not None:
498
                    tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
499
                        node)
500
                    if tensor_dist_attr.process_mesh is None:
501 502 503
                        msg_str = ""
                        for op_node in node.inputs:
                            if op_node.op() is not None:
504
                                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
505 506 507
                                    op_node)
                                msg_str += "{} [{}], ".format(
                                    op_node.op().type(),
508
                                    op_dist_attr.process_mesh)
509 510 511 512 513
                            else:
                                msg_str += "{} [{}], ".format(op_node.name(),
                                                              None)
                        for op_node in node.outputs:
                            if op_node.op() is not None:
514
                                op_dist_attr = dist_context.get_op_dist_attr_for_graph(
515 516 517
                                    op_node)
                                msg_str += "{} [{}], ".format(
                                    op_node.op().type(),
518
                                    op_dist_attr.process_mesh)
519 520 521 522 523 524 525 526
                            else:
                                msg_str += "{} [{}], ".format(op_node.name(),
                                                              None)
                        msg_str = "Cannot decide ProcessMesh of {} among {}. Please use shard_tensor api explicitly to annotate it".format(
                            node.var().name(), msg_str[:-2])
                        is_wrong = True
                        print(msg_str)
                if node.is_op() and node.op() is not None:
527 528
                    op_dist_attr = dist_context.get_op_dist_attr_for_graph(node)
                    if op_dist_attr.process_mesh is None:
529 530 531
                        msg_str = ""
                        for tensor_node in node.inputs:
                            if tensor_node.var() is not None:
532
                                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
533 534 535
                                    tensor_node)
                                msg_str += "{} [{}], ".format(
                                    tensor_node.var().name(),
536
                                    tensor_dist_attr.process_mesh)
537 538 539 540 541
                            else:
                                msg_str += "{} [{}], ".format(
                                    tensor_node.name(), None)
                        for tensor_node in node.outputs:
                            if tensor_node.var() is not None:
542
                                tensor_dist_attr = dist_context.get_tensor_dist_attr_for_graph(
543 544 545
                                    tensor_node)
                                msg_str += "{} [{}], ".format(
                                    tensor_node.var().name(),
546
                                    tensor_dist_attr.process_mesh)
547 548 549 550 551 552 553 554 555 556 557
                            else:
                                msg_str += "{} [{}], ".format(
                                    tensor_node.name(), None)
                        msg_str = "Cannot decide ProcessMesh of {} among {}. Please use shard_op api explicitly to annotate it".format(
                            node.op().type(), msg_str[:-2])
                        is_wrong = True
                        print(msg_str)
                if node.is_op() and node.op() is None:
                    print("op op is None", node.name())
            if is_wrong:
                assert False, "Cannot complete process_meshes of the program."
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

    # Complete dims_mapping for each node
    reach_fix_point = False
    while not reach_fix_point:
        changed = False
        for node in all_nodes:
            if node.is_var() and node.var() is not None:
                tensor_changed = update_tensor_node_dims_mapping(
                    dist_context, node, fwd=True)
                if tensor_changed:
                    changed = True
            if node.is_op() and node.op() is not None:
                op_changed = update_op_node_dims_mapping(
                    dist_context, node, fwd=True)
                if op_changed:
                    changed = True
        for node in reversed(all_nodes):
            if node.is_var() and node.var() is not None:
                tensor_changed = update_tensor_node_dims_mapping(
                    dist_context, node, fwd=False)
                if tensor_changed:
                    changed = True
            if node.is_op() and node.op() is not None:
                op_changed = update_op_node_dims_mapping(
                    dist_context, node, fwd=False)
                if op_changed:
                    changed = True
        if changed:
            reach_fix_point = False
        else:
            reach_fix_point = True

    # Copy the corresponding distributed attribute from graph to program
591 592
    dist_context.copy_dist_attr_from_graph_to_program()
    dist_context.clear_dist_info_for_graph()
593 594

    # Do the validation check and amend some completion
595 596 597 598
    dist_context.amend_dist_attr_for_program()

    # print_program_with_dist_attr(program, dist_context)
    dist_context.validate_dist_attr_for_program()
599 600

    return program
C
caozhou 已提交
601 602


603
def complete_backward_annotation(auto_parallel_main_prog, dist_context=None):
C
caozhou 已提交
604 605 606 607 608 609 610
    """Complete the annotation of vars and ops in the backward phase for parallel program."""

    def _is_grad_var_name(name):
        if "@GRAD" in name:
            return True
        return False

611 612 613 614 615 616 617 618 619 620 621 622 623 624
    def _get_forward_varname_from_grad_varname(grad_var_name):
        assert _is_grad_var_name(
            grad_var_name), "[{}] is not a grad varnme.".format(grad_var_name)
        return grad_var_name[:grad_var_name.find("@GRAD")]

    def _get_op_by_id(ops, id):
        for op in ops:
            if op.desc.id() == id:
                return op
        return None

    if dist_context is None:
        dist_context = get_default_distributed_context()

625
    first_backward_op_idx = -1
C
caozhou 已提交
626
    for idx, op in enumerate(auto_parallel_main_prog.global_block().ops):
627 628 629 630
        if int(op.attr('op_role')) == int(
                int(core.op_proto_and_checker_maker.OpRole.Backward) | int(
                    core.op_proto_and_checker_maker.OpRole.Loss)):
            assert op.type == "fill_constant"
631
            first_backward_op_idx = idx
632 633
            break

634
    assert first_backward_op_idx >= 0, "No backward procedure found in this program."
C
caozhou 已提交
635 636 637

    ops = list(auto_parallel_main_prog.global_block().ops)
    vars = auto_parallel_main_prog.global_block().vars
638
    dist_op_context = dist_context.dist_op_context
639

640
    for idx in range(first_backward_op_idx, len(ops)):
641 642

        # complete the initial grad loss op
643 644 645 646 647 648 649 650 651 652 653
        if idx == first_backward_op_idx:
            assert ops[idx].type == "fill_constant"
            assert len(
                ops[idx].input_arg_names
            ) == 0, "first backward op should has only ONE output, but got [{}]".format(
                len(ops[idx].input_arg_names))
            assert len(
                ops[idx].output_arg_names
            ) == 1, "first backward op should has only ONE output, but got [{}]".format(
                len(ops[idx].output_arg_names))

C
caozhou 已提交
654
            grad_var = vars[ops[idx].output_arg_names[0]]
655 656
            forward_var_name = _get_forward_varname_from_grad_varname(
                grad_var.name)
C
caozhou 已提交
657
            forward_var = vars[forward_var_name]
658 659

            # TODO complete other attribte for grad var
660 661 662 663 664 665 666 667 668 669 670 671 672 673
            tensor_dist_attr = TensorDistributedAttribute()
            process_mesh = dist_context.get_tensor_dist_attr_for_program(
                forward_var).process_mesh
            dims_mapping = dist_context.get_tensor_dist_attr_for_program(
                forward_var).dims_mapping
            tensor_dist_attr.dims_mapping = dims_mapping
            tensor_dist_attr.process_mesh = process_mesh
            dist_context.set_tensor_dist_attr_for_program(grad_var,
                                                          tensor_dist_attr)

            op_dist_attr = OperatorDistributedAttribute()
            op_dist_attr.process_mesh = process_mesh
            op_dist_attr.set_output_dims_mapping(grad_var.name, dims_mapping)
            dist_context.set_op_dist_attr_for_program(ops[idx], op_dist_attr)
C
caozhou 已提交
674 675
            continue

676
        # complete the annotation of grad op (xxx_grad op or sum op)
677
        # xxx_grad op will have a corresponding forward op in grad_op_id_to_op_id
678
        grad_op = ops[idx]
679
        if grad_op.desc.id() in dist_op_context.grad_op_id_to_op_id:
680 681
            # TODO support the case where one forward op corresponding to multiple xxx_grad op
            forward_op = _get_op_by_id(
682
                ops[:first_backward_op_idx],
683
                dist_op_context.grad_op_id_to_op_id[grad_op.desc.id()])
684 685 686
            assert forward_op is not None

            # op dist attr
687
            forward_op_dist_attr = dist_context.get_op_dist_attr_for_program(
688
                forward_op)
689 690 691
            forward_op_process_mesh = forward_op_dist_attr.process_mesh
            grad_op_dist_attr = OperatorDistributedAttribute()
            grad_op_dist_attr.process_mesh = forward_op_process_mesh
692 693

            # var 
Z
zhaoyingli 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
            for input_name in grad_op.input_arg_names:
                input_var = vars[input_name]
                ref_dims_mapping = None
                if "@GRAD" in input_name:
                    forward_name = _get_forward_varname_from_grad_varname(
                        input_name)
                    ref_dims_mapping = forward_op_dist_attr.get_output_dims_mapping(
                        forward_name)
                else:
                    if forward_op_dist_attr.get_input_dims_mapping(input_name):
                        ref_dims_mapping = forward_op_dist_attr.get_input_dims_mapping(
                            input_name)
                    else:
                        ref_dims_mapping = forward_op_dist_attr.get_output_dims_mapping(
                            input_name)

                assert ref_dims_mapping is not None, "[{}] 's dims mapping is NONE".format(
                    input_var.name)
                grad_op_dist_attr.set_input_dims_mapping(input_name,
                                                         ref_dims_mapping)

715 716 717 718 719
            for output_name in grad_op.desc.output_names():
                assert len(grad_op.desc.output(output_name)) in [0, 1]
                if _is_grad_var_name(output_name):
                    input_name = _get_forward_varname_from_grad_varname(
                        output_name)
720
                else:
721 722 723 724 725
                    assert grad_op.type in [
                        "cast", "c_identity", "c_allreduce_sum"
                    ]
                    input_name = "X"
                assert input_name in forward_op.desc.input_names(
Z
zhaoyingli 已提交
726
                ), "var [{}] in op [{}]'s output but could not find [{}] in its forward op".format(
727 728 729 730
                    output_name, grad_op.type, input_name)
                if len(grad_op.desc.output(output_name)) == 1:
                    # tensor dist attr
                    output_var = vars[grad_op.desc.output(output_name)[0]]
Z
zhaoyingli 已提交
731 732 733 734 735
                    forward_name = _get_forward_varname_from_grad_varname(
                        output_var.name)
                    ref_dims_mapping = forward_op_dist_attr.get_input_dims_mapping(
                        forward_name)

736 737 738 739 740
                    output_var_dist_attr = TensorDistributedAttribute()
                    output_var_dist_attr.dims_mapping = ref_dims_mapping
                    output_var_dist_attr.process_mesh = forward_op_process_mesh
                    dist_context.set_tensor_dist_attr_for_program(
                        output_var, output_var_dist_attr)
741

742 743
                    grad_op_dist_attr.set_output_dims_mapping(output_var.name,
                                                              ref_dims_mapping)
744

745 746
            dist_context.set_op_dist_attr_for_program(grad_op,
                                                      grad_op_dist_attr)
747

748
        # only sum op for merge mutiple version grad has no a corresponding mapping in grad_op_id_to_op_id
749 750 751 752 753 754 755 756 757
        else:
            assert grad_op.type == "sum", "got unexpect op [{}]".format(
                str(grad_op.type))
            assert all(map(_is_grad_var_name, grad_op.input_arg_names))
            assert len(grad_op.output_arg_names) == 1

            ref_forward_var_name = _get_forward_varname_from_grad_varname(
                grad_op.output_arg_names[0])
            forward_var = vars[ref_forward_var_name]
758 759 760 761
            ref_forward_var_dims_mapping = dist_context.get_tensor_dist_attr_for_program(
                forward_var).dims_mapping
            ref_forward_var_process_mesh = dist_context.get_tensor_dist_attr_for_program(
                forward_var).process_mesh
762 763

            # output
764 765 766 767 768
            tensor_dist_attr = TensorDistributedAttribute()
            tensor_dist_attr.dims_mapping = ref_forward_var_dims_mapping
            tensor_dist_attr.process_mesh = ref_forward_var_process_mesh
            dist_context.set_tensor_dist_attr_for_program(
                vars[grad_op.output_arg_names[0]], tensor_dist_attr)
769 770

            # op
771 772
            grad_op_dist_attr = OperatorDistributedAttribute()
            grad_op_dist_attr.process_mesh = ref_forward_var_process_mesh
773 774 775
            for var_name in grad_op.input_arg_names:
                assert _get_forward_varname_from_grad_varname(
                    var_name) == ref_forward_var_name
776
                grad_op_dist_attr.set_input_dims_mapping(
777
                    var_name, ref_forward_var_dims_mapping)
778

779 780 781 782
            grad_op_dist_attr.set_output_dims_mapping(
                grad_op.output_arg_names[0], ref_forward_var_dims_mapping)
            dist_context.set_op_dist_attr_for_program(grad_op,
                                                      grad_op_dist_attr)
783 784 785 786 787 788 789 790 791 792


def complete_update_annotation(auto_parallel_main_prog, dist_context):
    """Complete the annotation of vars and ops in the update phase for parallel program."""

    if dist_context is None:
        dist_context = get_default_distributed_context()

    ops = list(auto_parallel_main_prog.global_block().ops)
    vars = auto_parallel_main_prog.global_block().vars
793
    learning_rate_completed = False
794 795 796 797 798

    for idx in range(len(ops)):

        # complete the annotation of the optimizer op.
        # TODO to add attribute for moment var
799 800
        op = ops[idx]
        if int(op.attr('op_role')) == int(OpRole.Optimize):
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
            if op.type == "clip_by_norm":

                param_grad = vars[op.input("X")[0]]
                param_grad_dist_attr = dist_context.get_tensor_dist_attr_for_program(
                    param_grad)
                assert param_grad_dist_attr is not None
                ref_process_mesh = param_grad_dist_attr.process_mesh
                ref_dims_mapping = param_grad_dist_attr.dims_mapping

                out = vars[op.output("Out")[0]]
                out_dist_attr = TensorDistributedAttribute()
                out_dist_attr.process_mesh = ref_process_mesh
                out_dist_attr.dims_mapping = ref_dims_mapping
                dist_context.set_tensor_dist_attr_for_program(out,
                                                              out_dist_attr)

                op_dist_attr = OperatorDistributedAttribute()
                op_dist_attr.process_mesh = ref_process_mesh
                op_dist_attr.set_input_dist_attr(param_grad.name,
                                                 param_grad_dist_attr)
                op_dist_attr.set_output_dist_attr(out.name, out_dist_attr)
                dist_context.set_op_dist_attr_for_program(op, op_dist_attr)
823 824 825

            if "Grad" in op.input_names and "Param" in ops[idx].input_names:
                assert len(op.input(
826
                    "Param")) == 1, "Only support one-to-one now."
827
                assert len(op.input(
828
                    "Grad")) == 1, "Only support one-to-one now."
829 830 831
                param = vars[op.input("Param")[0]]
                grad_var = vars[op.input("Grad")[0]]

832
                param_dist_attr = dist_context.get_tensor_dist_attr_for_program(
833 834
                    param)
                assert param_dist_attr is not None
835 836
                ref_process_mesh = dist_context.get_tensor_dist_attr_for_program(
                    param).process_mesh
837
                assert ref_process_mesh is not None
838 839
                ref_dims_mapping = dist_context.get_tensor_dist_attr_for_program(
                    param).dims_mapping
840
                assert ref_dims_mapping is not None
841 842 843 844 845 846 847 848
                op_dist_attr = OperatorDistributedAttribute()
                op_dist_attr.process_mesh = ref_process_mesh
                op_dist_attr.set_input_dims_mapping(grad_var.name,
                                                    ref_dims_mapping)
                op_dist_attr.set_input_dims_mapping(param.name,
                                                    ref_dims_mapping)
                op_dist_attr.set_output_dims_mapping(param.name,
                                                     ref_dims_mapping)
849
                learning_var = vars[op.input("LearningRate")[0]]
850 851
                op_dist_attr.set_input_dims_mapping(learning_var.name, [-1])
                op_dist_attr.set_output_dims_mapping(learning_var.name, [-1])
852 853 854

                if not learning_rate_completed:
                    learning_rate_completed = True
855 856 857 858 859
                    var_dist_attr = TensorDistributedAttribute()
                    var_dist_attr.process_mesh = ref_process_mesh
                    var_dist_attr.dims_mapping = [-1]
                    dist_context.set_tensor_dist_attr_for_program(learning_var,
                                                                  var_dist_attr)
860 861 862 863 864 865 866 867 868 869 870 871

                for input_name in op.desc.input_names():

                    if input_name in [
                            'Param', 'Grad', 'LearningRate', "SkipUpdate",
                            "Beta1Tensor", "Beta2Tensor", "EpsilonTensor",
                            "MasterParam"
                    ]:
                        continue

                    assert len(op.desc.input(input_name)) == 1
                    input_var = vars[op.desc.input(input_name)[0]]
872
                    input_var_attr = TensorDistributedAttribute()
873 874

                    if "Beta1Pow" in input_name or "Beta2Pow" in input_name:
875 876 877 878 879
                        input_var_attr.dims_mapping = [-1]
                        op_dist_attr.set_input_dims_mapping(input_var.name,
                                                            [-1])
                        op_dist_attr.set_output_dims_mapping(input_var.name,
                                                             [-1])
880 881
                    else:
                        assert "Moment" in input_name
882 883 884 885 886 887 888 889
                        input_var_attr.dims_mapping = ref_dims_mapping
                        op_dist_attr.set_input_dims_mapping(input_var.name,
                                                            ref_dims_mapping)
                        op_dist_attr.set_output_dims_mapping(input_var.name,
                                                             ref_dims_mapping)

                    input_var_attr.process_mesh = ref_process_mesh
                    dist_context.set_tensor_dist_attr_for_program(
890 891
                        input_var, input_var_attr)

892
                dist_context.set_op_dist_attr_for_program(op, op_dist_attr)
893
                continue