|
| 1 | +from typing import Tuple |
| 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 QHAdam(Optimizer, BaseOptimizer): |
| 12 | + r"""Quasi-hyperbolic momentum and Adam for deep learning. |
| 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 nus: Tuple[float, float]. immediate discount factors used to estimate the gradient and its square. |
| 18 | + :param weight_decay: float. weight decay (L2 penalty). |
| 19 | + :param weight_decouple: bool. the optimizer uses decoupled weight decay as in AdamW. |
| 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.9, 0.999), |
| 28 | + nus: Tuple[float, float] = (1.0, 1.0), |
| 29 | + weight_decay: float = 0.0, |
| 30 | + weight_decouple: bool = False, |
| 31 | + eps: float = 1e-8, |
| 32 | + ): |
| 33 | + self.lr = lr |
| 34 | + self.betas = betas |
| 35 | + self.nus = nus |
| 36 | + self.weight_decay = weight_decay |
| 37 | + self.eps = eps |
| 38 | + |
| 39 | + self.validate_parameters() |
| 40 | + |
| 41 | + defaults: DEFAULTS = { |
| 42 | + 'lr': lr, |
| 43 | + 'betas': betas, |
| 44 | + 'nus': nus, |
| 45 | + 'weight_decay': weight_decay, |
| 46 | + 'weight_decouple': weight_decouple, |
| 47 | + 'eps': eps, |
| 48 | + } |
| 49 | + super().__init__(params, defaults) |
| 50 | + |
| 51 | + def validate_parameters(self): |
| 52 | + self.validate_learning_rate(self.lr) |
| 53 | + self.validate_betas(self.betas) |
| 54 | + self.validate_weight_decay(self.weight_decay) |
| 55 | + self.validate_epsilon(self.eps) |
| 56 | + self.validate_nus(self.nus) |
| 57 | + |
| 58 | + def __str__(self) -> str: |
| 59 | + return 'QHAdam' |
| 60 | + |
| 61 | + @torch.no_grad() |
| 62 | + def reset(self): |
| 63 | + for group in self.param_groups: |
| 64 | + group['step'] = 0 |
| 65 | + for p in group['params']: |
| 66 | + state = self.state[p] |
| 67 | + |
| 68 | + state['beta1_weight'] = torch.zeros((1,), dtype=p.dtype, device=p.device) |
| 69 | + state['beta2_weight'] = torch.zeros((1,), dtype=p.dtype, device=p.device) |
| 70 | + state['exp_avg'] = torch.zeros_like(p) |
| 71 | + state['exp_avg_sq'] = torch.zeros_like(p) |
| 72 | + |
| 73 | + @torch.no_grad() |
| 74 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 75 | + loss: LOSS = None |
| 76 | + if closure is not None: |
| 77 | + with torch.enable_grad(): |
| 78 | + loss = closure() |
| 79 | + |
| 80 | + for group in self.param_groups: |
| 81 | + if 'step' in group: |
| 82 | + group['step'] += 1 |
| 83 | + else: |
| 84 | + group['step'] = 1 |
| 85 | + |
| 86 | + beta1, beta2 = group['betas'] |
| 87 | + nu1, nu2 = group['nus'] |
| 88 | + |
| 89 | + for p in group['params']: |
| 90 | + if p.grad is None: |
| 91 | + continue |
| 92 | + |
| 93 | + grad = p.grad |
| 94 | + if grad.is_sparse: |
| 95 | + raise NoSparseGradientError(str(self)) |
| 96 | + |
| 97 | + state = self.state[p] |
| 98 | + |
| 99 | + if len(state) == 0: |
| 100 | + state['beta1_weight'] = torch.zeros((1,), dtype=grad.dtype, device=grad.device) |
| 101 | + state['beta2_weight'] = torch.zeros((1,), dtype=grad.dtype, device=grad.device) |
| 102 | + state['exp_avg'] = torch.zeros_like(p) |
| 103 | + state['exp_avg_sq'] = torch.zeros_like(p) |
| 104 | + |
| 105 | + if group['weight_decouple']: |
| 106 | + p.mul_(1.0 - group['weight_decay'] * group['lr']) |
| 107 | + elif group['weight_decay'] > 0.0: |
| 108 | + grad.add_(p, alpha=group['weight_decay']) |
| 109 | + |
| 110 | + beta1_weight, beta2_weight = state['beta1_weight'], state['beta2_weight'] |
| 111 | + beta1_weight.mul_(beta1).add_(1.0) |
| 112 | + beta2_weight.mul_(beta2).add_(1.0) |
| 113 | + |
| 114 | + beta1_adj = 1.0 - (1.0 / beta1_weight) |
| 115 | + beta2_adj = 1.0 - (1.0 / beta2_weight) |
| 116 | + |
| 117 | + grad_p2 = grad.pow(2) |
| 118 | + |
| 119 | + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] |
| 120 | + exp_avg.mul_(beta1_adj).add_((1.0 - beta1_adj) * grad) |
| 121 | + exp_avg_sq.mul_(beta2_adj).add_(1.0 - beta2_adj * grad_p2) |
| 122 | + |
| 123 | + avg_grad = exp_avg.mul(nu1) |
| 124 | + if nu1 != 1.0: |
| 125 | + avg_grad.add_(grad, alpha=1.0 - nu1) |
| 126 | + |
| 127 | + avg_grad_rms = exp_avg_sq.mul(nu2) |
| 128 | + if nu2 != 1.0: |
| 129 | + avg_grad_rms.add_(grad_p2, alpha=1.0 - nu2) |
| 130 | + |
| 131 | + avg_grad_rms.sqrt_().add_(group['eps']) |
| 132 | + |
| 133 | + p.addcdiv_(avg_grad, avg_grad_rms, value=-group['lr']) |
| 134 | + |
| 135 | + return loss |
0 commit comments