oneflow.optim.SGD¶
-
class
oneflow.optim.SGD(params: Union[Iterator[oneflow.nn.Parameter], List[Dict]], lr: float = 0.001, momentum: float = 0.0, dampening: float = 0.0, weight_decay: float = 0.0, nesterov: bool = False, maximize: bool = False, contiguous_params: bool = False, fused: bool = False)¶ Implements SGD algorithm.
This algorithm takes a random sample’s gradient as an approximate estimate of the overall gradient in small batch gradient descent.
When the momentum = 0, the equation of parameters updating is:
\[param_{new} = param_{old} - learning\_rate * grad\]With momentum, the equation of parameters updating is:
\[ \begin{align}\begin{aligned}& V_t = \beta * V_{t-1} - learning\_rate * (g_t + param_{old} * weight\_decay)\\& param_{new} = param_{old} + V_t\end{aligned}\end{align} \]- Parameters
params (iterable) – iterable of parameters to optimize or dicts defining parameter groups
lr (float, optional) – learning rate (default: 1e-3)
momentum (float, optional) – Momentum factor (default: 0.0)
weight_decay (float, optional) – weight decay (L2 penalty) (default: 0.0)
contiguous_params (bool, optional) – whether to use contiguous ParamGroup which puts all parameters of the same type, device and group into the same tensor and update them together. (default: False)
fused (bool, optional) – whether to divide all the parameters into several groups, then update each group of parameters with the fused kernel. (default: False)
For example:
Example 1:
# Assume net is a custom model. sgd = flow.optim.SGD(net.parameters(), lr=1e-3) for epoch in range(epochs): # Read data, Compute the loss and so on. # ... loss.backward() sgd.step() sgd.zero_grad()
Example 2:
# Assume net is a custom model. sgd = flow.optim.SGD( [ { "params": net.parameters(), "lr": learning_rate, "clip_grad_max_norm": 0.5, "clip_grad_norm_type": 2.0, } ], ) for epoch in range(epochs): # Read data, Compute the loss and so on. # ... loss.backward() sgd.clip_grad() sgd.step() sgd.zero_grad()
If you want to use clip_grad, you can refer this example.
For more details of clip_grad_max_norm and clip_grad_norm_type, you can refer to
oneflow.nn.utils.clip_grad_norm_().-
__init__(params: Union[Iterator[oneflow.nn.Parameter], List[Dict]], lr: float = 0.001, momentum: float = 0.0, dampening: float = 0.0, weight_decay: float = 0.0, nesterov: bool = False, maximize: bool = False, contiguous_params: bool = False, fused: bool = False)¶ Initialize self. See help(type(self)) for accurate signature.
Methods
__delattr__(name, /)Implement delattr(self, name).
__dir__()Default dir() implementation.
__eq__(value, /)Return self==value.
__format__(format_spec, /)Default object formatter.
__ge__(value, /)Return self>=value.
__getattribute__(name, /)Return getattr(self, name).
__gt__(value, /)Return self>value.
__hash__()Return hash(self).
__init__(params[, lr, momentum, dampening, …])Initialize self.
__init_subclass__This method is called when a class is subclassed.
__le__(value, /)Return self<=value.
__lt__(value, /)Return self<value.
__ne__(value, /)Return self!=value.
__new__(**kwargs)Create and return a new object.
__reduce__()Helper for pickle.
__reduce_ex__(protocol, /)Helper for pickle.
__repr__()Return repr(self).
__setattr__(name, value, /)Implement setattr(self, name, value).
__sizeof__()Size of object in memory, in bytes.
__str__()Return str(self).
__subclasshook__Abstract classes can override this to customize issubclass().
_check_variables_in_graph(vars_conf)_check_variables_optimizer_bound(vars_conf)_fused_update(param_group)_generate_conf_for_graph(train_conf, vars_conf)_generate_grad_clip_conf_for_optim_conf(…)_generate_indexed_slices_optimizer_conf(…)_generate_lr_scale_for_optim_conf(…)_parse_input_parameters(parameters)Supports such parameters:
_single_tensor_update(param_group)add_param_group(param_group)Add a param group to the
Optimizers param_groups.clip_grad([error_if_nonfinite])Clips gradient norm of an iterable of parameters.
load_state_dict(state_dict)Load the state of the optimizer which is created by state_dict function.
state_dict()Returns the state of the optimizer as a
dict.step([closure])Performs a single optimization step. :param closure: A closure that reevaluates the model and returns the loss. :type closure: callable, optional.
zero_grad([set_to_none])Sets the gradients of all optimized
oneflow.Tensors to zero.Attributes
support_sparseWhether SGD Optimizer support sparse update.