|
| 1 | +import torch |
| 2 | +from torch.nn.functional import softmax |
| 3 | +from torch.optim.optimizer import Optimizer |
| 4 | + |
| 5 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 6 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 7 | +from pytorch_optimizer.base.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 8 | + |
| 9 | + |
| 10 | +class Adalite(Optimizer, BaseOptimizer): |
| 11 | + r"""Adalite optimizer. |
| 12 | +
|
| 13 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 14 | + :param lr: float. learning rate. |
| 15 | + :param betas: BETAS. coefficients used for computing running averages of gradient and the squared hessian trace. |
| 16 | + :param weight_decay: float. weight decay (L2 penalty). |
| 17 | + :param weight_decouple: bool. the optimizer uses decoupled weight decay as in AdamW. |
| 18 | + :param fixed_decay: bool. fix weight decay. |
| 19 | + :param g_norm_min: float. |
| 20 | + :param ratio_min: float. |
| 21 | + :param tau: float. |
| 22 | + :param eps1: float. term added to the denominator to improve numerical stability. |
| 23 | + :param eps2: 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 | + betas: BETAS = (0.9, 0.999), |
| 31 | + weight_decay: float = 1e-2, |
| 32 | + weight_decouple: bool = False, |
| 33 | + fixed_decay: bool = False, |
| 34 | + g_norm_min: float = 1e-10, |
| 35 | + ratio_min: float = 1e-4, |
| 36 | + tau: float = 1.0, |
| 37 | + eps1: float = 1e-6, |
| 38 | + eps2: float = 1e-10, |
| 39 | + ): |
| 40 | + self.validate_learning_rate(lr) |
| 41 | + self.validate_betas(betas) |
| 42 | + self.validate_non_negative(weight_decay, 'weight_decay') |
| 43 | + self.validate_non_negative(eps1, 'eps1') |
| 44 | + self.validate_non_negative(eps2, 'eps1') |
| 45 | + |
| 46 | + defaults: DEFAULTS = { |
| 47 | + 'lr': lr, |
| 48 | + 'betas': betas, |
| 49 | + 'weight_decay': weight_decay, |
| 50 | + 'weight_decouple': weight_decouple, |
| 51 | + 'fixed_decay': fixed_decay, |
| 52 | + 'g_norm_min': g_norm_min, |
| 53 | + 'ratio_min': ratio_min, |
| 54 | + 'tau': tau, |
| 55 | + 'eps1': eps1, |
| 56 | + 'eps2': eps2, |
| 57 | + } |
| 58 | + super().__init__(params, defaults) |
| 59 | + |
| 60 | + def __str__(self) -> str: |
| 61 | + return 'Adalite' |
| 62 | + |
| 63 | + @torch.no_grad() |
| 64 | + def reset(self): |
| 65 | + for group in self.param_groups: |
| 66 | + group['step'] = 0 |
| 67 | + for p in group['params']: |
| 68 | + state = self.state[p] |
| 69 | + |
| 70 | + if len(p.shape) < 2: |
| 71 | + state['m_avg'] = torch.zeros_like(p) |
| 72 | + state['v_avg'] = torch.zeros_like(p) |
| 73 | + else: |
| 74 | + state['v_avg_0'] = torch.zeros_like(p.mean(dim=1)) |
| 75 | + state['v_avg_1'] = torch.zeros_like(p.mean(dim=0)) |
| 76 | + |
| 77 | + state['m_avg_c'] = torch.zeros_like(p.mean(dim=1)[:, None]) |
| 78 | + state['m_avg_r'] = torch.zeros_like(p.mean(dim=0)[None, :]) |
| 79 | + state['m_avg_u'] = torch.zeros_like(p.mean().unsqueeze(0).unsqueeze(0)) |
| 80 | + |
| 81 | + @torch.no_grad() |
| 82 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 83 | + loss: LOSS = None |
| 84 | + if closure is not None: |
| 85 | + with torch.enable_grad(): |
| 86 | + loss = closure() |
| 87 | + |
| 88 | + for group in self.param_groups: |
| 89 | + if 'step' in group: |
| 90 | + group['step'] += 1 |
| 91 | + else: |
| 92 | + group['step'] = 1 |
| 93 | + |
| 94 | + beta1, beta2 = group['betas'] |
| 95 | + |
| 96 | + for p in group['params']: |
| 97 | + if p.grad is None: |
| 98 | + continue |
| 99 | + |
| 100 | + grad = p.grad |
| 101 | + if grad.is_sparse: |
| 102 | + raise NoSparseGradientError(str(self)) |
| 103 | + |
| 104 | + state = self.state[p] |
| 105 | + |
| 106 | + if len(state) == 0: |
| 107 | + if len(p.shape) < 2: |
| 108 | + state['m_avg'] = torch.zeros_like(p) |
| 109 | + state['v_avg'] = torch.zeros_like(p) |
| 110 | + else: |
| 111 | + state['v_avg_0'] = torch.zeros_like(p.mean(dim=1)) |
| 112 | + state['v_avg_1'] = torch.zeros_like(p.mean(dim=0)) |
| 113 | + |
| 114 | + state['m_avg_c'] = torch.zeros_like(p.mean(dim=1)[:, None]) |
| 115 | + state['m_avg_r'] = torch.zeros_like(p.mean(dim=0)[None, :]) |
| 116 | + state['m_avg_u'] = torch.zeros_like(p.mean().unsqueeze(0).unsqueeze(0)) |
| 117 | + |
| 118 | + if sum(grad.shape) > 1: |
| 119 | + trust_ratio = (p.norm() / grad.norm().clip(min=group['g_norm_min'])).clip(min=group['ratio_min']) |
| 120 | + grad.mul_(trust_ratio) |
| 121 | + |
| 122 | + if len(grad.shape) < 2: |
| 123 | + m = state['m_avg'] |
| 124 | + v = state['v_avg'] |
| 125 | + else: |
| 126 | + r, c = state['v_avg_0'][:, None], state['v_avg_1'][None, :] |
| 127 | + v = (r * c) / r.sum().clamp(min=group['eps2']) |
| 128 | + m = state['m_avg_c'] @ state['m_avg_u'] @ state['m_avg_r'] |
| 129 | + |
| 130 | + m.lerp_(grad, 1.0 - beta1) |
| 131 | + v.lerp_((grad - m).square(), 1.0 - beta2) |
| 132 | + |
| 133 | + v_avg = v / (1.0 - beta2 ** group['step']) |
| 134 | + |
| 135 | + if len(grad.shape) == 2: |
| 136 | + imp_c = softmax(v.mean(dim=1), dim=0)[:, None] |
| 137 | + imp_r = softmax(v.mean(dim=0), dim=0)[None, :] |
| 138 | + m.lerp_(grad, 1.0 - imp_c * imp_r) |
| 139 | + |
| 140 | + u = m.lerp(grad, 1.0 - beta1) |
| 141 | + |
| 142 | + if len(grad.shape) < 2: |
| 143 | + state['m_avg'] = m |
| 144 | + state['v_avg'] = v |
| 145 | + else: |
| 146 | + state['v_avg_0'] = v.sum(dim=1) |
| 147 | + state['v_avg_1'] = v.sum(dim=0) / v.sum().clamp(min=group['eps2']) |
| 148 | + |
| 149 | + imp_c = softmax(v.mean(dim=1) / group['tau'], dim=-1)[:, None] |
| 150 | + imp_r = softmax(v.mean(dim=0) / group['tau'], dim=-1)[None, :] |
| 151 | + |
| 152 | + c = ((m * imp_r).sum(dim=1))[:, None] |
| 153 | + r = ((m * imp_c).sum(dim=0))[None, :] |
| 154 | + |
| 155 | + s = (c.T @ m @ r.T) / (c.T @ c @ r @ r.T).clamp(min=group['eps2']) |
| 156 | + |
| 157 | + state['m_avg_c'] = c |
| 158 | + state['m_avg_r'] = r |
| 159 | + state['m_avg_u'] = s |
| 160 | + |
| 161 | + u.div_((v_avg + group['eps1']).sqrt()) |
| 162 | + |
| 163 | + u = u.reshape(p.shape) |
| 164 | + u.add_(p, alpha=group['weight_decay']) |
| 165 | + |
| 166 | + p.add_(u, alpha=-group['lr']) |
| 167 | + |
| 168 | + return loss |
0 commit comments