\begin{split}\begin{aligned} &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\ &\hspace{5mm} \mu_t \leftarrow \beta_1 \big(1 - \frac{1}{2} \rho ^{t \psi} \big) \\ &\hspace{5mm} \mu_{t+1} \leftarrow \beta_1 \big(1 - \frac{1}{2} 0.96 ^{(t+1)\psi}\big)\\ &\hspace{5mm}m_t \leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t \\ &\hspace{5mm}v_t \leftarrow \beta_2 v_{t-1} + (1-\beta_2) g^2_t \\ &\hspace{5mm}\widehat{m_t} \leftarrow \mu_{t+1} m_t/(1-\prod_{i=1}^{t+1}\mu_i) + (1-\mu_t) g_t /(1-\prod_{i=1}^{t} \mu_{i}) \\ &\hspace{5mm}\widehat{v_t} \leftarrow v_t/\big(1-\beta_2^t \big) \\ &\hspace{5mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t}/ \big(\sqrt{\widehat{v_t}} + \epsilon \big) \\ &\hspace{0mm} \text{ with: } \gamma_t \text{ (lr)}, \: \beta_1,\beta_2 \text{ (betas)}, \: \theta_0 \text{ (params)}, \: f(\theta) \text{ (objective)} \\ &\hspace{0mm} \: \lambda \text{ (weight decay)}, \:\psi \text{ (momentum decay)} \\ \end{aligned}\end{split}
Parameters
• learning_rate (float|LRScheduler, optional) – The learning rate used to update Parameter. It can be a float value or a LRScheduler. The default value is 0.002.

• parameters (list|tuple, optional) – List/Tuple of Tensor names to update to minimize loss. 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 parameter groups represents the scale of base learning_rate. The default value is None in static graph mode, at this time all parameters will be updated.

• beta1 (float|Tensor, optional) – The exponential decay rate for the 1st moment estimates. It should be a float number or a 0-D Tensor with shape [] and data type as float32. The default value is 0.9.

• beta2 (float|Tensor, optional) – The exponential decay rate for the 2nd moment estimates. It should be a float number or a 0-D Tensor with shape [] and data type as float32. The default value is 0.999.

• epsilon (float, optional) – A small float value for numerical stability. The default value is 1e-08.

• weight_decay (float|Tensor, optional) – The weight decay coefficient, it can be float or Tensor. Default None, meaning there is no regularization.

• momentum_decay (float, optional) – momentum momentum_decay. The default value is 0.004.

• grad_clip (GradientClipBase, optional) – Gradient clipping strategy, it’s an instance of some derived class of GradientClipBase . There are three clipping strategies ( ClipGradByGlobalNorm , ClipGradByNorm , ClipGradByValue ). Default None, meaning there is no gradient clipping.

• name (str, optional) – Normally there is no need for user to set this property. For more information, please refer to Name. The default value is None.

Notes

Currently, NAdam doesn’t support sparse parameter optimization.

Examples

>>> import paddle

>>> out = linear(inp)

...                     parameters=linear.parameters())
>>> out.backward()

>>> # Note that the learning_rate of linear_2 is 0.01.
>>> inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
>>> out = linear_1(inp)
>>> out = linear_2(out)
...     learning_rate=0.1,
...     parameters=[{
...         'params': linear_1.parameters()
...     }, {
...         'params': linear_2.parameters(),
...         'weight_decay': 0.001,
...         'learning_rate': 0.1,
...         'beta1': 0.8
...     }],
...     weight_decay=0.01,
...     beta1=0.9
... )
>>> loss.backward()
>>> opt.step()


Create and add backward regularization Operators

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.

Parameters
• 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.

Returns

Return type

list[(Variable, Variable)]

Raises

Exception – Unknown regularization type

Clear the gradients of all optimized parameters for model.

Parameters

set_to_zero (bool, optional) – If set grads to zero or not, default is True.

Returns

None

Examples

>>> import paddle

>>> a = paddle.arange(26, dtype="float32").reshape([2, 13])
>>> # This can be any optimizer supported by dygraph.
...                             parameters = linear.parameters())
>>> out = linear(a)
>>> out.backward()

get_lr ( )

Get current learning rate of optimizer. 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.

Returns

The current learning rate of optimizer.

Return type

float

Examples

>>> # train on default dynamic graph mode
>>> import numpy as np

>>> ## example1: LRScheduler is not used, return the same value is all the same
>>> 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
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)
>>> 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...
...     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
...     x = paddle.static.data(name='x', shape=[None, 10])
...     scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1)

>>> 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

minimize ( loss, startup_program=None, parameters=None, no_grad_set=None )

Add operations to minimize loss by updating parameters.

Parameters
• loss (Tensor) – A Tensor containing the value to minimize.

• startup_program (Program, optional) – Program for initializing parameters in parameters. The default value is None, at this time default_startup_program will be used.

• 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 (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. 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 fetch_list before run, see details in Executor.

Return type

tuple

Examples

>>> import paddle
>>> input = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
>>> out = linear(input)

...         parameters=linear.parameters(),
...         weight_decay=0.01)
>>> loss.backward()

set_lr ( value )
Api_attr

imperative

Set the value of the learning rate manually in the optimizer. If the optimizer use LRScheduler, this API cannot be invoked, because it will lead to conflict.

Parameters

value (float) – the value of learning rate

Returns

None

Examples

>>> import paddle

>>> # 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):
...     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

set_lr_scheduler ( 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.

Parameters

scheduler (LRScheduler) – the LRScheduler of learning rate

Returns

None

Examples

>>> import paddle

>>> # set learning rate manually by class LRScheduler
>>> scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2,4,6], gamma=0.8)
>>> print("current lr is {}".format(lr))
current lr is 0.5

>>> # set learning rate manually by another LRScheduler
>>> scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.1, step_size=5, gamma=0.6)
>>> print("current lr is {}".format(lr))
current lr is 0.1

set_state_dict ( state_dict )

Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be changed.

Parameters

state_dict (dict) – Dict contains all the Tensor needed by optimizer

Returns

None

Examples

>>> import paddle

>>> layer_state_dict = emb.state_dict()

...     d_model=0.01, warmup_steps=100, verbose=True)
...     learning_rate=scheduler,
...     parameters=emb.parameters())


state_dict ( )

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. If the optimizer never be called(minimize function), the state_dict is empty.

Parameters

None

Returns

dict contains all the Tensor used by optimizer

Return type

state_dict(dict)

Examples

>>> import paddle


step ( )

Execute the optimizer and update parameters once.

Returns

None

Examples

>>> import paddle

>>> a = paddle.arange(26, dtype="float32").reshape([2, 13])