mirror of
https://github.com/pytorch/pytorch.git
synced 2025-10-21 05:34:18 +08:00
Summary: Previously in the PR: https://github.com/pytorch/pytorch/issues/58968 we added RAdam to Optimizers. Here in this PR we are proposing multi-tensor version of RAdam for PyTorch. Radam has been proposed in the paper https://arxiv.org/pdf/1908.03265.pdf Liyuan Liu et al. It has been one of the most used algorithm in Deep Learning community. Differing from the paper, we selected variance tractability cut-off as 5 instead of 4 as it is the common practice. Pull Request resolved: https://github.com/pytorch/pytorch/pull/59161 Reviewed By: vincentqb Differential Revision: D29360576 Pulled By: iramazanli fbshipit-source-id: 7ccdbf12b1ee7f12e66f7d7992123a70cc818b6b
120 lines
4.6 KiB
Python
120 lines
4.6 KiB
Python
import torch
|
|
from . import _functional as F
|
|
from ..optimizer import Optimizer
|
|
from collections import defaultdict
|
|
|
|
class RAdam(Optimizer):
|
|
r"""Implements RAdam algorithm with multi tensor APIs.
|
|
|
|
It has been proposed in `On the variance of the adaptive learning rate and beyond`_.
|
|
|
|
Args:
|
|
params (iterable): iterable of parameters to optimize or dicts defining
|
|
parameter groups
|
|
lr (float, optional): learning rate (default: 2e-3)
|
|
betas (Tuple[float, float], optional): coefficients used for computing
|
|
running averages of gradient and its square (default: (0.9, 0.999))
|
|
eps (float, optional): term added to the denominator to improve
|
|
numerical stability (default: 1e-8)
|
|
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
|
|
|
|
.. _On the variance of the adaptive learning rate and beyond:
|
|
https://arxiv.org/pdf/1908.03265.pdf
|
|
"""
|
|
|
|
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,
|
|
weight_decay=0):
|
|
if not 0.0 <= lr:
|
|
raise ValueError("Invalid learning rate: {}".format(lr))
|
|
if not 0.0 <= eps:
|
|
raise ValueError("Invalid epsilon value: {}".format(eps))
|
|
if not 0.0 <= betas[0] < 1.0:
|
|
raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
|
|
if not 0.0 <= betas[1] < 1.0:
|
|
raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
|
|
if not 0.0 <= weight_decay:
|
|
raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
|
|
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
|
|
super(RAdam, self).__init__(params, defaults)
|
|
|
|
@torch.no_grad()
|
|
def step(self, closure=None):
|
|
"""Performs a single optimization step.
|
|
|
|
Args:
|
|
closure (callable, optional): A closure that reevaluates the model
|
|
and returns the loss.
|
|
"""
|
|
loss = None
|
|
if closure is not None:
|
|
with torch.enable_grad():
|
|
loss = closure()
|
|
|
|
for group in self.param_groups:
|
|
params_with_grad = []
|
|
grads = []
|
|
exp_avg = []
|
|
exp_avg_sq = []
|
|
states = []
|
|
beta1, beta2 = group['betas']
|
|
|
|
for p in group['params']:
|
|
if p.grad is not None:
|
|
if p.grad.is_sparse:
|
|
raise RuntimeError('RAdam does not support sparse gradients')
|
|
params_with_grad.append(p)
|
|
grads.append(p.grad)
|
|
|
|
for p in params_with_grad:
|
|
state = self.state[p]
|
|
|
|
# State initialization
|
|
if len(state) == 0:
|
|
state['step'] = 0
|
|
# Exponential moving average of gradient values
|
|
state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
# Exponential moving average of squared gradient values
|
|
state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
|
|
exp_avg.append(state['exp_avg'])
|
|
exp_avg_sq.append(state['exp_avg_sq'])
|
|
|
|
state['step'] += 1
|
|
states.append(state)
|
|
|
|
F.radam(params_with_grad,
|
|
grads,
|
|
exp_avg,
|
|
exp_avg_sq,
|
|
states,
|
|
beta1=beta1,
|
|
beta2=beta2,
|
|
lr=group['lr'],
|
|
weight_decay=group['weight_decay'],
|
|
eps=group['eps'])
|
|
|
|
return loss
|
|
|
|
# TODO: refactor to a base class once foreach ops are in a good shape.
|
|
def zero_grad(self, set_to_none: bool = False):
|
|
per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list))
|
|
for group in self.param_groups:
|
|
for p in group['params']:
|
|
if p.grad is not None:
|
|
if set_to_none:
|
|
p.grad = None
|
|
else:
|
|
if p.grad.grad_fn is not None:
|
|
p.grad.detach_()
|
|
else:
|
|
p.grad.requires_grad_(False)
|
|
|
|
if p.grad.is_sparse:
|
|
p.grad.zero_()
|
|
else:
|
|
per_device_and_dtype_grads[p.grad.device][p.grad.dtype].append(p.grad)
|
|
|
|
for _, per_dtype_grads in per_device_and_dtype_grads.items():
|
|
for grads in per_dtype_grads.values():
|
|
torch._foreach_zero_(grads)
|