Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yiming-wange
GitHub Repository: yiming-wange/cs224n-2023-solution
Path: blob/main/minBERT/optimizer.py
984 views
1
from typing import Callable, Iterable, Tuple
2
import math
3
4
import torch
5
from torch.optim import Optimizer
6
7
8
class AdamW(Optimizer):
9
def __init__(
10
self,
11
params: Iterable[torch.nn.parameter.Parameter],
12
lr: float = 1e-3,
13
betas: Tuple[float, float] = (0.9, 0.999),
14
eps: float = 1e-6,
15
weight_decay: float = 0.0,
16
correct_bias: bool = True,
17
):
18
if lr < 0.0:
19
raise ValueError("Invalid learning rate: {} - should be >= 0.0".format(lr))
20
if not 0.0 <= betas[0] < 1.0:
21
raise ValueError("Invalid beta parameter: {} - should be in [0.0, 1.0[".format(betas[0]))
22
if not 0.0 <= betas[1] < 1.0:
23
raise ValueError("Invalid beta parameter: {} - should be in [0.0, 1.0[".format(betas[1]))
24
if not 0.0 <= eps:
25
raise ValueError("Invalid epsilon value: {} - should be >= 0.0".format(eps))
26
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, correct_bias=correct_bias)
27
super().__init__(params, defaults)
28
29
def step(self, closure: Callable = None):
30
loss = None
31
if closure is not None:
32
loss = closure()
33
34
for group in self.param_groups:
35
for p in group["params"]:
36
if p.grad is None:
37
continue
38
grad = p.grad.data
39
if grad.is_sparse:
40
raise RuntimeError("Adam does not support sparse gradients, please consider SparseAdam instead")
41
42
# State should be stored in this dictionary
43
state = self.state[p]
44
45
# Access hyperparameters from the `group` dictionary
46
alpha = group["lr"]
47
48
# Complete the implementation of AdamW here, reading and saving
49
# your state in the `state` dictionary above.
50
# The hyperparameters can be read from the `group` dictionary
51
# (they are lr, betas, eps, weight_decay, as saved in the constructor).
52
#
53
# 1- Update first and second moments of the gradients
54
# 2- Apply bias correction
55
# (using the "efficient version" given in https://arxiv.org/abs/1412.6980;
56
# also given in the pseudo-code in the project description).
57
# 3- Update parameters (p.data).
58
# 4- After that main gradient-based update, update again using weight decay
59
# (incorporating the learning rate again).
60
61
### TODO
62
device = "cuda" if torch.cuda.is_available() else "cpu"
63
if "t" not in state.keys():
64
state["t"] = 0
65
state["mt"] = torch.zeros(p.data.shape).to(device)
66
state["vt"] = torch.zeros(p.data.shape).to(device)
67
t = state["t"]
68
beta1 = group["betas"][0]
69
beta2 = group["betas"][1]
70
lr = group["lr"]
71
state["t"] = t + 1
72
state["mt"] = beta1*state["mt"] + (1-beta1)*grad
73
state["vt"] = beta2*state["vt"] + (1-beta2)*(torch.mul(grad,grad))
74
75
state["alphat"] = (lr * math.sqrt(1-beta2**state["t"]))/(1-beta1**state["t"])
76
p.data = p.data - (state["alphat"]*state["mt"]/(torch.sqrt(state["vt"]) + group["eps"]))
77
p.data = p.data - lr * group["weight_decay"] * p.data
78
79
return loss
80
81