|
| 1 | +import math |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch.optim.optimizer import Optimizer |
| 5 | + |
| 6 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 7 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 8 | +from pytorch_optimizer.base.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 9 | + |
| 10 | + |
| 11 | +class NovoGrad(Optimizer, BaseOptimizer): |
| 12 | + r"""Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks. |
| 13 | +
|
| 14 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 15 | + :param lr: float. learning rate. |
| 16 | + :param betas: BETAS. coefficients used for computing running averages of gradient and the squared hessian trace. |
| 17 | + :param weight_decay: float. weight decay (L2 penalty). |
| 18 | + :param grad_averaging: bool. multiply ck (1 - momentum). |
| 19 | + :param adamd_debias_term: bool. Only correct the denominator to avoid inflating step sizes early in training. |
| 20 | + :param eps: float. term added to the denominator to improve numerical stability. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + params: PARAMETERS, |
| 26 | + lr: float = 1e-3, |
| 27 | + betas: BETAS = (0.95, 0.98), |
| 28 | + weight_decay: float = 0.0, |
| 29 | + grad_averaging: bool = False, |
| 30 | + adamd_debias_term: bool = False, |
| 31 | + eps: float = 1e-8, |
| 32 | + ): |
| 33 | + self.lr = lr |
| 34 | + self.betas = betas |
| 35 | + self.weight_decay = weight_decay |
| 36 | + self.grad_averaging = grad_averaging |
| 37 | + self.adamd_debias_term = adamd_debias_term |
| 38 | + self.eps = eps |
| 39 | + |
| 40 | + self.validate_parameters() |
| 41 | + |
| 42 | + defaults: DEFAULTS = { |
| 43 | + 'lr': lr, |
| 44 | + 'betas': betas, |
| 45 | + 'weight_decay': weight_decay, |
| 46 | + 'eps': eps, |
| 47 | + } |
| 48 | + super().__init__(params, defaults) |
| 49 | + |
| 50 | + def validate_parameters(self): |
| 51 | + self.validate_learning_rate(self.lr) |
| 52 | + self.validate_betas(self.betas) |
| 53 | + self.validate_weight_decay(self.weight_decay) |
| 54 | + self.validate_epsilon(self.eps) |
| 55 | + |
| 56 | + @property |
| 57 | + def __str__(self) -> str: |
| 58 | + return 'NovoGrad' |
| 59 | + |
| 60 | + @torch.no_grad() |
| 61 | + def reset(self): |
| 62 | + for group in self.param_groups: |
| 63 | + group['step'] = 0 |
| 64 | + for p in group['params']: |
| 65 | + state = self.state[p] |
| 66 | + |
| 67 | + grad = p.grad |
| 68 | + g_2 = grad ** 2 # fmt: skip |
| 69 | + |
| 70 | + state['step'] = 0 |
| 71 | + state['moments'] = grad.div(g_2.sqrt() + group['eps']) + group['weight_decay'] * p |
| 72 | + state['grads_ema'] = g_2 |
| 73 | + |
| 74 | + @torch.no_grad() |
| 75 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 76 | + loss: LOSS = None |
| 77 | + if closure is not None: |
| 78 | + with torch.enable_grad(): |
| 79 | + loss = closure() |
| 80 | + |
| 81 | + for group in self.param_groups: |
| 82 | + if 'step' in group: |
| 83 | + group['step'] += 1 |
| 84 | + else: |
| 85 | + group['step'] = 1 |
| 86 | + |
| 87 | + beta1, beta2 = group['betas'] |
| 88 | + weight_decay = group['weight_decay'] |
| 89 | + |
| 90 | + bias_correction1 = 1.0 - beta1 ** group['step'] |
| 91 | + bias_correction2_sq = math.sqrt(1.0 - beta2 ** group['step']) |
| 92 | + |
| 93 | + step_size: float = group['lr'] * bias_correction2_sq |
| 94 | + if not self.adamd_debias_term: |
| 95 | + step_size /= bias_correction1 |
| 96 | + |
| 97 | + for p in group['params']: |
| 98 | + if p.grad is None: |
| 99 | + continue |
| 100 | + |
| 101 | + grad = p.grad |
| 102 | + if grad.is_sparse: |
| 103 | + raise NoSparseGradientError(self.__str__) |
| 104 | + |
| 105 | + state = self.state[p] |
| 106 | + g_2 = grad ** 2 # fmt: skip |
| 107 | + |
| 108 | + if len(state) == 0: |
| 109 | + state['moments'] = grad.div(g_2.sqrt() + group['eps']) + weight_decay * p |
| 110 | + state['grads_ema'] = g_2 |
| 111 | + |
| 112 | + moments, grads_ema = state['moments'], state['grads_ema'] |
| 113 | + |
| 114 | + grads_ema.mul_(beta2).add_(g_2, alpha=1.0 - beta2) |
| 115 | + |
| 116 | + de_nom = grads_ema.sqrt().add_(group['eps']) |
| 117 | + grad.div_(de_nom) |
| 118 | + |
| 119 | + if weight_decay > 0.0: |
| 120 | + grad.add_(p, alpha=weight_decay) |
| 121 | + |
| 122 | + if self.grad_averaging: |
| 123 | + grad.mul_(1.0 - beta1) |
| 124 | + |
| 125 | + moments.mul_(beta1).add_(grad) |
| 126 | + |
| 127 | + p.add_(moments, alpha=-step_size) |
| 128 | + |
| 129 | + return loss |
0 commit comments