|
| 1 | +import math |
| 2 | +import torch |
| 3 | +from torch.optim.optimizer import Optimizer |
| 4 | +from tabulate import tabulate |
| 5 | +from colorama import Fore, Back, Style |
| 6 | + |
| 7 | +version_higher = ( torch.__version__ >= "1.5.0" ) |
| 8 | + |
| 9 | +class AdaBelief(Optimizer): |
| 10 | + r"""Implements AdaBelief algorithm. Modified from Adam in PyTorch |
| 11 | + Arguments: |
| 12 | + params (iterable): iterable of parameters to optimize or dicts defining |
| 13 | + parameter groups |
| 14 | + lr (float, optional): learning rate (default: 1e-3) |
| 15 | + betas (Tuple[float, float], optional): coefficients used for computing |
| 16 | + running averages of gradient and its square (default: (0.9, 0.999)) |
| 17 | + eps (float, optional): term added to the denominator to improve |
| 18 | + numerical stability (default: 1e-16) |
| 19 | + weight_decay (float, optional): weight decay (L2 penalty) (default: 0) |
| 20 | + amsgrad (boolean, optional): whether to use the AMSGrad variant of this |
| 21 | + algorithm from the paper `On the Convergence of Adam and Beyond`_ |
| 22 | + (default: False) |
| 23 | + weight_decouple (boolean, optional): ( default: True) If set as True, then |
| 24 | + the optimizer uses decoupled weight decay as in AdamW |
| 25 | + fixed_decay (boolean, optional): (default: False) This is used when weight_decouple |
| 26 | + is set as True. |
| 27 | + When fixed_decay == True, the weight decay is performed as |
| 28 | + $W_{new} = W_{old} - W_{old} \times decay$. |
| 29 | + When fixed_decay == False, the weight decay is performed as |
| 30 | + $W_{new} = W_{old} - W_{old} \times decay \times lr$. Note that in this case, the |
| 31 | + weight decay ratio decreases with learning rate (lr). |
| 32 | + rectify (boolean, optional): (default: True) If set as True, then perform the rectified |
| 33 | + update similar to RAdam |
| 34 | + degenerated_to_sgd (boolean, optional) (default:True) If set as True, then perform SGD update |
| 35 | + when variance of gradient is high |
| 36 | + print_change_log (boolean, optional) (default: True) If set as True, print the modifcation to |
| 37 | + default hyper-parameters |
| 38 | + reference: AdaBelief Optimizer, adapting stepsizes by the belief in observed gradients, NeurIPS 2020 |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-16, |
| 42 | + weight_decay=0, amsgrad=False, weight_decouple=True, fixed_decay=False, rectify=True, |
| 43 | + degenerated_to_sgd=True, print_change_log = True): |
| 44 | + |
| 45 | + # ------------------------------------------------------------------------------ |
| 46 | + # Print modifications to default arguments |
| 47 | + if print_change_log: |
| 48 | + print(Fore.RED + 'Please check your arguments if you have upgraded adabelief-pytorch from version 0.0.5.') |
| 49 | + print(Fore.RED + 'Modifications to default arguments:') |
| 50 | + default_table = tabulate([ |
| 51 | + ['adabelief-pytorch=0.0.5','1e-8','False','False'], |
| 52 | + ['>=0.1.0 (Current 0.2.0)','1e-16','True','True']], |
| 53 | + headers=['eps','weight_decouple','rectify']) |
| 54 | + print(Fore.RED + default_table) |
| 55 | + |
| 56 | + recommend_table = tabulate([ |
| 57 | + ['Recommended eps = 1e-8', 'Recommended eps = 1e-16'], |
| 58 | + ], |
| 59 | + headers=['SGD better than Adam (e.g. CNN for Image Classification)','Adam better than SGD (e.g. Transformer, GAN)']) |
| 60 | + print(Fore.BLUE + recommend_table) |
| 61 | + |
| 62 | + print(Fore.BLUE +'For a complete table of recommended hyperparameters, see') |
| 63 | + print(Fore.BLUE + 'https://github.com/juntang-zhuang/Adabelief-Optimizer') |
| 64 | + |
| 65 | + print(Fore.GREEN + 'You can disable the log message by setting "print_change_log = False", though it is recommended to keep as a reminder.') |
| 66 | + |
| 67 | + print(Style.RESET_ALL) |
| 68 | + # ------------------------------------------------------------------------------ |
| 69 | + |
| 70 | + if not 0.0 <= lr: |
| 71 | + raise ValueError("Invalid learning rate: {}".format(lr)) |
| 72 | + if not 0.0 <= eps: |
| 73 | + raise ValueError("Invalid epsilon value: {}".format(eps)) |
| 74 | + if not 0.0 <= betas[0] < 1.0: |
| 75 | + raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) |
| 76 | + if not 0.0 <= betas[1] < 1.0: |
| 77 | + raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) |
| 78 | + |
| 79 | + self.degenerated_to_sgd = degenerated_to_sgd |
| 80 | + if isinstance(params, (list, tuple)) and len(params) > 0 and isinstance(params[0], dict): |
| 81 | + for param in params: |
| 82 | + if 'betas' in param and (param['betas'][0] != betas[0] or param['betas'][1] != betas[1]): |
| 83 | + param['buffer'] = [[None, None, None] for _ in range(10)] |
| 84 | + |
| 85 | + defaults = dict(lr=lr, betas=betas, eps=eps, |
| 86 | + weight_decay=weight_decay, amsgrad=amsgrad, buffer=[[None, None, None] for _ in range(10)]) |
| 87 | + super(AdaBelief, self).__init__(params, defaults) |
| 88 | + |
| 89 | + self.degenerated_to_sgd = degenerated_to_sgd |
| 90 | + self.weight_decouple = weight_decouple |
| 91 | + self.rectify = rectify |
| 92 | + self.fixed_decay = fixed_decay |
| 93 | + if self.weight_decouple: |
| 94 | + print('Weight decoupling enabled in AdaBelief') |
| 95 | + if self.fixed_decay: |
| 96 | + print('Weight decay fixed') |
| 97 | + if self.rectify: |
| 98 | + print('Rectification enabled in AdaBelief') |
| 99 | + if amsgrad: |
| 100 | + print('AMSGrad enabled in AdaBelief') |
| 101 | + |
| 102 | + def __setstate__(self, state): |
| 103 | + super(AdaBelief, self).__setstate__(state) |
| 104 | + for group in self.param_groups: |
| 105 | + group.setdefault('amsgrad', False) |
| 106 | + |
| 107 | + def reset(self): |
| 108 | + for group in self.param_groups: |
| 109 | + for p in group['params']: |
| 110 | + state = self.state[p] |
| 111 | + amsgrad = group['amsgrad'] |
| 112 | + |
| 113 | + # State initialization |
| 114 | + state['step'] = 0 |
| 115 | + # Exponential moving average of gradient values |
| 116 | + state['exp_avg'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 117 | + if version_higher else torch.zeros_like(p.data) |
| 118 | + |
| 119 | + # Exponential moving average of squared gradient values |
| 120 | + state['exp_avg_var'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 121 | + if version_higher else torch.zeros_like(p.data) |
| 122 | + |
| 123 | + if amsgrad: |
| 124 | + # Maintains max of all exp. moving avg. of sq. grad. values |
| 125 | + state['max_exp_avg_var'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 126 | + if version_higher else torch.zeros_like(p.data) |
| 127 | + |
| 128 | + def step(self, closure=None): |
| 129 | + """Performs a single optimization step. |
| 130 | + Arguments: |
| 131 | + closure (callable, optional): A closure that reevaluates the model |
| 132 | + and returns the loss. |
| 133 | + """ |
| 134 | + loss = None |
| 135 | + if closure is not None: |
| 136 | + loss = closure() |
| 137 | + |
| 138 | + for group in self.param_groups: |
| 139 | + for p in group['params']: |
| 140 | + if p.grad is None: |
| 141 | + continue |
| 142 | + |
| 143 | + # cast data type |
| 144 | + half_precision = False |
| 145 | + if p.data.dtype == torch.float16: |
| 146 | + half_precision = True |
| 147 | + p.data = p.data.float() |
| 148 | + p.grad = p.grad.float() |
| 149 | + |
| 150 | + grad = p.grad.data |
| 151 | + if grad.is_sparse: |
| 152 | + raise RuntimeError( |
| 153 | + 'AdaBelief does not support sparse gradients, please consider SparseAdam instead') |
| 154 | + amsgrad = group['amsgrad'] |
| 155 | + |
| 156 | + state = self.state[p] |
| 157 | + |
| 158 | + beta1, beta2 = group['betas'] |
| 159 | + |
| 160 | + # State initialization |
| 161 | + if len(state) == 0: |
| 162 | + state['step'] = 0 |
| 163 | + # Exponential moving average of gradient values |
| 164 | + state['exp_avg'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 165 | + if version_higher else torch.zeros_like(p.data) |
| 166 | + # Exponential moving average of squared gradient values |
| 167 | + state['exp_avg_var'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 168 | + if version_higher else torch.zeros_like(p.data) |
| 169 | + if amsgrad: |
| 170 | + # Maintains max of all exp. moving avg. of sq. grad. values |
| 171 | + state['max_exp_avg_var'] = torch.zeros_like(p.data,memory_format=torch.preserve_format) \ |
| 172 | + if version_higher else torch.zeros_like(p.data) |
| 173 | + |
| 174 | + # perform weight decay, check if decoupled weight decay |
| 175 | + if self.weight_decouple: |
| 176 | + if not self.fixed_decay: |
| 177 | + p.data.mul_(1.0 - group['lr'] * group['weight_decay']) |
| 178 | + else: |
| 179 | + p.data.mul_(1.0 - group['weight_decay']) |
| 180 | + else: |
| 181 | + if group['weight_decay'] != 0: |
| 182 | + grad.add_(p.data, alpha=group['weight_decay']) |
| 183 | + |
| 184 | + # get current state variable |
| 185 | + exp_avg, exp_avg_var = state['exp_avg'], state['exp_avg_var'] |
| 186 | + |
| 187 | + state['step'] += 1 |
| 188 | + bias_correction1 = 1 - beta1 ** state['step'] |
| 189 | + bias_correction2 = 1 - beta2 ** state['step'] |
| 190 | + |
| 191 | + # Update first and second moment running average |
| 192 | + exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) |
| 193 | + grad_residual = grad - exp_avg |
| 194 | + exp_avg_var.mul_(beta2).addcmul_( grad_residual, grad_residual, value=1 - beta2) |
| 195 | + |
| 196 | + if amsgrad: |
| 197 | + max_exp_avg_var = state['max_exp_avg_var'] |
| 198 | + # Maintains the maximum of all 2nd moment running avg. till now |
| 199 | + torch.max(max_exp_avg_var, exp_avg_var.add_(group['eps']), out=max_exp_avg_var) |
| 200 | + |
| 201 | + # Use the max. for normalizing running avg. of gradient |
| 202 | + denom = (max_exp_avg_var.sqrt() / math.sqrt(bias_correction2)).add_(group['eps']) |
| 203 | + else: |
| 204 | + denom = (exp_avg_var.add_(group['eps']).sqrt() / math.sqrt(bias_correction2)).add_(group['eps']) |
| 205 | + |
| 206 | + # update |
| 207 | + if not self.rectify: |
| 208 | + # Default update |
| 209 | + step_size = group['lr'] / bias_correction1 |
| 210 | + p.data.addcdiv_( exp_avg, denom, value=-step_size) |
| 211 | + |
| 212 | + else: # Rectified update, forked from RAdam |
| 213 | + buffered = group['buffer'][int(state['step'] % 10)] |
| 214 | + if state['step'] == buffered[0]: |
| 215 | + N_sma, step_size = buffered[1], buffered[2] |
| 216 | + else: |
| 217 | + buffered[0] = state['step'] |
| 218 | + beta2_t = beta2 ** state['step'] |
| 219 | + N_sma_max = 2 / (1 - beta2) - 1 |
| 220 | + N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t) |
| 221 | + buffered[1] = N_sma |
| 222 | + |
| 223 | + # more conservative since it's an approximated value |
| 224 | + if N_sma >= 5: |
| 225 | + step_size = math.sqrt( |
| 226 | + (1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / ( |
| 227 | + N_sma_max - 2)) / (1 - beta1 ** state['step']) |
| 228 | + elif self.degenerated_to_sgd: |
| 229 | + step_size = 1.0 / (1 - beta1 ** state['step']) |
| 230 | + else: |
| 231 | + step_size = -1 |
| 232 | + buffered[2] = step_size |
| 233 | + |
| 234 | + if N_sma >= 5: |
| 235 | + denom = exp_avg_var.sqrt().add_(group['eps']) |
| 236 | + p.data.addcdiv_(exp_avg, denom, value=-step_size * group['lr']) |
| 237 | + elif step_size > 0: |
| 238 | + p.data.add_( exp_avg, alpha=-step_size * group['lr']) |
| 239 | + |
| 240 | + if half_precision: |
| 241 | + p.data = p.data.half() |
| 242 | + p.grad = p.grad.half() |
| 243 | + |
| 244 | + return loss |
0 commit comments