completion.py 84.5 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
import copy
16
import logging
17

18
from paddle.distributed.fleet.meta_optimizers.common import OpRole
19
from paddle.framework import core
20

21
from .dist_attribute import OperatorDistAttr, TensorDistAttr
22
from .dist_context import _node_id
23
from .operators import find_compatible_distributed_operator_impls
24
from .process_group import get_world_process_group
25
from .process_mesh import ProcessMesh, compute_compatible_process_mesh
26 27 28 29 30 31
from .utils import (
    __no_shape_var_type__,
    get_logger,
    is_gradient_clip_op,
    is_naive_data_parallel,
)
32 33


34 35 36 37
def compute_compatible_dim_mapping(dim_mapping_list):
    """Compute the compatible dim mapping given a list of dim mapping."""
    if not dim_mapping_list:
        return None
38

39
    def _compute_compatible_dim_mapping_of_two(dm1, dm2):
40 41 42 43 44 45 46 47 48 49
        if dm1 == -1:
            return True, dm2
        if dm2 == -1:
            return True, dm1
        if dm1 == dm2:
            return True, dm1
        return False, None

    compatible_result = -1
    for mapping in dim_mapping_list:
50
        compatible, compatible_result = _compute_compatible_dim_mapping_of_two(
51 52
            compatible_result, mapping
        )
53 54 55 56 57 58 59
        if not compatible:
            return None
    return compatible_result


def compute_compatible_dims_mapping(dims_mapping_list):
    """Compute the compatible dims mapping given a list of dims mapping.
60
    Each of dims mapping is also a list.
61
    """
62 63 64 65 66 67 68 69 70 71 72
    if not dims_mapping_list:
        return None
    length = len(dims_mapping_list[0])
    for dims_mapping in dims_mapping_list:
        if dims_mapping is None:
            return None
        if len(dims_mapping) != length:
            return None
    compatible_result = []
    for dim_mappings in zip(*dims_mapping_list):
        compatible_dim_mapping = compute_compatible_dim_mapping(
73 74
            list(dim_mappings)
        )
75 76 77 78 79 80
        if compatible_dim_mapping is None:
            return None
        compatible_result.append(compatible_dim_mapping)
    return compatible_result


81 82 83 84 85 86
def merge_process_mesh_two(pm1, pm2):
    process_set1 = set()
    process_set2 = set()
    if pm1 is None and pm2 is None:
        return None
    if pm1 is not None:
87
        process_set1 = set(pm1.process_ids)
88
    if pm2 is not None:
89
        process_set2 = set(pm2.process_ids)
90 91 92 93 94
    merged_process_set = process_set1.union(process_set2)
    merged_process_mesh = ProcessMesh(list(merged_process_set))
    return merged_process_mesh


95 96 97 98
def _validate_dims_mapping(dims_mapping, process_mesh):
    if dims_mapping is None:
        return False
    for i in range(len(dims_mapping)):
99
        if dims_mapping[i] < -1 or dims_mapping[i] >= len(process_mesh.shape):
100
            return False
101
    for i in range(len(process_mesh.shape)):
102 103 104 105 106
        if dims_mapping.count(i) > 1:
            return False
    return True


107 108 109 110
class Completer:
    def __init__(self, dist_context):
        assert dist_context is not None
        self._dist_context = dist_context
111
        self._has_prepared = False
112
        self._logger = get_logger(logging.INFO, "Completer")
113 114 115 116 117 118 119

    def _update_tensor_node_dims_mapping(self, 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()
        # Skip reader tensor
Z
zhaoyingli 已提交
120
        if tensor_desc.type() in __no_shape_var_type__:
121 122
            return False
        tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph(
123 124
            tensor_node
        )
125 126 127 128 129 130 131 132
        assert tensor_dist_attr is not None
        if tensor_dist_attr.is_annotated("dims_mapping"):
            return False
        tensor_dims_mapping = tensor_dist_attr.dims_mapping
        if fwd:
            dims_mapping_list = []
            for pred_op_node in tensor_node.inputs:
                if pred_op_node.op() is not None:
133 134 135 136 137 138
                    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"
                    ):
139
                        continue
140 141 142 143 144 145 146 147 148
                    op_dist_attr = (
                        self._dist_context.get_op_dist_attr_for_graph(
                            pred_op_node
                        )
                    )
                    if (
                        op_dist_attr.process_mesh
                        == tensor_dist_attr.process_mesh
                    ):
149
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
150 151
                            tensor_desc.name()
                        )
152 153 154
                        dims_mapping_list.append(op_dims_mapping)
            dims_mapping_list.append(tensor_dims_mapping)
            compatible_dims_mapping = compute_compatible_dims_mapping(
155 156 157 158 159
                dims_mapping_list
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, tensor_dist_attr.process_mesh
            ):
160
                return False
161 162 163
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != tensor_dims_mapping
            ):
164
                tensor_dist_attr.dims_mapping = compatible_dims_mapping
165 166
                changed = True
        else:
167 168 169
            dims_mapping_list = []
            for succ_op_node in tensor_node.outputs:
                if succ_op_node.op() is not None:
170 171 172 173 174 175
                    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"
                    ):
176
                        continue
177 178 179 180 181 182 183 184 185
                    op_dist_attr = (
                        self._dist_context.get_op_dist_attr_for_graph(
                            succ_op_node
                        )
                    )
                    if (
                        op_dist_attr.process_mesh
                        == tensor_dist_attr.process_mesh
                    ):
186
                        op_dims_mapping = op_dist_attr.get_input_dims_mapping(
187 188
                            tensor_desc.name()
                        )
189 190 191
                        dims_mapping_list.append(op_dims_mapping)
            dims_mapping_list.append(tensor_dims_mapping)
            compatible_dims_mapping = compute_compatible_dims_mapping(
192 193 194 195 196
                dims_mapping_list
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, tensor_dist_attr.process_mesh
            ):
197
                return False
198 199 200
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != tensor_dims_mapping
            ):
201
                tensor_dist_attr.dims_mapping = compatible_dims_mapping
202
                changed = True
203
        return changed
204

205 206 207 208 209 210
    def _update_op_node_dims_mapping(self, op_node, fwd=True):
        changed = False
        if (not op_node.is_op()) or (op_node.op() is None):
            return False
        # Skip reader op
        op_desc = op_node.op()
211 212 213 214 215 216
        if (
            op_desc.type() == "create_py_reader"
            or op_desc.type() == "create_double_buffer_reader"
            or op_desc.type() == "while"
            or op_desc.type() == "read"
        ):
217 218 219
            return False
        dist_op = self._dist_context.get_dist_op_for_graph(op_node)
        op_dist_attr = dist_op.dist_attr
220
        original_op_dist_attr = copy.deepcopy(op_dist_attr)
221 222
        if fwd:
            for tensor_node in op_node.inputs:
223
                if tensor_node.is_var() and tensor_node.var() is not None:
224 225 226 227
                    if tensor_node.var().type() == core.VarDesc.VarType.READER:
                        continue
                    tensor_desc = tensor_node.var()
                    if op_dist_attr.is_annotated_input_dims_mapping(
228 229
                        tensor_desc.name()
                    ):
230
                        continue
231 232 233 234 235 236 237 238 239
                    tensor_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_graph(
                            tensor_node
                        )
                    )
                    if (
                        op_dist_attr.process_mesh
                        == tensor_dist_attr.process_mesh
                    ):
240 241
                        tensor_dims_mapping = tensor_dist_attr.dims_mapping
                        op_dims_mapping = op_dist_attr.get_input_dims_mapping(
242 243 244 245 246 247 248
                            tensor_desc.name()
                        )
                        compatible_dims_mapping = (
                            compute_compatible_dims_mapping(
                                [op_dims_mapping, tensor_dims_mapping]
                            )
                        )
249
                        if not _validate_dims_mapping(
250 251
                            compatible_dims_mapping, op_dist_attr.process_mesh
                        ):
252
                            continue
253 254 255
                        if (compatible_dims_mapping is not None) and (
                            compatible_dims_mapping != op_dims_mapping
                        ):
256
                            op_dist_attr.set_input_dims_mapping(
257 258
                                tensor_desc.name(), compatible_dims_mapping
                            )
259 260
                            changed = True
            # Find the most compatible implemenetations from the distributed operator
261 262 263
            op_dist_impls = find_compatible_distributed_operator_impls(
                dist_op, fwd=True
            )
264 265 266 267 268 269 270 271
            if op_dist_impls is not None:
                not_compatible = True
                backup_op_dist_attr = copy.deepcopy(op_dist_attr)
                backup_changed = changed
                for op_dist_impl in op_dist_impls:
                    dim_changed = op_dist_impl.update_dims_mapping(dist_op)
                    if dim_changed:
                        changed = True
272 273 274 275
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
276 277 278 279 280 281 282 283
                        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_type = op_dist_impl.type
                        op_dist_attr.impl_idx = op_dist_impl.idx
                        not_compatible = False
                        break
284
                    else:
285 286 287 288 289 290 291 292
                        dist_op.dist_attr = backup_op_dist_attr
                        changed = backup_changed
                if not_compatible:
                    dist_op.dist_attr = original_op_dist_attr
                    changed = False
            else:
                dist_op.dist_attr = original_op_dist_attr
                changed = False
