completion.py 88.0 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
from copy import deepcopy
17
import time
18
from numpy import sort
19 20 21 22

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

23
from .utils import is_gradient_clip_op, __not_shape_var_type__
24
from .operators import find_compatible_distributed_operator_impls
25
from .dist_context import get_default_distributed_context, _node_id
26 27 28 29
from .dist_tensor import DistributedTensor
from .dist_op import DistributedOperator
from .dist_attribute import TensorDistributedAttribute
from .dist_attribute import OperatorDistributedAttribute
30
from .process_mesh import ProcessMesh
31
from .process_group import get_world_process_group
32
from paddle.distributed.fleet.meta_optimizers.common import OpRole
33 34


35 36 37 38
def compute_compatible_process_mesh(process_mesh_list):
    """Compute the compatible process mesh given a list of process meshes."""
    if not process_mesh_list:
        return None
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    def _compute_compatible_process_mesh_two(pm1, pm2):
        if pm1 is None:
            return True, pm2
        if pm2 is None:
            return True, pm1
        if pm1 == pm2:
            return True, pm1
        if pm1.processes == pm2.processes:
            if len(pm1.topology) >= len(pm2.topology):
                return True, pm1
            else:
                return True, pm2
        process_set1 = set(pm1.processes)
        process_set2 = set(pm2.processes)
        if process_set1.issubset(process_set2):
            return True, pm2
        if process_set2.issubset(process_set1):
            return True, pm1
        return False, None

    compatible_result = None
    for process_mesh in process_mesh_list:
        compatible, compatible_result = _compute_compatible_process_mesh_two(
63 64
            compatible_result, process_mesh
        )
65 66 67 68 69 70 71 72 73
        if not compatible:
            return None
    return copy.deepcopy(compatible_result)


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
74

75 76 77 78 79 80 81 82 83 84 85 86
    def _compute_compatible_dim_mapping_two(dm1, dm2):
        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:
        compatible, compatible_result = _compute_compatible_dim_mapping_two(
87 88
            compatible_result, mapping
        )
89 90 91 92 93 94 95
        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.
96
    Each of dims mapping is also a list.
