public.py 51.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import reduce

17
import paddle
18 19 20
import collections
import math
import os
21
import warnings
22
import logging
23
from paddle.framework import core
24 25
from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode
from paddle.fluid.incubate.fleet.parameter_server.ir import vars_metatools
26 27 28 29
from paddle.fluid.incubate.fleet.parameter_server.ir.ps_dispatcher import (
    RoundRobin,
    PSDispatcher,
)
30
from paddle.fluid.transpiler.details.program_utils import delete_ops
31 32

OP_NAME_SCOPE = "op_namescope"
33
CLIP_OP_NAME_SCOPE = "gradient_clip"
34
STEP_COUNTER = "@PS_STEP_COUNTER@"
T
tangwei12 已提交
35 36
LEARNING_RATE_DECAY_COUNTER = "@LR_DECAY_COUNTER@"

37 38 39 40 41 42 43
OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName()
RPC_OP_ROLE_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleAttrName()
RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC
op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName()
LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched
OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize

44 45 46
SPARSE_OP_LIST = ["lookup_table", "lookup_table_v2"]
SPARSE_OP_TYPE_DICT = {"lookup_table": "W", "lookup_table_v2": "W"}

47 48 49 50 51

def _get_lr_ops(program):
    lr_ops = []
    for index, op in enumerate(program.global_block().ops):
        role_id = int(op.attr(RPC_OP_ROLE_ATTR_NAME))
52 53 54
        if role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) or role_id == int(
            LR_SCHED_OP_ROLE_ATTR_VALUE
        ) | int(OPT_OP_ROLE_ATTR_VALUE):
55 56 57 58
            lr_ops.append(op)
    return lr_ops


T
tangwei12 已提交
59 60 61 62 63 64 65 66 67 68 69
def _has_global_step(lr_ops):
    if len(lr_ops) > 0:
        for idx, op in enumerate(lr_ops):
            if op.type != 'increment':
                continue
            counter = op.input("X")[0]
            if counter == LEARNING_RATE_DECAY_COUNTER:
                return True
    return False


70
def is_sparse_op(op):
71 72 73 74 75
    if (
        op.type in SPARSE_OP_LIST
        and op.attr('is_sparse') is True
        and op.attr('is_distributed') is False
    ):
76 77
        return True

78 79 80 81
    if (
        op.type == "distributed_lookup_table"
        and op.attr('is_distributed') is False
    ):
82 83 84 85 86 87
        return True

    return False


def is_distributed_sparse_op(op):
88
    if op.type in SPARSE_OP_LIST and op.attr('is_distributed') is True:
89 90
        return True

91 92 93 94
    if (
        op.type == "distributed_lookup_table"
        and op.attr('is_distributed') is True
    ):
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        return True

    return False


def get_sparse_tablename(op):
    return op.input("W")[0]


def get_sparse_tablenames(program, is_distributed):
    tablenames = set()
    if is_distributed:
        for op in program.global_block().ops:
            if is_distributed_sparse_op(op):
                tablenames.add(get_sparse_tablename(op))
    else:
        for op in program.global_block().ops:
            if is_sparse_op(op):
                tablenames.add(get_sparse_tablename(op))
    return list(tablenames)


class MergedVariable:
    def __init__(self, merged, ordered, offsets):
        self.merged_var = merged
        self.ordered_vars = ordered
        self.offsets = offsets


124 125 126 127 128 129 130 131 132 133 134 135
def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton


@Singleton
136
class CompileTimeStrategy:
137
    def __init__(self, main_program, startup_program, strategy, role_maker):
1
123malin 已提交
138
        self.min_block_size = 81920
139 140 141

        self.origin_main_program = main_program
        self.origin_startup_program = startup_program
142 143
        self.origin_ps_main_program = main_program
        self.origin_ps_startup_program = startup_program
144 145 146

        self.strategy = strategy
        self.role_maker = role_maker
T
Thunderbrook 已提交
147
        self.use_ps_gpu = False
T
tangwei12 已提交
148 149 150 151 152 153 154
        try:
            self.is_heter_ps_mode = role_maker._is_heter_parameter_server_mode
        except:
            warnings.warn(
                "Using paddle.distributed.fleet instead of paddle.fluid.incubate.fleet"
            )
            self.is_heter_ps_mode = False
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

        self.origin_sparse_pairs = []
        self.origin_dense_pairs = []

        self.merged_variables_pairs = []
        self.merged_dense_pairs = []
        self.merged_sparse_pairs = []

        self.merged_variable_map = {}
        self.param_name_to_grad_name = {}
        self.grad_name_to_param_name = {}

        self.param_grad_ep_mapping = collections.OrderedDict()
        self.grad_param_mapping = collections.OrderedDict()

        self._build_var_distributed()

172 173
        self.tensor_table_dict = {}

174 175 176 177 178
        # for heter-ps save variables
        self.origin_merged_variables_pairs = list(self.merged_variables_pairs)
        self.origin_merged_dense_pairs = list(self.merged_dense_pairs)
        self.origin_merged_sparse_pairs = list(self.merged_sparse_pairs)

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    def get_distributed_mode(self):
        trainer = self.strategy.get_trainer_runtime_config()
        return trainer.mode

    def is_sync_mode(self):
        trainer = self.strategy.get_trainer_runtime_config()
        return trainer.mode == DistributedMode.SYNC

    def is_geo_mode(self):
        trainer = self.strategy.get_trainer_runtime_config()
        return trainer.mode == DistributedMode.GEO

    def is_async_mode(self):
        trainer = self.strategy.get_trainer_runtime_config()
        return trainer.mode == DistributedMode.ASYNC

    def get_role_id(self):
196 197 198 199
        try:
            return self.role_maker._role_id()
        except Exception:
            return self.role_maker.role_id()
200 201

    def get_trainers(self):
202 203 204 205
        try:
            return self.role_maker._worker_num()
        except Exception:
            return self.role_maker.worker_num()
206 207

    def get_ps_endpoint(self):
208 209 210 211
        try:
            return self.role_maker._get_pserver_endpoints()[self.get_role_id()]
        except Exception:
            return self.role_maker.get_pserver_endpoints()[self.get_role_id()]
212 213

    def get_ps_endpoints(self):
