# Lamb¶

class paddle.optimizer. Lamb ( learning_rate=0.001, lamb_weight_decay=0.01, beta1=0.9, beta2=0.999, epsilon=1e-06, parameters=None, grad_clip=None, exclude_from_weight_decay_fn=None, name=None ) [source]

LAMB (Layer-wise Adaptive Moments optimizer for Batching training) Optimizer.

LAMB Optimizer is designed to scale up the batch size of training without losing accuracy, which supports adaptive element-wise updating and accurate layer-wise correction. For more information, please refer to Large Batch Optimization for Deep Learning: Training BERT in 76 minutes .

The updating of parameters follows:

\begin{align}\begin{aligned}\begin{split}m_t &= \\beta_1 m_{t - 1}+ (1 - \\beta_1)g_t\end{split}\\\begin{split}v_t &= \\beta_2 v_{t - 1} + (1 - \\beta_2)g_t^2\end{split}\\\begin{split}m_t &= \\frac{m_t}{1 - \\beta_1^t}\end{split}\\\begin{split}v_t &= \\frac{v_t}{1 - \\beta_2^t}\end{split}\\\begin{split}r_t &= \\frac{m_t}{\\sqrt{v_t}+\\epsilon}\end{split}\\\begin{split}w_t &= w_{t-1} -\\eta_t \\frac{\\left \| w_{t-1}\\right \|}{\\left \| r_t + \\lambda w_{t-1}\\right \|} (r_t + \\lambda w_{t-1})\end{split}\end{aligned}\end{align}

where $$m$$ is the 1st moment, and $$v$$ the 2nd moment, $$\\eta$$ the learning rate, $$\\lambda$$ the LAMB weight decay rate.

Parameters
• learning_rate (float|Variable, optional) – the learning rate used to update parameters. Can be a float value or a Variable with data type float32. Default 0.001.

• lamb_weight_decay (float, optional) – The LAMB weight decay rate. Default 0.01. Remind that weight_decay should be None.

• beta1 (float, optional) – The exponential decay rate for the 1st moment estimates. Default 0.9.

• beta2 (float, optional) – The exponential decay rate for the 2nd moment estimates. Default 0.999.

• epsilon (float, optional) – A small float value for numerical stability. Default 1e-6.

• parameters (Iterable, optional) – Iterable of Variable names 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.

• grad_clip (GradientClipBase, optional) – Gradient cliping strategy, it’s an instance of some derived class of GradientClipBase . There are three cliping strategies ( ClipGradByGlobalNorm , ClipGradByNorm , ClipGradByValue ). If you want better convergence, it is recommended to use ClipGradByGlobalNorm . Default None, meaning there is no gradient clipping.

• exclude_from_weight_decay_fn (function|None) – Exclude a parameter from weight decay when exclude_from_weight_decay_fn(parameter) returns true. Default None.

• name (str|None) – For detailed information, please refer to Name . Usually name is no need to set and None by default.

Examples

import paddle
import numpy as np
inp = paddle.uniform(min=-0.1, max=0.1, shape=[10, 10], dtype='float32')
out = linear(inp)
back = out.backward()
lamb.step()

clear_grad ( )

Clear the gradients of all optimized parameters for model.

Returns

None

Examples

import numpy as np

value = np.arange(26).reshape(2, 13).astype("float32")
# 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):
out = emb(input)
out.backward()
print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.01

## example2: StepDecay is used, return the scheduled learning rate
for batch in range(10):
out = emb(input)
out.backward()
print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05...
scheduler.step()

# train on static graph mode

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
input = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
out = linear(input)

parameters=linear.parameters(),
weight_decay=0.01)
out.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))
# 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

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
import numpy as np

value = np.arange(26).reshape(2, 13).astype("float32")
# This can be any optimizer supported by dygraph.
parameters = linear.parameters())
out = linear(a)
out.backward()