|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch |
| 5 | +from torch.optim.optimizer import Optimizer |
| 6 | + |
| 7 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 8 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 9 | +from pytorch_optimizer.base.types import CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 10 | + |
| 11 | + |
| 12 | +class Apollo(Optimizer, BaseOptimizer): |
| 13 | + r"""An Adaptive Parameter-wise Diagonal Quasi-Newton Method for Nonconvex Stochastic Optimization. |
| 14 | +
|
| 15 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 16 | + :param lr: float. learning rate. |
| 17 | + :param init_lr: Optional[float]. initial learning rate (default lr / 1000). |
| 18 | + :param beta: float. coefficient used for computing running averages of gradient. |
| 19 | + :param rebound: str. rectified bound for diagonal hessian. (constant, belief). |
| 20 | + :param weight_decay: float. weight decay (L2 penalty). |
| 21 | + :param weight_decay_type: str. type of weight decay. (l2, decoupled, stable). |
| 22 | + :param warmup_steps: int. number of warmup steps. |
| 23 | + :param eps: float. term added to the denominator to improve numerical stability. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + params: PARAMETERS, |
| 29 | + lr: float = 1e-3, |
| 30 | + init_lr: Optional[float] = None, |
| 31 | + beta: float = 0.9, |
| 32 | + rebound: str = 'constant', |
| 33 | + weight_decay: float = 0.0, |
| 34 | + weight_decay_type: str = 'l2', |
| 35 | + warmup_steps: int = 500, |
| 36 | + eps: float = 1e-4, |
| 37 | + ): |
| 38 | + self.lr = lr |
| 39 | + self.beta = beta |
| 40 | + self.rebound = rebound |
| 41 | + self.weight_decay = weight_decay |
| 42 | + self.weight_decay_type = weight_decay_type |
| 43 | + self.warmup_steps = warmup_steps |
| 44 | + self.eps = eps |
| 45 | + |
| 46 | + self.validate_parameters() |
| 47 | + |
| 48 | + self.init_lr: float = init_lr if init_lr is not None else lr / 1000.0 |
| 49 | + |
| 50 | + defaults: DEFAULTS = { |
| 51 | + 'lr': lr, |
| 52 | + 'init_lr': self.init_lr, |
| 53 | + 'beta': beta, |
| 54 | + 'weight_decay': weight_decay, |
| 55 | + 'eps': eps, |
| 56 | + } |
| 57 | + super().__init__(params, defaults) |
| 58 | + |
| 59 | + def validate_parameters(self): |
| 60 | + self.validate_learning_rate(self.lr) |
| 61 | + self.validate_beta(self.beta) |
| 62 | + self.validate_rebound(self.rebound) |
| 63 | + self.validate_weight_decay(self.weight_decay) |
| 64 | + self.validate_weight_decay_type(self.weight_decay_type) |
| 65 | + self.validate_epsilon(self.eps) |
| 66 | + |
| 67 | + @property |
| 68 | + def __str__(self) -> str: |
| 69 | + return 'Apollo' |
| 70 | + |
| 71 | + @torch.no_grad() |
| 72 | + def reset(self): |
| 73 | + for group in self.param_groups: |
| 74 | + group['step'] = 0 |
| 75 | + for p in group['params']: |
| 76 | + state = self.state[p] |
| 77 | + |
| 78 | + state['step'] = 0 |
| 79 | + state['exp_avg_grad'] = torch.zeros_like(p) |
| 80 | + state['approx_hessian'] = torch.zeros_like(p) |
| 81 | + state['update'] = torch.zeros_like(p) |
| 82 | + |
| 83 | + @torch.no_grad() |
| 84 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 85 | + loss: LOSS = None |
| 86 | + if closure is not None: |
| 87 | + with torch.enable_grad(): |
| 88 | + loss = closure() |
| 89 | + |
| 90 | + for group in self.param_groups: |
| 91 | + if 'step' in group: |
| 92 | + group['step'] += 1 |
| 93 | + else: |
| 94 | + group['step'] = 1 |
| 95 | + |
| 96 | + current_lr: float = ( |
| 97 | + group['lr'] |
| 98 | + if group['step'] >= self.warmup_steps |
| 99 | + else (self.lr - group['init_lr']) * group['step'] / self.warmup_steps + group['init_lr'] |
| 100 | + ) |
| 101 | + |
| 102 | + weight_decay, eps = group['weight_decay'], group['eps'] |
| 103 | + |
| 104 | + bias_correction: float = 1.0 - group['beta'] ** group['step'] |
| 105 | + alpha: float = (1.0 - group['beta']) / bias_correction |
| 106 | + |
| 107 | + for p in group['params']: |
| 108 | + if p.grad is None: |
| 109 | + continue |
| 110 | + |
| 111 | + grad = p.grad |
| 112 | + if grad.is_sparse: |
| 113 | + raise NoSparseGradientError(self.__str__) |
| 114 | + |
| 115 | + state = self.state[p] |
| 116 | + if len(state) == 0: |
| 117 | + state['exp_avg_grad'] = torch.zeros_like(p) |
| 118 | + state['approx_hessian'] = torch.zeros_like(p) |
| 119 | + state['update'] = torch.zeros_like(p) |
| 120 | + |
| 121 | + exp_avg_grad, b, d_p = state['exp_avg_grad'], state['approx_hessian'], state['update'] |
| 122 | + |
| 123 | + if weight_decay > 0.0 and self.weight_decay_type == 'l2': |
| 124 | + grad.add_(p, alpha=weight_decay) |
| 125 | + |
| 126 | + delta_grad = grad - exp_avg_grad |
| 127 | + if self.rebound == 'belief': |
| 128 | + rebound = delta_grad.norm(p=np.inf) |
| 129 | + else: |
| 130 | + rebound = 1e-2 |
| 131 | + eps /= rebound |
| 132 | + |
| 133 | + exp_avg_grad.add_(delta_grad, alpha=alpha) |
| 134 | + |
| 135 | + de_nom = d_p.norm(p=4).add(eps) |
| 136 | + d_p.div_(de_nom) |
| 137 | + |
| 138 | + v_sq = d_p.mul(d_p) |
| 139 | + delta = delta_grad.div_(de_nom).mul_(d_p).sum().mul(-alpha) - b.mul(v_sq).sum() |
| 140 | + |
| 141 | + b.addcmul_(v_sq, delta) |
| 142 | + |
| 143 | + de_nom = b.abs().clamp_(min=rebound) |
| 144 | + if self.rebound == 'belief': |
| 145 | + de_nom.add_(eps / alpha) |
| 146 | + |
| 147 | + d_p.copy_(exp_avg_grad.div(de_nom)) |
| 148 | + |
| 149 | + if weight_decay > 0.0 and self.weight_decay_type != 'l2': |
| 150 | + if self.weight_decay_type == 'stable': |
| 151 | + weight_decay /= de_nom.mean().item() |
| 152 | + |
| 153 | + d_p.add_(p, alpha=weight_decay) |
| 154 | + |
| 155 | + p.add_(d_p, alpha=-current_lr) |
| 156 | + |
| 157 | + return loss |
0 commit comments