|
| 1 | +import math |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch.optim.optimizer import Optimizer |
| 5 | + |
| 6 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 7 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 8 | +from pytorch_optimizer.base.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 9 | +from pytorch_optimizer.optimizer.utils import debias_beta |
| 10 | + |
| 11 | + |
| 12 | +class StableAdamW(Optimizer, BaseOptimizer): |
| 13 | + r"""Stable and low-precision training for large-scale vision-language models. |
| 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 kahan_sum: bool. Enables Kahan summation for more accurate parameter updates when training in low precision |
| 19 | + (float16 or bfloat16). |
| 20 | + :param weight_decay: float. weight decay (L2 penalty). |
| 21 | + :param weight_decouple: bool. decoupled weight decay. |
| 22 | + :param eps: float. term added to the denominator to improve numerical stability. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + params: PARAMETERS, |
| 28 | + lr: float = 1e-3, |
| 29 | + betas: BETAS = (0.9, 0.99), |
| 30 | + kahan_sum: bool = True, |
| 31 | + weight_decay: float = 1e-2, |
| 32 | + weight_decouple: bool = True, |
| 33 | + eps: float = 1e-8, |
| 34 | + ): |
| 35 | + self.validate_learning_rate(lr) |
| 36 | + self.validate_betas(betas) |
| 37 | + self.validate_non_negative(weight_decay, 'weight_decay') |
| 38 | + self.validate_non_negative(eps, 'eps') |
| 39 | + |
| 40 | + defaults: DEFAULTS = { |
| 41 | + 'lr': lr, |
| 42 | + 'betas': betas, |
| 43 | + 'kahan_sum': kahan_sum, |
| 44 | + 'weight_decay': weight_decay, |
| 45 | + 'weight_decouple': weight_decouple, |
| 46 | + 'eps': eps, |
| 47 | + } |
| 48 | + |
| 49 | + super().__init__(params, defaults) |
| 50 | + |
| 51 | + def __str__(self) -> str: |
| 52 | + return 'StableAdamW' |
| 53 | + |
| 54 | + @torch.no_grad() |
| 55 | + def reset(self): |
| 56 | + for group in self.param_groups: |
| 57 | + group['step'] = 0 |
| 58 | + for p in group['params']: |
| 59 | + state = self.state[p] |
| 60 | + |
| 61 | + state['exp_avg'] = torch.zeros_like(p) |
| 62 | + state['exp_avg_sq'] = torch.zeros_like(p) |
| 63 | + |
| 64 | + state['kahan_comp'] = ( |
| 65 | + torch.zeros_like(p) if group['kahan_sum'] and p.dtype in {torch.float16, torch.bfloat16} else None |
| 66 | + ) |
| 67 | + |
| 68 | + @torch.no_grad() |
| 69 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 70 | + loss: LOSS = None |
| 71 | + if closure is not None: |
| 72 | + with torch.enable_grad(): |
| 73 | + loss = closure() |
| 74 | + |
| 75 | + for group in self.param_groups: |
| 76 | + if 'step' in group: |
| 77 | + group['step'] += 1 |
| 78 | + else: |
| 79 | + group['step'] = 1 |
| 80 | + |
| 81 | + beta1, beta2 = group['betas'] |
| 82 | + |
| 83 | + beta1_comp: float = 1.0 - debias_beta(beta1, group['step']) |
| 84 | + beta2_hat: float = debias_beta(beta2, group['step']) |
| 85 | + |
| 86 | + eps_p2: float = math.pow(group['eps'], 2) |
| 87 | + |
| 88 | + for p in group['params']: |
| 89 | + if p.grad is None: |
| 90 | + continue |
| 91 | + |
| 92 | + grad = p.grad |
| 93 | + if grad.is_sparse: |
| 94 | + raise NoSparseGradientError(str(self)) |
| 95 | + |
| 96 | + state = self.state[p] |
| 97 | + if len(state) == 0: |
| 98 | + state['exp_avg'] = torch.zeros_like(p) |
| 99 | + state['exp_avg_sq'] = torch.zeros_like(p) |
| 100 | + |
| 101 | + state['kahan_comp'] = ( |
| 102 | + torch.zeros_like(p) |
| 103 | + if (group['kahan_sum'] and p.dtype in {torch.float16, torch.bfloat16}) |
| 104 | + else None |
| 105 | + ) |
| 106 | + |
| 107 | + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] |
| 108 | + exp_avg.lerp_(grad, weight=beta1_comp) |
| 109 | + exp_avg_sq.mul_(beta2_hat).addcmul_(grad, grad, value=1.0 - beta2_hat) |
| 110 | + |
| 111 | + rms = grad.pow(2).div_(exp_avg_sq.clip(min=eps_p2)).mean().sqrt_() |
| 112 | + |
| 113 | + lr = group['lr'] / rms.clip(min=1.0) |
| 114 | + |
| 115 | + self.apply_weight_decay( |
| 116 | + p, |
| 117 | + p.grad, |
| 118 | + lr=lr, |
| 119 | + weight_decay=group['weight_decay'], |
| 120 | + weight_decouple=group['weight_decouple'], |
| 121 | + fixed_decay=False, |
| 122 | + ) |
| 123 | + |
| 124 | + if group['kahan_sum'] and p.dtype in {torch.float16, torch.bfloat16}: |
| 125 | + kahan_comp = state['kahan_comp'] |
| 126 | + kahan_comp.addcdiv_(exp_avg, exp_avg_sq.sqrt().add_(group['eps']), value=-lr) |
| 127 | + |
| 128 | + grad.copy_(p.detach()) |
| 129 | + p.add_(kahan_comp) |
| 130 | + |
| 131 | + kahan_comp.add_(grad.sub_(p)) |
| 132 | + else: |
| 133 | + p.addcdiv_(exp_avg, exp_avg_sq.sqrt().add_(group['eps']), value=-lr) |
| 134 | + |
| 135 | + return loss |
0 commit comments