293
        else:
294
            for tensor_node in op_node.outputs:
295
                if tensor_node.is_var() and tensor_node.var() is not None:
296 297 298 299
                    if tensor_node.var().type() == core.VarDesc.VarType.READER:
                        continue
                    tensor_desc = tensor_node.var()
                    if op_dist_attr.is_annotated_output_dims_mapping(
300 301
                        tensor_desc.name()
                    ):
302
                        continue
303 304 305 306 307 308 309 310 311
                    tensor_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_graph(
                            tensor_node
                        )
                    )
                    if (
                        op_dist_attr.process_mesh
                        == tensor_dist_attr.process_mesh
                    ):
312 313
                        tensor_dims_mapping = tensor_dist_attr.dims_mapping
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
314 315 316 317 318 319 320
                            tensor_desc.name()
                        )
                        compatible_dims_mapping = (
                            compute_compatible_dims_mapping(
                                [op_dims_mapping, tensor_dims_mapping]
                            )
                        )
321
                        if not _validate_dims_mapping(
322 323
                            compatible_dims_mapping, op_dist_attr.process_mesh
                        ):
324
                            continue
325 326 327
                        if (compatible_dims_mapping is not None) and (
                            compatible_dims_mapping != op_dims_mapping
                        ):
328
                            op_dist_attr.set_output_dims_mapping(
329 330
                                tensor_desc.name(), compatible_dims_mapping
                            )
331 332
                            changed = True
            # Find the most compatible implemenetations from the distributed operator
333
            op_dist_impls = find_compatible_distributed_operator_impls(
334 335
                dist_op, fwd=False
            )
336 337 338 339 340 341 342 343
            if op_dist_impls is not None:
                not_compatible = True
                backup_op_dist_attr = copy.deepcopy(op_dist_attr)
                backup_changed = changed
                for op_dist_impl in op_dist_impls:
                    dim_changed = op_dist_impl.update_dims_mapping(dist_op)
                    if dim_changed:
                        changed = True
344 345 346 347
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
348 349 350 351 352 353 354 355
                        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_type = op_dist_impl.type
                        op_dist_attr.impl_idx = op_dist_impl.idx
                        not_compatible = False
                        break
356
                    else:
357 358 359 360 361 362 363 364
                        dist_op.dist_attr = backup_op_dist_attr
                        changed = backup_changed
                if not_compatible:
                    dist_op.dist_attr = original_op_dist_attr
                    changed = False
            else:
                dist_op.dist_attr = original_op_dist_attr
                changed = False
365
        return changed
366

367 368 369 370
    def _update_dims_mapping_between_graphs(self):
        changed = False
        for parent_node, child_node in self._node_pairs_between_graphs:
            parent_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
371 372
                parent_node
            )
373
            child_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
374 375 376 377 378 379
                child_node
            )
            if (
                parent_node_dist_attr.process_mesh
                != child_node_dist_attr.process_mesh
            ):
380
                continue
381 382 383
            parent_node_dims_mapping = parent_node_dist_attr.dims_mapping
            child_node_dims_mapping = child_node_dist_attr.dims_mapping
            compatible_dims_mapping = compute_compatible_dims_mapping(
384 385 386 387 388
                [parent_node_dims_mapping, child_node_dims_mapping]
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, parent_node_dist_attr.process_mesh
            ):
389
                return False
390 391 392
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != parent_node_dims_mapping
            ):
393 394
                parent_node_dist_attr.dims_mapping = compatible_dims_mapping
                changed = True
395 396 397
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != child_node_dims_mapping
            ):
398
                child_node_dist_attr.dims_mapping = compatible_dims_mapping
399 400
                changed = True
        return changed
401

402 403 404
    def _update_dims_mapping_for_special(self):
        # Set the dims_mapping of a tensor to the dims_mapping inside the op which produces it
        op_nodes = self._dist_context._serial_ordered_op_nodes
405 406
        # NOTE: this list may be changed if Paddle changes the existing rules.
        related_reader_ops = [
407 408 409
            "create_py_reader",
            "create_double_buffer_reader",
            "read",
410
        ]
411
        for op_node in op_nodes:
412 413 414 415
            if (
                op_node.op() is not None
                and op_node.op().type() in related_reader_ops
            ):
416
                continue
417 418 419 420 421 422
            op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node)
            for tensor_node in op_node.outputs:
                if tensor_node.is_var() and tensor_node.var() is not None:
                    if tensor_node.var().type() == core.VarDesc.VarType.READER:
                        continue
                    tensor_desc = tensor_node.var()
423 424 425 426 427 428 429 430 431
                    tensor_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_graph(
                            tensor_node
                        )
                    )
                    if (
                        op_dist_attr.process_mesh
                        == tensor_dist_attr.process_mesh
                    ):
432
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
433 434
                            tensor_desc.name()
                        )
435 436
                        tensor_dist_attr.dims_mapping = op_dims_mapping

437 438 439 440
    def _update_dims_mapping(self):
        # Complete dims_mapping for each node
        reach_fix_point = False
        while not reach_fix_point:
441
            changed = False
442
            for is_fwd in [True, False]:
443 444 445 446 447
                all_nodes = (
                    self._dist_context.serial_ordered_nodes
                    if is_fwd
                    else reversed(self._dist_context.serial_ordered_nodes)
                )
448 449 450
                for node in all_nodes:
                    if node.is_var() and node.var() is not None:
                        tensor_changed = self._update_tensor_node_dims_mapping(
451 452
                            node, fwd=is_fwd
                        )
453 454 455 456
                        if tensor_changed:
                            changed = True
                    if node.is_op() and node.op() is not None:
                        op_changed = self._update_op_node_dims_mapping(
457 458
                            node, fwd=is_fwd
                        )
459 460
                        if op_changed:
                            changed = True
461 462 463
                graph_changed = self._update_dims_mapping_between_graphs()
                if graph_changed:
                    changed = True
464
            if changed:
465
                reach_fix_point = False
466
            else:
467
                reach_fix_point = True
468
        # NOTE: this will be removed after changing the reshard rule
469
        self._update_dims_mapping_for_special()
470

471 472 473 474 475 476
    def _update_process_mesh_by_nearest(self, op_node, nearest_op_node):
        op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node)
        # Set the process mesh of the op node by its nearest op node
        if not op_dist_attr.is_annotated("process_mesh"):
            process_mesh = op_dist_attr.process_mesh
            nearest_op_dis_attr = self._dist_context.get_dist_attr_for_graph(
477 478
                nearest_op_node
            )
479 480
            nearest_process_mesh = nearest_op_dis_attr.process_mesh
            compatible_process_mesh = compute_compatible_process_mesh(
481 482 483 484 485 486
                [process_mesh, nearest_process_mesh]
            )
            if (
                compatible_process_mesh is not None
                and process_mesh != compatible_process_mesh
            ):
487 488 489 490 491 492 493
                op_dist_attr.process_mesh = compatible_process_mesh
        # Skip the process_mesh setting of inputs and outputs of while_op
        if op_dist_attr.op_type == "while":
            return
        # Set the process mesh of the op node's leaf-inputs
        for tensor_node in op_node.inputs:
            if tensor_node.is_var() and tensor_node.var() is not None:
494 495 496 497 498
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_graph(
                        tensor_node
                    )
                )
499 500 501 502 503 504
                if tensor_dist_attr.is_annotated("process_mesh"):
                    continue
                # Skip the non-leaf var node
                if len(tensor_node.inputs) != 0:
                    continue
                compatible_process_mesh = compute_compatible_process_mesh(
505 506 507 508 509 510
                    [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]
                )
                if (
                    compatible_process_mesh is not None
                    and tensor_dist_attr.process_mesh != compatible_process_mesh
                ):
511
                    tensor_dist_attr.process_mesh = compatible_process_mesh
512
                # Set the process mesh of the op node's outputs
513 514
        for tensor_node in op_node.outputs:
            if tensor_node.is_var() and tensor_node.var() is not None:
515 516 517 518 519
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_graph(
                        tensor_node
                    )
                )
520 521 522
                if tensor_dist_attr.is_annotated("process_mesh"):
                    continue
                compatible_process_mesh = compute_compatible_process_mesh(
523 524 525 526 527 528
                    [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]
                )
                if (
                    compatible_process_mesh is not None
                    and tensor_dist_attr.process_mesh != compatible_process_mesh
                ):
529 530 531 532 533
                    tensor_dist_attr.process_mesh = compatible_process_mesh

    def _update_process_mesh_for_specials(self):
        def _find_nearest_tensor_node_before(nodes, idx, var_name):
            for node in reversed(nodes[:idx]):
534 535 536 537 538
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == var_name
                ):
539 540 541
                    return node

        def _find_nearest_tensor_node_after(nodes, idx, var_name):
542 543 544 545 546 547
            for node in nodes[idx + 1 :]:
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == var_name
                ):