97
    """
98 99 100 101 102 103 104 105 106 107 108
    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(
109 110
            list(dim_mappings)
        )
111 112 113 114 115 116
        if compatible_dim_mapping is None:
            return None
        compatible_result.append(compatible_dim_mapping)
    return compatible_result


117 118 119 120 121 122 123 124 125 126 127 128 129 130
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:
        process_set1 = set(pm1.processes)
    if pm2 is not None:
        process_set2 = set(pm2.processes)
    merged_process_set = process_set1.union(process_set2)
    merged_process_mesh = ProcessMesh(list(merged_process_set))
    return merged_process_mesh


131 132 133 134 135
def _validate_dims_mapping(dims_mapping, process_mesh):
    if dims_mapping is None:
        return False
    for i in range(len(dims_mapping)):
        if dims_mapping[i] < -1 or dims_mapping[i] >= len(
136 137
            process_mesh.topology
        ):
138 139 140 141 142 143 144
            return False
    for i in range(len(process_mesh.topology)):
        if dims_mapping.count(i) > 1:
            return False
    return True


145 146 147 148
class Completer:
    def __init__(self, dist_context):
        assert dist_context is not None
        self._dist_context = dist_context
149
        self._has_prepared = False
150 151 152 153 154 155 156

    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
157 158 159 160 161
        if (
            tensor_desc.type() == core.VarDesc.VarType.READER
            or tensor_desc.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY
            or tensor_desc.type == core.VarDesc.VarType.STEP_SCOPES
        ):
162 163
            return False
        tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph(
164 165
            tensor_node
        )
166 167 168 169 170 171 172 173
        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:
174 175 176 177 178 179
                    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"
                    ):
180
                        continue
181 182 183 184 185 186 187 188 189
                    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
                    ):
190
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
191 192
                            tensor_desc.name()
                        )
193 194 195
                        dims_mapping_list.append(op_dims_mapping)
            dims_mapping_list.append(tensor_dims_mapping)
            compatible_dims_mapping = compute_compatible_dims_mapping(
196 197 198 199 200
                dims_mapping_list
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, tensor_dist_attr.process_mesh
            ):
201
                return False
202 203 204
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != tensor_dims_mapping
            ):
205
                tensor_dist_attr.dims_mapping = compatible_dims_mapping
206 207
                changed = True
        else:
208 209 210
            dims_mapping_list = []
            for succ_op_node in tensor_node.outputs:
                if succ_op_node.op() is not None:
211 212 213 214 215 216
                    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"
                    ):
217
                        continue
218 219 220 221 222 223 224 225 226
                    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
                    ):
227
                        op_dims_mapping = op_dist_attr.get_input_dims_mapping(
228 229
                            tensor_desc.name()
                        )
230 231 232
                        dims_mapping_list.append(op_dims_mapping)
            dims_mapping_list.append(tensor_dims_mapping)
            compatible_dims_mapping = compute_compatible_dims_mapping(
233 234 235 236 237
                dims_mapping_list
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, tensor_dist_attr.process_mesh
            ):
238
                return False
239 240 241
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != tensor_dims_mapping
            ):
242
                tensor_dist_attr.dims_mapping = compatible_dims_mapping
243
                changed = True
244
        return changed
245

246 247 248 249 250 251
    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()
252 253 254 255 256 257
        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"
        ):
258 259 260
            return False
        dist_op = self._dist_context.get_dist_op_for_graph(op_node)
        op_dist_attr = dist_op.dist_attr
261
        original_op_dist_attr = copy.deepcopy(op_dist_attr)
262 263
        if fwd:
            for tensor_node in op_node.inputs:
264
                if tensor_node.is_var() and tensor_node.var() is not None:
265 266 267 268
                    if tensor_node.var().type() == core.VarDesc.VarType.READER:
                        continue
                    tensor_desc = tensor_node.var()
                    if op_dist_attr.is_annotated_input_dims_mapping(
269 270
                        tensor_desc.name()
                    ):
271
                        continue
272 273 274 275 276 277 278 279 280
                    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
                    ):
281 282
                        tensor_dims_mapping = tensor_dist_attr.dims_mapping
                        op_dims_mapping = op_dist_attr.get_input_dims_mapping(
283 284 285 286 287 288 289
                            tensor_desc.name()
                        )
                        compatible_dims_mapping = (
                            compute_compatible_dims_mapping(
                                [op_dims_mapping, tensor_dims_mapping]
                            )
                        )
290
                        if not _validate_dims_mapping(
291 292
                            compatible_dims_mapping, op_dist_attr.process_mesh
                        ):
293
                            continue
294 295 296
                        if (compatible_dims_mapping is not None) and (
                            compatible_dims_mapping != op_dims_mapping
                        ):
297
                            op_dist_attr.set_input_dims_mapping(
298 299
                                tensor_desc.name(), compatible_dims_mapping
                            )
300 301
                            changed = True
            # Find the most compatible implemenetations from the distributed operator
302 303 304
            op_dist_impls = find_compatible_distributed_operator_impls(
                dist_op, fwd=True
            )
305 306 307 308 309 310 311 312
            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
313 314 315 316
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
317 318 319 320 321 322 323 324
                        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
325
                    else:
326 327 328 329 330 331 332 333
                        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
334
        else:
335
            for tensor_node in op_node.outputs:
336
                if tensor_node.is_var() and tensor_node.var() is not None:
337 338 339 340
                    if tensor_node.var().type() == core.VarDesc.VarType.READER:
                        continue
                    tensor_desc = tensor_node.var()
                    if op_dist_attr.is_annotated_output_dims_mapping(
341 342
                        tensor_desc.name()
                    ):
343
                        continue
344 345 346 347 348 349 350 351 352
                    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
                    ):
353 354
                        tensor_dims_mapping = tensor_dist_attr.dims_mapping
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
355 356 357 358 359 360 361
                            tensor_desc.name()
                        )
                        compatible_dims_mapping = (
                            compute_compatible_dims_mapping(
                                [op_dims_mapping, tensor_dims_mapping]
                            )
                        )
362
                        if not _validate_dims_mapping(
363 364
                            compatible_dims_mapping, op_dist_attr.process_mesh
                        ):
365
                            continue
366 367 368
                        if (compatible_dims_mapping is not None) and (
                            compatible_dims_mapping != op_dims_mapping
                        ):
369
                            op_dist_attr.set_output_dims_mapping(
370 371
                                tensor_desc.name(), compatible_dims_mapping
                            )
372 373
                            changed = True
            # Find the most compatible implemenetations from the distributed operator
374
            op_dist_impls = find_compatible_distributed_operator_impls(
375 376
                dist_op, fwd=False
            )
377 378 379 380 381 382 383 384
            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
385 386 387 388
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
389 390 391 392 393 394 395 396
                        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
397
                    else:
398 399 400 401 402 403 404 405
                        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
406
        return changed
407

408 409 410 411
    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(
412 413
                parent_node
            )
414
            child_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
415 416 417 418 419 420
                child_node
            )
            if (
                parent_node_dist_attr.process_mesh
                != child_node_dist_attr.process_mesh
            ):
421
                continue
422 423 424
            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(
425 426 427 428 429
                [parent_node_dims_mapping, child_node_dims_mapping]
            )
            if not _validate_dims_mapping(
                compatible_dims_mapping, parent_node_dist_attr.process_mesh
            ):
430
                return False
431 432 433
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != parent_node_dims_mapping
            ):
434 435
                parent_node_dist_attr.dims_mapping = compatible_dims_mapping
                changed = True
436 437 438
            if (compatible_dims_mapping is not None) and (
                compatible_dims_mapping != child_node_dims_mapping
            ):
439
                child_node_dist_attr.dims_mapping = compatible_dims_mapping
440 441
                changed = True
        return changed
442

443 444 445
    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
446 447
        # NOTE: this list may be changed if Paddle changes the existing rules.
        related_reader_ops = [
448 449 450
            "create_py_reader",
            "create_double_buffer_reader",
            "read",
451
        ]
452
        for op_node in op_nodes:
453 454 455 456
            if (
                op_node.op() is not None
                and op_node.op().type() in related_reader_ops
            ):
457
                continue
458 459 460 461 462 463
            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()
464 465 466 467 468 469 470 471 472
                    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
                    ):
473
                        op_dims_mapping = op_dist_attr.get_output_dims_mapping(
474 475
                            tensor_desc.name()
                        )
476 477
                        tensor_dist_attr.dims_mapping = op_dims_mapping

478 479 480 481
    def _update_dims_mapping(self):
        # Complete dims_mapping for each node
        reach_fix_point = False
        while not reach_fix_point:
482
            changed = False
483
            for is_fwd in [True, False]:
484 485 486 487 488
                all_nodes = (
                    self._dist_context.serial_ordered_nodes
                    if is_fwd
                    else reversed(self._dist_context.serial_ordered_nodes)
                )
489 490 491
                for node in all_nodes:
                    if node.is_var() and node.var() is not None:
                        tensor_changed = self._update_tensor_node_dims_mapping(
492 493
                            node, fwd=is_fwd
                        )
494 495 496 497
                        if tensor_changed:
                            changed = True
                    if node.is_op() and node.op() is not None:
                        op_changed = self._update_op_node_dims_mapping(
498 499
                            node, fwd=is_fwd
                        )
500 501
                        if op_changed:
                            changed = True
502 503 504
                graph_changed = self._update_dims_mapping_between_graphs()
                if graph_changed:
                    changed = True
505
            if changed:
506
                reach_fix_point = False
507
            else:
508
                reach_fix_point = True
509
        # NOTE: this will be removed after changing the reshard rule
510
        self._update_dims_mapping_for_special()
511

512 513 514 515 516 517
    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(
518 519
                nearest_op_node
            )
520 521
            nearest_process_mesh = nearest_op_dis_attr.process_mesh
            compatible_process_mesh = compute_compatible_process_mesh(
522 523 524 525 526 527
                [process_mesh, nearest_process_mesh]
            )
            if (
                compatible_process_mesh is not None
                and process_mesh != compatible_process_mesh
            ):
528 529 530 531 532 533 534
                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:
535 536 537 538 539
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_graph(
                        tensor_node
                    )
                )
540 541 542 543 544 545
                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(
546 547 548 549 550 551
                    [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
                ):
552
                    tensor_dist_attr.process_mesh = compatible_process_mesh
553
                # Set the process mesh of the op node's outputs
554 555
        for tensor_node in op_node.outputs:
            if tensor_node.is_var() and tensor_node.var() is not None:
556 557 558 559 560
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_graph(
                        tensor_node
                    )
                )
561 562 563
                if tensor_dist_attr.is_annotated("process_mesh"):
                    continue
                compatible_process_mesh = compute_compatible_process_mesh(
564 565 566 567 568 569
                    [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
                ):
570 571 572 573 574
                    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]):
575 576 577 578 579
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == var_name
                ):
580 581 582
                    return node

        def _find_nearest_tensor_node_after(nodes, idx, var_name):
583 584 585 586 587 588
            for node in nodes[idx + 1 :]:
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == var_name
                ):
589 590 591 592 593 594 595 596 597 598 599 600 601 602
                    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
603 604
                neighbors = cur.inputs + cur.outputs
                for node in neighbors:
605
                    if node.is_var() and node.var() is not None:
606 607 608 609
                        if (
                            node.var().type() != core.VarDesc.VarType.READER
                            and len(node.var().shape()) == 1
                        ):
610 611 612 613
                            frontier.append(node)
                            related_nodes.append(node)
                    if node.is_op() and node.op() is not None:
                        flag = True
614 615 616 617 618
                        if (
                            node.op().type() == "create_py_reader"
                            or node.op().type() == "create_double_buffer_reader"
                            or node.op().type() == "read"
                        ):
619 620
                            flag = False
                        for tensor_node in node.inputs:
621 622 623 624 625 626 627 628 629
                            if (
                                tensor_node.is_var()
                                and tensor_node.var() is not None
                            ):
                                if (
                                    tensor_node.var().type()
                                    in __not_shape_var_type__
                                    or len(tensor_node.var().shape()) != 1
                                ):
630 631 632
                                    flag = False
                                    break
                        for tensor_node in node.outputs:
633 634 635 636 637 638 639 640 641
                            if (
                                tensor_node.is_var()
                                and tensor_node.var() is not None
                            ):
                                if (
                                    tensor_node.var().type()
                                    in __not_shape_var_type__
                                    or len(tensor_node.var().shape()) != 1
                                ):
642 643 644 645 646 647 648 649
                                    flag = False
                                    break
                        if flag:
                            frontier.append(node)
                            related_nodes.append(node)
                visited.add(_node_id(cur))
            return related_nodes

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
        def _make_dims_mapping_replicate(dist_attr):
            if isinstance(dist_attr, TensorDistributedAttribute):
                for i, _ in enumerate(dist_attr.dims_mapping):
                    dist_attr.dims_mapping[i] = -1
            if isinstance(dist_attr, OperatorDistributedAttribute):
                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)
666 667 668
                    dist_attr.set_output_dims_mapping(
                        arg_name, new_dims_mapping
                    )
669

670 671 672
        # 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")
673
            sub_graph = self._dist_context.serial_graph.get_sub_graph(
674 675
                sub_graph_id
            )
676 677
            sub_graph_nodes = list(sub_graph.all_nodes())
            while_dist_op = self._dist_context.get_dist_op_for_graph(
678 679
                while_op_node
            )
680 681 682 683 684
            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:
685 686 687
                if (node.is_var() and node.var() is not None) or (
                    node.is_op() and node.op() is not None
                ):
688 689
                    dist_attr = self._dist_context.get_dist_attr_for_graph(node)
                    merged_process_mesh = merge_process_mesh_two(
690 691
                        merged_process_mesh, dist_attr.process_mesh
                    )
692
            while_op_dist_attr.process_mesh = merged_process_mesh
693
            _make_dims_mapping_replicate(while_op_dist_attr)
694 695 696 697 698 699 700

            # 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:
701 702 703 704 705
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == cond_tensor_name
                ):
706 707 708 709 710
                    cond_tensor_node = node
                    cond_tensor_related_nodes.append(cond_tensor_node)
                    break

            cond_tensor_related_nodes.extend(
711 712
                _find_nodes_related_to_cond(cond_tensor_node)
            )
713 714 715 716

            # 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):
717 718 719 720 721 722
                if (
                    node.is_var()
                    and node.var() is not None
                    and node.var().name() == cond_tensor_name
                    and len(node.outputs) == 0
                ):
723 724 725 726
                    cond_tensor_node = node
                    break

            cond_tensor_related_nodes.extend(
727 728
                _find_nodes_related_to_cond(cond_tensor_node)
            )
729 730 731 732
            # 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:
733 734 735 736 737
                if (
                    output_node.is_var()
                    and output_node.var() is not None
                    and output_node.var().name() == stepscopes_tensor_name
                ):
738 739 740 741 742
                    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(
743 744
                    node
                )
745
                tensor_dist_attr.process_mesh = merged_process_mesh
746
                _make_dims_mapping_replicate(tensor_dist_attr)
747 748 749

            # 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
750 751 752 753
            for (
                tensor_name,
                tensor_dist_attr,
            ) in while_op_inputs_dist_attrs.items():
754
                nearest_tensor_node = _find_nearest_tensor_node_before(
755 756 757 758 759 760 761 762 763 764 765 766
                    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
                )
767 768 769

            # 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
770 771 772 773
            for (
                tensor_name,
                tensor_dist_attr,
            ) in while_op_outputs_dist_attrs.items():
774
                nearest_tensor_node = _find_nearest_tensor_node_before(
775 776 777 778
                    self._dist_context.serial_ordered_nodes,
                    while_op_node_idx,
                    tensor_name,
                )
779 780 781
                if nearest_tensor_node is None:
                    nearest_tensor_node = _find_nearest_tensor_node_after(
                        self._dist_context.serial_ordered_nodes,
782 783 784 785 786 787 788 789 790 791 792
                        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
                )
793 794 795 796 797 798

        # 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(
799 800
                    array_node
                )
801
                merged_process_mesh = merge_process_mesh_two(
802 803
                    merged_process_mesh, dist_attr.process_mesh
                )
804 805
            for array_node in array_node_list:
                dist_attr = self._dist_context.get_dist_attr_for_graph(
806 807
                    array_node
                )
808
                dist_attr.process_mesh = merged_process_mesh
809 810 811 812 813
                _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(
814 815
                parent_node
            )
816
            child_node_dist_attr = self._dist_context.get_dist_attr_for_graph(
817 818 819
                child_node
            )
            parent_node_dist_attr.process_mesh = (
820
                child_node_dist_attr.process_mesh
821 822 823 824 825 826 827 828 829 830 831 832
            )
            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
            ):
833
                parent_node_dist_attr.process_mesh = compatible_process_mesh
834 835 836 837
            if (
                compatible_process_mesh is not None
                and child_node_dist_attr.process_mesh != compatible_process_mesh
            ):
838
                child_node_dist_attr.process_mesh = compatible_process_mesh
839 840 841 842 843 844 845

    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:
846 847 848
            tensor_dist_attr = (
                self._dist_context.get_tensor_dist_attr_for_graph(tensor_node)
            )
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
            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(
866 867
                first_op_node
            )
868
            if op_dist_attr is not None and not op_dist_attr.is_annotated(
869 870
                "process_mesh"
            ):
871
                compatible_process_mesh = compute_compatible_process_mesh(
872 873 874 875 876 877
                    [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
                ):
878 879 880 881 882 883 884
                    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)
885 886 887 888
            if (
                op_dist_attr.process_mesh is not None
                and idx_of_first_op_node_has_process_mesh == -1
            ):
889 890 891 892 893 894
                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
895
        for idx, op_node in enumerate(
896 897
            ordered_op_nodes[idx_of_first_op_node_has_process_mesh + 1 :]
        ):
898
            original_idx = idx_of_first_op_node_has_process_mesh + idx + 1
899 900
            nearest_op_node = ordered_op_nodes[original_idx - 1]
            nearest_op_dist_attr = self._dist_context.get_dist_attr_for_graph(
901 902
                nearest_op_node
            )
903 904 905 906 907
            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[
908 909
            idx_of_first_op_node_has_process_mesh
        ]
910 911 912 913 914 915
        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()

916
        # Step 4: adjust the process meshes between graphs
917 918
        self._update_process_mesh_between_graphs()

919
    def _prepare(self):
920 921 922 923 924 925 926 927 928 929 930 931 932 933
        def _find_nearest_parent_nodes(sorted_parent_nodes, child_idx):
            before_node = None
            after_node = None
            pos = -1
            for pos, (parent_idx, parent_node) in enumerate(
                sorted_parent_nodes
            ):
                if parent_idx > child_idx:
                    after_node = parent_node
                    break
            if pos > 0:
                _, before_node = sorted_parent_nodes[pos - 1]
            return before_node, after_node

934 935
        if self._has_prepared:
            return
936 937 938 939 940 941 942 943 944 945 946 947 948
        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)
949 950
                    # Add the array input node
                    self._array_nodes[array_var_name].append(node.inputs[0])
951 952 953 954 955 956
                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])
957 958
            # TODO: Use dict and name as the key to store the nodes,
            # and use the id comparsion to deal with the before or after position
959 960
            if node.is_var() and node.var() is not None:
                if node.node.graph_id() != 0:
961 962 963 964 965 966 967 968 969 970
                    parent_nodes = (
                        self._dist_context._tensor_nodes_with_same_name[
                            node.node.graph_id() - 1
                        ].get(node.var().name(), None)
                    )
                    if parent_nodes is not None:
                        sorted_parent_nodes = sorted(
                            parent_nodes, key=lambda x: x[0]
                        )
                        for _, parent_node in sorted_parent_nodes:
971
                            self._node_pairs_between_graphs.append(
972 973
                                (parent_node, node)
                            )
974
        self._has_prepared = True
975

976
    def complete_forward_annotation(self, serial_main_program=None):
977
        """Complete annotation for the partial annotated serial_main_program.
