-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEwc_class.py
184 lines (147 loc) · 6.32 KB
/
Ewc_class.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import sys
sys.path.append('../')
import copy
import numpy as np
import os
import shutil
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch import autograd
from torch.autograd import Variable
class EWC(object):
def __init__(self, model: nn.Module, cuda, lamda=40):
self.model = model
#self.dataset = dataset
self._is_on_cuda = cuda
self.lamda = lamda
def estimate_fisher(self, data_loader, sample_size, batch_size=32):
loglikelihoods = []
for x, y in data_loader:
x = Variable(x).cuda() if self._is_on_cuda else Variable(x)
y = Variable(y).cuda() if self._is_on_cuda else Variable(y)
loglikelihoods.append(F.log_softmax(self.model(x), dim=1)[range(batch_size), y.data])
if len(loglikelihoods) >= 1:
break
print("Estimate the fisher information of the parameters:\n one")
loglikelihoods = torch.cat(loglikelihoods).unbind()
loglikelihood_grads = zip(*[autograd.grad(l, self.model.parameters(), retain_graph=(i < len(loglikelihoods)), allow_unused=True) \
for i, l in enumerate(loglikelihoods, 1)])
print("next:")
fisher_diagonals = []
os.system("nvidia-smi")
for gs in loglikelihood_grads:
try:
gs = torch.stack(gs)
g = 0
for _b in range(gs.shape[0]):
g += (gs[_b]).pow(2)
g /= gs.shape[0]
fisher_diagonals.append(g)
except:
print("========> Why am i here? <========")
continue
torch.cuda.empty_cache()
param_names = [n.replace('.', '__') for n, p in self.model.named_parameters()]
return {n: f.detach() for n, f in zip(param_names, fisher_diagonals)}
def consolidate(self, fisher):
for n, p in self.model.named_parameters():
n = n.replace('.', '__')
try:
self.model.register_buffer('{}_mean'.format(n), p.data.clone())
self.model.register_buffer('{}_fisher'.format(n), fisher[n].data.clone())
except:
continue
def ewc_loss(self, cuda=False):
try:
losses = []
for index, (n, p) in enumerate(self.model.named_parameters()):
# retrieve the consolidated mean and fisher information.
if index<16 or index>27:
continue
n = n.replace('.', '__')
mean = getattr(self, '{}_mean'.format(n))
fisher = getattr(self, '{}_fisher'.format(n))
mean = Variable(mean)
fisher = Variable(fisher)
# calculate a ewc loss. (assumes the parameter's prior as gaussian distribution with the estimated mean and the
# estimated cramer-rao lower bound variance, which is equivalent to the inverse of fisher information)
losses.append((fisher * (p-mean)**2).sum())
print("ewc loss > 0")
return (self.lamda/2)*sum(losses)
except AttributeError:
return (
Variable(torch.zeros(1)).cuda() if cuda else
Variable(torch.zeros(1))
)
class EWC_vgg(object):
def __init__(self, model: nn.Module, cuda, lamda=40 ):
self.model = model
self._is_on_cuda = cuda
self.lamda = lamda
def estimate_fisher(self, data_loader, sample_size, batch_size=32):
loglikelihoods = []
for x, y in data_loader:
x = Variable(x).cuda() if self._is_on_cuda else Variable(x)
y = Variable(y).cuda() if self._is_on_cuda else Variable(y)
loglikelihoods.append(
F.log_softmax(self.model(x), dim=1)[range(batch_size), y.data]
)
if len(loglikelihoods) >= sample_size // batch_size:
break
print("Estimate the fisher information of the parameters:\n one")
loglikelihoods = torch.cat(loglikelihoods).unbind()
loglikelihood_grads = zip(*[autograd.grad(
l, self.model.parameters(),
retain_graph=(i < len(loglikelihoods)),
allow_unused=True
) for i, l in enumerate(loglikelihoods, 1)])
print("next:")
fisher_diagonals = []
os.system("nvidia-smi")
for gs in loglikelihood_grads:
try:
gs = torch.stack(gs)
g = 0
for _b in range(gs.shape[0]):
g += (gs[_b]).pow(2)
g /= gs.shape[0]
fisher_diagonals.append(g)
except:
print("========> Why am i here? <========")
continue
torch.cuda.empty_cache()
param_names = [
n.replace('.', '__') for n, p in self.model.named_parameters()
]
return {n: f.detach() for n, f in zip(param_names, fisher_diagonals)}
def consolidate(self, fisher):
for n, p in self.model.named_parameters():
n = n.replace('.', '__')
try:
self.model.register_buffer('{}_mean'.format(n), p.data.clone())
self.model.register_buffer('{}_fisher'.format(n), fisher[n].data.clone())
except:
continue
def ewc_loss(self, cuda=False):
try:
losses = []
for index, (n, p) in enumerate(self.model.named_parameters()):
if index<34 or index>45:
continue
n = n.replace('.', '__')
mean = getattr(self, '{}_mean'.format(n))
fisher = getattr(self, '{}_fisher'.format(n))
mean = Variable(mean)
fisher = Variable(fisher)
losses.append((fisher * (p-mean)**2).sum())
print("ewc loss > 0")
return (self.lamda/2)*sum(losses)
except AttributeError:
return (
Variable(torch.zeros(1)).cuda() if cuda else
Variable(torch.zeros(1))
)