|
| 1 | +import math |
| 2 | + |
| 3 | +import torch |
| 4 | + |
| 5 | +from pytorch_optimizer.base.exception import NoComplexParameterError, NoSparseGradientError |
| 6 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 7 | +from pytorch_optimizer.base.type import BETAS, CLOSURE, DEFAULTS, GROUP, LOSS, PARAMETERS |
| 8 | + |
| 9 | + |
| 10 | +class AdamC(BaseOptimizer): |
| 11 | + r"""Why Gradients Rapidly Increase Near the End of Training. |
| 12 | +
|
| 13 | + Set `normalized=True` for LayerNorm and BatchNorm layers. |
| 14 | +
|
| 15 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 16 | + :param lr: float. learning rate. |
| 17 | + :param betas: BETAS. coefficients used for computing running averages of gradient and the squared hessian trace. |
| 18 | + :param weight_decay: float. weight decay (L2 penalty). |
| 19 | + :param weight_decouple: bool. the optimizer uses decoupled weight decay as in AdamW. |
| 20 | + :param fixed_decay: bool. fix weight decay. |
| 21 | + :param ams_bound: bool. whether to use the AMSBound variant. |
| 22 | + :param eps: float. term added to the denominator to improve numerical stability. |
| 23 | + :param maximize: bool. maximize the objective with respect to the params, instead of minimizing. |
| 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 = 0.0, |
| 32 | + weight_decouple: bool = True, |
| 33 | + fixed_decay: bool = False, |
| 34 | + ams_bound: bool = False, |
| 35 | + eps: float = 1e-8, |
| 36 | + maximize: bool = False, |
| 37 | + **kwargs, |
| 38 | + ): |
| 39 | + self.validate_learning_rate(lr) |
| 40 | + self.validate_betas(betas) |
| 41 | + self.validate_non_negative(weight_decay, 'weight_decay') |
| 42 | + self.validate_non_negative(eps, 'eps') |
| 43 | + |
| 44 | + self.maximize = maximize |
| 45 | + self.max_lr: float = lr |
| 46 | + |
| 47 | + defaults: DEFAULTS = { |
| 48 | + 'lr': lr, |
| 49 | + 'betas': betas, |
| 50 | + 'weight_decay': weight_decay, |
| 51 | + 'weight_decouple': weight_decouple, |
| 52 | + 'fixed_decay': fixed_decay, |
| 53 | + 'ams_bound': ams_bound, |
| 54 | + 'eps': eps, |
| 55 | + **kwargs, |
| 56 | + } |
| 57 | + |
| 58 | + super().__init__(params, defaults) |
| 59 | + |
| 60 | + def __str__(self) -> str: |
| 61 | + return 'AdamC' |
| 62 | + |
| 63 | + def init_group(self, group: GROUP, **kwargs) -> None: |
| 64 | + for p in group['params']: |
| 65 | + if p.grad is None: |
| 66 | + continue |
| 67 | + |
| 68 | + grad = p.grad |
| 69 | + if grad.is_sparse: |
| 70 | + raise NoSparseGradientError(str(self)) |
| 71 | + |
| 72 | + if torch.is_complex(p): |
| 73 | + raise NoComplexParameterError(str(self)) |
| 74 | + |
| 75 | + state = self.state[p] |
| 76 | + |
| 77 | + if len(state) == 0: |
| 78 | + state['exp_avg'] = torch.zeros_like(p) |
| 79 | + state['exp_avg_sq'] = torch.zeros_like(p) |
| 80 | + |
| 81 | + if group['ams_bound']: |
| 82 | + state['max_exp_avg_sq'] = torch.zeros_like(p) |
| 83 | + |
| 84 | + @torch.no_grad() |
| 85 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 86 | + loss: LOSS = None |
| 87 | + if closure is not None: |
| 88 | + with torch.enable_grad(): |
| 89 | + loss = closure() |
| 90 | + |
| 91 | + for group in self.param_groups: |
| 92 | + if 'step' not in group: |
| 93 | + self.init_group(group) |
| 94 | + group['step'] = 1 |
| 95 | + else: |
| 96 | + group['step'] += 1 |
| 97 | + |
| 98 | + beta1, beta2 = group['betas'] |
| 99 | + |
| 100 | + bias_correction1: float = self.debias(beta1, group['step']) |
| 101 | + bias_correction2_sq: float = math.sqrt(self.debias(beta2, group['step'])) |
| 102 | + |
| 103 | + wd_step_size: float = group['lr'] if not group.get('normalized') else (group['lr'] ** 2) / self.max_lr |
| 104 | + |
| 105 | + for p in group['params']: |
| 106 | + if p.grad is None: |
| 107 | + continue |
| 108 | + |
| 109 | + grad = p.grad |
| 110 | + |
| 111 | + self.maximize_gradient(grad, maximize=self.maximize) |
| 112 | + |
| 113 | + state = self.state[p] |
| 114 | + |
| 115 | + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] |
| 116 | + |
| 117 | + self.apply_weight_decay( |
| 118 | + p=p, |
| 119 | + grad=grad, |
| 120 | + lr=wd_step_size, |
| 121 | + weight_decay=group['weight_decay'], |
| 122 | + weight_decouple=group['weight_decouple'], |
| 123 | + fixed_decay=group['fixed_decay'], |
| 124 | + ) |
| 125 | + |
| 126 | + exp_avg.mul_(beta1).add_(grad, alpha=1.0 - beta1) |
| 127 | + exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2) |
| 128 | + |
| 129 | + de_nom = self.apply_ams_bound( |
| 130 | + ams_bound=group['ams_bound'], |
| 131 | + exp_avg_sq=exp_avg_sq, |
| 132 | + max_exp_avg_sq=state.get('max_exp_avg_sq', None), |
| 133 | + eps=group['eps'], |
| 134 | + ) |
| 135 | + de_nom.div_(bias_correction2_sq) |
| 136 | + |
| 137 | + p.addcdiv_(exp_avg / bias_correction1, de_nom, value=-group['lr']) |
| 138 | + |
| 139 | + return loss |
0 commit comments