-
Notifications
You must be signed in to change notification settings - Fork 44
/
cbp.py
85 lines (74 loc) · 2.56 KB
/
cbp.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from torch import optim
from lop.algos.gnt import GnT
from lop.utils.AdamGnT import AdamGnT
import torch.nn.functional as F
class ContinualBackprop(object):
"""
The Continual Backprop algorithm, used in https://arxiv.org/abs/2108.06325v3
"""
def __init__(
self,
net,
step_size=0.001,
loss='mse',
opt='sgd',
beta=0.9,
beta_2=0.999,
replacement_rate=0.001,
decay_rate=0.9,
device='cpu',
maturity_threshold=100,
util_type='contribution',
init='kaiming',
accumulate=False,
momentum=0,
outgoing_random=False,
weight_decay=0
):
self.net = net
# define the optimizer
if opt == 'sgd':
self.opt = optim.SGD(self.net.parameters(), lr=step_size, momentum=momentum, weight_decay=weight_decay)
elif opt == 'adam':
self.opt = AdamGnT(self.net.parameters(), lr=step_size, betas=(beta, beta_2), weight_decay=weight_decay)
# define the loss function
self.loss_func = {'nll': F.cross_entropy, 'mse': F.mse_loss}[loss]
# a placeholder
self.previous_features = None
# define the generate-and-test object for the given network
self.gnt = None
self.gnt = GnT(
net=self.net.layers,
hidden_activation=self.net.act_type,
opt=self.opt,
replacement_rate=replacement_rate,
decay_rate=decay_rate,
maturity_threshold=maturity_threshold,
util_type=util_type,
device=device,
loss_func=self.loss_func,
init=init,
accumulate=accumulate,
)
def learn(self, x, target):
"""
Learn using one step of gradient-descent and generate-&-test
:param x: input
:param target: desired output
:return: loss
"""
# do a forward pass and get the hidden activations
output, features = self.net.predict(x=x)
loss = self.loss_func(output, target)
self.previous_features = features
# do the backward pass and take a gradient step
self.opt.zero_grad()
loss.backward()
self.opt.step()
# take a generate-and-test step
self.opt.zero_grad()
if type(self.gnt) is GnT:
self.gnt.gen_and_test(features=self.previous_features)
if self.loss_func == F.cross_entropy:
return loss.detach(), output.detach()
return loss.detach()