|
| 1 | +from __future__ import annotations |
| 2 | +from typing import Callable |
| 3 | + |
| 4 | +import torch |
| 5 | +from torch import atan2, sqrt |
| 6 | +from torch.optim.optimizer import Optimizer |
| 7 | + |
| 8 | +# functions |
| 9 | + |
| 10 | +def exists(val): |
| 11 | + return val is not None |
| 12 | + |
| 13 | +# class |
| 14 | + |
| 15 | +class AdamAtan2(Optimizer): |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + params, |
| 19 | + lr = 1e-4, |
| 20 | + betas: tuple[float, float] = (0.9, 0.99), |
| 21 | + weight_decay = 0., |
| 22 | + regen_reg_rate = 0., |
| 23 | + decoupled_wd = False, |
| 24 | + a = 1.27, |
| 25 | + b = 1. |
| 26 | + ): |
| 27 | + assert lr > 0. |
| 28 | + assert all([0. <= beta <= 1. for beta in betas]) |
| 29 | + assert weight_decay >= 0. |
| 30 | + assert regen_reg_rate >= 0. |
| 31 | + assert not (weight_decay > 0. and regen_reg_rate > 0.) |
| 32 | + |
| 33 | + self._init_lr = lr |
| 34 | + self.decoupled_wd = decoupled_wd |
| 35 | + |
| 36 | + defaults = dict( |
| 37 | + lr = lr, |
| 38 | + betas = betas, |
| 39 | + a = a, |
| 40 | + b = b, |
| 41 | + weight_decay = weight_decay, |
| 42 | + regen_reg_rate = regen_reg_rate, |
| 43 | + ) |
| 44 | + |
| 45 | + super().__init__(params, defaults) |
| 46 | + |
| 47 | + @torch.no_grad() |
| 48 | + def step( |
| 49 | + self, |
| 50 | + closure: Callable | None = None |
| 51 | + ): |
| 52 | + |
| 53 | + loss = None |
| 54 | + if exists(closure): |
| 55 | + with torch.enable_grad(): |
| 56 | + loss = closure() |
| 57 | + |
| 58 | + for group in self.param_groups: |
| 59 | + for p in filter(lambda p: exists(p.grad), group['params']): |
| 60 | + |
| 61 | + grad, lr, wd, regen_rate, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr |
| 62 | + |
| 63 | + # maybe decoupled weight decay |
| 64 | + |
| 65 | + if self.decoupled_wd: |
| 66 | + wd /= init_lr |
| 67 | + |
| 68 | + # weight decay |
| 69 | + |
| 70 | + if wd > 0.: |
| 71 | + p.mul_(1. - lr * wd) |
| 72 | + |
| 73 | + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 |
| 74 | + |
| 75 | + if regen_rate > 0. and 'param_init' in state: |
| 76 | + param_init = state['param_init'] |
| 77 | + |
| 78 | + shape = param_init.shape |
| 79 | + |
| 80 | + # wasserstein compares using ordered statistics, iiuc |
| 81 | + |
| 82 | + indices = p.flatten().sort(dim = -1).indices |
| 83 | + indices = indices.argsort(dim = -1) |
| 84 | + |
| 85 | + target = param_init.flatten()[indices] |
| 86 | + target = target.reshape(shape) |
| 87 | + |
| 88 | + p.lerp_(target, lr / init_lr * regen_rate) |
| 89 | + |
| 90 | + # init state if needed |
| 91 | + |
| 92 | + if len(state) == 0: |
| 93 | + state['steps'] = 0 |
| 94 | + state['exp_avg'] = torch.zeros_like(grad) |
| 95 | + state['exp_avg_sq'] = torch.zeros_like(grad) |
| 96 | + |
| 97 | + if regen_rate > 0.: |
| 98 | + |
| 99 | + # wasserstein reg - https://arxiv.org/abs/2406.06811v1 |
| 100 | + # initial parameters sorted for efficiency |
| 101 | + |
| 102 | + shape = p.shape |
| 103 | + p = p.flatten().sort(dim = -1).values |
| 104 | + p = p.reshape(shape) |
| 105 | + |
| 106 | + state['param_init'] = p.clone() |
| 107 | + |
| 108 | + # get some of the states |
| 109 | + |
| 110 | + exp_avg, exp_avg_sq, steps = state['exp_avg'], state['exp_avg_sq'], state['steps'] |
| 111 | + |
| 112 | + steps += 1 |
| 113 | + |
| 114 | + # bias corrections |
| 115 | + |
| 116 | + bias_correct1 = 1. - beta1 ** steps |
| 117 | + bias_correct2 = 1. - beta2 ** steps |
| 118 | + |
| 119 | + # decay running averages |
| 120 | + |
| 121 | + exp_avg.lerp_(grad, 1. - beta1) |
| 122 | + exp_avg_sq.lerp_(grad * grad, 1. - beta2) |
| 123 | + |
| 124 | + # the following line is the proposed change to the update rule |
| 125 | + # using atan2 instead of a division with epsilon in denominator |
| 126 | + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) |
| 127 | + |
| 128 | + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() |
| 129 | + update = exp_avg.mul(1. / bias_correct1).atan2_(den) |
| 130 | + |
| 131 | + # update parameters |
| 132 | + |
| 133 | + p.add_(update, alpha = -lr * a) |
| 134 | + |
| 135 | + # increment steps |
| 136 | + |
| 137 | + state['steps'] = steps |
| 138 | + |
| 139 | + return loss |
0 commit comments