mirror of
https://github.com/pytorch/pytorch.git
synced 2025-10-21 05:34:18 +08:00
Summary: I've written custom parsers and emitters for everything from docstrings to classes and functions. However, I recently came across an issue when I was parsing/generating from the TensorFlow codebase: inconsistent use of `Args:` and `Arguments:` in its docstrings. ```sh (pytorch#c348fae)$ for name in 'Args:' 'Arguments:'; do printf '%-10s %04d\n' "$name" "$(rg -IFtpy --count-matches "$name" | paste -s -d+ -- | bc)"; done Args: 1095 Arguments: 0336 ``` It is easy enough to extend my parsers to support both variants, however it looks like `Arguments:` is wrong anyway, as per: - https://google.github.io/styleguide/pyguide.html#doc-function-args @ [`ddccc0f`](https://github.com/google/styleguide/blob/ddccc0f/pyguide.md) - https://chromium.googlesource.com/chromiumos/docs/+/master/styleguide/python.md#describing-arguments-in-docstrings @ [`9fc0fc0`](https://chromium.googlesource.com/chromiumos/docs/+/9fc0fc0/styleguide/python.md) - https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html @ [`c0ae8e3`](https://github.com/sphinx-contrib/napoleon/blob/c0ae8e3/docs/source/example_google.rst) Therefore, only `Args:` is valid. This PR replaces them throughout the codebase. PS: For related PRs, see tensorflow/tensorflow/pull/45420 PPS: The trackbacks automatically appearing below are sending the same changes to other repositories in the [PyTorch](https://github.com/pytorch) organisation. Pull Request resolved: https://github.com/pytorch/pytorch/pull/49736 Reviewed By: albanD Differential Revision: D25710534 Pulled By: soumith fbshipit-source-id: 61e8ff01abb433e9f78185c2d1d0cbd7c22c1619
129 lines
5.0 KiB
Python
129 lines
5.0 KiB
Python
import torch
|
|
from ..optimizer import Optimizer
|
|
from collections import defaultdict
|
|
|
|
class Adamax(Optimizer):
|
|
"""Implements Adamax algorithm (a variant of Adam based on infinity norm).
|
|
|
|
It has been proposed in `Adam: A Method for Stochastic Optimization`__.
|
|
|
|
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
|
|
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)
|
|
|
|
__ https://arxiv.org/abs/1412.6980
|
|
"""
|
|
|
|
def __init__(self, params, lr=2e-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(Adamax, 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:
|
|
grads = []
|
|
params_with_grad = []
|
|
states = []
|
|
exp_avgs = []
|
|
exp_infs = []
|
|
|
|
beta1, beta2 = group['betas']
|
|
eps = group['eps']
|
|
|
|
for p in group['params']:
|
|
if p.grad is not None:
|
|
if p.grad.is_sparse:
|
|
raise RuntimeError('Adamax does not support sparse gradients')
|
|
|
|
grads.append(p.grad)
|
|
params_with_grad.append(p)
|
|
|
|
state = self.state[p]
|
|
|
|
# State initialization
|
|
if len(state) == 0:
|
|
state['step'] = 0
|
|
state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
state['exp_inf'] = torch.zeros_like(p, memory_format=torch.preserve_format)
|
|
|
|
exp_avgs.append(state['exp_avg'])
|
|
exp_infs.append(state['exp_inf'])
|
|
|
|
state['step'] += 1
|
|
states.append(state)
|
|
|
|
if group['weight_decay'] != 0:
|
|
torch._foreach_add_(grads, params_with_grad, alpha=group['weight_decay'])
|
|
|
|
# Update biased first moment estimate.
|
|
torch._foreach_mul_(exp_avgs, beta1)
|
|
torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1)
|
|
|
|
# Update the exponentially weighted infinity norm.
|
|
torch._foreach_mul_(exp_infs, beta2)
|
|
|
|
for exp_inf, grad in zip(exp_infs, grads):
|
|
norm_buf = torch.cat([
|
|
exp_inf.unsqueeze(0),
|
|
grad.abs().add_(eps).unsqueeze_(0)
|
|
], 0)
|
|
torch.max(norm_buf, 0, keepdim=False, out=(exp_inf, exp_inf.new().long()))
|
|
|
|
bias_corrections = [1 - beta1 ** state['step'] for state in states]
|
|
clr = [-1 * (group['lr'] / bias_correction) for bias_correction in bias_corrections]
|
|
torch._foreach_addcdiv_(params_with_grad, exp_avgs, exp_infs, clr)
|
|
|
|
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)
|