optimizer.py 68.5 KB
Newer Older
M
MRXLT 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2019 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.

import logging
from collections import defaultdict

18 19
import numpy as np

20
import paddle
21
import paddle.autograd as imperative_base
22
from paddle import _C_ops
23 24
from paddle.base import core
from paddle.base.framework import (
25
    Variable,
26
    _current_expected_place,
27 28
    default_main_program,
    device_guard,
29
    in_dygraph_mode,
30 31
    name_scope,
)
32
from paddle.regularizer import L2Decay
M
MRXLT 已提交
33

34 35 36 37
from ..base import framework, unique_name
from ..base.backward import _get_no_grad_set_name, append_backward
from ..base.framework import Parameter, program_guard
from ..base.layer_helper import LayerHelper
38
from .lr import LRScheduler
M
MRXLT 已提交
39

40 41
__all__ = []

M
MRXLT 已提交
42

43
@framework.static_only
44 45 46 47 48 49 50 51
def append_backward_new(
    loss_list,
    parameter_list=None,
    no_grad_set=None,
    callbacks=None,
    checkpoints=None,
    distop_context=None,
):
52
    from paddle.incubate.autograd.primx import Transform, orig2prim
53

54
    program = default_main_program()
55 56 57
    assert (
        program.num_blocks == 1
    ), "The append_backward_new interface is designed to process only one block."
58
    block = program.current_block()
59
    for el in loss_list:
60 61 62
        assert (
            el.block == block
        ), 'variable in loss_list should be in current block of main program'
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    orig2prim(block)
    ad = Transform(block)
    if parameter_list is None:
        parameter_list = program.global_block().all_parameters()
    param_dot, loss_dot = ad.linearize(parameter_list, loss_list)
    loss_bar, param_bar = ad.transpose(loss_dot, param_dot)

    # remove param_dot and their constructor ops
    op_indexes = []
    for var in param_dot:
        if var is not None:
            op_index = block.ops.index(var.op)
            assert op_index >= 0
            op_indexes.append(op_index)

    ad.erase_ops(sorted(op_indexes))
    ad.erase_dots(param_dot)

    if len(parameter_list) == 1:
        params_and_grads = [(parameter_list, param_bar)]
    else:
        params_and_grads = []
        for i, param in enumerate(parameter_list):
            params_and_grads.append((param, param_bar[i]))
    return params_and_grads


91
class Optimizer:
92
    r"""Optimizer Base class.
M
MRXLT 已提交
93 94 95 96 97 98

    Define the common interface of an optimizer.
    User should not use this class directly,
    but need to use one of it's implementation.

    Args:
99 100
        learning_rate (float|LRScheduler): The learning rate used to update ``Parameter``.
            It can be a float value or any subclass of ``LRScheduler`` .
101
        parameters (list|tuple, optional): List/Tuple of ``Tensor`` names to update to minimize ``loss``. \
102 103 104 105
            This parameter is required in dygraph mode. And you can specify different options for \
            different parameter groups such as the learning rate, weight decay, etc, \
            then the parameters are list of dict. Note that the learning_rate in paramter groups \
            represents the scale of base learning_rate. \
106
            The default value is None in static graph mode, at this time all parameters will be updated.
M
MRXLT 已提交
107 108
        weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \
            It canbe a float value as coeff of L2 regularization or \
109 110
            :ref:`api_base_regularizer_L1Decay`, :ref:`api_base_regularizer_L2Decay`.
            If a parameter has set regularizer using :ref:`api_base_ParamAttr` already, \
M
MRXLT 已提交
111 112 113 114 115
            the regularization setting here in optimizer will be ignored for this parameter. \
            Otherwise, the regularization setting here in optimizer will take effect. \
            Default None, meaning there is no regularization.
        grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of \
            some derived class of ``GradientClipBase`` . There are three cliping strategies \
116 117
            ( :ref:`api_base_clip_GradientClipByGlobalNorm` , :ref:`api_base_clip_GradientClipByNorm` , \
            :ref:`api_base_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping.
M
MRXLT 已提交
118 119 120 121 122
        name (str, optional): Normally there is no need for user to set this property.
            For more information, please refer to :ref:`api_guide_Name`.
            The default value is None.

    Returns:
123 124
       Base class for optimizer.

M
MRXLT 已提交
125 126 127
    Examples:
        .. code-block:: python

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            >>> # Take the subclass adam as an example
            >>> import paddle
            >>> linear = paddle.nn.Linear(10, 10)
            >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
            >>> out = linear(inp)
            >>> loss = paddle.mean(out)
            >>> adam = paddle.optimizer.Adam(learning_rate=0.1,
            ...         parameters=linear.parameters())
            >>> loss.backward()
            >>> adam.step()
            >>> adam.clear_grad()

            >>> #Take the subclass sgd as an example
            >>> #optimize parameters in linear_1 and linear2 in different options.
            >>> #Note that the learning_rate of linear_2 is 0.01.
            >>> linear_1 = paddle.nn.Linear(10, 10)
            >>> linear_2 = paddle.nn.Linear(10, 10)
            >>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
            >>> out = linear_1(inp)
            >>> out = linear_2(out)
            >>> loss = paddle.mean(out)
            >>> sgd = paddle.optimizer.SGD(
            ...     learning_rate=0.1,
            ...     parameters=[{
            ...         'params': linear_1.parameters()
            ...     }, {
            ...         'params': linear_2.parameters(),
            ...         'weight_decay': 0.001,
            ...         'learning_rate': 0.1
            ...     }],
            ...     weight_decay=0.01)
            >>> loss.backward()
            >>> sgd.step()
            >>> sgd.clear_grad()
162

M
MRXLT 已提交
163 164
    """

165
    @imperative_base.no_grad()
166 167 168 169 170 171 172 173
    def __init__(
        self,
        learning_rate,
        parameters=None,
        weight_decay=None,
        grad_clip=None,
        name=None,
    ):
174 175 176 177
        if parameters is not None:
            # paddle.Tensor is also iterable, so here we don't check whether
            # the input is iterable, if the input is paddle.Tensor, the
            # list(paddle.Tensor) will be a error value
178
            if isinstance(parameters, (paddle.Tensor, core.eager.Tensor)):
179 180
                raise TypeError(
                    "`parameters` argument given to the optimizer should be "
181 182 183 184
                    "an iterable of paddle Tensors, but got argument type is `{}`.".format(
                        type(parameters)
                    )
                )
185 186 187 188
            if isinstance(parameters, dict):
                raise TypeError(
                    "`parameters` argument should not get dict type, "
                    "if parameter groups is needed, please set `parameters`"
189 190
                    " as list of dict"
                )
191 192 193 194
            self._parameter_list = list(parameters)
        else:
            self._parameter_list = None

M
MRXLT 已提交
195
        self._name = name
196
        if framework.in_dygraph_mode():
M
MRXLT 已提交
197 198 199 200 201
            if self._parameter_list is None:
                raise AttributeError(
                    "parameters argument given to the Optimizer should not be None in dygraph mode."
                )
            if weight_decay is not None:
202 203
                if not isinstance(self._parameter_list[0], dict):
                    for param in self._parameter_list:
204 205 206 207
                        if (
                            hasattr(param, 'regularizer')
                            and param.regularizer is not None
                        ):
208 209 210
                            logging.info(
                                "If regularizer of a Parameter has been set by 'paddle.ParamAttr' or 'static.WeightNormParamAttr' already. "
                                "The weight_decay[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!"
211 212
                                % weight_decay.__str__()
                            )
213 214
                            break

215
        if not isinstance(learning_rate, (float, LRScheduler)):
216
            raise TypeError(
217 218 219
                "learning rate should be float or LRScheduler, got %s here"
                % type(learning_rate)
            )
M
MRXLT 已提交
220
        if grad_clip is not None:
221
            if not isinstance(grad_clip, paddle.nn.clip.GradientClipBase):
M
MRXLT 已提交
222 223 224 225 226 227 228 229 230
                raise TypeError(
                    "'grad_clip' should be an instance of GradientClipBase's derived class"
                )
        if isinstance(weight_decay, float):
            self.regularization = L2Decay(weight_decay)
        else:
            self.regularization = weight_decay
        self._grad_clip = grad_clip
        self._learning_rate = learning_rate