214 215 216 217
        try:
            return self.role_maker._get_pserver_endpoints()
        except Exception:
            return self.role_maker.get_pserver_endpoints()
218

219
    def get_heter_worker_endpoints(self):
220 221 222 223
        try:
            return self.role_maker._get_heter_worker_endpoints()
        except Exception:
            return self.role_maker.get_heter_worker_endpoints()
224

225 226 227 228 229 230
    def get_next_stage_trainers(self):
        try:
            return self.role_maker._get_next_trainers()
        except Exception:
            return self.role_maker.get_next_trainers()

231
    def get_heter_worker_endpoint(self):
232 233 234 235
        try:
            return self.role_maker._get_heter_worker_endpoint()
        except Exception:
            return self.role_maker.get_heter_worker_endpoint()
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    def get_trainer_endpoints(self):
        try:
            return self.role_maker._get_trainer_endpoints()
        except Exception:
            return self.role_maker.get_trainer_endpoints()

    def get_trainer_endpoint(self):
        try:
            return self.role_maker._get_trainer_endpoint()
        except Exception:
            return self.role_maker.get_trainer_endpoint()

    def get_previous_stage_trainers(self):
        try:
            return self.role_maker._get_previous_trainers()
        except Exception:
            return self.role_maker.get_previous_trainers()

255 256 257 258 259 260 261 262 263
    def get_origin_programs(self):
        return self.origin_main_program, self.origin_startup_program

    def get_origin_main_program(self):
        return self.origin_main_program

    def get_origin_startup_program(self):
        return self.origin_startup_program

264 265 266 267 268 269 270 271 272 273 274 275
    def set_origin_ps_main_program(self, program):
        self.origin_ps_main_program = program

    def set_origin_ps_startup_program(self, program):
        self.origin_ps_startup_program = program

    def get_origin_ps_main_program(self):
        return self.origin_ps_main_program

    def get_origin_ps_startup_program(self):
        return self.origin_ps_startup_program

276 277 278 279 280 281 282 283
    def add_tensor_table(
        self,
        feed_var_name,
        fetch_var_name="",
        startup_program=None,
        main_program=None,
        tensor_table_class="",
    ):
284 285 286 287
        self.tensor_table_dict[feed_var_name] = {}
        self.tensor_table_dict[feed_var_name]["feed_var_name"] = feed_var_name
        self.tensor_table_dict[feed_var_name]["fetch_var_name"] = fetch_var_name
        self.tensor_table_dict[feed_var_name][
288 289
            "startup_program"
        ] = startup_program
290 291
        self.tensor_table_dict[feed_var_name]["main_program"] = main_program
        self.tensor_table_dict[feed_var_name][
292 293
            "tensor_table_class"
        ] = tensor_table_class
294 295 296 297

    def get_tensor_table_dict(self):
        return self.tensor_table_dict

298 299 300
    def get_sparse_varname_on_ps(self, is_distributed, endpoint=None):
        if not endpoint:
            endpoint = self.get_ps_endpoint()
301 302 303
        varnames = get_sparse_tablenames(
            self.get_origin_main_program(), is_distributed
        )
304

305 306 307 308 309 310 311 312 313
        ps_sparse_varnames = []
        for varname in varnames:
            tables = self.get_var_distributed(varname, True)
            for i in range(len(tables)):
                table, ep, _ = tables[i]
                if ep == endpoint:
                    ps_sparse_varnames.append(table)
        return ps_sparse_varnames

314 315 316 317 318 319
    def get_optimize_varname_on_ps(self, param_name):
        origin_param_name, _, _ = _get_varname_parts(param_name)
        optimize_var_names = []
        for op in self.get_origin_main_program().global_block().ops:
            # check all optimizer op
            if int(op.all_attrs()["op_role"]) == 2:
T
tangwei12 已提交
320
                # check param name
321 322 323 324 325
                if op.input("Param")[0] != origin_param_name:
                    continue
                # check all input
                for key in op.input_names:
                    if key in [
326 327 328 329 330
                        "Param",
                        "Grad",
                        "LearningRate",
                        "Beta1Tensor",
                        "Beta2Tensor",
331 332 333
                    ]:
                        continue
                    # check varibale shape related param, e.g: Moment1
334 335 336 337 338
                    optimize_var_names += (
                        self._get_optimizer_param_related_var_name(
                            op, op.type, key
                        )
                    )
339 340 341 342
        return optimize_var_names

    def _get_optimizer_param_related_var_name(self, op, op_type, varkey):
        """
T
tangwei12 已提交
343
        Returns the names for optimizer inputs that need to be load
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        """
        related_var_names = []
        if op_type == "adam":
            if varkey in ["Moment1", "Moment2"]:
                related_var_names.append(op.input(varkey)[0])
        elif op_type == "adagrad":
            if varkey == "Moment":
                related_var_names.append(op.input(varkey)[0])
        elif op_type in ["momentum", "lars_momentum"]:
            if varkey == "Velocity":
                related_var_names.append(op.input(varkey)[0])
        elif op_type == "rmsprop":
            if varkey in ["Moment", "MeanSquare"]:
                related_var_names.append(op.input(varkey)[0])
        elif op_type == "ftrl":
            if varkey in ["SquaredAccumulator", "LinearAccumulator"]:
                related_var_names.append(op.input(varkey)[0])
        elif op_type == "sgd":
            pass
        else:
            raise ValueError(
365 366
                "Not supported optimizer for distributed training: %s" % op_type
            )
367 368
        return related_var_names

369 370 371
    def build_ctx(
        self, vars, mapping, is_grad, is_sparse, is_send, is_distributed=False
    ):
372 373 374 375 376 377 378 379 380 381 382
        def get_grad_var_ep(slices):
            names = []
            eps = []
            sections = []

            for slice in slices:
                if self.is_geo_mode():
                    if is_send:
                        names.append("{}.delta".format(slice.name))
                    else:
                        names.append(slice.name)
