|
| 1 | +from typing import Literal |
| 2 | + |
| 3 | +import torch |
| 4 | + |
| 5 | +from pytorch_optimizer.base.exception import NoSparseGradientError |
| 6 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 7 | +from pytorch_optimizer.base.type import CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 8 | +from pytorch_optimizer.optimizer.shampoo_utils import zero_power_via_newton_schulz_5 |
| 9 | + |
| 10 | +LMO_TYPE = Literal['spectral', 'sign', 'col_norm', 'row_norm'] |
| 11 | + |
| 12 | + |
| 13 | +class SCION(BaseOptimizer): |
| 14 | + r"""Training Deep Learning Models with Norm-Constrained LMOs. |
| 15 | +
|
| 16 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 17 | + :param lr: float. learning rate. |
| 18 | + :param momentum: float. momentum factor. |
| 19 | + :param constraint: bool. whether to use a constraint SCG or not. |
| 20 | + :param lmo_type: LMO_TYPE. supported LMO types. |
| 21 | + :param weight_decay: float. weight decay (L2 penalty). |
| 22 | + :param weight_decouple: bool. the optimizer uses decoupled weight decay as in AdamW. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + params: PARAMETERS, |
| 28 | + lr: float = 1e-4, |
| 29 | + momentum: float = 0.1, |
| 30 | + constraint: bool = False, |
| 31 | + lmo_type: LMO_TYPE = 'spectral', |
| 32 | + weight_decay: float = 0.0, |
| 33 | + weight_decouple: bool = True, |
| 34 | + **kwargs, |
| 35 | + ): |
| 36 | + self.validate_learning_rate(lr) |
| 37 | + self.validate_range(momentum, 'momentum', 0.0, 1.0, '(]') |
| 38 | + self.validate_options(lmo_type, 'lmo_type', ['spectral', 'sign', 'col_norm', 'row_norm']) |
| 39 | + |
| 40 | + defaults: DEFAULTS = { |
| 41 | + 'lr': lr, |
| 42 | + 'momentum': momentum, |
| 43 | + 'constraint': constraint, |
| 44 | + 'lmo_type': lmo_type, |
| 45 | + 'weight_decay': weight_decay, |
| 46 | + 'weight_decouple': weight_decouple, |
| 47 | + } |
| 48 | + super().__init__(params, defaults) |
| 49 | + |
| 50 | + def __str__(self) -> str: |
| 51 | + return 'SCION' |
| 52 | + |
| 53 | + @torch.no_grad() |
| 54 | + def reset(self): |
| 55 | + for group in self.param_groups: |
| 56 | + for p in group['params']: |
| 57 | + state = self.state[p] |
| 58 | + state['d'] = torch.zeros_like(p) |
| 59 | + |
| 60 | + @staticmethod |
| 61 | + def get_lmo_direction(grad: torch.Tensor, lmo_type: str) -> torch.Tensor: |
| 62 | + r"""Get LMO direction.""" |
| 63 | + if lmo_type == 'spectral' and grad.ndim == 2: |
| 64 | + return zero_power_via_newton_schulz_5(grad) |
| 65 | + if lmo_type == 'sign': |
| 66 | + return torch.sign(grad) |
| 67 | + if lmo_type == 'col_norm': |
| 68 | + return grad / torch.norm(grad, dim=0, keepdim=True).add_(1e-6) |
| 69 | + if lmo_type == 'row_norm' and grad.ndim == 2: |
| 70 | + return grad / torch.norm(grad, dim=1, keepdim=True).add_(1e-6) |
| 71 | + return torch.sign(grad) |
| 72 | + |
| 73 | + @torch.no_grad() |
| 74 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 75 | + loss: LOSS = None |
| 76 | + if closure is not None: |
| 77 | + with torch.enable_grad(): |
| 78 | + loss = closure() |
| 79 | + |
| 80 | + for group in self.param_groups: |
| 81 | + step_size: float = -group['lr'] |
| 82 | + for p in group['params']: |
| 83 | + if p.grad is None: |
| 84 | + continue |
| 85 | + |
| 86 | + grad = p.grad |
| 87 | + if grad.is_sparse: |
| 88 | + raise NoSparseGradientError(str(self)) |
| 89 | + |
| 90 | + state = self.state[p] |
| 91 | + if 'd' not in state: |
| 92 | + state['d'] = torch.zeros_like(p) |
| 93 | + |
| 94 | + d = state['d'] |
| 95 | + d.mul_(1.0 - group['momentum']).add_(grad, alpha=group['momentum']) |
| 96 | + |
| 97 | + update = self.get_lmo_direction(d, group['lmo_type']) |
| 98 | + |
| 99 | + if not group['constraint']: |
| 100 | + self.apply_weight_decay( |
| 101 | + p, |
| 102 | + grad, |
| 103 | + lr=group['lr'], |
| 104 | + weight_decay=group['weight_decay'], |
| 105 | + weight_decouple=group['weight_decouple'], |
| 106 | + fixed_decay=False, |
| 107 | + ) |
| 108 | + |
| 109 | + p.add_(update, alpha=step_size) |
| 110 | + else: |
| 111 | + p.mul_(1.0 - step_size).add_(update, alpha=step_size) |
| 112 | + |
| 113 | + return loss |
0 commit comments