548 549 550 551 552 553 554 555 556 557 558 559 560 561
                    return node

        def _find_nodes_related_to_cond(source_node):
            related_nodes = []
            visited = set()
            frontier = list()
            frontier.append(source_node)
            # BFS
            while len(frontier) != 0:
                cur = frontier[0]
                frontier = frontier[1:]
                if _node_id(cur) in visited:
                    continue
                # TODO: need more restrictions
562 563
                neighbors = cur.inputs + cur.outputs
                for node in neighbors:
564
                    if node.is_var() and node.var() is not None:
565 566 567 568
                        if (
                            node.var().type() != core.VarDesc.VarType.READER
                            and len(node.var().shape()) == 1
                        ):
569 570 571 572
                            frontier.append(node)
                            related_nodes.append(node)
                    if node.is_op() and node.op() is not None:
                        flag = True
573 574 575 576 577
                        if (
                            node.op().type() == "create_py_reader"
                            or node.op().type() == "create_double_buffer_reader"
                            or node.op().type() == "read"
                        ):
578 579
                            flag = False
                        for tensor_node in node.inputs:
580 581 582 583 584 585
                            if (
                                tensor_node.is_var()
                                and tensor_node.var() is not None
                            ):
                                if (
                                    tensor_node.var().type()
Z
zhaoyingli 已提交
586
                                    in __no_shape_var_type__
587 588
                                    or len(tensor_node.var().shape()) != 1
                                ):
589 590 591
                                    flag = False
                                    break
                        for tensor_node in node.outputs:
592 593 594 595 596 597
                            if (
                                tensor_node.is_var()
                                and tensor_node.var() is not None
                            ):
                                if (
                                    tensor_node.var().type()
Z
zhaoyingli 已提交
598
                                    in __no_shape_var_type__
599 600
                                    or len(tensor_node.var().shape()) != 1
                                ):
601 602 603 604 605 606 607 608
                                    flag = False
                                    break
                        if flag:
                            frontier.append(node)
                            related_nodes.append(node)
                visited.add(_node_id(cur))
            return related_nodes

609
        def _make_dims_mapping_replicate(dist_attr):
610
            if isinstance(dist_attr, TensorDistAttr):
611 612
                for i, _ in enumerate(dist_attr.dims_mapping):
                    dist_attr.dims_mapping[i] = -1
613
            if isinstance(dist_attr, OperatorDistAttr):
614 615 616 617 618 619 620 621 622 623 624
                for arg_name in dist_attr.inputs_dist_attrs.keys():
                    new_dims_mapping = []
                    dims_mapping = dist_attr.get_input_dims_mapping(arg_name)
                    for _ in dims_mapping:
                        new_dims_mapping.append(-1)
                    dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping)
                for arg_name in dist_attr.outputs_dist_attrs.keys():
                    new_dims_mapping = []
                    dims_mapping = dist_attr.get_output_dims_mapping(arg_name)
                    for _ in dims_mapping:
                        new_dims_mapping.append(-1)
625 626 627
                    dist_attr.set_output_dims_mapping(
                        arg_name, new_dims_mapping
                    )
628

629 630 631
        # Amend the process meshes related to while_op
        for while_op_node, while_op_node_idx in self._while_op_nodes.values():
            sub_graph_id = while_op_node.op()._block_attr_id("sub_block")
632
            sub_graph = self._dist_context.serial_graph.get_sub_graph(
633 634
                sub_graph_id
            )
635 636
            sub_graph_nodes = list(sub_graph.all_nodes())
            while_dist_op = self._dist_context.get_dist_op_for_graph(
637 638
                while_op_node
            )
639 640 641 642 643
            while_op_dist_attr = while_dist_op.dist_attr

            # Step 1: set the process mesh of while_op to the merged process mesh of its subblock
            merged_process_mesh = while_op_dist_attr.process_mesh
            for node in sub_graph_nodes:
644 645 646
                if (node.is_var() and node.var() is not None) or (
                    node.is_op() and node.op() is not None
                ):
647 648
                    dist_attr = self._dist_context.get_dist_attr_for_graph(node)
                    merged_process_mesh = merge_process_mesh_two(
649 650
                        merged_process_mesh, dist_attr.process_mesh
                    )
651
            while_op_dist_attr.process_mesh = merged_process_mesh
652
            _make_dims_mapping_replicate(while_op_dist_attr)
653 654 655 656 657 658 659

            # Step 2: set the related nodes of while_op to the process mesh of while_op
            # Step 2.1: Find related nodes of cond var the graph of while_op
            cond_tensor_related_nodes = []
            cond_tensor_name = while_op_node.op().input("Condition")[0]
            cond_tensor_node = None
            for node in while_op_node.inputs:
660 661 662 663 664
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == cond_tensor_name
                ):
665 666 667 668 669
                    cond_tensor_node = node
                    cond_tensor_related_nodes.append(cond_tensor_node)
                    break

            cond_tensor_related_nodes.extend(
670 671
                _find_nodes_related_to_cond(cond_tensor_node)
            )
672 673 674 675

            # Step 2.2: Find related nodes of cond var in the subgraph of while_op
            cond_tensor_node = None
            for node in reversed(sub_graph_nodes):
676 677 678 679 680 681
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == cond_tensor_name
                    and len(node.outputs) == 0
                ):
682 683 684 685
                    cond_tensor_node = node
                    break

            cond_tensor_related_nodes.extend(
686 687
                _find_nodes_related_to_cond(cond_tensor_node)
            )
688 689 690 691
            # Step 2.3: Add the StepScops output of while_op
            stepscopes_tensor_name = while_op_node.op().output("StepScopes")[0]
            stepscopes_tensor_node = None
            for output_node in while_op_node.outputs:
692 693 694 695 696
                if (
                    output_node.is_var()
                    and output_node.var() is not None
                    and output_node.var().name() == stepscopes_tensor_name
                ):
697 698 699 700 701
                    stepscopes_tensor_node = output_node
            cond_tensor_related_nodes.append(stepscopes_tensor_node)
            # Step 2.4: Set the process meshes of all nodes related to cond var to the process mesh of while op
            for node in cond_tensor_related_nodes:
                tensor_dist_attr = self._dist_context.get_dist_attr_for_graph(
702 703
                    node
                )
704
                tensor_dist_attr.process_mesh = merged_process_mesh
705
                _make_dims_mapping_replicate(tensor_dist_attr)
706 707 708

            # Step 3: set the process meshes of the inputs in while_op to the process meshes of the outside input nodes
            while_op_inputs_dist_attrs = while_op_dist_attr.inputs_dist_attrs
709 710 711 712
            for (
                tensor_name,
                tensor_dist_attr,
            ) in while_op_inputs_dist_attrs.items():
713
                nearest_tensor_node = _find_nearest_tensor_node_before(
714 715 716 717 718 719 720 721 722 723 724 725
                    self._dist_context.serial_ordered_nodes,
                    while_op_node_idx,
                    tensor_name,
                )
                nearest_tensor_dist_attr = (
                    self._dist_context.get_dist_attr_for_graph(
                        nearest_tensor_node
                    )
                )
                tensor_dist_attr.process_mesh = (
                    nearest_tensor_dist_attr.process_mesh
                )
726 727 728

            # Step 4: set the process meshes of the outputs in while_op to the process meshes of the outside output nodes
            while_op_outputs_dist_attrs = while_op_dist_attr.outputs_dist_attrs
729 730 731 732
            for (
                tensor_name,
                tensor_dist_attr,
            ) in while_op_outputs_dist_attrs.items():
733
                nearest_tensor_node = _find_nearest_tensor_node_before(
734 735 736 737
                    self._dist_context.serial_ordered_nodes,
                    while_op_node_idx,
                    tensor_name,
                )
738 739 740
                if nearest_tensor_node is None:
                    nearest_tensor_node = _find_nearest_tensor_node_after(
                        self._dist_context.serial_ordered_nodes,
741 742 743 744 745 746 747 748 749 750 751
                        while_op_node_idx,
                        tensor_name,
                    )
                nearest_tensor_dist_attr = (
                    self._dist_context.get_dist_attr_for_graph(
                        nearest_tensor_node
                    )
                )
                tensor_dist_attr.process_mesh = (
                    nearest_tensor_dist_attr.process_mesh
                )
752 753 754 755 756 757

        # Amend the process meshes related to array
        for array_node_list in self._array_nodes.values():
            merged_process_mesh = None
            for array_node in array_node_list:
                dist_attr = self._dist_context.get_dist_attr_for_graph(
758 759
                    array_node
                )
760
                merged_process_mesh = merge_process_mesh_two(
761 762
                    merged_process_mesh, dist_attr.process_mesh
                )
763 764
            for array_node in array_node_list:
                dist_attr = self._dist_context.get_dist_attr_for_graph(
765 766
                    array_node
                )
767
                dist_attr.process_mesh = merged_process_mesh
768 769 770 771 772
                _make_dims_mapping_replicate(dist_attr)

    def _update_process_mesh_between_graphs(self):
        for parent_node, child_node in self._node_pairs_between_graphs:
            parent_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
773 774
                parent_node
            )
775
            child_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