383 384 385 386 387 388
                elif (
                    is_grad and self.is_sync_mode() and self.get_trainers() > 1
                ):
                    names.append(
                        "{}.trainer_{}".format(slice.name, self.get_role_id())
                    )
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
                else:
                    names.append(slice.name)

                sections.append(slice.shape[0])

                for ep, pairs in self.param_grad_ep_mapping.items():
                    params, grads = pairs["params"], pairs["grads"]

                    for var in params + grads:
                        if slice.name == var.name:
                            eps.append(ep)
                            break
            return names, eps, sections

        if isinstance(vars, MergedVariable):
            name = vars.merged_var.name
            slices = mapping[name]
            names, eps, sections = get_grad_var_ep(slices)
            origin_varnames = [var.name for var in vars.ordered_vars]
        else:
            name = vars.name
            slices = mapping[name]
            names, eps, sections = get_grad_var_ep(slices)
            origin_varnames = [vars.name]

        trainer_id = self.get_role_id()
        aggregate = True
416
        ctx = core.CommContext(
417 418 419 420 421 422 423 424 425 426 427
            name,
            names,
            eps,
            sections,
            origin_varnames,
            trainer_id,
            aggregate,
            is_sparse,
            is_distributed,
            [],
        )
428 429 430 431
        return ctx

    def get_trainer_send_context(self):
        send_ctx = {}
432 433 434
        distibuted_varnames = get_sparse_tablenames(
            self.origin_main_program, True
        )
435
        idx = 0
436 437 438 439

        if not self.is_geo_mode():
            for merged in self.merged_dense_pairs:
                grad = merged[1]
440 441 442
                ctx = self.build_ctx(
                    grad, self.grad_var_mapping, True, False, True
                )
443 444 445 446 447 448 449 450
                send_ctx[ctx.var_name()] = ctx

            for merged in self.merged_sparse_pairs:
                param = merged[0]
                grad = merged[1]

                param_name = param.merged_var.name

451 452 453 454 455 456 457 458 459 460 461 462
                is_distributed = (
                    True if param_name in distibuted_varnames else False
                )

                ctx = self.build_ctx(
                    grad,
                    self.grad_var_mapping,
                    True,
                    True,
                    True,
                    is_distributed,
                )
463
                send_ctx[ctx.var_name()] = ctx
464
                idx += 1
465 466

            if self.is_async_mode():
467
                name, ctx = self._step_ctx(idx)
468 469 470 471 472
                send_ctx[name] = ctx
        else:
            for pairs in self.origin_sparse_pairs:
                param, grad = pairs
                param_name = param.name
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                is_distributed = (
                    True if param_name in distibuted_varnames else False
                )

                param_ctx = self.build_ctx(
                    param,
                    self.param_var_mapping,
                    False,
                    True,
                    True,
                    is_distributed,
                )
                grad_ctx = self.build_ctx(
                    grad,
                    self.grad_var_mapping,
                    True,
                    True,
                    True,
                    is_distributed,
                )

494
                ctx = core.CommContext(
495 496 497 498 499 500 501 502 503 504 505
                    param_ctx.var_name(),
                    param_ctx.split_varnames(),
                    param_ctx.split_endpoints(),
                    param_ctx.sections(),
                    grad_ctx.origin_varnames(),
                    param_ctx.trainer_id(),
                    param_ctx.aggregate(),
                    param_ctx.is_sparse(),
                    param_ctx.is_distributed(),
                    [],
                )
506 507

                send_ctx[ctx.var_name()] = ctx
508 509
                idx += 1
            name, ctx = self._step_ctx(idx)
510 511 512 513 514
            send_ctx[name] = ctx
        return send_ctx

    def get_communicator_send_context(self):
        send_ctx = {}
515 516 517
        distibuted_varnames = get_sparse_tablenames(
            self.origin_main_program, True
        )
518
        idx = 0
519 520 521 522

        if self.is_geo_mode():
            for pairs in self.merged_dense_pairs:
                param = pairs[0]
523 524 525
                ctx = self.build_ctx(
                    param, self.param_var_mapping, False, False, True
                )
526 527 528 529 530
                send_ctx[ctx.var_name()] = ctx

            for pairs in self.merged_sparse_pairs:
                param = pairs[0]
                param_name = param.merged_var.name
531 532 533 534 535 536 537 538 539 540 541 542
                is_distributed = (
                    True if param_name in distibuted_varnames else False
                )

                ctx = self.build_ctx(
                    param,
                    self.param_var_mapping,
                    False,
                    True,
                    True,
                    is_distributed,
                )
543
                send_ctx[ctx.var_name()] = ctx
544 545
                idx += 1
            name, ctx = self._step_ctx(idx)
546 547 548 549
            send_ctx[name] = ctx
        else:
            for merged in self.merged_dense_pairs:
                grad = merged[1]
550 551 552
                ctx = self.build_ctx(
                    grad, self.grad_var_mapping, True, False, True
                )
553 554 555 556 557 558
                send_ctx[ctx.var_name()] = ctx

            for merged in self.merged_sparse_pairs:
                param, grad = merged
                param_name = param.merged_var.name

559 560 561 562 563 564 565 566 567 568 569 570
                is_distributed = (
                    True if param_name in distibuted_varnames else False
                )

                ctx = self.build_ctx(
                    grad,
                    self.grad_var_mapping,
                    True,
                    True,
                    True,
                    is_distributed,
                )
571
                send_ctx[ctx.var_name()] = ctx
572
                idx += 1
573

574
            name, ctx = self._step_ctx(idx)
575 576 577
            send_ctx[name] = ctx
        return send_ctx

578 579 580
    def get_communicator_recv_context(
        self, recv_type=1, use_origin_program=False
    ):
581 582
        # recv_type
        # 1 : DENSE 2. SPARSE 3. DISTRIBUTED 4. ALL
583 584 585
        distibuted_varnames = get_sparse_tablenames(
            self.origin_main_program, True
        )
586 587 588 589 590 591 592 593 594
        sparse_varnames = []
        for pairs in self.origin_sparse_pairs:
            param, grad = pairs
            sparse_varnames.append(param.name)

        dense_recv_ctx = {}
        sparse_recv_ctx = {}
        distributed_recv_ctx = {}

595 596 597 598 599
        variables_pairs = (
            self.merged_variables_pairs
            if not use_origin_program
            else self.origin_merged_variables_pairs
        )
600
        for merged in variables_pairs:
601 602 603 604
            params = merged[0]
            if params.merged_var.name in sparse_varnames:
                continue

605 606 607
            ctx = self.build_ctx(
                params, self.param_var_mapping, False, False, False, False
            )
