|
| 1 | +import torch |
| 2 | +from torch.optim.optimizer import Optimizer |
| 3 | + |
| 4 | +from pytorch_optimizer.base.optimizer import BaseOptimizer |
| 5 | +from pytorch_optimizer.base.types import CLOSURE, DEFAULTS, LOSS, PARAMETERS |
| 6 | + |
| 7 | + |
| 8 | +class SM3(Optimizer, BaseOptimizer): |
| 9 | + r"""Memory-Efficient Adaptive Optimization. |
| 10 | +
|
| 11 | + Reference : https://github.com/Enealor/PyTorch-SM3/blob/master/src/SM3/SM3.py |
| 12 | +
|
| 13 | + :param params: PARAMETERS. iterable of parameters to optimize or dicts defining parameter groups. |
| 14 | + :param lr: float. learning rate. |
| 15 | + :param momentum: float. coefficient used to scale prior updates before adding. This drastically increases |
| 16 | + memory usage if `momentum > 0.0`. This is ignored if the parameter's gradient is sparse. |
| 17 | + :param beta: float. coefficient used for exponential moving averages. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + params: PARAMETERS, |
| 23 | + lr: float = 1e-1, |
| 24 | + momentum: float = 0.0, |
| 25 | + beta: float = 0.0, |
| 26 | + eps: float = 1e-30, |
| 27 | + ): |
| 28 | + self.lr = lr |
| 29 | + self.momentum = momentum |
| 30 | + self.beta = beta |
| 31 | + self.eps = eps |
| 32 | + |
| 33 | + self.validate_parameters() |
| 34 | + |
| 35 | + defaults: DEFAULTS = {'lr': lr, 'momentum': momentum, 'beta': beta} |
| 36 | + super().__init__(params, defaults) |
| 37 | + |
| 38 | + def validate_parameters(self): |
| 39 | + self.validate_learning_rate(self.lr) |
| 40 | + self.validate_momentum(self.momentum) |
| 41 | + self.validate_beta(self.beta) |
| 42 | + self.validate_epsilon(self.eps) |
| 43 | + |
| 44 | + def __str__(self) -> str: |
| 45 | + return 'SM3' |
| 46 | + |
| 47 | + @torch.no_grad() |
| 48 | + def reset(self): |
| 49 | + for group in self.param_groups: |
| 50 | + for p in group['params']: |
| 51 | + state = self.state[p] |
| 52 | + |
| 53 | + state['step'] = 0 |
| 54 | + state['momentum_buffer'] = torch.zeros_like(p) |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def max_reduce_except_dim(x: torch.Tensor, dim: int) -> torch.Tensor: |
| 58 | + r"""Perform reduce-max along all dimensions except the given dim.""" |
| 59 | + rank: int = len(x.shape) |
| 60 | + if rank == 0: |
| 61 | + return x |
| 62 | + |
| 63 | + if dim >= rank: |
| 64 | + raise ValueError(f'[-] given dim is bigger than rank. {dim} >= {rank}') |
| 65 | + |
| 66 | + for d in range(rank): |
| 67 | + if d != dim: |
| 68 | + x = x.max(dim=d, keepdim=True).values |
| 69 | + return x |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def make_sparse(grad: torch.Tensor, values: torch.Tensor) -> torch.Tensor: |
| 73 | + if grad._indices().dim() == 0 or values.dim() == 0: |
| 74 | + return grad.new().resize_as_(grad) |
| 75 | + return grad.new(grad._indices(), values, grad.size()) |
| 76 | + |
| 77 | + @torch.no_grad() |
| 78 | + def step(self, closure: CLOSURE = None) -> LOSS: |
| 79 | + loss: LOSS = None |
| 80 | + if closure is not None: |
| 81 | + with torch.enable_grad(): |
| 82 | + loss = closure() |
| 83 | + |
| 84 | + for group in self.param_groups: |
| 85 | + momentum, beta = group['momentum'], group['beta'] |
| 86 | + for p in group['params']: |
| 87 | + if p.grad is None: |
| 88 | + continue |
| 89 | + |
| 90 | + grad = p.grad |
| 91 | + |
| 92 | + shape = grad.shape |
| 93 | + rank: int = len(shape) |
| 94 | + |
| 95 | + state = self.state[p] |
| 96 | + if len(state) == 0: |
| 97 | + state['step'] = 0 |
| 98 | + state['momentum_buffer'] = torch.zeros_like(p) |
| 99 | + |
| 100 | + if grad.is_sparse: |
| 101 | + state['accumulator_0'] = torch.zeros(shape[0]) |
| 102 | + elif rank == 0: |
| 103 | + state['accumulator_0'] = torch.zeros(shape) |
| 104 | + else: |
| 105 | + for i in range(rank): |
| 106 | + state[f'accumulator_{i}'] = torch.zeros([1] * i + [shape[i]] + [1] * (rank - 1 - i)) |
| 107 | + |
| 108 | + state['step'] += 1 |
| 109 | + |
| 110 | + if grad.is_sparse: |
| 111 | + grad = grad.coalesce() |
| 112 | + |
| 113 | + acc = state['accumulator_0'] |
| 114 | + update_values = torch.gather(acc, 0, grad._indices()[0]) |
| 115 | + if beta > 0.0: |
| 116 | + update_values.mul_(beta) |
| 117 | + update_values.addcmul_(grad._values(), grad._values(), value=1.0 - beta) |
| 118 | + |
| 119 | + nu_max = self.max_reduce_except_dim( |
| 120 | + x=self.make_sparse(grad, update_values).to_dense(), |
| 121 | + dim=0, |
| 122 | + ).squeeze_() |
| 123 | + |
| 124 | + if beta > 0.0: |
| 125 | + torch.max(acc, nu_max, out=acc) |
| 126 | + else: |
| 127 | + acc.copy_(nu_max) |
| 128 | + |
| 129 | + update_values.add_(self.eps).rsqrt_().mul_(grad._values()) |
| 130 | + |
| 131 | + update = self.make_sparse(grad, update_values) |
| 132 | + else: |
| 133 | + update = state['accumulator_0'].clone() |
| 134 | + for i in range(1, rank): |
| 135 | + update = torch.min(update, state[f'accumulator_{i}']) |
| 136 | + |
| 137 | + if beta > 0.0: |
| 138 | + update.mul_(beta) |
| 139 | + update.addcmul_(grad, grad, value=1.0 - beta) |
| 140 | + |
| 141 | + for i in range(rank): |
| 142 | + acc = state[f'accumulator_{i}'] |
| 143 | + nu_max = self.max_reduce_except_dim(update, i) |
| 144 | + if beta > 0.0: |
| 145 | + torch.max(acc, nu_max, out=acc) |
| 146 | + else: |
| 147 | + acc.copy_(nu_max) |
| 148 | + |
| 149 | + update.add_(self.eps).rsqrt_().mul_(grad) |
| 150 | + |
| 151 | + if momentum > 0.0: |
| 152 | + m = state['momentum_buffer'] |
| 153 | + m.mul_(momentum).add_(update, alpha=1.0 - momentum) |
| 154 | + update = m |
| 155 | + |
| 156 | + p.add_(update, alpha=-group['lr']) |
| 157 | + |
| 158 | + return loss |
0 commit comments