776 777 778
                child_node
            )
            parent_node_dist_attr.process_mesh = (
779
                child_node_dist_attr.process_mesh
780 781 782 783 784 785 786 787 788 789 790 791
            )
            compatible_process_mesh = compute_compatible_process_mesh(
                [
                    parent_node_dist_attr.process_mesh,
                    child_node_dist_attr.process_mesh,
                ]
            )
            if (
                compatible_process_mesh is not None
                and parent_node_dist_attr.process_mesh
                != compatible_process_mesh
            ):
792
                parent_node_dist_attr.process_mesh = compatible_process_mesh
793 794 795 796
            if (
                compatible_process_mesh is not None
                and child_node_dist_attr.process_mesh != compatible_process_mesh
            ):
797
                child_node_dist_attr.process_mesh = compatible_process_mesh
798 799 800 801 802 803 804

    def _update_process_mesh(self):
        ordered_op_nodes = self._dist_context._serial_ordered_op_nodes

        # Step 1: Set the annotated process meshes from tensors to the first ops using them
        ordered_tensor_nodes = self._dist_context._serial_ordered_tensor_nodes
        for tensor_node in ordered_tensor_nodes:
805 806 807
            tensor_dist_attr = (
                self._dist_context.get_tensor_dist_attr_for_graph(tensor_node)
            )
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
            if not tensor_dist_attr.is_annotated("process_mesh"):
                continue
            first_op_node = None
            for op_node in ordered_op_nodes:
                # TODO: Need a better rule for the control flow ops.
                # For now, do not set the process mesh of while_op from its inputs
                if op_node.op().type() == "while":
                    continue
                for input_tensor_node in op_node.inputs:
                    if _node_id(tensor_node) == _node_id(input_tensor_node):
                        first_op_node = op_node
                        break
                if first_op_node is not None:
                    break
            if first_op_node is None:
                continue
            op_dist_attr = self._dist_context.get_dist_attr_for_graph(
825 826
                first_op_node
            )
827
            if op_dist_attr is not None and not op_dist_attr.is_annotated(
828 829
                "process_mesh"
            ):
830
                compatible_process_mesh = compute_compatible_process_mesh(
831 832 833 834 835 836
                    [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]
                )
                if (
                    compatible_process_mesh is not None
                    and op_dist_attr.process_mesh != compatible_process_mesh
                ):
837 838 839 840 841 842 843
                    op_dist_attr.process_mesh = compatible_process_mesh

        # Step 2: set the process meshes of ops with the nearest op before them
        # Step 2.1: find the first op node which has the process mesh
        idx_of_first_op_node_has_process_mesh = -1
        for idx, op_node in enumerate(ordered_op_nodes):
            op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node)
844 845 846 847
            if (
                op_dist_attr.process_mesh is not None
                and idx_of_first_op_node_has_process_mesh == -1
            ):
848 849 850 851 852 853
                idx_of_first_op_node_has_process_mesh = idx
                # Reuse the following method to set the related tensors for same op node
                self._update_process_mesh_by_nearest(op_node, op_node)
        # Step 2.2: set the process meshes of ops by the nearest op node after the first op node
        if idx_of_first_op_node_has_process_mesh + 1 > len(ordered_op_nodes):
            return None
854
        for idx, op_node in enumerate(
855 856
            ordered_op_nodes[idx_of_first_op_node_has_process_mesh + 1 :]
        ):
857
            original_idx = idx_of_first_op_node_has_process_mesh + idx + 1
858 859
            nearest_op_node = ordered_op_nodes[original_idx - 1]
            nearest_op_dist_attr = self._dist_context.get_dist_attr_for_graph(
860 861
                nearest_op_node
            )
862 863 864 865 866
            op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node)
            assert nearest_op_dist_attr.process_mesh is not None
            self._update_process_mesh_by_nearest(op_node, nearest_op_node)
        # Step 2.3: set the process meshes of ops by the nearest op node before the first op node
        nearest_op_node = ordered_op_nodes[
867 868
            idx_of_first_op_node_has_process_mesh
        ]
869 870 871 872 873 874
        for op_node in ordered_op_nodes[:idx_of_first_op_node_has_process_mesh]:
            self._update_process_mesh_by_nearest(op_node, nearest_op_node)

        # Step 3: adjust the process meshes for special ops
        self._update_process_mesh_for_specials()

875
        # Step 4: adjust the process meshes between graphs
876 877
        self._update_process_mesh_between_graphs()

878
    def _prepare(self):
879 880
        if self._has_prepared:
            return
881 882 883 884 885 886 887 888 889 890 891 892 893
        self._while_op_nodes = {}
        self._array_nodes = {}
        self._node_pairs_between_graphs = []
        all_nodes = self._dist_context.serial_ordered_nodes
        for idx, node in enumerate(all_nodes):
            if node.is_op():
                if node.op().type() == "while":
                    self._while_op_nodes[_node_id(node)] = (node, idx)
                if node.op().type() == "read_from_array":
                    array_var_name = node.op().input("X")[0]
                    if self._array_nodes.get(array_var_name, None) is None:
                        self._array_nodes[array_var_name] = []
                    self._array_nodes[array_var_name].append(node)
894 895
                    # Add the array input node
                    self._array_nodes[array_var_name].append(node.inputs[0])
896 897 898 899 900 901 902 903 904
                if node.op().type() == "write_to_array":
                    array_var_name = node.op().output("Out")[0]
                    if self._array_nodes.get(array_var_name, None) is None:
                        self._array_nodes[array_var_name] = []
                    self._array_nodes[array_var_name].append(node)
                    self._array_nodes[array_var_name].append(node.outputs[0])
            if node.is_var() and node.var() is not None:
                if node.node.graph_id() != 0:
                    for before_node in reversed(all_nodes[:idx]):
905 906 907 908 909 910 911
                        if (
                            before_node.is_var()
                            and before_node.var() is not None
                            and before_node.node.graph_id()
                            == node.node.graph_id() - 1
                            and before_node.var().name() == node.var().name()
                        ):
912
                            self._node_pairs_between_graphs.append(
913 914 915 916 917 918 919 920 921 922
                                (before_node, node)
                            )
                    for after_node in all_nodes[idx + 1 :]:
                        if (
                            after_node.is_var()
                            and after_node.var() is not None
                            and after_node.node.graph_id()
                            == node.node.graph_id() - 1
                            and after_node.var().name() == node.var().name()
                        ):
923
                            self._node_pairs_between_graphs.append(
924 925
                                (after_node, node)
                            )
926
        self._has_prepared = True
927

928
    def complete_forward_annotation(self, serial_main_program=None):
929
        """Complete annotation for the partial annotated serial_main_program.
930 931
        Arguments:
            serial_main_program: partial annotated serial_main_program.
932
        Returns:e
933 934 935
            serial_main_program: completed annotated serial_main_program.
        """

936 937 938
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
939
            self._dist_context._serial_main_program = serial_main_program
940

941
        if not is_naive_data_parallel(self._dist_context):
942 943 944 945 946 947 948
            self._dist_context.initialize(with_graph=True)
            self._prepare()
            self._update_process_mesh()
            self._update_dims_mapping()
            # Copy the corresponding distributed attribute from graph to serial_main_program
            self._dist_context.copy_dist_attr_from_graph_to_program()
        else:
Z
zhaoyingli 已提交
949
            self._logger.info("Default distributed attributed will be set.")
950 951 952 953
            self._dist_context.initialize(with_graph=False)
            # A fast and special completion for data parallel
            self._update_dist_attr_for_dp()

954
        # NOTE:[HighOrderGrad] update vars and ops distributed attribute in high order gradient
955
        self._complete_high_order_grad_annotation(serial_main_program)
956 957 958 959 960
        # Do the validation check and amend some completion
        self._dist_context.amend_dist_attr_for_program()
        self._dist_context.validate_dist_attr_for_program()
        return serial_main_program

961 962 963 964
    def _update_dist_attr_for_dp(self):
        # TODO: we must ensure the world process group contains all ranks
        ranks = get_world_process_group().ranks
        process_mesh = ProcessMesh(ranks)
965 966 967 968 969 970 971

        dist_tensors = self._dist_context._dist_tensors_for_program
        for dist_tensor in dist_tensors.values():
            dist_tensor.dist_attr.process_mesh = process_mesh

        dist_ops = self._dist_context._dist_ops_for_program
        for dist_op in dist_ops.values():
972 973 974 975
            serial_op = dist_op.serial_op
            op_dist_attr = dist_op.dist_attr
            op_dist_attr.process_mesh = process_mesh
            original_op_dist_attr = copy.deepcopy(op_dist_attr)
976

977 978 979
            for arg_name in serial_op.input_arg_names:
                serial_tensor = dist_op.get_serial_input(arg_name)
                if not serial_tensor.is_parameter:
980 981 982
                    dist_tensor = (
                        self._dist_context.get_dist_tensor_for_program(
                            serial_tensor
983 984
                        )
                    )
985 986 987 988 989 990
                    op_dist_attr = dist_op.dist_attr
                    op_dist_attr.process_mesh = (
                        dist_tensor.dist_attr.process_mesh
                    )
                    op_dist_attr.set_input_dims_mapping(
                        arg_name, dist_tensor.dist_attr.dims_mapping
991
                    )