978 979
        Arguments:
            serial_main_program: partial annotated serial_main_program.
980
        Returns:e
981 982 983
            serial_main_program: completed annotated serial_main_program.
        """

984 985 986
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
987
            self._dist_context._serial_main_program = serial_main_program
988

989 990 991 992
        start_time = time.time()
        # print("start time", start_time, flush=True)
        if not self._dist_context.data_parallel:
            self._dist_context.initialize(with_graph=True)
993

994
            # self._dist_context.validate_dist_attr_for_program()
995

996
            start_time = time.time()
997
            self._prepare()
998
            # print("completion-prepare: ", time.time() - start_time, flush=True)
999

1000
            start_time = time.time()
1001
            self._update_process_mesh()
1002
            # print("completion-mesh: ", time.time() - start_time, flush=True)
1003

1004
            start_time = time.time()
1005
            self._update_dims_mapping()
1006
            # print("graph-dims: ", time.time() - start_time, flush=True)
1007

1008
            start_time = time.time()
1009 1010
            # Copy the corresponding distributed attribute from graph to serial_main_program
            self._dist_context.copy_dist_attr_from_graph_to_program()
1011
            # print("completion-copy: ", time.time() - start_time, flush=True)
1012 1013 1014 1015 1016 1017 1018 1019
        else:
            self._dist_context.initialize(with_graph=False)

            # A fast and special completion for data parallel
            self._update_dist_attr_for_dp()

            # print_program_with_dist_attr(self._dist_context.serial_main_program,
            #                              self._dist_context)
1020

1021
        # NOTE:[HighOrderGrad] update vars and ops distributed attribute in high order gradient
1022
        self._complete_high_order_grad_annotation(serial_main_program)
1023

1024 1025 1026 1027 1028
        # Do the validation check and amend some completion
        self._dist_context.amend_dist_attr_for_program()

        self._dist_context.validate_dist_attr_for_program()

1029 1030 1031 1032
        end_time = time.time()
        # print("end time", end_time, flush=True)
        # print("elapsed time", end_time - start_time, flush=True)

1033 1034
        return serial_main_program

1035 1036 1037 1038
    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)
1039 1040 1041
        for (
            dist_tensor
        ) in self._dist_context._dist_tensors_for_program.values():
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
            serial_tensor = dist_tensor.serial_tensor
            tensor_dist_attr = dist_tensor.dist_attr
            tensor_dist_attr.process_mesh = process_mesh

        for dist_op in self._dist_context._dist_ops_for_program.values():
            serial_op = dist_op.serial_op
            op_desc = serial_op.desc
            op_dist_attr = dist_op.dist_attr
            op_dist_attr.process_mesh = process_mesh
            original_op_dist_attr = copy.deepcopy(op_dist_attr)
            input_xshape_arg_names = []
            if "XShape" in op_desc.input_names():
                input_xshape_arg_names = op_desc.input("XShape")
            for arg_name in serial_op.input_arg_names:
                serial_tensor = dist_op.get_serial_input(arg_name)
                if not serial_tensor.is_parameter:
                    if arg_name not in input_xshape_arg_names:
                        old_dims_mapping = op_dist_attr.get_input_dims_mapping(
1060 1061
                            arg_name
                        )
1062 1063 1064 1065 1066
                        if len(old_dims_mapping) > 0:
                            new_dims_mapping = [0] + [
                                -1 for _ in range(len(old_dims_mapping) - 1)
                            ]
                            op_dist_attr.set_input_dims_mapping(
1067 1068
                                arg_name, new_dims_mapping
                            )
1069 1070
                    else:
                        old_dims_mapping = op_dist_attr.get_input_dims_mapping(
1071 1072
                            arg_name
                        )
1073 1074 1075 1076 1077
                        if len(old_dims_mapping) > 1:
                            new_dims_mapping = [-1, 0] + [
                                -1 for _ in range(len(old_dims_mapping) - 2)
                            ]
                            op_dist_attr.set_input_dims_mapping(
1078 1079
                                arg_name, new_dims_mapping
                            )
1080
                # Set tensor's dims_mapping by the op's
1081 1082 1083 1084 1085 1086 1087 1088
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_program(
                        serial_tensor
                    )
                )
                tensor_dist_attr.dims_mapping = (
                    op_dist_attr.get_input_dims_mapping(arg_name)
                )
1089 1090 1091 1092 1093 1094 1095 1096
            output_xshape_arg_names = []
            if "XShape" in op_desc.output_names():
                output_xshape_arg_names = op_desc.output("XShape")
            for arg_name in serial_op.output_arg_names:
                serial_tensor = dist_op.get_serial_output(arg_name)
                if not serial_tensor.is_parameter:
                    if arg_name not in output_xshape_arg_names:
                        old_dims_mapping = op_dist_attr.get_output_dims_mapping(
1097 1098
                            arg_name
                        )
1099 1100 1101 1102 1103
                        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(
1104 1105
                                arg_name, new_dims_mapping
                            )
1106 1107
                    else:
                        old_dims_mapping = op_dist_attr.get_output_dims_mapping(
1108 1109
                            arg_name
                        )
1110 1111 1112 1113 1114
                        if len(old_dims_mapping) > 1:
                            new_dims_mapping = [-1, 0] + [
                                -1 for _ in range(len(old_dims_mapping) - 2)
                            ]
                            op_dist_attr.set_output_dims_mapping(
1115 1116
                                arg_name, new_dims_mapping
                            )
1117
                # Set tensor's dims_mapping by the op's
1118 1119 1120 1121 1122 1123 1124 1125
                tensor_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_program(
                        serial_tensor
                    )
                )
                tensor_dist_attr.dims_mapping = (
                    op_dist_attr.get_output_dims_mapping(arg_name)
                )
1126 1127

            op_dist_impls = find_compatible_distributed_operator_impls(
1128 1129
                dist_op, partial=False
            )
1130 1131 1132 1133 1134
            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)
1135 1136 1137 1138
                    if (
                        op_dist_impl.is_auto_compatible(dist_op)
                        and dist_op.validate_dist_attr()
                    ):
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                        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

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    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
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                        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()]
                        )
1193 1194 1195 1196 1197 1198
                        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
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
                        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)
                        )
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
                        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()

1228
    def _complete_high_order_grad_annotation(self, serial_main_program=None):
1229
        """