L
Leo Chen 已提交
231

M
MRXLT 已提交
232
        self._dtype = None
L
Leo Chen 已提交
233 234
        # Infer the dtype form parameter
        if self._parameter_list:
235 236
            if isinstance(self._parameter_list[0], dict):
                for param_group in self._parameter_list:
237 238 239
                    assert (
                        'params' in param_group
                    ), 'params should be set in parameters if parameter groups are optimized in different options'
240 241 242
                self._dtype = self._parameter_list[0]['params'][0].dtype
            else:
                self._dtype = self._parameter_list[0].dtype
L
Leo Chen 已提交
243

M
MRXLT 已提交
244 245
        # each program should have a independent learning rate
        # program -> tensor(learning_rate)
246
        self._learning_rate_map = {}
M
MRXLT 已提交
247 248 249 250
        # Dictionary of accumulators. Some optimizer subclasses need to
        # allocate and manage extra tensors associated with the parameters
        # to train. These tensors are called accumulators.
        # {accum_name : { paramter_name : accumulator_for_parameter, ...}, ...}
251
        self._accumulators = defaultdict(lambda: {})
M
MRXLT 已提交
252 253 254
        self.helper = None
        self._opti_name_list = []
        self._accumulators_holder = {}
255
        self._param_device_map = {}
M
MRXLT 已提交
256
        self.clear_gradients = self.clear_grad
257 258
        self._default_dict = {
            'weight_decay': self.regularization,
259
            'grad_clip': self._grad_clip,
260 261 262 263 264 265 266 267
        }

        self._param_groups = []
        if self._parameter_list and isinstance(self._parameter_list[0], dict):
            for param_group in self._parameter_list:
                self._add_param_group(param_group.copy())
        else:
            self._param_groups = self._parameter_list
M
MRXLT 已提交
268

269
        # NOTE: Multi Tensor: Pass in all parameters and gradients to the op kernel of the Optimizer at one time for updating for dygraph mode.
Z
zhangbo9674 已提交
270
        # Optimizer support list: [ paddle.optimizer.Momentum, paddle.optimizer.Adam].
271 272
        self._use_multi_tensor = None

273
        self._param_dict = self._create_multi_tensor_dict()
274
        self._auxiliary_vars = {}
W
wanghuancoder 已提交
275
        self._already_create_accumulater = set()
276

277 278 279 280 281 282 283 284
        # create master gradients' states
        self._create_master_grad_states()

    def _create_master_grad_states(self):
        # master gradients states
        self._master_grads = {}
        self._master_grad = False

285 286 287
    def _set_auxiliary_var(self, key, val):
        self._auxiliary_vars[key] = val

288 289 290 291 292 293 294
    def _create_multi_tensor_dict(self):
        n = len(self._param_groups) if self._param_groups is not None else 1
        return {
            'FP32_LODTensor': [[] for _ in range(n)],
            'FP16_LODTensor': [[] for _ in range(n)],
        }

295 296 297
    def _get_auxiliary_var(self, key):
        return self._auxiliary_vars.get(key, None)

M
MRXLT 已提交
298 299 300
    @framework.dygraph_only
    def state_dict(self):
        '''
301
        Get state dict information from optimizer. It contain all the tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be include in state dict.
M
MRXLT 已提交
302 303
        If the optimizer never be called(minimize function), the state_dict is empty.

304
        Args:
M
MRXLT 已提交
305 306 307 308
            None

        Returns:
            state_dict(dict) : dict contains all the Tensor used by optimizer
309

M
MRXLT 已提交
310 311 312 313
        Examples:
            .. code-block:: python

                import paddle
M
MRXLT 已提交
314
                emb = paddle.nn.Embedding(10, 10)
M
MRXLT 已提交
315 316 317 318 319 320 321 322 323

                adam = paddle.optimizer.Adam(0.001, parameters=emb.parameters())
                state_dict = adam.state_dict()

        '''
        state_dict = {}
        for k, v in self._accumulators.items():
            for para_name, var_tmp in v.items():
                state_dict[var_tmp.name] = var_tmp
324 325 326 327
        # if has master weight and then save master weight
        if hasattr(self, "_master_weights"):
            if len(self._master_weights) != 0:
                state_dict["master_weights"] = self._master_weights
M
MRXLT 已提交
328
        # global step if use lr decay
329
        if isinstance(self._learning_rate, LRScheduler):
M
MRXLT 已提交
330 331 332 333 334 335
            state_dict["LR_Scheduler"] = self._learning_rate.state_dict()
        return state_dict

    @framework.dygraph_only
    def set_state_dict(self, state_dict):
        '''
336
        Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be changed.
M
MRXLT 已提交
337

338
        Args:
M
MRXLT 已提交
339 340 341
            state_dict(dict) : Dict contains all the Tensor needed by optimizer
        Return:
            None
342

M
MRXLT 已提交
343 344 345
        Examples:
            .. code-block:: python

346
                >>> import paddle
M
MRXLT 已提交
347

348
                >>> emb = paddle.nn.Embedding(10, 10)
M
MRXLT 已提交
349

350 351
                >>> layer_state_dict = emb.state_dict()
                >>> paddle.save(layer_state_dict, "emb.pdparams")
M
MRXLT 已提交
352

353 354 355 356 357 358 359
                >>> scheduler = paddle.optimizer.lr.NoamDecay(
                ...     d_model=0.01, warmup_steps=100, verbose=True)
                >>> adam = paddle.optimizer.Adam(
                ...     learning_rate=scheduler,
                ...     parameters=emb.parameters())
                >>> opt_state_dict = adam.state_dict()
                >>> paddle.save(opt_state_dict, "adam.pdopt")
M
MRXLT 已提交
360

361 362
                >>> opti_state_dict = paddle.load("adam.pdopt")
                >>> adam.set_state_dict(opti_state_dict)
M
MRXLT 已提交
363 364

        '''
365
        if isinstance(self._learning_rate, LRScheduler):
366
            self._learning_rate.set_state_dict(state_dict["LR_Scheduler"])
M
MRXLT 已提交
367

368
        # NOTE: exclude learning rate scheduler's state from
369 370 371 372
        # _accumulators_holder.
        state_dict = state_dict.copy()
        if "LR_Scheduler" in state_dict:
            state_dict.pop("LR_Scheduler")
373 374 375 376
        if "master_weights" in state_dict:
            if hasattr(self, "_master_weights"):
                self._master_weights = state_dict["master_weights"]
            state_dict.pop("master_weights")
M
MRXLT 已提交
377 378 379
        self._accumulators_holder = state_dict
        for k, v in self._accumulators.items():
            for para_name, var_tmp in v.items():
380 381
                assert (
                    var_tmp.name in state_dict
382
                ), f"optimizer Tensor {var_tmp.name} not found"
M
MRXLT 已提交
383 384 385 386 387 388 389
                var = var_tmp.value()
                tensor = var.get_tensor()
                model_np = np.array(tensor)

                load_para = state_dict[var_tmp.name]

                if isinstance(load_para, Variable):
390
                    load_para_np = np.array(load_para)
W
wanghuancoder 已提交
391
                elif isinstance(load_para, core.eager.Tensor):
392
                    load_para_np = np.array(load_para)
M
MRXLT 已提交
393 394 395
                elif isinstance(load_para, np.ndarray):
                    load_para_np = load_para
                else:
396 397 398 399 400 401 402 403 404 405 406
                    raise RuntimeError(
                        "State dict type {} not supprt".format(
                            str(type(load_para))
                        )
                    )

                assert (
                    model_np.shape == load_para_np.shape
                ), "Parameter shape not match, Dygraph Parameter [ {} ] need tensor with shape {} but load tensor with shape {}".format(
                    model_np.name, model_np.shape, load_para_np.shape
                )
M
MRXLT 已提交
407

408 409 410 411 412
                assert (
                    model_np.dtype == load_para_np.dtype
                ), "Parameter dtype not match, Dygraph Parameter [ {} ] need tensor with dtype {}  but load tensor with dtype {}".format(
                    model_np.name, model_np.dtype, load_para_np.dtype
                )