992 993

            op_dist_impls = find_compatible_distributed_operator_impls(
994
                dist_op, fwd=True
995
            )
996 997 998 999 1000
            if op_dist_impls is not None:
                not_compatible = True
                backup_op_dist_attr = copy.deepcopy(op_dist_attr)
                for op_dist_impl in op_dist_impls:
                    op_dist_impl.update_dims_mapping(dist_op)
1001 1002 1003 1004
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                        op_dist_attr.impl_type = op_dist_impl.type
                        op_dist_attr.impl_idx = op_dist_impl.idx
                        not_compatible = False
                        break
                    else:
                        dist_op.dist_attr = backup_op_dist_attr
                if not_compatible:
                    dist_op.dist_attr = original_op_dist_attr
            else:
                dist_op.dist_attr = original_op_dist_attr

1016 1017 1018
            for arg_name in serial_op.output_arg_names:
                op_dist_attr = dist_op.dist_attr
                serial_tensor = dist_op.get_serial_output(arg_name)
Z
zhaoyingli 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                if serial_op.type in ["fill_constant"]:
                    old_dims_mapping = op_dist_attr.get_output_dims_mapping(
                        arg_name
                    )
                    if len(old_dims_mapping) > 0:
                        new_dims_mapping = [0] + [
                            -1 for _ in range(len(old_dims_mapping) - 1)
                        ]
                        op_dist_attr.set_output_dims_mapping(
                            arg_name, new_dims_mapping
                        )
1030 1031 1032 1033 1034 1035 1036
                dist_tensor = self._dist_context.get_dist_tensor_for_program(
                    serial_tensor
                )
                dist_tensor.dist_attr.dims_mapping = (
                    op_dist_attr.get_output_dims_mapping(arg_name)
                )

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    def _complete_tensor_dist_attr_by_op(self, serial_main_program=None):
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
            self._dist_context._serial_main_program = serial_main_program

        self._dist_context.initialize()

        self._prepare()

        has_set_dist_attr = set()

        all_nodes = self._dist_context.serial_ordered_nodes
        for node in all_nodes:
            if node.is_op():
                if node.op().type() in ["while"]:
                    continue
                dist_op = self._dist_context.get_dist_op_for_graph(node)
                op_dist_attr = dist_op.dist_attr
                for tensor_node in node.inputs:
                    if tensor_node.is_var() and tensor_node.var() is not None:
                        # Skip the non-leaf var node
                        if len(tensor_node.inputs) != 0:
                            continue
                        tensor_desc = tensor_node.var()
                        tensor_name = tensor_desc.name()
                        tensor = dist_op.get_serial_input(tensor_name)
                        # Use the first op to set the tensor dist attr
                        if tensor_name in has_set_dist_attr:
                            continue
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
                        tensor_dist_attr = (
                            self._dist_context.get_tensor_dist_attr_for_graph(
                                tensor_node
                            )
                        )
                        tensor_dist_attr.process_mesh = (
                            op_dist_attr.process_mesh
                        )
                        tensor_dist_attr.dims_mapping = (
                            op_dist_attr.get_input_dims_mapping(tensor_name)
                            if tensor.is_parameter
                            else [-1 for i in tensor_desc.shape()]
                        )
1080 1081 1082 1083 1084 1085
                        has_set_dist_attr.add(tensor_name)
                for tensor_node in node.outputs:
                    if tensor_node.is_var() and tensor_node.var() is not None:
                        tensor_name = tensor_node.var().name()
                        if tensor_name in has_set_dist_attr:
                            continue
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
                        tensor_dist_attr = (
                            self._dist_context.get_tensor_dist_attr_for_graph(
                                tensor_node
                            )
                        )
                        tensor_dist_attr.process_mesh = (
                            op_dist_attr.process_mesh
                        )
                        tensor_dist_attr.dims_mapping = (
                            op_dist_attr.get_output_dims_mapping(tensor_name)
                        )
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
                        has_set_dist_attr.add(tensor_name)

        self._update_process_mesh_for_specials()

        self._update_process_mesh_between_graphs()

        self._update_dims_mapping_for_special()

        self._update_dims_mapping_between_graphs()

        # Copy the corresponding distributed attribute from graph to serial_main_program
        self._dist_context.copy_dist_attr_from_graph_to_program()

        # Do the validation check and amend some completion
        self._dist_context.amend_dist_attr_for_program()

        self._dist_context.validate_dist_attr_for_program()

1115
    def _complete_high_order_grad_annotation(self, serial_main_program=None):
1116
        """
1117
        NOTE:
1118 1119 1120 1121
            [HighOrderGrad] Complete the annotation of vars and ops only for high order gradient.
            This function is temporary to support high order gradient, and will be removed in the future.
        """

1122 1123 1124 1125 1126
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
            self._dist_context._serial_main_program = serial_main_program

1127 1128 1129 1130 1131 1132 1133
        def _is_grad_var_name(name):
            if "@GRAD" in name:
                return True
            return False

        def _get_op_by_id(ops, id):
            for op in ops:
1134
                if op.desc.original_id() == id:
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
                    return op
            return None

        ops = list(serial_main_program.global_block().ops)
        vars = serial_main_program.global_block().vars
        dist_op_context = self._dist_context.dist_op_context
        grad_var_to_var = dist_op_context.grad_var_to_var

        appended_grad_times = 0
        for idx in range(0, len(ops)):
            op = ops[idx]
            if int(op.attr('op_role')) == int(
1147 1148
                core.op_proto_and_checker_maker.OpRole.Forward
            ):
1149 1150 1151
                continue

            if int(op.attr('op_role')) == int(
1152 1153 1154 1155
                core.op_proto_and_checker_maker.OpRole.Backward
            ) and int(ops[idx - 1].attr('op_role')) == int(
                core.op_proto_and_checker_maker.OpRole.Forward
            ):
1156 1157
                appended_grad_times += 1

1158
            if int(op.attr('op_role')) == int(
1159 1160 1161
                int(core.op_proto_and_checker_maker.OpRole.Backward)
                | int(core.op_proto_and_checker_maker.OpRole.Loss)
            ):
1162 1163 1164
                assert op.type == "fill_constant"
                break

1165 1166 1167
            # complete the annotation of grad op (xxx_grad op or sum op)
            # xxx_grad op will have a corresponding forward op in grad_op_id_to_op_id
            grad_op = ops[idx]
1168 1169 1170 1171
            if (
                grad_op.desc.original_id()
                in dist_op_context.grad_op_id_to_op_id
            ):
1172
                # TODO support the case where one forward op corresponding to multiple xxx_grad op
1173
                forward_op = _get_op_by_id(
1174 1175 1176 1177 1178
                    ops,
                    dist_op_context.grad_op_id_to_op_id[
                        grad_op.desc.original_id()
                    ],
                )
1179 1180
                assert forward_op is not None

1181 1182 1183
                fwd_op_dist_attr = (
                    self._dist_context.get_op_dist_attr_for_program(forward_op)
                )
1184
                fwd_op_process_mesh = fwd_op_dist_attr.process_mesh
1185
                grad_op_dist_attr = OperatorDistAttr()
1186 1187 1188
                grad_op_dist_attr.process_mesh = fwd_op_process_mesh

                for input_name in grad_op.input_arg_names:
1189 1190 1191 1192
                    if (
                        input_name not in forward_op.input_arg_names
                        and input_name not in forward_op.output_arg_names
                    ):
1193 1194
                        if input_name in grad_var_to_var[appended_grad_times]:
                            fwd_name = grad_var_to_var[appended_grad_times][
1195 1196 1197 1198 1199 1200 1201
                                input_name
                            ]
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    fwd_name
                                )
                            )
1202 1203 1204
                        else:
                            input_var = vars[input_name]
                            ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program(
1205 1206
                                input_var
                            ).dims_mapping
1207
                    else:
1208
                        if input_name in forward_op.input_arg_names:
1209 1210 1211 1212 1213
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_input_dims_mapping(
                                    input_name
                                )
                            )
1214
                        else:
1215 1216 1217 1218 1219 1220 1221 1222
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    input_name
                                )
                            )
                    assert (
                        ref_dims_mapping is not None
                    ), "[{}] 's dims mapping is NONE".format(input_name)
1223
                    grad_op_dist_attr.set_input_dims_mapping(
1224 1225
                        input_name, ref_dims_mapping
                    )
1226 1227 1228 1229 1230

                for output_name in grad_op.output_arg_names:
                    assert output_name in grad_var_to_var[appended_grad_times]
                    fwd_name = grad_var_to_var[appended_grad_times][output_name]
                    ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping(
1231 1232
                        fwd_name
                    )
1233 1234
                    # var
                    output_var = vars[output_name]
1235
                    tensor_dist_attr = TensorDistAttr()
1236 1237 1238
                    tensor_dist_attr.dims_mapping = ref_dims_mapping
                    tensor_dist_attr.process_mesh = fwd_op_process_mesh
                    self._dist_context.set_tensor_dist_attr_for_program(
1239 1240
                        output_var, tensor_dist_attr
                    )
1241
                    # op
1242
                    grad_op_dist_attr.set_output_dims_mapping(
1243 1244
                        output_name, ref_dims_mapping
                    )
