|
| 1 | +import torch |
| 2 | +from torch.optim.optimizer import Optimizer |
| 3 | + |
| 4 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 5 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 6 | +from pytorch_optimizer.base.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS, HUTCHINSON_G |
| 7 | + |
| 8 | +# Modified from https://github.com/davda54/ada-hessian/blob/master/ada_hessian.py (MIT David Samuel) |
| 9 | + |
| 10 | + |
| 11 | +class AdaHessian(Optimizer, BaseOptimizer): |
| 12 | + r"""An Adaptive Second Order Optimizer for Machine Learning |
| 13 | +
|
| 14 | + Requires `loss.backward(create_graph=True)` in order to calculate hessians |
| 15 | +
|
| 16 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 17 | + :param lr: float. learning rate. |
| 18 | + :param betas: BETAS. coefficients used for computing running averages of gradient and the squared hessian trace. |
| 19 | + :param weight_decay: float. weight decay (L2 penalty). |
| 20 | + :param weight_decouple: bool. the optimizer uses decoupled weight decay as in AdamW. |
| 21 | + :param fixed_decay: bool. fix weight decay. |
| 22 | + :param hessian_power: float. exponent of the hessian trace |
| 23 | + :param update_period: int. number of steps after which to apply hessian approximation |
| 24 | + :param n_samples: int. times to sample `z` for the approximation of the hessian trace |
| 25 | + :param eps: float. term added to the denominator to improve numerical stability. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, |
| 29 | + params: PARAMETERS, |
| 30 | + lr: float = 1e-1, |
| 31 | + betas: BETAS = (0.9, 0.999), |
| 32 | + weight_decay: float = 0.0, |
| 33 | + weight_decouple: bool = True, |
| 34 | + fixed_decay: bool = False, |
| 35 | + hessian_power: float = 1.0, |
| 36 | + update_period: int = 1, |
| 37 | + n_samples: int = 1, |
| 38 | + hessian_distribution: HUTCHINSON_G = 'rademacher', |
| 39 | + eps: float = 1e-16): |
| 40 | + |
| 41 | + self.validate_learning_rate(lr) |
| 42 | + self.validate_betas(betas) |
| 43 | + self.validate_non_negative(weight_decay, 'weight_decay') |
| 44 | + self.validate_non_negative(eps, 'eps') |
| 45 | + self.validate_range(hessian_power, "Hessian Power", 0, 1, range_type='(]') |
| 46 | + |
| 47 | + self.distribution = hessian_distribution |
| 48 | + self.update_period = update_period |
| 49 | + self.n_samples = n_samples |
| 50 | + defaults: DEFAULTS = { |
| 51 | + 'lr': lr, |
| 52 | + 'betas': betas, |
| 53 | + 'weight_decay': weight_decay, |
| 54 | + 'weight_decouple': weight_decouple, |
| 55 | + 'fixed_decay': fixed_decay, |
| 56 | + 'hessian_power': hessian_power, |
| 57 | + 'eps': eps, |
| 58 | + } |
| 59 | + self._step = 0 |
| 60 | + super().__init__(params, defaults) |
| 61 | + |
| 62 | + @torch.no_grad() |
| 63 | + def reset(self): |
| 64 | + self._step = 0 |
| 65 | + for group in self.param_groups: |
| 66 | + for p in group['params']: |
| 67 | + state = self.state[p] |
| 68 | + state['exp_avg'] = torch.zeros_like(p) |
| 69 | + state['exp_hessian_diag_sq'] = torch.zero_like(p) |
| 70 | + |
| 71 | + @torch.no_grad() |
| 72 | + def step(self, closure: CLOSURE = None, hessian: tuple[torch.Tensor] = None) -> LOSS: |
| 73 | + loss: LOSS = None |
| 74 | + if closure is not None: |
| 75 | + with torch.enable_grad(): |
| 76 | + loss = closure() |
| 77 | + |
| 78 | + if hessian is not None: |
| 79 | + self.set_hessian(hessian) |
| 80 | + elif self._step % self.update_period == 0: |
| 81 | + self.compute_hutchinson_hessian(self.n_samples, distribution=self.distribution) |
| 82 | + |
| 83 | + for group in self.param_groups: |
| 84 | + for p in group['params']: |
| 85 | + if p.grad is None: |
| 86 | + continue |
| 87 | + |
| 88 | + grad = p.grad |
| 89 | + if grad.is_sparse: |
| 90 | + raise NoSparseGradientError(str(self)) |
| 91 | + |
| 92 | + # State initialization |
| 93 | + state = self.state[p] |
| 94 | + if 'exp_avg' not in state: |
| 95 | + state['exp_avg'] = torch.zeros_like(p.data) |
| 96 | + state['exp_hessian_diag_sq'] = torch.zeros_like(p.data) |
| 97 | + |
| 98 | + self.apply_weight_decay( |
| 99 | + p=p, |
| 100 | + grad=grad, |
| 101 | + lr=group['lr'], |
| 102 | + weight_decay=group['weight_decay'], |
| 103 | + weight_decouple=group['weight_decouple'], |
| 104 | + fixed_decay=group['fixed_decay'], |
| 105 | + ) |
| 106 | + |
| 107 | + exp_avg, exp_hessian_diag_sq = state['exp_avg'], state['exp_hessian_diag_sq'] |
| 108 | + beta1, beta2 = group['betas'] |
| 109 | + |
| 110 | + # Decay the first and second moment running average coefficient |
| 111 | + exp_avg.mul_(beta1).add_(p.grad, alpha=1 - beta1) |
| 112 | + if (self._step % self.update_period == 0 or hessian is not None) and 'hessian' in state: |
| 113 | + # if self.average_conv_kernel and p.dim() == 4: |
| 114 | + # state['hessian'] = torch.abs(state['hessian']).mean(dim=[2, 3], keepdim=True).expand_as(state['hessian']).clone() |
| 115 | + exp_hessian_diag_sq.mul_(beta2).addcmul_(state['hessian'], state['hessian'], value=1 - beta2) |
| 116 | + |
| 117 | + bias_correction1 = 1 - beta1 ** (self._step+1) |
| 118 | + bias_correction2 = 1 - beta2 ** (self._step+1) |
| 119 | + |
| 120 | + k = group['hessian_power'] |
| 121 | + denom = (exp_hessian_diag_sq / bias_correction2).pow_(k / 2).add_(group['eps']) |
| 122 | + |
| 123 | + # make update |
| 124 | + step_size = group['lr'] / bias_correction1 |
| 125 | + p.addcdiv_(exp_avg, denom, value=-step_size) |
| 126 | + |
| 127 | + self._step += 1 |
| 128 | + return loss |
0 commit comments