M
MRXLT 已提交
413 414 415 416 417 418 419

                tensor.set(load_para_np, framework._current_expected_place())

    def get_opti_var_name_list(self):
        return self._opti_name_list

    def _create_global_learning_rate(self):
420 421 422 423 424 425
        def do_create():
            # lr var can't be float16 or bfloat16, for pure fp16 or bf16 training, should extra handle the dtype for lr
            _lr_dtype = (
                paddle.get_default_dtype()
                if self._dtype is None
                else self._dtype
426
            )
427 428 429 430 431 432 433 434 435 436 437
            _lr_dtype = (
                paddle.float32
                if (
                    (
                        paddle.get_default_dtype() != "float16"
                        and _lr_dtype == paddle.float16
                    )
                    or (
                        paddle.get_default_dtype() != "bfloat16"
                        and _lr_dtype == paddle.bfloat16
                    )
438
                )
439
                else _lr_dtype
440
            )
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            if isinstance(self._learning_rate, LRScheduler):
                lr_var = self._global_learning_rate()
                # only create global lr_var once
                if not isinstance(lr_var, framework.Variable):
                    lr_name = unique_name.generate('learning_rate')
                    self._learning_rate._var_name = lr_name
                    lr_var = self.helper.create_global_variable(
                        name=lr_name,
                        shape=[],
                        persistable=True,
                        stop_gradient=True,
                        dtype=_lr_dtype,
                    )
                    main_prog = framework.default_main_program()
                    main_prog.lr_scheduler = self._learning_rate
                    main_prog.lr_var = lr_var

                    self._learning_rate_map[
                        framework.default_main_program()
                    ] = lr_var

                lr_value = float(self._learning_rate())
                self.helper.set_variable_initializer(
                    lr_var,
                    initializer=paddle.nn.initializer.Constant(value=lr_value),
466
                )
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
            elif isinstance(self._learning_rate, float):
                # only create global lr_var once
                lr = self._global_learning_rate()
                if isinstance(lr, framework.Variable):
                    return
                else:
                    self._learning_rate_map[
                        framework.default_main_program()
                    ] = paddle.static.create_global_var(
                        name=unique_name.generate("learning_rate"),
                        shape=[],
                        value=float(self._learning_rate),
                        dtype=_lr_dtype,
                        persistable=True,
                    )

483
        with paddle.base.framework.dygraph_guard_if_declarative():
484
            do_create()
M
MRXLT 已提交
485 486 487 488 489

    @framework.dygraph_only
    def set_lr(self, value):
        """
        :api_attr: imperative
490

491
        Set the value of the learning rate manually in the optimizer. If the optimizer use LRScheduler,
M
MRXLT 已提交
492 493 494
        this API cannot be invoked, because it will lead to conflict.

        Args:
M
MRXLT 已提交
495
            value (float): the value of learning rate
M
MRXLT 已提交
496 497 498

        Returns:
            None
499

M
MRXLT 已提交
500 501 502
        Examples:
            .. code-block:: python

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
                >>> import paddle
                >>> linear = paddle.nn.Linear(10, 10)

                >>> adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters())

                >>> # set learning rate manually by python float value
                >>> lr_list = [0.2, 0.3, 0.4, 0.5, 0.6]
                >>> for i in range(5):
                ...     adam.set_lr(lr_list[i])
                ...     lr = adam.get_lr()
                ...     print("current lr is {}".format(lr))
                current lr is 0.2
                current lr is 0.3
                current lr is 0.4
                current lr is 0.5
                current lr is 0.6
M
MRXLT 已提交
519 520

        """
521
        if not isinstance(value, (int, float)):
M
MRXLT 已提交
522
            raise TypeError(
523
                "The type of 'value' in optimizer.set_lr must be float, but received %s."
524 525
                % (type(value))
            )
526
        if isinstance(self._learning_rate, LRScheduler):
M
MRXLT 已提交
527
            raise RuntimeError(
528
                "optimizer's learning rate can't be LRScheduler when invoke this API, because this will lead to conflict."
M
MRXLT 已提交
529
            )
530 531 532
        self._learning_rate = float(value)
        current_lr = self._global_learning_rate()
        if current_lr is not None:
533 534
            if in_dygraph_mode():
                place = _current_expected_place()
535 536 537 538 539 540 541
                _C_ops.full_(
                    current_lr,
                    list(current_lr.shape),
                    float(value),
                    current_lr.dtype,
                    place,
                )
542 543
            else:
                global_block = framework.default_main_program().global_block()
544 545 546 547 548 549 550 551 552 553
                global_block.append_op(
                    type='fill_constant',
                    outputs={'Out': [current_lr]},
                    attrs={
                        'dtype': current_lr.dtype,
                        'shape': list(current_lr.shape),
                        'value': float(value),
                    },
                    stop_gradient=True,
                )
M
MRXLT 已提交
554

Z
zqw_1997 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    @framework.dygraph_only
    def set_lr_scheduler(self, scheduler):
        """
        :api_attr: imperative

        Set the LRScheduler of the learning rate manually in the optimizer. If the optimizer already used LRScheduler previously,
        this API will set it be the new one.

        Args:
            scheduler (LRScheduler): the LRScheduler of learning rate

        Returns:
            None

        Examples:
            .. code-block:: python

572 573
                >>> import paddle
                >>> linear = paddle.nn.Linear(10, 10)
Z
zqw_1997 已提交
574

575
                >>> adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters())
Z
zqw_1997 已提交
576

577 578 579 580 581 582
                >>> # set learning rate manually by class LRScheduler
                >>> scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2,4,6], gamma=0.8)
                >>> adam.set_lr_scheduler(scheduler)
                >>> lr = adam.get_lr()
                >>> print("current lr is {}".format(lr))
                current lr is 0.5
Z
zqw_1997 已提交
583

584 585 586 587 588 589
                >>> # set learning rate manually by another LRScheduler
                >>> scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.1, step_size=5, gamma=0.6)
                >>> adam.set_lr_scheduler(scheduler)
                >>> lr = adam.get_lr()
                >>> print("current lr is {}".format(lr))
                current lr is 0.1
Z
zqw_1997 已提交
590 591 592 593 594 595 596 597 598 599 600

        """
        from paddle.optimizer.lr import LRScheduler

        if not isinstance(scheduler, LRScheduler):
            raise TypeError(
                "The type of 'scheduler' in optimizer.set_lr_schduler must be LRScheduler, but received %s."
                % (type(scheduler))
            )
        self._learning_rate = scheduler