608 609 610 611 612 613
            dense_recv_ctx[ctx.var_name()] = ctx

        for pairs in self.origin_sparse_pairs:
            param, grad = pairs

            if param.name in distibuted_varnames:
614 615 616
                ctx = self.build_ctx(
                    param, self.param_var_mapping, False, True, False, True
                )
617 618
                distributed_recv_ctx[ctx.var_name()] = ctx
            else:
619 620 621
                ctx = self.build_ctx(
                    param, self.param_var_mapping, False, True, False, False
                )
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
                sparse_recv_ctx[ctx.var_name()] = ctx

        if recv_type == 1:
            return dense_recv_ctx
        if recv_type == 2:
            return sparse_recv_ctx
        if recv_type == 3:
            return distributed_recv_ctx
        if recv_type == 4:
            dense_recv_ctx.update(sparse_recv_ctx)
            dense_recv_ctx.update(distributed_recv_ctx)
            return dense_recv_ctx
        assert ValueError(
            "recv_type can only be 1/2/3/4, 1 : DENSE 2. SPARSE 3. DISTRIBUTED 4. ALL"
        )

T
tangwei12 已提交
638 639 640 641 642 643 644
    def get_the_one_trainer_send_context(self, split_dense_table):
        if self.is_geo_mode():
            send_ctx = {}
            trainer_id = self.get_role_id()
            idx = 0

            distibuted_varnames = get_sparse_tablenames(
645 646
                self.origin_main_program, True
            )
T
tangwei12 已提交
647 648 649 650
            for merged in self.merged_sparse_pairs:
                param, grad = merged
                grad_name = grad.merged_var.name
                param_name = param.merged_var.name
651 652 653
                is_distributed = (
                    True if param_name in distibuted_varnames else False
                )
T
tangwei12 已提交
654 655

                var = self.origin_main_program.global_block().vars[
656 657
                    grad.merged_var.name
                ]
T
tangwei12 已提交
658 659
                var_numel = reduce(lambda x, y: x * y, var.shape[1:])

660
                sparse_ctx = core.CommContext(
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
                    grad_name,
                    [grad_name],
                    ["127.0.0.1:6071"],
                    [var_numel],
                    [grad_name],
                    trainer_id,
                    True,
                    True,
                    is_distributed,
                    idx,
                    False,
                    False,
                    -1,
                    [],
                )
T
tangwei12 已提交
676 677 678 679 680
                idx += 1
                send_ctx[sparse_ctx.var_name()] = sparse_ctx

            if len(send_ctx) == 0:
                raise ValueError(
681 682
                    "GeoSGD require sparse parameters in your net."
                )
T
tangwei12 已提交
683

684 685 686 687
            if len(self.tensor_table_dict) > 0 and self.role_maker._is_worker():
                name, ctx = self._step_ctx(idx)
                send_ctx[name] = ctx

T
tangwei12 已提交
688 689 690 691
            return send_ctx
        else:
            return self.get_the_one_send_context(split_dense_table)

692 693 694 695 696 697 698 699
    def get_dense_send_context(
        self,
        send_ctx,
        idx,
        merged_dense_pairs,
        trainer_id,
        split_dense_table=False,
    ):
T
tangwei12 已提交
700 701 702 703 704 705 706 707 708
        if len(merged_dense_pairs) < 1:
            return idx
        if not split_dense_table:
            origin_varnames = []
            var_numel = 0
            for merged in merged_dense_pairs:
                grad = merged[1]
                origin_varnames.append(grad.merged_var.name)
                var = self.origin_main_program.global_block().vars[
709 710
                    grad.merged_var.name
                ]
T
tangwei12 已提交
711 712 713 714
                var_numel += reduce(lambda x, y: x * y, var.shape)
            grad_name = "Dense@Grad"
            trainer_id = self.get_role_id()
            aggregate = True
715
            dense_ctx = core.CommContext(
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
                grad_name,
                [grad_name],
                ["127.0.0.1:6071"],
                [var_numel],
                origin_varnames,
                trainer_id,
                aggregate,
                False,
                False,
                idx,
                False,
                False,
                -1,
                [],
            )
T
tangwei12 已提交
731 732 733 734 735 736
            send_ctx[grad_name] = dense_ctx
            idx += 1
        else:
            for merged in merged_dense_pairs:
                grad = merged[1]
                origin_varname = grad.merged_var.name
737 738 739
                var = self.origin_main_program.global_block().vars[
                    origin_varname
                ]
T
tangwei12 已提交
740 741 742
                var_numel = reduce(lambda x, y: x * y, var.shape)
                grad_name = origin_varname
                aggregate = True
743
                dense_ctx = core.CommContext(
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
                    grad_name,
                    [grad_name],
                    ["127.0.0.1:6071"],
                    [var_numel],
                    [origin_varname],
                    trainer_id,
                    aggregate,
                    False,
                    False,
                    idx,
                    False,
                    False,
                    -1,
                    [],
                )
T
tangwei12 已提交
759 760 761 762
                send_ctx[grad_name] = dense_ctx
                idx += 1
        return idx

763 764 765
    def get_the_one_send_context(
        self, split_dense_table=False, use_origin_program=False, ep_list=None
    ):
T
tangwei12 已提交
766 767 768 769 770 771
        if ep_list is None:
            ep_list = ["127.0.0.1:6071"]
        send_ctx = {}
        trainer_id = self.get_role_id()
        idx = 0

772 773 774 775 776 777 778 779 780 781
        merged_dense_pairs = (
            self.origin_merged_dense_pairs
            if use_origin_program
            else self.merged_dense_pairs
        )
        merged_sparse_pairs = (
            self.origin_merged_sparse_pairs
            if use_origin_program
            else self.merged_sparse_pairs
        )
T
tangwei12 已提交
782

783 784 785
        idx += self.get_dense_send_context(
            send_ctx, idx, merged_dense_pairs, trainer_id, split_dense_table
        )
T
tangwei12 已提交
786

787 788 789
        distibuted_varnames = get_sparse_tablenames(
            self.origin_main_program, True
        )
T
tangwei12 已提交
790 791 792 793 794 795 796 797 798
        for merged in merged_sparse_pairs:
            param, grad = merged
            grad_name = grad.merged_var.name
            param_name = param.merged_var.name
            splited_varname = []

            for i in range(len(ep_list)):
                splited_varname.append("{}.block{}".format(param_name, i))

