|
1 | 1 | import math
|
2 |
| -import numpy as np |
| 2 | +import torch |
| 3 | +from torch.optim import Optimizer |
| 4 | +from torch.nn.utils import clip_grad_norm |
3 | 5 |
|
4 | 6 | def warmup_cosine(x, warmup=0.002):
|
5 |
| - pass |
| 7 | + s = 1 if x <= warmup else 0 |
| 8 | + return s*(x/warmup) + (1-s)*(0.5 * (1 + torch.cos(math.pi * x))) |
6 | 9 |
|
7 | 10 | def warmup_constant(x, warmup=0.002):
|
8 |
| - pass |
| 11 | + s = 1 if x <= warmup else 0 |
| 12 | + return s*(x/warmup) + (1-s)*1 |
9 | 13 |
|
10 | 14 | def warmup_linear(x, warmup=0.002):
|
11 |
| - pass |
| 15 | + s = 1 if x <= warmup else 0 |
| 16 | + return (s*(x/warmup) + (1-s))*(1-x) |
12 | 17 |
|
13 |
| -schedules = { |
| 18 | +SCHEDULES = { |
14 | 19 | 'warmup_cosine':warmup_cosine,
|
15 | 20 | 'warmup_constant':warmup_constant,
|
16 | 21 | 'warmup_linear':warmup_linear,
|
17 | 22 | }
|
18 | 23 |
|
19 |
| -def adam(params, grads, lr, schedule, t_total, b1=0.9, b2=0.999, e=1e-8, l2=0, vector_l2=False, max_grad_norm=-1, **kwargs): |
20 |
| - """ |
21 |
| - adam with weight decay fix |
| 24 | + |
| 25 | +class OpenAIAdam(Optimizer): |
| 26 | + """Implements Open AI version of Adam algorithm with weight decay fix. |
22 | 27 | """
|
23 |
| - pass |
| 28 | + def __init__(self, params, lr, schedule, warmup, t_total, |
| 29 | + b1=0.9, b2=0.999, e=1e-8, l2=0, |
| 30 | + vector_l2=False, max_grad_norm=-1, **kwargs): |
| 31 | + if not 0.0 <= lr: |
| 32 | + raise ValueError("Invalid learning rate: {}".format(lr)) |
| 33 | + if schedule not in SCHEDULES: |
| 34 | + raise ValueError("Invalid schedule parameter: {}".format(schedule)) |
| 35 | + if not 0 <= warmup: |
| 36 | + raise ValueError("Invalid warmup: {}".format(warmup)) |
| 37 | + if not 0.0 <= b1 < 1.0: |
| 38 | + raise ValueError("Invalid b1 parameter: {}".format(b1)) |
| 39 | + if not 0.0 <= b2 < 1.0: |
| 40 | + raise ValueError("Invalid b2 parameter: {}".format(b2)) |
| 41 | + if not 0.0 <= e: |
| 42 | + raise ValueError("Invalid epsilon value: {}".format(e)) |
| 43 | + defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, |
| 44 | + b1=b1, b2=b2, e=e, l2=l2, vector_l2=vector_l2, |
| 45 | + max_grad_norm=max_grad_norm) |
| 46 | + super(OpenAIAdam, self).__init__(params, defaults) |
| 47 | + |
| 48 | + def step(self, closure=None): |
| 49 | + """Performs a single optimization step. |
| 50 | +
|
| 51 | + Arguments: |
| 52 | + closure (callable, optional): A closure that reevaluates the model |
| 53 | + and returns the loss. |
| 54 | + """ |
| 55 | + loss = None |
| 56 | + if closure is not None: |
| 57 | + loss = closure() |
| 58 | + |
| 59 | + for group in self.param_groups: |
| 60 | + for p in group['params']: |
| 61 | + if p.grad is None: |
| 62 | + continue |
| 63 | + grad = p.grad.data |
| 64 | + if grad.is_sparse: |
| 65 | + raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') |
| 66 | + |
| 67 | + state = self.state[p] |
| 68 | + |
| 69 | + # State initialization |
| 70 | + if len(state) == 0: |
| 71 | + state['step'] = 0 |
| 72 | + # Exponential moving average of gradient values |
| 73 | + state['exp_avg'] = torch.zeros_like(p.data) |
| 74 | + # Exponential moving average of squared gradient values |
| 75 | + state['exp_avg_sq'] = torch.zeros_like(p.data) |
| 76 | + |
| 77 | + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] |
| 78 | + beta1, beta2 = group['b1'], group['b2'] |
| 79 | + |
| 80 | + state['step'] += 1 |
| 81 | + |
| 82 | + # Add grad clipping |
| 83 | + if group['max_grad_norm'] > 0: |
| 84 | + clip_grad_norm(p, group['max_grad_norm']) |
| 85 | + |
| 86 | + # Decay the first and second moment running average coefficient |
| 87 | + exp_avg.mul_(beta1).add_(1 - beta1, grad) |
| 88 | + exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) |
| 89 | + denom = exp_avg_sq.sqrt().add_(group['eps']) |
| 90 | + |
| 91 | + bias_correction1 = 1 - beta1 ** state['step'] |
| 92 | + bias_correction2 = 1 - beta2 ** state['step'] |
| 93 | + |
| 94 | + schedule_fct = SCHEDULES[group['schedule']] |
| 95 | + lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup']) |
| 96 | + step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1 |
| 97 | + |
| 98 | + p.data.addcdiv_(-step_size, exp_avg, denom) |
| 99 | + |
| 100 | + # Add weight decay at the end (fixed version) |
| 101 | + if (len(p.size()) > 1 or group['vector_l2']) and group['l2'] > 0: |
| 102 | + p.data.add_(-lr_scheduled * group['l2'], p.data) |
| 103 | + |
| 104 | + return loss |
0 commit comments