1230
        NOTE:
1231 1232 1233 1234
            [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.
        """

1235 1236 1237 1238 1239
        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

1240 1241 1242 1243 1244 1245 1246
        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:
1247
                if op.desc.original_id() == id:
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
                    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(
1260 1261
                core.op_proto_and_checker_maker.OpRole.Forward
            ):
1262 1263 1264
                continue

            if int(op.attr('op_role')) == int(
1265 1266 1267 1268
                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
            ):
1269 1270
                appended_grad_times += 1

1271
            if int(op.attr('op_role')) == int(
1272 1273 1274
                int(core.op_proto_and_checker_maker.OpRole.Backward)
                | int(core.op_proto_and_checker_maker.OpRole.Loss)
            ):
1275 1276 1277
                assert op.type == "fill_constant"
                break

1278 1279 1280
            # 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]
1281 1282 1283 1284
            if (
                grad_op.desc.original_id()
                in dist_op_context.grad_op_id_to_op_id
            ):
1285
                # TODO support the case where one forward op corresponding to multiple xxx_grad op
1286
                forward_op = _get_op_by_id(
1287 1288 1289 1290 1291
                    ops,
                    dist_op_context.grad_op_id_to_op_id[
                        grad_op.desc.original_id()
                    ],
                )
1292 1293
                assert forward_op is not None

1294 1295 1296
                fwd_op_dist_attr = (
                    self._dist_context.get_op_dist_attr_for_program(forward_op)
                )
1297 1298 1299 1300 1301
                fwd_op_process_mesh = fwd_op_dist_attr.process_mesh
                grad_op_dist_attr = OperatorDistributedAttribute()
                grad_op_dist_attr.process_mesh = fwd_op_process_mesh

                for input_name in grad_op.input_arg_names:
1302 1303 1304 1305
                    if (
                        input_name not in forward_op.input_arg_names
                        and input_name not in forward_op.output_arg_names
                    ):
1306 1307
                        if input_name in grad_var_to_var[appended_grad_times]:
                            fwd_name = grad_var_to_var[appended_grad_times][
1308 1309 1310 1311 1312 1313 1314
                                input_name
                            ]
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    fwd_name
                                )
                            )
1315 1316 1317
                        else:
                            input_var = vars[input_name]
                            ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program(
1318 1319
                                input_var
                            ).dims_mapping
1320 1321
                    else:
                        if fwd_op_dist_attr.get_input_dims_mapping(input_name):
1322 1323 1324 1325 1326
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_input_dims_mapping(
                                    input_name
                                )
                            )
1327
                        else:
1328 1329 1330 1331 1332 1333 1334 1335
                            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)
1336
                    grad_op_dist_attr.set_input_dims_mapping(
1337 1338
                        input_name, ref_dims_mapping
                    )
1339 1340 1341 1342 1343

                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(
1344 1345
                        fwd_name
                    )
1346 1347 1348 1349 1350 1351
                    # var
                    output_var = vars[output_name]
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1352 1353
                        output_var, tensor_dist_attr
                    )
1354
                    # op
1355
                    grad_op_dist_attr.set_output_dims_mapping(
1356 1357
                        output_name, ref_dims_mapping
                    )
1358 1359

                self._dist_context.set_op_dist_attr_for_program(
1360 1361
                    grad_op, grad_op_dist_attr
                )
1362 1363 1364 1365 1366 1367 1368

            # 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]
1369 1370 1371 1372 1373
                    assert (
                        output_name in grad_var_to_var[appended_grad_times]
                    ), "sum op's output '{}' has no corresponding var".format(
                        output_name
                    )
1374
                    ref_fwd_var_name = grad_var_to_var[appended_grad_times][
1375 1376
                        output_name
                    ]
1377
                    ref_fwd_var = vars[ref_fwd_var_name]
1378 1379 1380 1381 1382
                    ref_fwd_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_fwd_var
                        )
                    )
1383 1384 1385 1386 1387 1388 1389 1390
                    ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping
                    ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh
                    # output
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1391 1392
                        output_var, tensor_dist_attr
                    )
1393 1394 1395 1396 1397
                    # op
                    grad_op_dist_attr = OperatorDistributedAttribute()
                    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(
1398 1399
                            var_name, ref_fwd_dims_mapping
                        )
1400
                    grad_op_dist_attr.set_output_dims_mapping(
1401 1402
                        output_name, ref_fwd_dims_mapping
                    )
1403

1404
                elif grad_op.type == 'fill_any_like':
1405 1406
                    ref_var_name = grad_op.input_arg_names[0]
                    ref_var = vars[ref_var_name]
1407 1408 1409 1410 1411
                    ref_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_var
                        )
                    )
1412 1413 1414 1415 1416 1417 1418 1419 1420
                    ref_dims_mapping = ref_dist_attr.dims_mapping
                    ref_process_mesh = ref_dist_attr.process_mesh
                    # output
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1421 1422
                        output_var, tensor_dist_attr
                    )
1423 1424 1425
                    # op
                    grad_op_dist_attr = OperatorDistributedAttribute()
                    grad_op_dist_attr.process_mesh = ref_process_mesh
1426
                    grad_op_dist_attr.set_input_dims_mapping(
1427 1428
                        ref_var_name, ref_dims_mapping
                    )
1429
                    grad_op_dist_attr.set_output_dims_mapping(
1430 1431
                        output_var_name, ref_dims_mapping
                    )
1432 1433 1434 1435 1436

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

                else:
1437 1438 1439
                    raise ValueError(
                        "got unexpect op [{}]".format(str(grad_op.type))
                    )
1440 1441

                self._dist_context.set_op_dist_attr_for_program(
1442 1443
                    grad_op, grad_op_dist_attr
                )
1444

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

1448 1449 1450
        if serial_main_program is None:
            serial_main_program = self._dist_context.serial_main_program
        else:
1451
            self._dist_context._serial_main_program = serial_main_program
1452 1453 1454 1455 1456 1457 1458 1459

        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(
1460 1461 1462
                grad_var_name
            ), "[{}] is not a grad varnme.".format(grad_var_name)
            return grad_var_name[: grad_var_name.find("@GRAD")]
1463 1464 1465

        def _get_op_by_id(ops, id):
            for op in ops:
1466
                if op.desc.original_id() == id:
1467 1468 1469 1470 1471 1472
                    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(
1473 1474 1475
                int(core.op_proto_and_checker_maker.OpRole.Backward)
                | int(core.op_proto_and_checker_maker.OpRole.Loss)
            ):
1476 1477 1478 1479
                assert op.type == "fill_constant"
                first_backward_op_idx = idx
                break

1480 1481 1482
        assert (
            first_backward_op_idx >= 0
        ), "No backward procedure found in this program."
1483 1484 1485 1486

        ops = list(serial_main_program.global_block().ops)
        vars = serial_main_program.global_block().vars
        dist_op_context = self._dist_context.dist_op_context
1487 1488 1489
        grad_var_to_var = dist_op_context.grad_var_to_var[
            len(dist_op_context.grad_var_to_var)
        ]
1490 1491 1492 1493 1494 1495

        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"
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
                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)
                )
1506 1507 1508

                grad_var = vars[ops[idx].output_arg_names[0]]
                forward_var_name = _get_forward_varname_from_grad_varname(
1509 1510
                    grad_var.name
                )
1511 1512 1513 1514
                forward_var = vars[forward_var_name]

                # TODO complete other attribte for grad var
                tensor_dist_attr = TensorDistributedAttribute()
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
                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
                )
1525 1526 1527
                tensor_dist_attr.dims_mapping = dims_mapping
                tensor_dist_attr.process_mesh = process_mesh
                self._dist_context.set_tensor_dist_attr_for_program(
1528 1529
                    grad_var, tensor_dist_attr
                )
1530

1531 1532
                op_dist_attr = OperatorDistributedAttribute()
                op_dist_attr.process_mesh = process_mesh
1533 1534 1535
                op_dist_attr.set_output_dims_mapping(
                    grad_var.name, dims_mapping
                )
1536
                self._dist_context.set_op_dist_attr_for_program(
1537 1538
                    ops[idx], op_dist_attr
                )
1539
                continue
1540

1541 1542 1543
            # 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]
1544 1545 1546 1547
            if (
                grad_op.desc.original_id()
                in dist_op_context.grad_op_id_to_op_id
            ):
1548
                # TODO support the case where one forward op corresponding to multiple xxx_grad op
1549 1550 1551
                forward_op = _get_op_by_id(
                    ops[:first_backward_op_idx],
                    dist_op_context.grad_op_id_to_op_id[
1552 1553 1554
                        grad_op.desc.original_id()
                    ],
                )
1555 1556
                assert forward_op is not None

J
JZ-LIANG 已提交
1557
                if grad_op.type == "concat" and forward_op.type == "split":
1558 1559 1560 1561 1562
                    forward_op_dist_attr = (
                        self._dist_context.get_op_dist_attr_for_program(
                            forward_op
                        )
                    )
J
JZ-LIANG 已提交
1563 1564
                    output_var = vars[grad_op.desc.output('Out')[0]]
                    split_input_var_name = forward_op.input("X")[0]
1565 1566 1567 1568 1569
                    ref_dims_mapping = (
                        forward_op_dist_attr.get_input_dims_mapping(
                            split_input_var_name
                        )
                    )
J
JZ-LIANG 已提交
1570 1571 1572 1573 1574
                    ref_mesh = forward_op_dist_attr.process_mesh

                    grad_op_dist_attr = OperatorDistributedAttribute()
                    for input_name in grad_op.input_arg_names:
                        grad_op_dist_attr.set_input_dims_mapping(
1575 1576
                            input_name, ref_dims_mapping
                        )
J
JZ-LIANG 已提交
1577 1578 1579 1580

                    output_var_dist_attr = TensorDistributedAttribute()
                    output_var_dist_attr.dims_mapping = ref_dims_mapping
                    output_var_dist_attr.process_mesh = ref_mesh
Z
zhaoyingli 已提交
1581
                    self._dist_context.set_tensor_dist_attr_for_program(
1582 1583
                        output_var, output_var_dist_attr
                    )
J
JZ-LIANG 已提交
1584

1585
                    grad_op_dist_attr.set_output_dims_mapping(
1586 1587
                        output_var.name, ref_dims_mapping
                    )
J
JZ-LIANG 已提交
1588
                    grad_op_dist_attr.process_mesh = ref_mesh
Z
zhaoyingli 已提交
1589
                    self._dist_context.set_op_dist_attr_for_program(
1590 1591
                        grad_op, grad_op_dist_attr
                    )
1592 1593 1594
                    grad_op_dist_attr.impl_type = fwd_op_dist_attr.impl_type
                    grad_op_dist_attr.impl_idx = fwd_op_dist_attr.impl_idx

J
JZ-LIANG 已提交
1595 1596
                    continue

1597 1598 1599
                fwd_op_dist_attr = (
                    self._dist_context.get_op_dist_attr_for_program(forward_op)
                )
1600
                fwd_op_process_mesh = fwd_op_dist_attr.process_mesh
1601
                grad_op_dist_attr = OperatorDistributedAttribute()
1602
                grad_op_dist_attr.process_mesh = fwd_op_process_mesh
1603 1604

                for input_name in grad_op.input_arg_names:
1605 1606 1607 1608
                    if (
                        input_name not in forward_op.input_arg_names
                        and input_name not in forward_op.output_arg_names
                    ):
1609 1610
                        if input_name in grad_var_to_var:
                            fwd_name = grad_var_to_var[input_name]
1611 1612 1613 1614 1615
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_output_dims_mapping(
                                    fwd_name
                                )
                            )
1616 1617 1618
                        else:
                            input_var = vars[input_name]
                            ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program(
1619 1620
                                input_var
                            ).dims_mapping
1621
                    else:
1622
                        if fwd_op_dist_attr.get_input_dims_mapping(input_name):
1623 1624 1625 1626 1627
                            ref_dims_mapping = (
                                fwd_op_dist_attr.get_input_dims_mapping(
                                    input_name
                                )
                            )
1628
                        else:
1629 1630 1631 1632 1633 1634 1635 1636
                            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)
1637
                    grad_op_dist_attr.set_input_dims_mapping(
1638 1639
                        input_name, ref_dims_mapping
                    )
1640

1641 1642 1643 1644
                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(
1645 1646
                        fwd_name
                    )
1647 1648 1649 1650 1651 1652
                    # var
                    output_var = vars[output_name]
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1653 1654
                        output_var, tensor_dist_attr
                    )
1655
                    # op
1656
                    grad_op_dist_attr.set_output_dims_mapping(
1657 1658
                        output_name, ref_dims_mapping
                    )
1659

1660 1661
                grad_op_dist_attr.impl_type = fwd_op_dist_attr.impl_type
                grad_op_dist_attr.impl_idx = fwd_op_dist_attr.impl_idx
1662
                self._dist_context.set_op_dist_attr_for_program(
1663 1664
                    grad_op, grad_op_dist_attr
                )
1665

1666
            # grad ops that have not a corresponding mapping in grad_op_id_to_op_id
1667
            else:
1668 1669 1670
                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]
1671 1672 1673 1674 1675
                    assert (
                        output_name in grad_var_to_var
                    ), "sum op's output '{}' has no corresponding var".format(
                        output_name
                    )
1676 1677
                    ref_fwd_var_name = grad_var_to_var[output_name]
                    ref_fwd_var = vars[ref_fwd_var_name]
1678 1679 1680 1681 1682
                    ref_fwd_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_fwd_var
                        )
                    )
1683 1684 1685 1686 1687 1688 1689 1690 1691
                    ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping
                    ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh

                    # output
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1692 1693
                        output_var, tensor_dist_attr
                    )
1694

1695 1696 1697 1698 1699
                    # op
                    grad_op_dist_attr = OperatorDistributedAttribute()
                    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(
1700 1701
                            var_name, ref_fwd_dims_mapping
                        )
1702
                    grad_op_dist_attr.set_output_dims_mapping(
1703 1704
                        output_name, ref_fwd_dims_mapping
                    )
1705 1706
                    grad_op_dist_attr.impl_type = "default"
                    grad_op_dist_attr.impl_idx = 0
1707

1708
                elif grad_op.type == 'fill_any_like':
1709 1710
                    ref_var_name = grad_op.input_arg_names[0]
                    ref_var = vars[ref_var_name]
1711 1712 1713 1714 1715
                    ref_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            ref_var
                        )
                    )
1716 1717 1718 1719 1720 1721 1722 1723 1724
                    ref_dims_mapping = ref_dist_attr.dims_mapping
                    ref_process_mesh = ref_dist_attr.process_mesh
                    # output
                    tensor_dist_attr = TensorDistributedAttribute()
                    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(
1725 1726
                        output_var, tensor_dist_attr
                    )
1727 1728 1729
                    # op
                    grad_op_dist_attr = OperatorDistributedAttribute()
                    grad_op_dist_attr.process_mesh = ref_process_mesh
1730
                    grad_op_dist_attr.set_input_dims_mapping(
1731 1732
                        ref_var_name, ref_dims_mapping
                    )
1733
                    grad_op_dist_attr.set_output_dims_mapping(
1734 1735
                        output_var_name, ref_dims_mapping
                    )
1736 1737

                else:
1738 1739 1740
                    raise ValueError(
                        "got unexpect op [{}]".format(str(grad_op.type))
                    )
1741 1742

                self._dist_context.set_op_dist_attr_for_program(
1743 1744
                    grad_op, grad_op_dist_attr
                )
1745

1746
    def complete_update_annotation(self, serial_main_program):
1747
        """Complete the annotation of vars and ops in the update phase for parallel program."""
1748 1749
        # Copy the dist tensors and dist ops annotated by users from the default context
        # global mesh
1750 1751 1752 1753
        from paddle.distributed.auto_parallel.process_group import (
            get_world_process_group,
        )

1754
        world_ranks = get_world_process_group().ranks
1755 1756

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

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
        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):
1770
                if is_gradient_clip_op(op):
1771
                    if op.type in [
1772 1773 1774 1775 1776
                        "sum",
                        "sqrt",
                        "fill_constant",
                        "elementwise_max",
                        "elementwise_div",
1777 1778 1779 1780 1781 1782
                    ]:
                        op_dist_attr = OperatorDistributedAttribute()
                        op_dist_attr.process_mesh = world_ranks
                        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(
1783 1784
                                in_var
                            )
1785
                            op_dist_attr.set_input_dist_attr(
1786 1787
                                in_name, in_dist_attr
                            )
1788 1789 1790 1791 1792 1793 1794 1795
                        for out_name in op.output_arg_names:
                            out_var = vars[out_name]
                            out_dist_attr = TensorDistributedAttribute()
                            out_dist_attr.process_mesh = world_ranks
                            out_dist_attr.dims_mapping = [
                                -1 for _ in range(len(out_var.shape))
                            ]
                            self._dist_context.set_tensor_dist_attr_for_program(
1796 1797
                                out_var, out_dist_attr
                            )
1798
                            op_dist_attr.set_output_dist_attr(
1799 1800
                                out_name, out_dist_attr
                            )
1801 1802
                    else:
                        in_var = vars[op.input("X")[0]]
1803 1804 1805 1806 1807
                        in_dist_attr = (
                            self._dist_context.get_tensor_dist_attr_for_program(
                                in_var
                            )
                        )
1808 1809 1810 1811
                        assert in_dist_attr is not None
                        ref_process_mesh = in_dist_attr.process_mesh
                        ref_dims_mapping = in_dist_attr.dims_mapping

1812 1813 1814 1815
                        if (
                            op.type == "cast"
                            and ops[idx + 1].type == "elementwise_mul"
                        ):
1816 1817
                            ref_var = vars[ops[idx + 1].input("X")[0]]
                            ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program(
1818 1819
                                ref_var
                            )
1820 1821 1822 1823 1824 1825 1826 1827 1828
                            assert ref_dist_attr is not None
                            ref_process_mesh = ref_dist_attr.process_mesh

                        out_var = vars[op.output("Out")[0]]
                        out_dist_attr = TensorDistributedAttribute()
                        out_dist_attr.process_mesh = ref_process_mesh
                        if out_var.shape == in_var.shape:
                            out_dist_attr.dims_mapping = ref_dims_mapping
                        else:
1829 1830 1831 1832
                            assert (
                                len(out_var.shape) == 1
                                and out_var.shape[0] == 1
                            )
1833 1834
                            out_dist_attr.dims_mapping = [-1]
                        self._dist_context.set_tensor_dist_attr_for_program(
1835 1836
                            out_var, out_dist_attr
                        )
1837 1838 1839 1840

                        op_dist_attr = OperatorDistributedAttribute()
                        op_dist_attr.process_mesh = ref_process_mesh
                        op_dist_attr.set_input_dist_attr(
1841 1842
                            in_var.name, in_dist_attr
                        )
1843
                        op_dist_attr.set_output_dist_attr(
1844 1845
                            out_var.name, out_dist_attr
                        )
Z
zhaoyingli 已提交
1846 1847

                    self._dist_context.set_op_dist_attr_for_program(
1848 1849
                        op, op_dist_attr
                    )
1850 1851

                if "Grad" in op.input_names and "Param" in ops[idx].input_names:
1852 1853 1854 1855 1856 1857
                    assert (
                        len(op.input("Param")) == 1
                    ), "Only support one-to-one now."
                    assert (
                        len(op.input("Grad")) == 1
                    ), "Only support one-to-one now."
1858 1859 1860
                    param = vars[op.input("Param")[0]]
                    grad_var = vars[op.input("Grad")[0]]

1861 1862 1863 1864 1865
                    param_dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        )
                    )
1866
                    assert param_dist_attr is not None
1867 1868 1869 1870 1871
                    ref_process_mesh = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        ).process_mesh
                    )
1872
                    assert ref_process_mesh is not None
1873 1874 1875 1876 1877
                    ref_dims_mapping = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            param
                        ).dims_mapping
                    )
1878 1879 1880
                    assert ref_dims_mapping is not None
                    op_dist_attr = OperatorDistributedAttribute()
                    op_dist_attr.process_mesh = ref_process_mesh
1881 1882 1883 1884 1885 1886
                    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
                    )
1887
                    op_dist_attr.set_output_dims_mapping(
1888 1889
                        param.name, ref_dims_mapping
                    )
1890 1891
                    learning_var = vars[op.input("LearningRate")[0]]
                    op_dist_attr.set_input_dims_mapping(learning_var.name, [-1])
1892
                    op_dist_attr.set_output_dims_mapping(
1893 1894
                        learning_var.name, [-1]
                    )
1895 1896 1897 1898

                    if not learning_rate_completed:
                        learning_rate_completed = True
                        var_dist_attr = TensorDistributedAttribute()
1899
                        var_dist_attr.process_mesh = world_ranks
1900 1901
                        var_dist_attr.dims_mapping = [-1]
                        self._dist_context.set_tensor_dist_attr_for_program(
1902 1903
                            learning_var, var_dist_attr
                        )
1904 1905 1906 1907

                    for input_name in op.desc.input_names():

                        if input_name in [
1908 1909 1910 1911 1912 1913 1914
                            'Param',
                            'Grad',
                            'LearningRate',
                            "SkipUpdate",
                            "Beta1Tensor",
                            "Beta2Tensor",
                            "EpsilonTensor",
1915 1916
                        ]:
                            continue
1917 1918
                        if len(op.desc.input(input_name)) == 0:
                            continue
1919 1920 1921 1922 1923 1924 1925

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

                        if "Beta1Pow" in input_name or "Beta2Pow" in input_name:
                            input_var_attr.dims_mapping = [-1]
1926
                            op_dist_attr.set_input_dims_mapping(
1927 1928
                                input_var.name, [-1]
                            )
1929
                            op_dist_attr.set_output_dims_mapping(
1930 1931
                                input_var.name, [-1]
                            )
1932 1933 1934
                        else:
                            input_var_attr.dims_mapping = ref_dims_mapping
                            op_dist_attr.set_input_dims_mapping(
1935 1936
                                input_var.name, ref_dims_mapping
                            )
1937
                            op_dist_attr.set_output_dims_mapping(
1938 1939
                                input_var.name, ref_dims_mapping
                            )
1940 1941 1942

                        input_var_attr.process_mesh = ref_process_mesh
                        self._dist_context.set_tensor_dist_attr_for_program(
1943 1944
                            input_var, input_var_attr
                        )
1945 1946

                    self._dist_context.set_op_dist_attr_for_program(
1947 1948
                        op, op_dist_attr
                    )
1949
                    continue
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962

    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 已提交
1963
            self._dist_context._serial_main_program = serial_main_program
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983

        import time

        start_time = time.time()
        self._dist_context._is_initialized = True

        start_time = time.time()
        self._dist_context._init_dist_attr_for_program()

        start_time = time.time()
        self._init_global_mesh_for_program()

        # Do the validation check and amend some completion
        start_time = time.time()
        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
1984 1985 1986 1987
        from paddle.distributed.auto_parallel.process_group import (
            get_world_process_group,
        )

1988 1989 1990 1991 1992 1993
        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(
1994 1995
                    tensor
                )
1996 1997 1998 1999 2000 2001 2002 2003 2004
                assert dist_tensor is not None
                dist_tensor.dist_attr.process_mesh = world_ranks
            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
                dist_op.dist_attr.process_mesh = world_ranks

                # Find the most compatible implemenetations from the distributed operator
2005
                op_dist_impls = find_compatible_distributed_operator_impls(
2006 2007
                    dist_op, fwd=True
                )
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
                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