1245 1246

                self._dist_context.set_op_dist_attr_for_program(
1247 1248
                    grad_op, grad_op_dist_attr
                )
1249 1250 1251 1252 1253 1254 1255

            # grad ops that have not a corresponding mapping in grad_op_id_to_op_id
            else:

                if grad_op.type == 'sum':
                    assert all(map(_is_grad_var_name, grad_op.input_arg_names))
                    output_name = grad_op.output_arg_names[0]
1256 1257 1258 1259 1260
                    assert (
                        output_name in grad_var_to_var[appended_grad_times]
                    ), "sum op's output '{}' has no corresponding var".format(
                        output_name
                    )
1261
                    ref_fwd_var_name = grad_var_to_var[appended_grad_times][
1262 1263
                        output_name
                    ]
1264
                    ref_fwd_var = vars[ref_fwd_var_name]
1265 1266 1267 1268 1269
                    ref_fwd_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_fwd_var
                        )
                    )
1270 1271 1272
                    ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping
                    ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh
                    # output
1273
                    tensor_dist_attr = TensorDistAttr()
1274 1275 1276 1277
                    tensor_dist_attr.dims_mapping = ref_fwd_dims_mapping
                    tensor_dist_attr.process_mesh = ref_fwd_process_mesh
                    output_var = vars[output_name]
                    self._dist_context.set_tensor_dist_attr_for_program(
1278 1279
                        output_var, tensor_dist_attr
                    )
1280
                    # op
1281
                    grad_op_dist_attr = OperatorDistAttr()
1282 1283 1284
                    grad_op_dist_attr.process_mesh = ref_fwd_process_mesh
                    for var_name in grad_op.input_arg_names:
                        grad_op_dist_attr.set_input_dims_mapping(
1285 1286
                            var_name, ref_fwd_dims_mapping
                        )
1287
                    grad_op_dist_attr.set_output_dims_mapping(
1288 1289
                        output_name, ref_fwd_dims_mapping
                    )
1290

1291
                elif grad_op.type == 'fill_any_like':
1292 1293
                    ref_var_name = grad_op.input_arg_names[0]
                    ref_var = vars[ref_var_name]
1294 1295 1296 1297 1298
                    ref_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_var
                        )
                    )
1299 1300 1301
                    ref_dims_mapping = ref_dist_attr.dims_mapping
                    ref_process_mesh = ref_dist_attr.process_mesh
                    # output
1302
                    tensor_dist_attr = TensorDistAttr()
1303 1304 1305 1306 1307
                    tensor_dist_attr.dims_mapping = ref_dims_mapping
                    tensor_dist_attr.process_mesh = ref_process_mesh
                    output_var_name = grad_op.output_arg_names[0]
                    output_var = vars[output_var_name]
                    self._dist_context.set_tensor_dist_attr_for_program(
1308 1309
                        output_var, tensor_dist_attr
                    )
1310
                    # op
1311
                    grad_op_dist_attr = OperatorDistAttr()
1312
                    grad_op_dist_attr.process_mesh = ref_process_mesh
1313
                    grad_op_dist_attr.set_input_dims_mapping(
1314 1315
                        ref_var_name, ref_dims_mapping
                    )
1316
                    grad_op_dist_attr.set_output_dims_mapping(
1317 1318
                        output_var_name, ref_dims_mapping
                    )
1319 1320 1321 1322 1323

                elif grad_op.type in ['shape', 'fill_constant']:
                    continue

                else:
1324 1325 1326
                    raise ValueError(
                        "got unexpect op [{}]".format(str(grad_op.type))
                    )
1327 1328

                self._dist_context.set_op_dist_attr_for_program(
1329 1330
                    grad_op, grad_op_dist_attr
                )
1331

1332
    def complete_backward_annotation(self, serial_main_program=None):
1333
        """Complete the annotation of vars and ops in the backward phase for parallel program."""
1334

1335 1336 1337
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
1338
            self._dist_context._serial_main_program = serial_main_program
1339 1340 1341 1342 1343 1344 1345 1346

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

        def _get_forward_varname_from_grad_varname(grad_var_name):
            assert _is_grad_var_name(
1347 1348 1349
                grad_var_name
            ), "[{}] is not a grad varnme.".format(grad_var_name)
            return grad_var_name[: grad_var_name.find("@GRAD")]
1350 1351 1352

        def _get_op_by_id(ops, id):
            for op in ops:
1353
                if op.desc.original_id() == id:
1354 1355 1356 1357 1358 1359
                    return op
            return None

        first_backward_op_idx = -1
        for idx, op in enumerate(serial_main_program.global_block().ops):
            if int(op.attr('op_role')) == int(
1360 1361 1362
                int(core.op_proto_and_checker_maker.OpRole.Backward)
                | int(core.op_proto_and_checker_maker.OpRole.Loss)
            ):
1363 1364 1365 1366
                assert op.type == "fill_constant"
                first_backward_op_idx = idx
                break

1367 1368 1369
        assert (
            first_backward_op_idx >= 0
        ), "No backward procedure found in this program."
1370 1371 1372 1373

        ops = list(serial_main_program.global_block().ops)
        vars = serial_main_program.global_block().vars
        dist_op_context = self._dist_context.dist_op_context
1374 1375 1376
        grad_var_to_var = dist_op_context.grad_var_to_var[
            len(dist_op_context.grad_var_to_var)
        ]
1377 1378 1379 1380 1381 1382

        for idx in range(first_backward_op_idx, len(ops)):

            # complete the initial grad loss op
            if idx == first_backward_op_idx:
                assert ops[idx].type == "fill_constant"
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
                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)
                )
1393 1394 1395

                grad_var = vars[ops[idx].output_arg_names[0]]
                forward_var_name = _get_forward_varname_from_grad_varname(
1396 1397
                    grad_var.name
                )
1398 1399 1400
                forward_var = vars[forward_var_name]

                # TODO complete other attribte for grad var
1401
                tensor_dist_attr = TensorDistAttr()
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
                process_mesh = (
                    self._dist_context.get_tensor_dist_attr_for_program(
                        forward_var
                    ).process_mesh
                )
                dims_mapping = (
                    self._dist_context.get_tensor_dist_attr_for_program(
                        forward_var
                    ).dims_mapping
                )
1412 1413 1414
                tensor_dist_attr.dims_mapping = dims_mapping
                tensor_dist_attr.process_mesh = process_mesh
                self._dist_context.set_tensor_dist_attr_for_program(
1415 1416
                    grad_var, tensor_dist_attr
                )
1417

1418
                op_dist_attr = OperatorDistAttr()
1419
                op_dist_attr.process_mesh = process_mesh
1420 1421 1422
                op_dist_attr.set_output_dims_mapping(
                    grad_var.name, dims_mapping
                )
1423
                self._dist_context.set_op_dist_attr_for_program(
1424 1425
                    ops[idx], op_dist_attr
                )
1426
                continue
1427

1428 1429 1430
            # complete the annotation of grad op (xxx_grad op or sum op)
            # xxx_grad op will have a corresponding forward op in grad_op_id_to_op_id
            grad_op = ops[idx]
1431 1432 1433 1434
            if (
                grad_op.desc.original_id()
                in dist_op_context.grad_op_id_to_op_id
            ):
1435
                # TODO support the case where one forward op corresponding to multiple xxx_grad op
1436 1437 1438
                forward_op = _get_op_by_id(
                    ops[:first_backward_op_idx],
                    dist_op_context.grad_op_id_to_op_id[
1439 1440 1441
                        grad_op.desc.original_id()
                    ],
                )
1442 1443
                assert forward_op is not None

J
JZ-LIANG 已提交
1444
                if grad_op.type == "concat" and forward_op.type == "split":
1445 1446 1447 1448 1449
                    forward_op_dist_attr = (
                        self._dist_context.get_op_dist_attr_for_program(
                            forward_op
                        )
                    )
J
JZ-LIANG 已提交
1450 1451
                    output_var = vars[grad_op.desc.output('Out')[0]]
                    split_input_var_name = forward_op.input("X")[0]
1452 1453 1454 1455 1456
                    ref_dims_mapping = (
                        forward_op_dist_attr.get_input_dims_mapping(
                            split_input_var_name
                        )
                    )
J
JZ-LIANG 已提交
1457 1458
                    ref_mesh = forward_op_dist_attr.process_mesh

1459
                    grad_op_dist_attr = OperatorDistAttr()
J
JZ-LIANG 已提交
1460 1461
                    for input_name in grad_op.input_arg_names:
                        grad_op_dist_attr.set_input_dims_mapping(
1462 1463
                            input_name, ref_dims_mapping
                        )
J
JZ-LIANG 已提交
1464

1465
                    output_var_dist_attr = TensorDistAttr()
J
JZ-LIANG 已提交
1466 1467
                    output_var_dist_attr.dims_mapping = ref_dims_mapping
                    output_var_dist_attr.process_mesh = ref_mesh
Z
zhaoyingli 已提交
1468
                    self._dist_context.set_tensor_dist_attr_for_program(
1469 1470
                        output_var, output_var_dist_attr
                    )
J
JZ-LIANG 已提交
1471