799 800 801
            is_distributed = (
                True if param_name in distibuted_varnames else False
            )
T
tangwei12 已提交
802 803

            var = self.origin_main_program.global_block().vars[
804 805
                grad.merged_var.name
            ]
T
tangwei12 已提交
806 807 808 809

            shape = list(var.shape)
            shape[0] = 0 if is_distributed else shape[0]

810
            sparse_ctx = core.CommContext(
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
                grad_name,
                splited_varname,
                ep_list,
                shape,
                [grad_name],
                trainer_id,
                True,
                True,
                is_distributed,
                idx,
                False,
                False,
                -1,
                [],
            )
T
tangwei12 已提交
826 827 828

            idx += 1
            send_ctx[sparse_ctx.var_name()] = sparse_ctx
829 830 831 832 833

        if len(self.tensor_table_dict) > 0 and self.role_maker._is_worker():
            name, ctx = self._step_ctx(idx)
            send_ctx[name] = ctx

T
tangwei12 已提交
834 835
        return send_ctx

836 837 838
    def get_the_one_recv_context(
        self, is_dense=True, split_dense_table=False, use_origin_program=False
    ):
T
tangwei12 已提交
839 840 841 842
        recv_id_maps = {}
        if is_dense:
            send_ctx = self.get_the_one_send_context(
                split_dense_table=split_dense_table,
843 844
                use_origin_program=use_origin_program,
            )
T
tangwei12 已提交
845 846 847
            for idx, (name, ctx) in enumerate(send_ctx.items()):
                if ctx.is_sparse():
                    continue
848 849
                if ctx.is_tensor_table():
                    continue
T
tangwei12 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

                origin_grad_varnames = ctx.origin_varnames()

                param_names = []
                for grad_varname in origin_grad_varnames:
                    param_name = self.grad_name_to_param_name[grad_varname]
                    param_names.append(param_name)
                recv_id_maps[ctx.table_id()] = param_names
        else:
            send_ctx = self.get_the_one_send_context()
            for idx, (name, ctx) in enumerate(send_ctx.items()):
                if not ctx.is_sparse():
                    continue

                origin_grad_varnames = ctx.origin_varnames()

                param_names = []
                for grad_varname in origin_grad_varnames:
                    param_name = self.grad_name_to_param_name[grad_varname]
                    param_names.append(param_name)
                recv_id_maps[ctx.table_id()] = param_names
        return recv_id_maps

873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
    def get_server_runtime_config(self):
        return self.strategy.get_server_runtime_config()

    def get_var_distributed(self, varname, is_param):
        var_distributed = []
        offset = 0
        if is_param:
            params = self.param_var_mapping[varname]
            param_varnames = [var.name for var in params]
            for ep, pairs in self.param_grad_ep_mapping.items():
                for p in pairs["params"]:
                    if p.name in param_varnames:
                        offset += p.shape[0]
                        var_distributed.append((p.name, ep, p.shape[0]))
        else:
            grads = self.grad_var_mapping[varname]
            grad_varnames = [var.name for var in grads]
            for ep, pairs in self.param_grad_ep_mapping.items():
                for g in pairs["grads"]:
                    if g.name in grad_varnames:
                        var_distributed.append((g.name, ep, g.shape[0]))
        return var_distributed

896
    def _step_ctx(self, idx):
897 898 899 900 901
        name = STEP_COUNTER
        trainer_id = self.get_role_id()
        endpoints = self.get_ps_endpoints()
        sections = [1] * len(endpoints)
        names = [name] * len(endpoints)
902
        ctx = core.CommContext(
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
            name,
            names,
            endpoints,
            sections,
            [name],
            trainer_id,
            True,
            False,
            False,
            idx,
            True,
            False,
            -1,
            [],
        )
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        return name, ctx

    def _create_vars_from_blocklist(self, block_list):
        """
        Create vars for each split.
        NOTE: only grads need to be named for different trainers, use
              add_trainer_suffix to rename the grad vars.
        Args:
            block_list (list[(varname, block_id, block_size)]): List of gradient blocks.
            add_trainer_suffix (Bool): Add trainer suffix to new variable's name if set True.
        Returns:
            var_mapping (collections.OrderedDict(varname->[new_varname_variable])):A dict mapping
                from original var name to each var split.
        """

        # varname->[(block_id, current_block_size)]
        block_map = collections.OrderedDict()
        var_mapping = collections.OrderedDict()

        for block_str in block_list:
            varname, offset, size = block_str.split(":")
            if varname not in block_map:
                block_map[varname] = []
            block_map[varname].append((int(offset), int(size)))

943
        for varname, split in block_map.items():
944 945 946 947
            orig_var = self.merged_variable_map[varname]

            if len(split) == 1:
                var_mapping[varname] = [orig_var]
948 949 950 951 952 953 954 955
                self.var_distributed.add_distributed_var(
                    origin_var=orig_var,
                    slice_var=orig_var,
                    block_id=0,
                    offset=0,
                    is_slice=False,
                    vtype="Param",
                )
956 957 958 959 960 961
            else:
                var_mapping[varname] = []
                orig_shape = orig_var.shape
                orig_dim1_flatten = 1

                if len(orig_shape) >= 2:
962 963 964
                    orig_dim1_flatten = reduce(
                        lambda x, y: x * y, orig_shape[1:]
                    )
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979

                for i, block in enumerate(split):
                    size = block[1]
                    rows = size // orig_dim1_flatten
                    splited_shape = [rows]
                    if len(orig_shape) >= 2:
                        splited_shape.extend(orig_shape[1:])

                    new_var_name = "%s.block%d" % (varname, i)
                    slice_var = vars_metatools.VarStruct(
                        name=new_var_name,
                        shape=splited_shape,
                        dtype=orig_var.dtype,
                        type=orig_var.type,
                        lod_level=orig_var.lod_level,
980 981
                        persistable=False,
                    )
982 983 984 985 986 987 988 989
                    var_mapping[varname].append(slice_var)

                    self.var_distributed.add_distributed_var(
                        origin_var=orig_var,
                        slice_var=slice_var,
                        block_id=i,
                        offset=-1,
                        is_slice=False,
990 991
                        vtype="Param",
                    )
992 993 994 995 996 997

        return var_mapping

    def _dispatcher(self):
        ps_dispatcher = RoundRobin(self.get_ps_endpoints())
        ps_dispatcher.reset()