M
MRXLT 已提交
601 602
    def get_lr(self):
        """
603
        Get current learning rate of optimizer.
604 605
        If 'LRScheduler' is not used, the return value is all the same.
        If 'LRScheduler' is used, the return value is the current scheduled learing rete.
M
MRXLT 已提交
606

M
MRXLT 已提交
607
        Returns:
608
            float: The current learning rate of optimizer.
M
MRXLT 已提交
609 610 611 612

        Examples:
            .. code-block:: python

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
                >>> # train on default dynamic graph mode
                >>> import paddle
                >>> import numpy as np
                >>> emb = paddle.nn.Embedding(10, 3)

                >>> ## example1: LRScheduler is not used, return the same value is all the same
                >>> adam = paddle.optimizer.Adam(0.01, parameters = emb.parameters())
                >>> for batch in range(10):
                ...     input = paddle.randint(low=0, high=5, shape=[5])
                ...     out = emb(input)
                ...     out.backward()
                ...     print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.01
                ...     adam.step()
                Learning rate of step0: 0.01
                Learning rate of step1: 0.01
                Learning rate of step2: 0.01
                Learning rate of step3: 0.01
                Learning rate of step4: 0.01
                Learning rate of step5: 0.01
                Learning rate of step6: 0.01
                Learning rate of step7: 0.01
                Learning rate of step8: 0.01
                Learning rate of step9: 0.01

                >>> ## example2: StepDecay is used, return the scheduled learning rate
                >>> scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1)
                >>> adam = paddle.optimizer.Adam(scheduler, parameters = emb.parameters())
                >>> for batch in range(10):
                ...     input = paddle.randint(low=0, high=5, shape=[5])
                ...     out = emb(input)
                ...     out.backward()
                ...     print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05...
                ...     adam.step()
                ...     scheduler.step()
                Learning rate of step0: 0.5
                Learning rate of step1: 0.5
                Learning rate of step2: 0.05
                Learning rate of step3: 0.05
                Learning rate of step4: 0.005000000000000001
                Learning rate of step5: 0.005000000000000001
                Learning rate of step6: 0.0005000000000000001
                Learning rate of step7: 0.0005000000000000001
                Learning rate of step8: 5.000000000000001e-05
                Learning rate of step9: 5.000000000000001e-05

                >>> # train on static graph mode
                >>> paddle.enable_static()
                >>> main_prog = paddle.static.Program()
                >>> start_prog = paddle.static.Program()
                >>> with paddle.static.program_guard(main_prog, start_prog):
                ...     x = paddle.static.data(name='x', shape=[None, 10])
                ...     z = paddle.static.nn.fc(x, 100)
                ...     loss = paddle.mean(z)
                ...     scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1)
                ...     adam = paddle.optimizer.Adam(learning_rate=scheduler)
                ...     adam.minimize(loss)

                >>> exe = paddle.static.Executor()
                >>> exe.run(start_prog)
                >>> for batch in range(10):
                ...     print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05->0.005...
                ...     out = exe.run(main_prog, feed={'x': np.random.randn(3, 10).astype('float32')})
                ...     scheduler.step()
                Learning rate of step0: 0.5
                Learning rate of step1: 0.5
                Learning rate of step2: 0.05
                Learning rate of step3: 0.05
                Learning rate of step4: 0.005000000000000001
                Learning rate of step5: 0.005000000000000001
                Learning rate of step6: 0.0005000000000000001
                Learning rate of step7: 0.0005000000000000001
                Learning rate of step8: 5.000000000000001e-05
                Learning rate of step9: 5.000000000000001e-05
M
MRXLT 已提交
686 687 688 689
        """
        if isinstance(self._learning_rate, float):
            return self._learning_rate
        else:
690
            return self._learning_rate()
M
MRXLT 已提交
691 692 693 694 695 696 697 698 699 700 701

    def _global_learning_rate(self, program=None):
        """
        get global decayed learning rate
        :return:
        """
        if program is None:
            program = framework.default_main_program()
        return self._learning_rate_map.get(program, None)

    def _append_optimize_op(self, block, param_and_grad):
702
        """append optimize operator to block and return all the added optimize_op"""
M
MRXLT 已提交
703 704 705 706 707 708 709
        raise NotImplementedError(
            "Class \"Optimizer\" connot be used directly as an optimizer, please use its subclasses such as \"Adam\""
        )

    def _create_param_lr(self, param_and_grad):
        # create learning rate tensor for every parameter
        param = param_and_grad[0]
710 711 712 713
        if hasattr(param, 'optimize_attr'):
            param_lr = param.optimize_attr['learning_rate']
            if type(param_lr) == Variable:
                return param_lr
M
MRXLT 已提交
714
            else:
715 716 717 718
                if param_lr == 1.0:
                    return self._global_learning_rate()
                else:
                    with default_main_program()._lr_schedule_guard(
719 720
                        is_with_opt=True
                    ), framework.name_scope('scale_with_param_lr'):
721 722 723
                        return self._global_learning_rate() * param_lr
        else:
            return self._global_learning_rate()
M
MRXLT 已提交
724

725 726 727 728 729 730
    def _create_master_weight(self, param):
        if param.name in self._master_weights:
            var = self._master_weights[param.name]
        else:
            assert isinstance(self.helper, LayerHelper)

731
            var_name = self._gen_master_weight_var_name(param)
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
            var = paddle.static.create_global_var(
                name=var_name,
                shape=param.shape,
                value=0,
                dtype='float32',
                persistable=True,
            )
            block = self.helper.startup_program.global_block()
            block.append_op(
                type="cast",
                inputs={"X": [param]},
                outputs={"Out": [var]},
                attrs={
                    "in_dtype": param.dtype,
                    "out_dtype": core.VarDesc.VarType.FP32,
                },
            )
            self._master_weights[param.name] = var
        return var

752 753 754 755
    def _gen_master_weight_var_name(self, param):
        var_name = param.name + "_fp32_master"
        return unique_name.generate(var_name)

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    def _create_master_grad(self, grad):
        assert self._is_dtype_fp16_or_bf16(grad.dtype)
        if grad.name in self._master_grads:
            var = self._master_grads[grad.name]
        else:
            var_name = grad.name + "_fp32_master"
            var_name = unique_name.generate(var_name)
            var = grad.block.create_var(
                name=var_name,
                shape=grad.shape,
                value=0,
                dtype='float32',
                lod_level=grad.lod_level,
                persistable=grad.persistable,
                is_data=grad.is_data,
            )
            self._master_grads[grad.name] = var
        return var

M
MRXLT 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    def _create_accumulators(self, block, parameters):
        """Create all accumulators needed by the parameters

        Args:
            block: the block in which the loss tensor is present
            parameters: list of parameter tensors for the optimizer
        """
        pass

    def _finish_update(self, block, parameters_and_grads):
        """Finish any custom updates needed
           before completing an optimization step

        Args:
            block: the block in which the loss tensor is present
            parameters: list of parameter tensors for the optimizer

        Returns:
            None
        """
        pass

797 798 799 800 801 802 803 804 805 806
    def _add_accumulator(
        self,
        name,
        param,
        dtype=None,
        fill_value=0.0,
        shape=None,
        type=None,
        device=None,
    ):
M
MRXLT 已提交
807 808 809 810 811 812 813 814 815 816 817
        """Utility function to add an accumulator for a parameter

        Args:
            block: the block in which the loss tensor is present
            name: name of the accumulator
            param: parameter tensor for which accumulator is to be added
            dtype: data type of the accumulator tensor
            fill_value: value to initialize the accumulator tensor
        """
        if self._name is not None:
            name = self._name + "_" + name
818 819 820 821
        if (
            name in self._accumulators
            and param.name in self._accumulators[name]
        ):
822
            if framework.in_dygraph_mode():
M
MRXLT 已提交
823
                return self._accumulators[name][param.name]
824 825
            raise Exception(
                "Accumulator {} already exists for parameter {}".format(
826 827 828
                    name, param.name
                )
            )
829
        if shape is None:
M
MRXLT 已提交
830 831 832 833 834 835 836 837 838 839 840
            shape = param.shape
        assert isinstance(self.helper, LayerHelper)

        var_name = param.name + "_" + name
        var_name = unique_name.generate(var_name)
        self._opti_name_list.append(var_name)

        var = self.helper.create_global_variable(
            name=var_name,
            persistable=True,
            dtype=dtype or param.dtype,
841
            type=core.VarDesc.VarType.LOD_TENSOR,
M
MRXLT 已提交
842
            shape=shape,
843 844
            belong_to_optimizer=True,
        )
M
MRXLT 已提交
845 846
        if device is None:
            device = self._get_device_for_param(param.name)
847

W
wanghuancoder 已提交
848 849 850 851
        if (
            in_dygraph_mode()
            and (device == 'cpu' or isinstance(device, core.CPUPlace))
            and (not core.is_compiled_with_xpu())
852 853 854 855 856 857 858
        ):
            _C_ops.full_(
                var,
                var.shape,
                str(float(fill_value)),
                var.dtype,
                core.CPUPlace(),
859
            )
860 861 862
        else:
            with device_guard(device):
                self.helper.set_variable_initializer(
863 864 865 866
                    var,
                    initializer=paddle.nn.initializer.Constant(
                        value=float(fill_value)
                    ),
867
                )
M
MRXLT 已提交
868

869
        if framework.in_dygraph_mode():
M
MRXLT 已提交
870
            if len(self._accumulators_holder) > 0:
871 872 873 874 875
                assert (
                    var_name in self._accumulators_holder
                ), "Optimizer set error, {} should in state dict".format(
                    var_name
                )