1472
                    grad_op_dist_attr.set_output_dims_mapping(
1473 1474
                        output_var.name, ref_dims_mapping
                    )
J
JZ-LIANG 已提交
1475
                    grad_op_dist_attr.process_mesh = ref_mesh
Z
zhaoyingli 已提交
1476
                    self._dist_context.set_op_dist_attr_for_program(
1477 1478
                        grad_op, grad_op_dist_attr
                    )
1479 1480 1481 1482 1483 1484
                    grad_op_dist_attr.impl_type = (
                        fwd_op_dist_attr.impl_type  # noqa: F821
                    )
                    grad_op_dist_attr.impl_idx = (
                        fwd_op_dist_attr.impl_idx  # noqa: F821
                    )
1485

J
JZ-LIANG 已提交
1486 1487
                    continue

1488 1489 1490
                fwd_op_dist_attr = (
                    self._dist_context.get_op_dist_attr_for_program(forward_op)
                )
1491
                fwd_op_process_mesh = fwd_op_dist_attr.process_mesh
1492
                grad_op_dist_attr = OperatorDistAttr()
1493
                grad_op_dist_attr.process_mesh = fwd_op_process_mesh
1494 1495

                for input_name in grad_op.input_arg_names:
1496 1497 1498 1499
                    if (
                        input_name not in forward_op.input_arg_names
                        and input_name not in forward_op.output_arg_names
                    ):
1500 1501
                        if input_name in grad_var_to_var:
                            fwd_name = grad_var_to_var[input_name]
1502 1503 1504 1505 1506
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    fwd_name
                                )
                            )
1507 1508 1509
                        else:
                            input_var = vars[input_name]
                            ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program(
1510 1511
                                input_var
                            ).dims_mapping
1512
                    else:
1513
                        if input_name in forward_op.input_arg_names:
1514 1515 1516 1517 1518
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_input_dims_mapping(
                                    input_name
                                )
                            )
1519
                        else:
1520 1521 1522 1523 1524 1525 1526 1527
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    input_name
                                )
                            )
                    assert (
                        ref_dims_mapping is not None
                    ), "[{}] 's dims mapping is NONE".format(input_name)
1528
                    grad_op_dist_attr.set_input_dims_mapping(
1529 1530
                        input_name, ref_dims_mapping
                    )
1531

1532 1533 1534 1535
                for output_name in grad_op.output_arg_names:
                    assert output_name in grad_var_to_var
                    fwd_name = grad_var_to_var[output_name]
                    ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping(
1536 1537
                        fwd_name
                    )
1538 1539
                    # var
                    output_var = vars[output_name]
1540
                    tensor_dist_attr = TensorDistAttr()
1541 1542 1543
                    tensor_dist_attr.dims_mapping = ref_dims_mapping
                    tensor_dist_attr.process_mesh = fwd_op_process_mesh
                    self._dist_context.set_tensor_dist_attr_for_program(
1544 1545
                        output_var, tensor_dist_attr
                    )
1546
                    # op
1547
                    grad_op_dist_attr.set_output_dims_mapping(
1548 1549
                        output_name, ref_dims_mapping
                    )
1550

1551 1552
                grad_op_dist_attr.impl_type = fwd_op_dist_attr.impl_type
                grad_op_dist_attr.impl_idx = fwd_op_dist_attr.impl_idx
1553
                self._dist_context.set_op_dist_attr_for_program(
1554 1555
                    grad_op, grad_op_dist_attr
                )
1556
            # grad ops that have not a corresponding mapping in grad_op_id_to_op_id
1557
            else:
1558 1559 1560
                if grad_op.type == 'sum':
                    assert all(map(_is_grad_var_name, grad_op.input_arg_names))
                    output_name = grad_op.output_arg_names[0]
1561 1562 1563 1564 1565
                    assert (
                        output_name in grad_var_to_var
                    ), "sum op's output '{}' has no corresponding var".format(
                        output_name
                    )
1566 1567
                    ref_fwd_var_name = grad_var_to_var[output_name]
                    ref_fwd_var = vars[ref_fwd_var_name]
1568 1569 1570 1571 1572
                    ref_fwd_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_fwd_var
                        )
                    )
1573 1574 1575 1576
                    ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping
                    ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh

                    # output
1577
                    tensor_dist_attr = TensorDistAttr()
1578 1579 1580 1581
                    tensor_dist_attr.dims_mapping = ref_fwd_dims_mapping
                    tensor_dist_attr.process_mesh = ref_fwd_process_mesh
                    output_var = vars[output_name]
                    self._dist_context.set_tensor_dist_attr_for_program(
1582 1583
                        output_var, tensor_dist_attr
                    )
1584

1585
                    # op
1586
                    grad_op_dist_attr = OperatorDistAttr()
1587 1588 1589
                    grad_op_dist_attr.process_mesh = ref_fwd_process_mesh
                    for var_name in grad_op.input_arg_names:
                        grad_op_dist_attr.set_input_dims_mapping(
1590 1591
                            var_name, ref_fwd_dims_mapping
                        )
1592
                    grad_op_dist_attr.set_output_dims_mapping(
1593 1594
                        output_name, ref_fwd_dims_mapping
                    )
1595 1596
                    grad_op_dist_attr.impl_type = "default"
                    grad_op_dist_attr.impl_idx = 0
1597

1598
                elif grad_op.type == 'fill_any_like':
1599 1600
                    ref_var_name = grad_op.input_arg_names[0]
                    ref_var = vars[ref_var_name]
1601 1602 1603 1604 1605
                    ref_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_var
                        )
                    )
1606 1607 1608
                    ref_dims_mapping = ref_dist_attr.dims_mapping
                    ref_process_mesh = ref_dist_attr.process_mesh
                    # output
1609
                    tensor_dist_attr = TensorDistAttr()
1610 1611 1612 1613 1614
                    tensor_dist_attr.dims_mapping = ref_dims_mapping
                    tensor_dist_attr.process_mesh = ref_process_mesh
                    output_var_name = grad_op.output_arg_names[0]
                    output_var = vars[output_var_name]
                    self._dist_context.set_tensor_dist_attr_for_program(
1615 1616
                        output_var, tensor_dist_attr
                    )
1617
                    # op
1618
                    grad_op_dist_attr = OperatorDistAttr()
1619
                    grad_op_dist_attr.process_mesh = ref_process_mesh
1620
                    grad_op_dist_attr.set_input_dims_mapping(
1621 1622
                        ref_var_name, ref_dims_mapping
                    )
1623
                    grad_op_dist_attr.set_output_dims_mapping(
1624 1625
                        output_var_name, ref_dims_mapping
                    )
1626 1627

                else:
1628 1629 1630
                    raise ValueError(
                        "got unexpect op [{}]".format(str(grad_op.type))
                    )
1631 1632

                self._dist_context.set_op_dist_attr_for_program(
1633 1634
                    grad_op, grad_op_dist_attr
                )
1635

1636
    def complete_update_annotation(self, serial_main_program):
1637
        """Complete the annotation of vars and ops in the update phase for parallel program."""
1638 1639
        # Copy the dist tensors and dist ops annotated by users from the default context
        # global mesh
1640 1641 1642 1643
        from paddle.distributed.auto_parallel.process_group import (
            get_world_process_group,
        )

1644
        world_ranks = get_world_process_group().ranks
1645 1646

        # Notice: serial_main_program is actually a dist_main_program of current rank,
1647
        # and must be passed into this function.
1648 1649
        # TODO: We should fix this behavior.

1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
        ops = list(serial_main_program.global_block().ops)
        vars = serial_main_program.global_block().vars
        learning_rate_completed = False

        for idx in range(len(ops)):

            # complete the annotation of the optimizer op.
            # TODO to add attribute for moment var
            op = ops[idx]
            if int(op.attr('op_role')) == int(OpRole.Optimize):
1660
                if is_gradient_clip_op(op):
1661
                    if op.type in [
1662 1663 1664 1665 1666
                        "sum",
                        "sqrt",
                        "fill_constant",
                        "elementwise_max",
                        "elementwise_div",
1667
                    ]:
1668
                        # complete op dist_attr with global world ranks
1669 1670 1671
                        op_dist_attr = OperatorDistAttr()
                        op_dist_attr.process_mesh = ProcessMesh(world_ranks)

1672 1673 1674
                        for in_name in op.input_arg_names:
                            in_var = vars[in_name]
                            in_dist_attr = self._dist_context.get_tensor_dist_attr_for_program(
1675 1676
                                in_var
                            )
1677 1678
                            op_dist_attr.set_input_dims_mapping(
                                in_name, in_dist_attr.dims_mapping
1679
                            )
1680 1681
                        for out_name in op.output_arg_names:
                            out_var = vars[out_name]
1682 1683 1684 1685
                            out_dist_attr = TensorDistAttr()
                            out_dist_attr.process_mesh = ProcessMesh(
                                world_ranks
                            )
1686 1687 1688 1689
                            out_dist_attr.dims_mapping = [
                                -1 for _ in range(len(out_var.shape))
                            ]
                            self._dist_context.set_tensor_dist_attr_for_program(
1690 1691
                                out_var, out_dist_attr
                            )