998
        grad_var_mapping_items = list(self.grad_var_mapping.items())
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039

        sparse_gradnames = [grad.name for _, grad in self.origin_sparse_pairs]

        for grad_varname, splited_vars in grad_var_mapping_items:
            if grad_varname in sparse_gradnames:
                continue

            send_vars = []
            for _, var in enumerate(splited_vars):
                send_vars.append(var)

            recv_vars = []
            for _, var in enumerate(send_vars):
                recv_vars.append(self.grad_param_mapping[var])

            eps = ps_dispatcher.dispatch(recv_vars)

            for i, ep in enumerate(eps):
                self.param_grad_ep_mapping[ep]["params"].append(recv_vars[i])
                self.param_grad_ep_mapping[ep]["grads"].append(send_vars[i])

        for grad_varname, splited_vars in grad_var_mapping_items:
            if grad_varname not in sparse_gradnames:
                continue

            ps_dispatcher.reset()

            send_vars = []
            for _, var in enumerate(splited_vars):
                send_vars.append(var)

            recv_vars = []
            for _, var in enumerate(send_vars):
                recv_vars.append(self.grad_param_mapping[var])

            eps = ps_dispatcher.dispatch(recv_vars)

            for i, ep in enumerate(eps):
                self.param_grad_ep_mapping[ep]["params"].append(recv_vars[i])
                self.param_grad_ep_mapping[ep]["grads"].append(send_vars[i])

1040 1041 1042
    def _slice_variable(
        self, var_list, slice_count, min_block_size, uniform=False
    ):
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        """
        We may need to split dense tensor to one or more blocks and put
        them equally onto parameter server. One block is a sub-tensor
        aligned by dim[0] of the tensor.

        We need to have a minimal block size so that the calculations in
        the parameter server side can gain better performance. By default
        minimum block size 8K elements (maybe 16bit or 32bit or 64bit).

        Args:
            var_list (list): List of variables.
            slice_count (int): Numel of count that variables will be sliced, which
                could be the pserver services' count.
            min_block_size (int): Minimum split block size.
        Returns:
            blocks (list[(varname, block_id, current_block_size)]): A list
                of VarBlocks. Each VarBlock specifies a shard of the var.
        """
        blocks = []
        for var in var_list:
            if not uniform:
                var_numel = reduce(lambda x, y: x * y, var.shape)

                split_count = 1

1
123malin 已提交
1068 1069 1070 1071 1072
                if min_block_size == -1:
                    split_count = 1
                else:
                    split_count = slice_count
                    max_pserver_count = int(
1073 1074
                        math.floor(var_numel / float(min_block_size))
                    )
1
123malin 已提交
1075 1076 1077 1078
                    if max_pserver_count == 0:
                        max_pserver_count = 1
                    if max_pserver_count < slice_count:
                        split_count = max_pserver_count
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
                block_size = int(math.ceil(var_numel / float(split_count)))

                if len(var.shape) >= 2:
                    # align by dim1(width)
                    dim1 = reduce(lambda x, y: x * y, var.shape[1:])
                    remains = block_size % dim1
                    if remains != 0:
                        block_size += dim1 - remains
                        # update split_count after aligning
                split_count = int(math.ceil(var_numel / float(block_size)))
                for block_id in range(split_count):
1090 1091 1092 1093 1094 1095
                    curr_block_size = min(
                        block_size, var_numel - ((block_id) * block_size)
                    )
                    block = vars_metatools.VarBlock(
                        var.name, block_id, curr_block_size
                    )
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
                    blocks.append(str(block))
            else:
                block_size = var.shape[0] / slice_count
                remainder = var.shape[0] % slice_count

                if block_size == 0:
                    dim0s = [block_size] * remainder
                else:
                    dim0s = [block_size] * slice_count
                for i in range(remainder):
                    dim0s[i] = dim0s[i] + 1

                dim1 = reduce(lambda x, y: x * y, var.shape[1:])

                for block_id in range(len(dim0s)):
                    numel = dim0s[block_id] * dim1
                    block = vars_metatools.VarBlock(var.name, block_id, numel)
                    blocks.append(str(block))
        return blocks

    def _get_param_grad_blocks(self, pairs, min_block_size, uniform=False):
        param_list = []
        grad_list = []
        param_grad_set = set()
        for p, g in pairs:
            # todo(tangwei12) skip parameter marked not trainable
            # if type(p) == Parameter and p.trainable == False:
            # continue
            p = p.merged_var
            g = g.merged_var

            if p.name not in param_grad_set:
                param_list.append(p)
                param_grad_set.add(p.name)
            if g.name not in param_grad_set:
                grad_list.append(g)
                param_grad_set.add(g.name)

                # when we slice var up into blocks, we will slice the var according to
                # pserver services' count. A pserver may have two or more listening ports.
1136 1137 1138
        grad_blocks = self._slice_variable(
            grad_list, len(self.get_ps_endpoints()), min_block_size, uniform
        )
1139

1140 1141 1142
        param_blocks = self._slice_variable(
            param_list, len(self.get_ps_endpoints()), min_block_size, uniform
        )
1143 1144 1145 1146 1147 1148 1149 1150 1151
        return param_blocks, grad_blocks

    def _var_slice_and_distribute(self):
        # update these mappings for further transpile:
        # 1. param_var_mapping : param var name->[split params vars]
        # 2. grad_var_mapping : grad var name->[split grads vars]
        # 3. grad_param_mapping : grad.blockx->param.blockx
        # 4. param_grad_ep_mapping : ep->{"params" : [], "grads" : [] }

1152 1153 1154 1155 1156 1157
        dps, dgs = self._get_param_grad_blocks(
            self.merged_dense_pairs, self.min_block_size, False
        )
        sps, sgs = self._get_param_grad_blocks(
            self.merged_sparse_pairs, self.min_block_size, True
        )
1158 1159 1160 1161

        param_blocks = dps + sps
        grad_blocks = dgs + sgs

1162
        assert len(grad_blocks) == len(param_blocks)
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

        # origin_param_name->[splited_param_vars]
        self.param_var_mapping = self._create_vars_from_blocklist(param_blocks)
        self.grad_var_mapping = self._create_vars_from_blocklist(grad_blocks)

        # dict(grad_splited_var->param_splited_var)
        self.grad_param_mapping = collections.OrderedDict()
        for g, p in zip(grad_blocks, param_blocks):
            g_name, g_bid, _ = g.split(":")
            p_name, p_bid, _ = p.split(":")
