|
| 1 | +""" |
| 2 | +AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py |
| 3 | +
|
| 4 | +Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 |
| 5 | +Code: https://github.com/clovaai/AdamP |
| 6 | +
|
| 7 | +Copyright (c) 2020-present NAVER Corp. |
| 8 | +MIT license |
| 9 | +""" |
| 10 | + |
| 11 | +import torch |
| 12 | +import torch.nn as nn |
| 13 | +from torch.optim.optimizer import Optimizer, required |
| 14 | +import math |
| 15 | + |
| 16 | +class AdamP(Optimizer): |
| 17 | + def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, |
| 18 | + weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False): |
| 19 | + defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, |
| 20 | + delta=delta, wd_ratio=wd_ratio, nesterov=nesterov) |
| 21 | + super(AdamP, self).__init__(params, defaults) |
| 22 | + |
| 23 | + def _channel_view(self, x): |
| 24 | + return x.view(x.size(0), -1) |
| 25 | + |
| 26 | + def _layer_view(self, x): |
| 27 | + return x.view(1, -1) |
| 28 | + |
| 29 | + def _cosine_similarity(self, x, y, eps, view_func): |
| 30 | + x = view_func(x) |
| 31 | + y = view_func(y) |
| 32 | + |
| 33 | + x_norm = x.norm(dim=1).add_(eps) |
| 34 | + y_norm = y.norm(dim=1).add_(eps) |
| 35 | + dot = (x * y).sum(dim=1) |
| 36 | + |
| 37 | + return dot.abs() / x_norm / y_norm |
| 38 | + |
| 39 | + def _projection(self, p, grad, perturb, delta, wd_ratio, eps): |
| 40 | + wd = 1 |
| 41 | + expand_size = [-1] + [1] * (len(p.shape) - 1) |
| 42 | + for view_func in [self._channel_view, self._layer_view]: |
| 43 | + |
| 44 | + cosine_sim = self._cosine_similarity(grad, p.data, eps, view_func) |
| 45 | + |
| 46 | + if cosine_sim.max() < delta / math.sqrt(view_func(p.data).size(1)): |
| 47 | + p_n = p.data / view_func(p.data).norm(dim=1).view(expand_size).add_(eps) |
| 48 | + perturb -= p_n * view_func(p_n * perturb).sum(dim=1).view(expand_size) |
| 49 | + wd = wd_ratio |
| 50 | + |
| 51 | + return perturb, wd |
| 52 | + |
| 53 | + return perturb, wd |
| 54 | + |
| 55 | + def step(self, closure=None): |
| 56 | + loss = None |
| 57 | + if closure is not None: |
| 58 | + loss = closure() |
| 59 | + |
| 60 | + for group in self.param_groups: |
| 61 | + for p in group['params']: |
| 62 | + if p.grad is None: |
| 63 | + continue |
| 64 | + |
| 65 | + grad = p.grad.data |
| 66 | + beta1, beta2 = group['betas'] |
| 67 | + nesterov = group['nesterov'] |
| 68 | + |
| 69 | + state = self.state[p] |
| 70 | + |
| 71 | + # State initialization |
| 72 | + if len(state) == 0: |
| 73 | + state['step'] = 0 |
| 74 | + state['exp_avg'] = torch.zeros_like(p.data) |
| 75 | + state['exp_avg_sq'] = torch.zeros_like(p.data) |
| 76 | + |
| 77 | + # Adam |
| 78 | + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] |
| 79 | + |
| 80 | + state['step'] += 1 |
| 81 | + bias_correction1 = 1 - beta1 ** state['step'] |
| 82 | + bias_correction2 = 1 - beta2 ** state['step'] |
| 83 | + |
| 84 | + exp_avg.mul_(beta1).add_(1 - beta1, grad) |
| 85 | + exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) |
| 86 | + |
| 87 | + denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps']) |
| 88 | + step_size = group['lr'] / bias_correction1 |
| 89 | + |
| 90 | + if nesterov: |
| 91 | + perturb = (beta1 * exp_avg + (1 - beta1) * grad) / denom |
| 92 | + else: |
| 93 | + perturb = exp_avg / denom |
| 94 | + |
| 95 | + # Projection |
| 96 | + wd_ratio = 1 |
| 97 | + if len(p.shape) > 1: |
| 98 | + perturb, wd_ratio = self._projection(p, grad, perturb, group['delta'], group['wd_ratio'], group['eps']) |
| 99 | + |
| 100 | + # Weight decay |
| 101 | + if group['weight_decay'] > 0: |
| 102 | + p.data.mul_(1 - group['lr'] * group['weight_decay'] * wd_ratio) |
| 103 | + |
| 104 | + # Step |
| 105 | + p.data.add_(-step_size, perturb) |
| 106 | + |
| 107 | + return loss |
0 commit comments