forked from facebookresearch/msn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsgd.py
53 lines (42 loc) · 1.69 KB
/
sgd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
from torch.optim import Optimizer
class SGD(Optimizer):
def __init__(self, params, lr, momentum=0, weight_decay=0, nesterov=False):
if lr < 0.0:
raise ValueError(f"Invalid learning rate: {lr}")
if weight_decay < 0.0:
raise ValueError(f"Invalid weight_decay value: {weight_decay}")
defaults = dict(lr=lr, momentum=momentum, weight_decay=weight_decay, nesterov=nesterov)
super(SGD, self).__init__(params, defaults)
@torch.no_grad()
def step(self):
for group in self.param_groups:
weight_decay = group["weight_decay"]
momentum = group["momentum"]
nesterov = group["nesterov"]
for p in group["params"]:
if p.grad is None:
continue
d_p = p.grad
if weight_decay != 0:
d_p = d_p.add(p, alpha=weight_decay)
d_p.mul_(-group["lr"])
if momentum != 0:
param_state = self.state[p]
if "momentum_buffer" not in param_state:
buf = param_state["momentum_buffer"] = d_p.clone().detach()
else:
buf = param_state["momentum_buffer"]
buf.mul_(momentum).add_(d_p)
if nesterov:
d_p.add_(buf, alpha=momentum)
else:
d_p = buf
p.add_(d_p)
return None