1173 1174 1175
            self.grad_param_mapping[
                self.grad_var_mapping[g_name][int(g_bid)]
            ] = self.param_var_mapping[p_name][int(p_bid)]
1176 1177 1178 1179 1180 1181 1182 1183

        print_maps = {}
        for k, v in self.grad_param_mapping.items():
            print_maps[str(k)] = str(v)

        # create mapping of endpoint->split var to create pserver side program
        self.param_grad_ep_mapping = collections.OrderedDict()
        [
1184 1185
            self.param_grad_ep_mapping.update({ep: {"params": [], "grads": []}})
            for ep in self.get_ps_endpoints()
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        ]

    def _build_var_distributed(self):
        self.var_distributed = vars_metatools.VarsDistributed()

        sparse_pairs, dense_pairs = self.get_param_grads()
        origin_for_sparse = []
        origin_for_dense = []
        param_name_grad_name = dict()
        grad_name_to_param_name = dict()

        for param, grad in sparse_pairs:
            param = vars_metatools.create_var_struct(param)
            grad = vars_metatools.create_var_struct(grad)
            origin_for_sparse.append((param, grad))

        for param, grad in dense_pairs:
            param = vars_metatools.create_var_struct(param)
            grad = vars_metatools.create_var_struct(grad)
            origin_for_dense.append((param, grad))

        for dense_pair in origin_for_dense:
            param, grad = dense_pair

            m_param = MergedVariable(param, [param], [0])
            m_grad = MergedVariable(grad, [grad], [0])
            self.merged_variables_pairs.append((m_param, m_grad))
            self.merged_dense_pairs.append((m_param, m_grad))

        for sparse_pair in origin_for_sparse:
            param, grad = sparse_pair

            m_param = MergedVariable(param, [param], [0])
            m_grad = MergedVariable(grad, [grad], [0])
            self.merged_variables_pairs.append((m_param, m_grad))
            self.merged_sparse_pairs.append((m_param, m_grad))

        for merged in self.merged_variables_pairs:
            m_param, m_grad = merged
            self.merged_variable_map[
1226 1227
                m_param.merged_var.name
            ] = m_param.merged_var
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
            self.merged_variable_map[m_grad.merged_var.name] = m_grad.merged_var

        param_merges = []
        param_merges.extend(origin_for_sparse)
        param_merges.extend(origin_for_dense)

        for param, grad in param_merges:
            param_name_grad_name[param.name] = grad.name
            grad_name_to_param_name[grad.name] = param.name

        self.origin_sparse_pairs = origin_for_sparse
        self.origin_dense_pairs = origin_for_dense
        self.param_name_to_grad_name = param_name_grad_name
        self.grad_name_to_param_name = grad_name_to_param_name

        sparse_pair_map = collections.OrderedDict()

        for pair in self.origin_sparse_pairs + self.origin_dense_pairs:
            param, grad = pair
            sparse_pair_map[param.name] = str(param)
            sparse_pair_map[grad.name] = str(grad)

        self._var_slice_and_distribute()
        self._dispatcher()

    def get_param_grads(self):
        origin_program = self.origin_main_program

        def _get_params_grads(sparse_varnames):
            block = origin_program.global_block()

            dense_param_grads = []
            sparse_param_grads = []

            optimize_params = set()
            origin_var_dict = origin_program.global_block().vars
            role_id = int(core.op_proto_and_checker_maker.OpRole.Backward)
            for op in block.ops:
                if _is_opt_role_op(op):
                    # delete clip op from opt_ops when run in Parameter Server mode
1268 1269 1270 1271
                    if (
                        OP_NAME_SCOPE in op.all_attrs()
                        and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE)
                    ):
1272 1273 1274 1275 1276 1277 1278
                        op._set_attr("op_role", role_id)
                        continue
                    if op.attr(OP_ROLE_VAR_ATTR_NAME):
                        param_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[0]
                        grad_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[1]
                        if param_name not in optimize_params:
                            optimize_params.add(param_name)
1279 1280 1281 1282
                            param_grad = (
                                origin_var_dict[param_name],
                                origin_var_dict[grad_name],
                            )
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

                            if param_name in sparse_varnames:
                                sparse_param_grads.append(param_grad)
                            else:
                                dense_param_grads.append(param_grad)
            return sparse_param_grads, dense_param_grads

        def _get_sparse_varnames():
            varnames = []
            for op in origin_program.global_block().ops:
1293 1294 1295 1296
                if (
                    op.type in SPARSE_OP_TYPE_DICT.keys()
                    and op.attr('remote_prefetch') is True
                ):
1297
                    param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0]
1298 1299 1300 1301 1302 1303
                    varnames.append(param_name)

            return list(set(varnames))

        sparse_varnames = _get_sparse_varnames()
        sparse_param_grads, dense_param_grads = _get_params_grads(
1304 1305
            sparse_varnames
        )
1306 1307 1308

        return sparse_param_grads, dense_param_grads

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    def remove_var_pair_by_grad(self, var_name):

        for index, pair in enumerate(self.merged_variables_pairs):
            var = pair[0]
            var_grad = pair[1]
            if var_grad.merged_var.name == var_name:
                del self.merged_variables_pairs[index]

        for index, pair in enumerate(self.merged_dense_pairs):
            var = pair[0]
            var_grad = pair[1]
            if var_grad.merged_var.name == var_name:
                del self.merged_dense_pairs[index]
                return

        for index, pair in enumerate(self.merged_sparse_pairs):
            var = pair[0]
            var_grad = pair[1]
            if var_grad.merged_var.name == var_name:
                del self.merged_sparse_pairs[index]
                return

        print("Not find {} in self.merge_pairs".format(var_name))

1333 1334 1335 1336 1337 1338

def _is_opt_role_op(op):
    # NOTE : depend on oprole to find out whether this op is for
    # optimize
    op_maker = core.op_proto_and_checker_maker
    optimize_role = core.op_proto_and_checker_maker.OpRole.Optimize