876
                var.set_value(self._accumulators_holder.pop(var_name))
M
MRXLT 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

        self._accumulators[name][param.name] = var
        return var

    def _get_accumulator(self, name, param):
        """Utility function to fetch an accumulator for a parameter

        Args:
            name: name of the accumulator
            param: parameter tensor for which accumulator is to be fetched

        Returns:
            accumulator tensor for the parameter
        """
        if self._name is not None:
            name = self._name + "_" + name
893 894 895 896
        if (
            name not in self._accumulators
            or param.name not in self._accumulators[name]
        ):
897 898
            raise Exception(
                "Accumulator {} does not exist for parameter {}".format(
899 900 901
                    name, param.name
                )
            )
M
MRXLT 已提交
902 903
        return self._accumulators[name][param.name]

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    def _get_accumulator_master(self, name, param):
        """Utility function to fetch an accumulator for a parameter
        Args:
            name: name of the accumulator
            param: parameter variable for which accumulator is to be fetched
        Returns:
            accumulator variable for the parameter
        """
        if self._name is not None:
            name = self._name + "_" + name
        find_master = self._multi_precision and self._is_dtype_fp16_or_bf16(
            param.dtype
        )
        target_param = (
            self._master_weights[param.name] if find_master else param
        )
        target_name = target_param.name
        if (
            name not in self._accumulators
            or target_name not in self._accumulators[name]
        ):
            raise Exception(
                "Accumulator {} does not exist for parameter {}".format(
                    name, target_name
                )
            )
        return self._accumulators[name][target_name]

M
MRXLT 已提交
932 933
    def _update_param_device_map(self, parameters_and_grads, target_block):
        for param_and_grad in parameters_and_grads:
934
            if param_and_grad[0].stop_gradient is False:
M
MRXLT 已提交
935 936
                param_name = param_and_grad[0].name
                ops = target_block.ops
937 938
                device_attr_name = (
                    core.op_proto_and_checker_maker.kOpDeviceAttrName()
M
MRXLT 已提交
939 940 941 942 943
                )
                for op in ops:
                    input_arg_names = op.input_arg_names
                    if param_name in input_arg_names:
                        self._param_device_map[param_name] = op.attr(
944 945
                            device_attr_name
                        )
M
MRXLT 已提交
946 947 948 949 950 951 952 953
                        break

    def _get_device_for_param(self, param_name):
        device = None
        if param_name in self._param_device_map:
            device = self._param_device_map[param_name]
        return device

954 955 956
    def _create_optimization_pass(
        self, parameters_and_grads, param_group_idx=0
    ):
M
MRXLT 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
        """Add optimization operators to update gradients to tensors.

        Args:
          parameters_and_grads(list(tuple(Tensor, Tensor))):
            a list of (tensor, gradient) pair to update.

        Returns:
          return_op_list: a list of operators that will complete one step of
            optimization. This will include parameter update ops, global step
            update ops and any other custom ops required by subclasses to manage
            their internal state.
        """
        # This is a default implementation of create_optimization_pass that
        # can be shared by most optimizers. This implementation assumes that
        # the subclass will implement the _append_optimize_op method and the
        #  _initialize_tensors method. The subclass can extend the
        # _create_accumulators method if it needs to create accumulators
        # for parameters and extend _finish_update method to add custom ops.

        # Allways called under program_guard use global block as loss block
        # But if current block is in control flow, append optimize op in the
        # grad block of current block

        global_block = framework.default_main_program().global_block()
        target_block = global_block
        current_block = framework.default_main_program().current_block()
        if current_block.idx != global_block.idx:
984 985 986
            assert (
                current_block.backward_block_idx != -1
            ), "current block is not global_block, but it doesn't have backward block."
M
MRXLT 已提交
987
            target_block = framework.default_main_program().blocks[
988 989
                current_block.backward_block_idx
            ]
M
MRXLT 已提交
990 991 992

        start = len(target_block.ops)
        self.helper = LayerHelper(self.__class__.__name__)
993

M
MRXLT 已提交
994 995
        self._create_global_learning_rate()

Z
zhangbo9674 已提交
996 997
        # NOTE: Multi Tensor support [ Momentum, Adam ] for dygraph mode
        if self._use_multi_tensor and self.__class__.__name__ in [
998 999
            'Momentum',
            'Adam',
Z
zhangbo9674 已提交
1000
        ]:
1001
            if (
1002 1003 1004
                len(self._param_dict['FP32_LODTensor'][param_group_idx]) == 0
                and len(self._param_dict['FP16_LODTensor'][param_group_idx])
                == 0
1005
            ):
1006
                if isinstance(parameters_and_grads, list):
1007
                    assert param_group_idx == 0
1008 1009 1010 1011 1012 1013 1014
                    self._multi_tensor_init(
                        target_block,
                        [
                            p[0]
                            for p in parameters_and_grads
                            if not p[0].stop_gradient
                        ],
1015
                        param_group_idx,
1016
                    )
1017 1018
                else:
                    self._update_param_group(parameters_and_grads)
1019 1020 1021 1022 1023 1024 1025
                    self._multi_tensor_init(
                        target_block,
                        [
                            p[0]
                            for p in parameters_and_grads['params']
                            if not p[0].stop_gradient
                        ],
1026
                        param_group_idx,
1027
                    )
1028
            if framework.in_dygraph_mode():
1029
                self._append_optimize_multi_tensor_op(
1030 1031 1032
                    target_block,
                    parameters_and_grads,
                    param_group_idx=param_group_idx,
1033
                )
1034
            else:
1035 1036 1037
                self._update_param_device_map(
                    parameters_and_grads, target_block
                )
1038 1039 1040
                # NOTE: Multi Tensor requires all parameters to be in the same device and program.
                # param_grad_list = [p_0,g_0,p_1,g_1,....]
                param_grad_list = []
1041
                for param_and_grad in parameters_and_grads:
1042 1043 1044 1045
                    if (
                        not param_and_grad[0].stop_gradient
                        and param_and_grad[1] is not None
                    ):
1046 1047 1048
                        param_grad_list.append(param_and_grad[0])
                        param_grad_list.append(param_and_grad[1])
                with param_grad_list[0].block.program._optimized_guard(
1049 1050
                    param_grad_list
                ), name_scope("optimizer"):
1051 1052 1053
                    device = self._get_device_for_param(param_grad_list[0].name)
                    with device_guard(device):
                        self._append_optimize_multi_tensor_op(
1054 1055 1056
                            target_block,
                            parameters_and_grads,
                            param_group_idx=param_group_idx,
1057
                        )
1058
        else:
1059
            if not framework.in_dygraph_mode():
1060 1061 1062 1063 1064 1065 1066 1067
                params_grads_device_map = (
                    parameters_and_grads['params']
                    if isinstance(parameters_and_grads, dict)
                    else parameters_and_grads
                )
                self._update_param_device_map(
                    params_grads_device_map, target_block
                )
1068

1069
            if isinstance(parameters_and_grads, list):
1070
                with paddle.base.framework.dygraph_guard_if_declarative():
1071 1072 1073 1074 1075 1076 1077 1078
                    self._create_accumulators(
                        target_block,
                        [
                            p[0]
                            for p in parameters_and_grads
                            if not p[0].stop_gradient
                        ],
                    )
1079
            else:
1080 1081
                params_acc_dict = parameters_and_grads.copy()
                params_acc_dict['params'] = [
1082 1083
                    p[0]
                    for p in params_acc_dict['params']
1084 1085
                    if not p[0].stop_gradient
                ]
1086
                with paddle.base.framework.dygraph_guard_if_declarative():
1087
                    self._create_accumulators(target_block, params_acc_dict)
1088

1089
            if framework.in_dygraph_mode():
W
wanghuancoder 已提交
1090 1091 1092 1093
                found_inf = self._get_auxiliary_var('found_inf')
                if found_inf:
                    if isinstance(found_inf, core.eager.Tensor):
                        self._set_auxiliary_var('found_inf', True)
1094
                else:
W
wanghuancoder 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
                    if isinstance(found_inf, core.eager.Tensor):
                        self._set_auxiliary_var('found_inf', False)
                    if isinstance(parameters_and_grads, list):
                        for param_and_grad in parameters_and_grads:
                            if param_and_grad[1] is None:
                                continue
                            if param_and_grad[0].stop_gradient is False:
                                self._append_optimize_op(
                                    target_block, param_and_grad
                                )
                    else:
                        for param_and_grad in parameters_and_grads['params']:
                            if param_and_grad[1] is None:
                                continue
                            if param_and_grad[0].stop_gradient is False:
1110
                                param_grad_dict = {}
W
wanghuancoder 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
                                param_grad_dict['params'] = param_and_grad
                                param_grad_dict.update(
                                    {
                                        k: v
                                        for k, v in parameters_and_grads.items()
                                        if k != 'params'
                                    }
                                )
                                self._append_optimize_op(
                                    target_block, param_grad_dict
                                )
1122 1123
            else:
                for param_and_grad in parameters_and_grads:
1124 1125
                    if param_and_grad[1] is None:
                        continue
1126
                    with param_and_grad[0].block.program._optimized_guard(
1127 1128
                        param_and_grad
                    ), name_scope("optimizer"):
1129
                        if param_and_grad[0].stop_gradient is False:
1130
                            device = self._get_device_for_param(
1131 1132
                                param_and_grad[0].name
                            )
1133 1134
                            with device_guard(device):
                                optimize_op = self._append_optimize_op(
1135 1136
                                    target_block, param_and_grad
                                )
M
MRXLT 已提交
1137 1138 1139 1140 1141 1142 1143 1144

        # Get custom finish ops for subclasses
        # FIXME: Need to fix this once we figure out how to handle dependencies
        self._finish_update(target_block, parameters_and_grads)

        end = len(target_block.ops)
        return target_block._slice_ops(start, end)

1145 1146 1147 1148 1149 1150 1151 1152
    def backward(
        self,
        loss,
        startup_program=None,
        parameters=None,
        no_grad_set=None,
        callbacks=None,
    ):
M
MRXLT 已提交
1153 1154 1155 1156 1157 1158
        """
        The first part of ``minimize``, do auto-diff to append backward operations for
        the current program.

        Args:
            loss (Tensor): ``loss`` tensor to run optimizations.
1159
            startup_program (Program, optional): :ref:`api_base_Program` for
M
MRXLT 已提交
1160
                initializing parameters in ``parameters``. The default value
1161
                is None, at this time :ref:`api_base_default_startup_program` will be used.
M
MRXLT 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
            parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update
                to minimize ``loss``. The default value is None, at this time all parameters
                will be updated.
            no_grad_set (set, optional): Set of ``Tensor``  or ``Tensor.name`` that don't need
                to be updated. The default value is None.
            callbacks (list, optional): list of callable objects to run when appending backward
                operator for one parameter. The default value is None.

        Return:
            list: list of (param, grad) tensor pairs, param is ``Parameter``,
                grad is the gradient value corresponding to the parameter.

        Examples:
            .. code-block:: python

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                >>> import paddle
                >>> x = paddle.arange(26, dtype="float32").reshape([2, 13])

                >>> linear = paddle.nn.Linear(13, 5)
                >>> # This can be any optimizer supported by dygraph.
                >>> adam = paddle.optimizer.Adam(learning_rate = 0.01,
                ...                             parameters = linear.parameters())
                >>> out = linear(x)
                >>> out.backward()
                >>> adam.step()
                >>> adam.clear_grad()
M
MRXLT 已提交
1188 1189
        """
        act_no_grad_set = None
1190
        if framework.in_dygraph_mode():
M
MRXLT 已提交
1191 1192 1193 1194
            pass
        else:
            act_no_grad_set = self._get_no_grad_set(loss, no_grad_set)

L
Leo Chen 已提交
1195 1196 1197 1198
        # Infer dtype by loss if None
        if self._dtype is None:
            self._dtype = loss.dtype

1199
        if framework.in_dygraph_mode():
1200
            parameter_list = parameters if parameters else self._parameter_list
1201

1202 1203 1204 1205 1206 1207 1208
            # It is very time-consuming to call c++ functions in a loop on the python side.
            # We put this part of the code on the c++ side to improve the speed in eager mode.
            params_grads = []
            grads = core.eager.get_all_grads(parameter_list)
            for index, grad in enumerate(grads):
                if grad is not None:
                    params_grads.append((parameter_list[index], grad))
M
MRXLT 已提交
1209 1210
        else:
            if callbacks is None:
1211
                callbacks = [paddle.nn.clip.error_clip_callback]
M
MRXLT 已提交
1212
            else:
1213
                assert isinstance(callbacks, list)
M
MRXLT 已提交
1214
            program = loss.block.program
zhouweiwei2014's avatar
zhouweiwei2014 已提交
1215 1216
            assert np.prod(loss.shape) == 1, (
                "The number of elements of loss should be 1, but the current loss.shape is {}, whose number of elements is not 1. "
M
MRXLT 已提交
1217
                "Maybe that you should call paddle.mean to process the current loss.".format(
1218 1219 1220 1221
                    loss.shape
                )
            )
            parameter_list = parameters if parameters else self._parameter_list
M
MRXLT 已提交
1222
            with program_guard(program, startup_program):
1223
                from paddle.incubate.autograd.utils import prim_enabled
1224

1225
                if prim_enabled():
1226 1227 1228
                    params_grads = append_backward_new(
                        [loss], parameter_list, act_no_grad_set, callbacks
                    )
1229
                else:
1230 1231 1232
                    params_grads = append_backward(
                        loss, parameter_list, act_no_grad_set, callbacks
                    )
M
MRXLT 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
        return params_grads

    def apply_gradients(self, params_grads):
        """
        Second part of `minimize`, appending optimization operators for
        given `params_grads` pairs.

        Args:
            params_grads (list): list of (param, grad) pair to do optimization.

        Returns:
            list: A list of operators appended to the current program.

        Examples:
            .. code-block:: python

1249
                >>> import paddle
M
MRXLT 已提交
1250

1251 1252 1253 1254 1255 1256 1257 1258
                >>> inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1)
                >>> linear = paddle.nn.Linear(10, 10)
                >>> out = linear(inp)
                >>> loss = paddle.mean(out)
                >>> optimizer = paddle.optimizer.Adam(learning_rate=0.1,
                ...         parameters=linear.parameters())
                >>> params_grads = optimizer.backward(loss)
                >>> optimizer.apply_gradients(params_grads)
M
MRXLT 已提交
1259 1260

        """
1261 1262 1263
        # NOTE(zhaoyinglia): AutoParallel set '_sorted' attribute to skip the 'sorted' operator.
        if not hasattr(self, "_sorted"):
            params_grads = sorted(params_grads, key=lambda x: x[0].name)
M
MRXLT 已提交
1264 1265 1266 1267 1268

        # 'optimizer(grad_clip)' or 'set_gradient_clip'
        if self._grad_clip is not None:
            params_grads = self._grad_clip(params_grads)
        else:
1269
            params_grads = paddle.nn.clip.append_gradient_clip_ops(params_grads)
M
MRXLT 已提交
1270 1271

        # Add regularization if any
1272 1273 1274
        params_grads = self.append_regularization_ops(
            params_grads, self.regularization
        )
M
MRXLT 已提交
1275 1276 1277 1278

        optimize_ops = self._create_optimization_pass(params_grads)
        return optimize_ops

1279 1280 1281
    def _apply_optimize(
        self, loss, startup_program, params_grads, param_group_idx=0
    ):
M
MRXLT 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
        """
        Second part of `minimize`, appending optimization operators for
        given `params_grads` pairs.
        Args:
            loss (Tensor): loss tensor to run optimizations.
            startup_program (Program): startup_program for initializing parameters
                in `parameters`.
            params_grads (list): list of (param, grad) pair to do optimization.
        Returns:
            list: A list of operators appended to the current program.
        """
1293
        if framework.in_dygraph_mode():
1294 1295 1296 1297
            with program_guard(
                framework.default_main_program(),
                framework.default_startup_program(),
            ):
