# RMSProp¶

class paddle.optimizer. RMSProp ( learning_rate, rho=0.95, epsilon=1e-06, momentum=0.0, centered=False, parameters=None, weight_decay=None, grad_clip=None, name=None ) [source]

Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning rate method. The original slides proposed RMSProp: Slide 29 of http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf .

The original equation is as follows:

\begin{align}\begin{aligned}\begin{split}r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2\end{split}\\\begin{split}w & = w - \\frac{\\eta} {\\sqrt{r(w,t) + \\epsilon}} \\nabla Q_{i}(w)\end{split}\end{aligned}\end{align}

The first equation calculates moving average of the squared gradient for each weight. Then dividing the gradient by $$sqrt{v(w,t)}$$.

In some cases, adding a momentum term :math: \beta is beneficial. In our implementation, Nesterov momentum is used:

\begin{align}\begin{aligned}\begin{split}r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2\end{split}\\\begin{split}v(w, t) & = \\beta v(w, t-1) + \\frac{\\eta} {\\sqrt{r(w,t) + \\epsilon}} \\nabla Q_{i}(w)\end{split}\\w & = w - v(w, t)\end{aligned}\end{align}

if centered is True:

\begin{align}\begin{aligned}\begin{split}r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2\end{split}\\\begin{split}g(w, t) & = \\rho g(w, t-1) + (1 - \\rho)\\nabla Q_{i}(w)\end{split}\\\begin{split}v(w, t) & = \\beta v(w, t-1) + \\frac{\\eta} {\\sqrt{r(w,t) - (g(w, t))^2 + \\epsilon}} \\nabla Q_{i}(w)\end{split}\\w & = w - v(w, t)\end{aligned}\end{align}

where, $$\\rho$$ is a hyperparameter and typical values are 0.9, 0.95 and so on. :math: beta is the momentum term. :math: \epsilon is a smoothing term to avoid division by zero, usually set somewhere in range from 1e-4 to 1e-8.

Parameters
• learning_rate (float|LRScheduler) – The learning rate used to update Parameter. It can be a float value or a LRScheduler.

• rho (float) – rho is :math: \rho in equation, default is 0.95.

• epsilon (float) –

math

\epsilon in equation is smoothing term to

System Message: WARNING/2 (/usr/local/lib/python3.8/site-packages/paddle/optimizer/rmsprop.py:docstring of paddle.optimizer.rmsprop.RMSProp, line 53)

Field list ends without a blank line; unexpected unindent.

avoid division by zero, default is 1e-6.

• momentum (float) – $$\\beta$$ in equation is the momentum term, default is 0.0.

• centered (bool) – If True, gradients are normalized by the estimated variance of the gradient; if False, by the uncentered second moment. Setting this to True may help with training, but is slightly more expensive in terms of computation and memory. Defaults to False.

• parameters (list, optional) – List of Tensor to update to minimize loss. This parameter is required in dygraph mode. The default value is None in static mode, at this time all parameters will be updated.

• weight_decay (float|WeightDecayRegularizer, optional) – The strategy of regularization. It canbe a float value as coeff of L2 regularization or api_fluid_regularizer_L1Decay, api_fluid_regularizer_L2Decay. If a parameter has set regularizer using api_fluid_ParamAttr already, 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 ( api_fluid_clip_GradientClipByGlobalNorm , api_fluid_clip_GradientClipByNorm , api_fluid_clip_GradientClipByValue ). Default None, meaning there is no gradient clipping.

• name (str, optional) – This parameter is used by developers to print debugging information. For details, please refer to Name. Default is None.

Raises

ValueError – If learning_rate, rho, epsilon, momentum are None.

Examples

import paddle

inp = paddle.rand([10,10], dtype="float32")
linear = paddle.nn.Linear(10, 10)
out = linear(inp)
loss = paddle.mean(out)

rmsprop = paddle.optimizer.RMSProp(learning_rate=0.1,
parameters=linear.parameters(),
weight_decay=0.01)
out.backward()
rmsprop.step()
rmsprop.clear_grad()

clear_grad ( )

Clear the gradients of all optimized parameters for model.

If not, new gradient will accumulat on previous gradient.

Returns

None

Examples

import numpy as np
import paddle

value = np.arange(26).reshape(2, 13).astype("float32")
a = paddle.to_tensor(value)
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()

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

## 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()

# 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{}: {}", 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()

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) – api_fluid_Program for initializing parameters in parameters. The default value is None, at this time api_fluid_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
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)

beta1 = paddle.to_tensor([0.9], dtype="float32")
beta2 = paddle.to_tensor([0.99], dtype="float32")

adam = paddle.optimizer.Adam(learning_rate=0.1,
parameters=linear.parameters(),
weight_decay=0.01)
out.backward()
adam.minimize(loss)
adam.clear_grad()

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
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))
# Print:
#    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_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

emb = paddle.nn.Embedding(10, 10)

layer_state_dict = emb.state_dict()
paddle.save(layer_state_dict, "emb.pdparams")

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

opti_state_dict = paddle.load("adam.pdopt")
adam.set_state_dict(opti_state_dict)

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
emb = paddle.nn.Embedding(10, 10)

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

step ( )

Execute the optimizer and update parameters once.

Returns

None

Examples

import paddle
import numpy as np

value = np.arange(26).reshape(2, 13).astype("float32")
a = paddle.to_tensor(value)
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()