1339 1340 1341
    if op_maker.kOpRoleAttrName() in op.attr_names and int(
        op.all_attrs()[op_maker.kOpRoleAttrName()]
    ) == int(optimize_role):
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
        return True
    return False


def _get_optimize_ops(_program):
    block = _program.global_block()
    opt_ops = []
    for op in block.ops:
        if _is_opt_role_op(op):
            # delete clip op from opt_ops when run in Parameter Server mode
1352 1353 1354 1355
            if (
                OP_NAME_SCOPE in op.all_attrs()
                and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE)
            ):
1356 1357
                op._set_attr(
                    "op_role",
1358 1359
                    int(core.op_proto_and_checker_maker.OpRole.Backward),
                )
1360 1361 1362 1363 1364
                continue
            opt_ops.append(op)
    return opt_ops


1365 1366 1367
def _add_lr_decay_table_pass(main_program, compiled_config, lr_decay_steps):
    if hasattr(compiled_config.origin_main_program, 'lr_sheduler'):
        from paddle.optimizer.lr import LRScheduler
1368 1369 1370 1371

        assert isinstance(
            compiled_config.origin_main_program.lr_sheduler, LRScheduler
        ), "must be LRScheduler"
1372 1373
        ops = _get_optimize_ops(compiled_config.origin_main_program)
        lr_param_dict = _get_lr_param_dict(ops)
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
        (
            lr_decay_main_program,
            lr_decay_startup_program,
            lr_name,
        ) = _get_lr_sheduler_program(
            compiled_config.origin_main_program.lr_sheduler,
            lr_param_dict,
            lr_decay_steps,
        )
        compiled_config.add_tensor_table(
            "@LR_DECAY_COUNTER@",
            lr_name,
            lr_decay_startup_program,
            lr_decay_main_program,
            "GlobalStepTable",
        )
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404


def _get_lr_param_dict(opt_ops):
    lr_param_dict = {}
    for op in opt_ops:
        lr_name = op.input("LearningRate")[0]
        param_name = op.input("Param")[0]
        if lr_name not in lr_param_dict:
            lr_param_dict[lr_name] = []
        lr_param_dict[lr_name].append(param_name)
    return lr_param_dict


def _get_lr_sheduler_program(lr_sheduler, lr_param_dict, lr_decay_steps):
    schedler_decay = [
1405 1406 1407 1408
        'NoamDecay',
        'NaturalExpDecay',
        'InverseTimeDecay',
        'ExponentialDecay',
1409 1410
    ]

1411 1412 1413 1414 1415 1416 1417
    from paddle.optimizer.lr import (
        ExponentialDecay,
        NoamDecay,
        PiecewiseDecay,
        NaturalExpDecay,
        InverseTimeDecay,
    )
1418
    from paddle.static.learning_rate_scheduler import (
1419 1420 1421 1422 1423 1424
        exponential_decay,
        noam_decay,
        piecewise_decay,
        natural_exp_decay,
        inverse_time_decay,
    )
1425

1426 1427
    decay_main_program = paddle.static.Program()
    decay_startup_program = paddle.static.Program()
1428 1429 1430
    lr_name = ""

    if isinstance(lr_sheduler, ExponentialDecay):
1431 1432 1433
        with paddle.static.program_guard(
            decay_main_program, decay_startup_program
        ):
1434 1435 1436 1437 1438 1439 1440
            lr = exponential_decay(1.0, lr_decay_steps, lr_sheduler.gamma, True)
            lr_name = lr.name
            logging.warn(
                "ExponentialDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n"
                "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n "
                "\t strategy.a_sync = True \n"
                "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n"
1441 1442
                % lr_decay_steps
            )
1443
    elif isinstance(lr_sheduler, NoamDecay):
1444 1445 1446
        with paddle.static.program_guard(
            decay_main_program, decay_startup_program
        ):
1447 1448
            lr = noam_decay(lr_sheduler.d_model, lr_sheduler.warmup_steps, 1.0)
            lr_name = lr.name
1449 1450 1451 1452
            logging.warn(
                "NoamDecay is set, warmup steps is [ %d ]"
                % lr_sheduler.warmup_steps
            )
1453
    elif isinstance(lr_sheduler, NaturalExpDecay):
1454 1455 1456
        with paddle.static.program_guard(
            decay_main_program, decay_startup_program
        ):
1457 1458 1459 1460 1461 1462 1463
            lr = natural_exp_decay(1.0, lr_decay_steps, lr_sheduler.gamma, True)
            lr_name = lr.name
            logging.warn(
                "NaturalExpDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n"
                "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n "
                "\t strategy.a_sync = True \n"
                "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n"
1464 1465
                % lr_decay_steps
            )
1466
    elif isinstance(lr_sheduler, InverseTimeDecay):
1467 1468 1469
        with paddle.static.program_guard(
            decay_main_program, decay_startup_program
        ):
1470 1471 1472
            lr = inverse_time_decay(
                1.0, lr_decay_steps, lr_sheduler.gamma, True
            )
1473 1474 1475 1476 1477 1478
            lr_name = lr.name
            logging.warn(
                "InverseTimeDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n"
                "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n "
                "\t strategy.a_sync = True \n"
                "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n"
1479 1480
                % lr_decay_steps
            )
1481 1482
    else:
        raise ValueError(
1483 1484 1485 1486
            "Not supported current LearningRate strategy, please use follow decay strategy: {}".format(
                schedler_decay
            )
        )
1487 1488 1489 1490

    return decay_main_program, decay_startup_program, lr_name


1491 1492 1493 1494 1495 1496 1497
def _get_varname_parts(varname):
    # returns origin, blockid, trainerid
    orig_var_name = ""
    trainer_part = ""
    block_part = ""
    trainer_idx = varname.find(".trainer_")
    if trainer_idx >= 0:
1498
        trainer_part = varname[trainer_idx + 1 :]
1499 1500 1501 1502
    else:
        trainer_idx = len(varname)
    block_index = varname.find(".block")
    if block_index >= 0:
1503
        block_part = varname[block_index + 1 : trainer_idx]
1504 1505
    else:
        block_index = len(varname)
1506
    orig_var_name = varname[0 : min(block_index, trainer_idx)]
1507 1508 1509 1510 1511 1512
    return orig_var_name, block_part, trainer_part


def _orig_varname(varname):
    orig, _, _ = _get_varname_parts(varname)
    return orig