1298 1299 1300
                if isinstance(params_grads, list):
                    if self._grad_clip is not None:
                        params_grads = self._grad_clip(params_grads)
1301
                    params_grads = self.append_regularization_ops(
1302 1303
                        params_grads, self.regularization
                    )
1304 1305 1306
                else:
                    grad_clip = params_grads['grad_clip']
                    if grad_clip is not None:
1307
                        params_grads['params'] = grad_clip(
1308 1309
                            params_grads['params']
                        )
1310

1311
                    params_grads['params'] = self.append_regularization_ops(
1312 1313
                        params_grads['params'], self.regularization
                    )
1314 1315 1316
                optimize_ops = self._create_optimization_pass(
                    params_grads, param_group_idx=param_group_idx
                )
M
MRXLT 已提交
1317
        else:
1318
            assert param_group_idx == 0
M
MRXLT 已提交
1319 1320 1321 1322 1323
            program = loss.block.program
            with program_guard(program, startup_program):
                optimize_ops = self.apply_gradients(params_grads)
        return optimize_ops

1324
    def _create_regularization_of_grad(self, param, grad, regularization=None):
1325
        """Create and add backward regularization Operators
1326

1327 1328 1329
        Function helper of append_regularization_ops.
        """
        # If no gradient or no regularization is specified,  then we don't need to do anything
1330
        if grad is None or (
1331 1332 1333 1334 1335 1336
            (
                not hasattr(param, 'regularizer')
                or (hasattr(param, 'regularizer') and param.regularizer is None)
            )
            and regularization is None
        ):
1337 1338
            return grad
        regularization_term = None
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

        # when master_grad is true in amp training, grad will be fp32, but param maybe fp16.
        # we get master weight when master_grad is true to avoid type mismatch error.
        def get_target_param(param, grad):
            target_param = param
            if param.dtype != grad.dtype:
                find_master = (
                    self._multi_precision
                    and self._is_dtype_fp16_or_bf16(param.dtype)
                )
                if find_master and len(self._master_weights) != 0:
                    target_param = self._master_weights[param.name]
                else:
                    target_param = param.astype(grad.dtype)
            return target_param

        param = get_target_param(param, grad)
1356 1357 1358 1359 1360 1361 1362 1363
        if hasattr(param, 'regularizer') and param.regularizer is not None:
            # Add variable for regularization term in grad block
            regularization_term = param.regularizer(param, grad, grad.block)
        elif regularization is not None:
            regularization_term = regularization(param, grad, grad.block)

        assert regularization_term is not None

1364
        if framework.in_dygraph_mode():
Y
YuanRisheng 已提交
1365
            return _C_ops.add_n([grad, regularization_term])
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        else:
            new_grad = grad
            if grad.type == core.VarDesc.VarType.SELECTED_ROWS:
                # FIXME(zcd): If the grad is SELECTED_ROWS, after regularization,
                # the grad's type and name will be changed. But the gradient's name
                # is used in ParallelExecutor Reduce mode, so I add a flag for
                # the new_grad here.
                new_grad = grad.block.create_var(
                    name=grad.name + core.kNewGradSuffix(),
                    dtype=param.dtype,
                    shape=param.shape,
                    lod_level=param.lod_level,
                    type=core.VarDesc.VarType.LOD_TENSOR,
                )
1380

1381 1382 1383
            inputs = {"X": [grad, regularization_term]}
            outputs = {"Out": [new_grad]}
            grad.block.append_op(type='sum', inputs=inputs, outputs=outputs)
1384

1385
            return new_grad
1386

1387 1388 1389
    def append_regularization_ops(
        self, parameters_and_grads, regularization=None
    ):
1390
        r"""Create and add backward regularization Operators
1391

1392 1393 1394 1395
        Creates and adds backward regularization operators in the BlockDesc.
        This will add gradients of the regularizer function to the gradients
        of the parameters and return these modified gradients. This is the
        same as implementing weight decay in optimizers for regularization.
1396

1397 1398 1399 1400 1401
        Args:
            parameters_and_grads: A list of (parameters, gradients) pairs
                                  that need to be regularized.
            regularization: A global regularizer. If the parameter is not
                            set. It will be applied with regularizer.
1402

1403 1404 1405
        Returns:
            list[(Variable, Variable)]: list of (parameters, gradients) \
            pair with the regularized gradient
1406

1407 1408 1409 1410
        Raises:
            Exception: Unknown regularization type
        """
        params_and_grads = []
1411
        if framework.in_dygraph_mode():
1412
            for param, grad in parameters_and_grads:
1413
                new_grad = self._create_regularization_of_grad(
1414 1415
                    param, grad, regularization
                )
1416 1417 1418 1419 1420
                params_and_grads.append((param, new_grad))
        else:
            repeate_regularizer = False
            with framework.name_scope('regularization'):
                for param, grad in parameters_and_grads:
1421 1422 1423 1424 1425
                    if (
                        not repeate_regularizer
                        and param.regularizer is not None
                        and regularization is not None
                    ):
1426 1427
                        repeate_regularizer = True
                        logging.info(
1428
                            "If regularizer of a Parameter has been set by 'base.ParamAttr' or 'base.WeightNormParamAttr' already. "
1429
                            "The Regularization[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!"
1430 1431
                            % regularization.__str__()
                        )
1432 1433
                    with param.block.program._optimized_guard([param, grad]):
                        new_grad = self._create_regularization_of_grad(
1434 1435
                            param, grad, regularization
                        )
1436 1437 1438
                        params_and_grads.append((param, new_grad))
        return params_and_grads

M
MRXLT 已提交
1439 1440 1441
    def _get_no_grad_set(self, loss, no_grad_set=None):
        no_grad_set = _get_no_grad_set_name(no_grad_set)
        parameters = loss.block.program.global_block().all_parameters()
1442 1443 1444
        param_no_trainable = {
            param.name for param in parameters if param.stop_gradient is True
        }
M
MRXLT 已提交
1445 1446 1447 1448 1449
        # If the parameter is no trainable, it should not have a gradient.
        no_grad_set.update(param_no_trainable)

        return no_grad_set

1450
    @framework.non_static_only
1451
    def clear_grad(self, set_to_zero=True):
M
MRXLT 已提交
1452 1453
        """
        Clear the gradients of all optimized parameters for model.
1454 1455

        If not, new gradient will accumulat on previous gradient.
1456 1457

        There are two method to clear grad: set_to_zero or delete grad.
1458

1459 1460
        Args:
            set_to_zero (bool, optional): If set grads to zero or not, default is True.
1461

M
MRXLT 已提交
1462 1463
        Returns:
            None
1464

M
MRXLT 已提交
1465 1466 1467
        Examples:
            .. code-block:: python

1468
                >>> import paddle
1469

1470 1471 1472 1473 1474 1475 1476 1477 1478
                >>> a = paddle.arange(26, dtype="float32").reshape([2, 13])
                >>> linear = paddle.nn.Linear(13, 5)
                >>> # This can be any optimizer supported by dygraph.
                >>> adam = paddle.optimizer.Adam(learning_rate = 0.01,
                ...                             parameters = linear.parameters())
                >>> out = linear(a)
                >>> out.backward()
                >>> adam.step()
                >>> adam.clear_grad()
M
MRXLT 已提交
1479 1480

        """
1481
        param_list = []
1482
        if self._parameter_list is None or not isinstance(
1483 1484
            self._parameter_list[0], dict
        ):
1485 1486
            for p in self._parameter_list:
                if not p.stop_gradient:
1487
                    param_list.append(p)
1488 1489 1490 1491
        else:
            for param_group in self._param_groups:
                for p in param_group['params']:
                    if not p.stop_gradient:
1492
                        param_list.append(p)
1493

1494 1495
        for p in param_list:
            p.clear_gradient(set_to_zero)
M
MRXLT 已提交
1496

1497
    @imperative_base.no_grad()
1498 1499 1500
    def minimize(
        self, loss, startup_program=None, parameters=None, no_grad_set=None
    ):