1692 1693
                            op_dist_attr.set_output_dims_mapping(
                                out_name, out_dist_attr.dims_mapping
1694
                            )
1695
                    else:
1696
                        # get ref_process_mesh and ref_dims_mapping from input_var
1697
                        in_var = vars[op.input("X")[0]]
1698 1699 1700 1701 1702
                        in_dist_attr = (
                            self._dist_context.get_tensor_dist_attr_for_program(
                                in_var
                            )
                        )
1703 1704 1705 1706
                        assert in_dist_attr is not None
                        ref_process_mesh = in_dist_attr.process_mesh
                        ref_dims_mapping = in_dist_attr.dims_mapping

1707 1708 1709 1710
                        if (
                            op.type == "cast"
                            and ops[idx + 1].type == "elementwise_mul"
                        ):
1711 1712 1713
                            ref_var = vars[
                                ops[idx + 1].input("X")[0]
                            ]  # elementwise_mul 的输入
1714
                            ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program(
1715 1716
                                ref_var
                            )
1717 1718 1719
                            assert ref_dist_attr is not None
                            ref_process_mesh = ref_dist_attr.process_mesh

1720
                        # complete out_var's tensor_dist_attr
1721
                        out_var = vars[op.output("Out")[0]]
1722
                        out_dist_attr = TensorDistAttr()
1723 1724 1725 1726
                        out_dist_attr.process_mesh = ref_process_mesh
                        if out_var.shape == in_var.shape:
                            out_dist_attr.dims_mapping = ref_dims_mapping
                        else:
1727 1728 1729 1730
                            assert (
                                len(out_var.shape) == 1
                                and out_var.shape[0] == 1
                            )
1731 1732
                            out_dist_attr.dims_mapping = [-1]
                        self._dist_context.set_tensor_dist_attr_for_program(
1733 1734
                            out_var, out_dist_attr
                        )
1735

1736 1737
                        # complete op'd dist_attr
                        # complete op process_mesh with input_var's process_mesh
1738
                        op_dist_attr = OperatorDistAttr()
1739
                        op_dist_attr.process_mesh = ref_process_mesh
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
                        for in_name in op.input_arg_names:
                            in_var = vars[in_name]
                            in_dist_attr = self._dist_context.get_tensor_dist_attr_for_program(
                                in_var
                            )
                            op_dist_attr.set_input_dims_mapping(
                                in_name, in_dist_attr.dims_mapping
                            )
                        for out_name in op.output_arg_names:
                            out_var = vars[out_name]
                            out_dist_attr = self._dist_context.get_tensor_dist_attr_for_program(
                                out_var
                            )
                            op_dist_attr.set_output_dims_mapping(
                                out_name, out_dist_attr.dims_mapping
                            )
Z
zhaoyingli 已提交
1756 1757

                    self._dist_context.set_op_dist_attr_for_program(
1758 1759
                        op, op_dist_attr
                    )
1760 1761

                if "Grad" in op.input_names and "Param" in ops[idx].input_names:
1762 1763 1764 1765 1766 1767
                    assert (
                        len(op.input("Param")) == 1
                    ), "Only support one-to-one now."
                    assert (
                        len(op.input("Grad")) == 1
                    ), "Only support one-to-one now."
1768 1769 1770
                    param = vars[op.input("Param")[0]]
                    grad_var = vars[op.input("Grad")[0]]

1771 1772 1773 1774 1775
                    param_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        )
                    )
1776
                    assert param_dist_attr is not None
1777 1778 1779 1780 1781
                    ref_process_mesh = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        ).process_mesh
                    )
1782
                    assert ref_process_mesh is not None
1783 1784 1785 1786 1787
                    ref_dims_mapping = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        ).dims_mapping
                    )
1788
                    assert ref_dims_mapping is not None
1789
                    op_dist_attr = OperatorDistAttr()
1790
                    op_dist_attr.process_mesh = ref_process_mesh
1791 1792 1793 1794 1795 1796
                    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
                    )
1797
                    op_dist_attr.set_output_dims_mapping(
1798 1799
                        param.name, ref_dims_mapping
                    )
1800 1801
                    learning_var = vars[op.input("LearningRate")[0]]
                    op_dist_attr.set_input_dims_mapping(learning_var.name, [-1])
1802
                    op_dist_attr.set_output_dims_mapping(
1803 1804
                        learning_var.name, [-1]
                    )
1805 1806 1807

                    if not learning_rate_completed:
                        learning_rate_completed = True
1808 1809
                        var_dist_attr = TensorDistAttr()
                        var_dist_attr.process_mesh = ProcessMesh(world_ranks)
1810 1811
                        var_dist_attr.dims_mapping = [-1]
                        self._dist_context.set_tensor_dist_attr_for_program(
1812 1813
                            learning_var, var_dist_attr
                        )
1814 1815 1816 1817

                    for input_name in op.desc.input_names():

                        if input_name in [
1818 1819 1820 1821 1822 1823
                            'Param',
                            'Grad',
                            'LearningRate',
                            "Beta1Tensor",
                            "Beta2Tensor",
                            "EpsilonTensor",
1824 1825
                        ]:
                            continue
1826 1827
                        if len(op.desc.input(input_name)) == 0:
                            continue
1828 1829 1830

                        assert len(op.desc.input(input_name)) == 1
                        input_var = vars[op.desc.input(input_name)[0]]
1831
                        input_var_attr = TensorDistAttr()
1832

1833 1834 1835 1836 1837
                        if (
                            "Beta1Pow" in input_name
                            or "Beta2Pow" in input_name
                            or "SkipUpdate" in input_name
                        ):
1838
                            input_var_attr.dims_mapping = [-1]
1839
                            op_dist_attr.set_input_dims_mapping(
1840 1841
                                input_var.name, [-1]
                            )
1842
                            op_dist_attr.set_output_dims_mapping(
1843 1844
                                input_var.name, [-1]
                            )
1845 1846 1847
                        else:
                            input_var_attr.dims_mapping = ref_dims_mapping
                            op_dist_attr.set_input_dims_mapping(
1848 1849
                                input_var.name, ref_dims_mapping
                            )
1850
                            op_dist_attr.set_output_dims_mapping(
1851 1852
                                input_var.name, ref_dims_mapping
                            )
1853 1854 1855

                        input_var_attr.process_mesh = ref_process_mesh
                        self._dist_context.set_tensor_dist_attr_for_program(
1856 1857
                            input_var, input_var_attr
                        )
1858 1859

                    self._dist_context.set_op_dist_attr_for_program(
1860 1861
                        op, op_dist_attr
                    )
1862
                    continue
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875

    def complete_prim_annotation(self, serial_main_program=None):
        """
        fill default data parallel annotation for program with primitive operators.

        Arguments:
            serial_main_program: partial annotated serial_main_program.
        Returns:
            serial_main_program: completed annotated serial_main_program.
        """
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
Z
zhaoyingli 已提交
1876
            self._dist_context._serial_main_program = serial_main_program
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

        self._dist_context._is_initialized = True
        self._dist_context._init_dist_attr_for_program()
        self._init_global_mesh_for_program()
        # Do the validation check and amend some completion
        self._dist_context.amend_dist_attr_for_program()
        self._dist_context.validate_dist_attr_for_program()

    def _init_global_mesh_for_program(self):
        # Copy the dist tensors and dist ops annotated by users from the default context
        # global mesh
1888 1889 1890 1891
        from paddle.distributed.auto_parallel.process_group import (
            get_world_process_group,
        )

1892 1893 1894 1895 1896 1897
        world_ranks = get_world_process_group().ranks

        for block in self._dist_context._serial_main_program.blocks:
            for tensor in block.vars.values():
                # Copy the distributed tensors in the default context
                dist_tensor = self._dist_context.get_dist_tensor_for_program(
1898 1899
                    tensor
                )
1900
                assert dist_tensor is not None
1901
                dist_tensor.dist_attr.process_mesh = ProcessMesh(world_ranks)
1902 1903 1904 1905
            for op in block.ops:
                # Copy the distributed operators in the default context
                dist_op = self._dist_context.get_dist_op_for_program(op)
                assert dist_op is not None
1906
                dist_op.dist_attr.process_mesh = ProcessMesh(world_ranks)
1907 1908

                # Find the most compatible implemenetations from the distributed operator
1909
                op_dist_impls = find_compatible_distributed_operator_impls(
1910 1911
                    dist_op, fwd=True
                )
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
                if op_dist_impls is not None:
                    backup_op_dist_attr = copy.deepcopy(dist_op.dist_attr)
                    for op_dist_impl in op_dist_impls:
                        dim_changed = op_dist_impl.update_dims_mapping(dist_op)
                        if op_dist_impl.is_auto_compatible(dist_op):
                            if op_dist_impl.type == "elementwise":
                                dist_op.dist_attr.impl_type = "default"
                            else:
                                dist_op.dist_attr.impl_type = op_dist_impl.type
                            # op_dist_attr.impl_type = op_dist_impl.type
                            dist_op.dist_attr.impl_idx = op_dist_impl.idx
                            break
                        else:
                            dist_op.dist_attr = backup_op_dist_attr