M
MRXLT 已提交
1501 1502 1503 1504 1505
        """
        Add operations to minimize ``loss`` by updating ``parameters``.

        Args:
            loss (Tensor): A ``Tensor`` containing the value to minimize.
1506
            startup_program (Program, optional): :ref:`api_base_Program` for
M
MRXLT 已提交
1507
                initializing parameters in ``parameters``. The default value
1508
                is None, at this time :ref:`api_base_default_startup_program` will be used.
M
MRXLT 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
            parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update
                to minimize ``loss``. The default value is None, at this time all parameters
                will be updated.
            no_grad_set (set, optional): Set of ``Tensor``  or ``Tensor.name`` that don't need
                to be updated. The default value is None.

        Returns:
            tuple: tuple (optimize_ops, params_grads), A list of operators appended
            by minimize and a list of (param, grad) tensor pairs, param is
            ``Parameter``, grad is the gradient value corresponding to the parameter.
1519 1520
            In static graph mode, the returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to
            indicate program pruning. If so, the program will be pruned by ``feed`` and
M
MRXLT 已提交
1521 1522 1523 1524
            ``fetch_list`` before run, see details in ``Executor``.

        Examples:
            .. code-block:: python
1525

1526 1527 1528 1529 1530
                >>> import paddle
                >>> linear = paddle.nn.Linear(10, 10)
                >>> input = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
                >>> out = linear(input)
                >>> loss = paddle.mean(out)
M
MRXLT 已提交
1531

1532 1533
                >>> beta1 = paddle.to_tensor([0.9], dtype="float32")
                >>> beta2 = paddle.to_tensor([0.99], dtype="float32")
M
MRXLT 已提交
1534

1535 1536 1537 1538 1539 1540
                >>> adam = paddle.optimizer.Adam(learning_rate=0.1,
                ...         parameters=linear.parameters(),
                ...         weight_decay=0.01)
                >>> loss.backward()
                >>> adam.minimize(loss)
                >>> adam.clear_grad()
M
MRXLT 已提交
1541

M
MRXLT 已提交
1542 1543 1544
        """
        assert isinstance(loss, Variable), "The loss should be an Tensor."

1545
        parameter_list = parameters if parameters else self._parameter_list
1546

1547 1548 1549 1550 1551 1552
        params_grads = self.backward(
            loss,
            startup_program=startup_program,
            parameters=parameter_list,
            no_grad_set=no_grad_set,
        )
M
MRXLT 已提交
1553

1554 1555 1556
        optimize_ops = self._apply_optimize(
            loss, startup_program=startup_program, params_grads=params_grads
        )
M
MRXLT 已提交
1557 1558 1559

        return optimize_ops, params_grads

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    def _declarative_step(self):
        """
        In declarative mode, we forward `call step` to `call apply_gradients`
        """
        params = (
            paddle.static.default_main_program().global_block().all_parameters()
        )
        assert not isinstance(
            self._parameter_list[0], dict
        ), "Only list of parameters is supported while using optimizer in @paddle.jit.static."
        selected_params = {param.name for param in self._parameter_list}
        parameters = [param for param in params if param.trainable]
        parameters = list(
            filter(
                lambda x: x.name in selected_params and hasattr(x, "grad"),
                parameters,
            )
        )
        params_grads = [(param, param.grad) for param in parameters]
        optimize_ops = self.apply_gradients(params_grads)
        return

1582
    @imperative_base.no_grad()
1583
    @framework.non_static_only
M
MRXLT 已提交
1584 1585
    def step(self):
        """
M
MRXLT 已提交
1586
        Execute the optimizer and update parameters once.
1587

M
MRXLT 已提交
1588 1589 1590 1591 1592 1593
        Returns:
            None

        Examples:
            .. code-block:: python

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
                >>> import paddle

                >>> a = paddle.arange(26, dtype="float32").reshape([2, 13])
                >>> linear = paddle.nn.Linear(13, 5)
                >>> # This can be any optimizer supported by dygraph.
                >>> adam = paddle.optimizer.Adam(learning_rate = 0.01,
                ...                         parameters = linear.parameters())
                >>> out = linear(a)
                >>> out.backward()
                >>> adam.step()
                >>> adam.clear_grad()
M
MRXLT 已提交
1605
        """
1606
        if paddle.base.dygraph.base.in_declarative_mode():
1607 1608
            self._declarative_step()
            return
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618

        if not isinstance(self._param_groups[0], dict):
            params_grads = []
            for param in self._param_groups:
                if param.stop_gradient:
                    continue
                if param._grad_ivar() is not None:
                    grad_var = param._grad_ivar()
                    params_grads.append((param, grad_var))

1619
            self._apply_optimize(
1620 1621 1622 1623
                loss=None,
                startup_program=None,
                params_grads=params_grads,
                param_group_idx=0,
1624
            )
1625 1626 1627

        else:
            # optimize parameters in groups
1628
            for idx, param_group in enumerate(self._param_groups):
1629
                params_grads = defaultdict(lambda: [])
1630 1631 1632 1633 1634 1635 1636
                for param in param_group['params']:
                    if param.stop_gradient:
                        continue
                    if param._grad_ivar() is not None:
                        grad_var = param._grad_ivar()
                        params_grads['params'].append((param, grad_var))
                params_grads.update(
1637 1638 1639
                    {k: v for k, v in param_group.items() if k != 'params'}
                )
                self._apply_optimize(
1640 1641 1642 1643
                    loss=None,
                    startup_program=None,
                    params_grads=params_grads,
                    param_group_idx=idx,
1644
                )
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659

    def _add_param_group(self, param_group):
        """
        Add a param group to parameter_list.

        Args:
            param_group (dict): The group of Tensors to be optimzed with
            different optimization options.
        """
        params = param_group['params']
        if isinstance(params, Parameter):
            param_group['params'] = [params]
        elif isinstance(params, set):
            raise TypeError(
                "optimizer parameters should be in ordered collections,"
1660 1661
                "but received set, please use list instead."
            )
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
        else:
            param_group['params'] = list(params)

        # Update optimization options for each groups
        for k, v in self._default_dict.items():
            param_group.setdefault(k, v)

        param_set = set()
        for group in self._param_groups:
            param_set.update(set(group['params']))

        if not param_set.isdisjoint(set(param_group['params'])):
            raise ValueError(
1675 1676
                "some parameters appear in more than one parameter group"
            )
1677 1678 1679 1680 1681 1682 1683 1684

        for param in param_group['params']:
            weight_decay = param_group['weight_decay']
            if isinstance(weight_decay, float):
                regularization = L2Decay(weight_decay)
            else:
                regularization = weight_decay
            param.regularizer = regularization
W
wangguanzhong 已提交
1685
            param.optimize_attr['learning_rate'] = param_group.get(
1686 1687
                'learning_rate', 1.0
            )
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698

        self._param_groups.append(param_group)

    def _update_param_group(self, parameters):
        """
        Update the param group with new entry
        Args:
            parameters (dict): The extra group of Tensors to be optimzed with
            different optimization options. Only used in child class.
        """
        pass
1699 1700

    @framework.dygraph_only
1701
    def _multi_tensor_init(self, target_block, parameters, param_group_idx):
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
        """
        All parameters used for optimizer (such as: parameters, master_weight, velocity_acc for momentum) calculations are grouped into a python list by data type (float16, float32).
        This function will be overridden in the corresponding optimizer file.

        Args:
            target_block: the block in which the loss tensor is present
            parameters: list of parameter tensors for the optimizer
        """
        pass

    @framework.dygraph_only
1713
    def _append_optimize_multi_tensor_op(
1714
        self, target_block, parameters_and_grads, param_group_idx
1715
    ):
1716
        """
1717 1718 1719
        For Multi Tensor, append optimize merged_operator to block.
        """
        pass
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733

    def _is_dtype_fp16_or_bf16(self, dtype):
        """
        check the dtype is fp16 or the dtype is bf16
        :param dtype: instance of core.VarDesc.VarType
        :return: True if dtype is one of fp16 or bf16, False otherwise
        """
        assert isinstance(
            dtype, core.VarDesc.VarType
        ), "The dtype should be an instance of core.VarDesc.VarType."
        return (
            dtype == core.VarDesc.VarType.FP16
            or dtype == core.VarDesc.VarType.BF16
        )