forked from lilanpei/Continual-Calibration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContinual_Calibration.py
210 lines (195 loc) · 9.41 KB
/
Continual_Calibration.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Continual calibration via temperature scaling
Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger
On Calibration of Modern Neural Networks.
Adapted from: https://github.com/gpleiss/temperature_scaling
"""
import torch as th
import numpy as np
from avalanche.training.supervised import Naive, JointTraining, Replay, DER
from avalanche.benchmarks.utils import make_classification_dataset, AvalancheDataset, AvalancheConcatDataset, AvalancheSubset
from ModelDecorator import ModelWithTemperature, MatrixAndVectorScaling
from typing import Iterable
class Continual_Calibration:
def __init__(self,
tb_logger,
model,
optimizer,
plugins,
criterion,
strategy_name,
benchmark,
train_mb_size,
train_epochs,
mem_size,
eval_mb_size,
eval_plugin,
device,
pp_calibration_mode,
pp_cal_mixed_data,
pp_cal_vector_scaling,
pp_cal_matrix_scaling,
calibration_mode_str,
num_classes,
lrpp,
max_iter,
num_bins,
batch_size_mem,
alpha,
beta,
logdir
):
self.lrpp = lrpp
self.max_iter = max_iter
self.tb_logger = tb_logger
self.model = model
self.num_classes = num_classes
self.strategy_name = strategy_name
self.benchmark = benchmark
self.mem_size = mem_size
self.train_mb_size = train_mb_size
self.train_epochs = train_epochs
self.eval_mb_size = eval_mb_size
self.batch_size_mem=batch_size_mem
self.alpha=alpha
self.beta=beta
self.device = device
self.eval_plugin = eval_plugin
self.optimizer = optimizer
self.criterion = criterion
self.pp_calibration_mode = pp_calibration_mode
self.pp_cal_mixed_data = pp_cal_mixed_data
self.pp_cal_vector_scaling = pp_cal_vector_scaling
self.pp_cal_matrix_scaling = pp_cal_matrix_scaling
self.calibration_mode_str = calibration_mode_str
self.num_bins = num_bins
self.log_dir = logdir
if self.strategy_name == "JointTraining":
self.strategy = JointTraining(
self.model,
optimizer,
self.criterion,
train_mb_size=self.train_mb_size,
train_epochs=self.train_epochs,
eval_mb_size=self.eval_mb_size,
evaluator=self.eval_plugin,
plugins=plugins,
eval_every=1,
device=self.device
)
else:
if self.strategy_name == "Replay":
self.strategy = Replay(
self.model,
self.optimizer,
mem_size=self.mem_size,
criterion=self.criterion,
train_mb_size=self.train_mb_size,
train_epochs=self.train_epochs,
eval_mb_size=self.eval_mb_size,
evaluator=self.eval_plugin,
plugins=plugins,
eval_every=1,
device=self.device
)
elif self.strategy_name == "DER":
self.strategy = DER(
self.model,
self.optimizer,
mem_size=self.mem_size,
criterion=self.criterion,
train_mb_size=self.train_mb_size,
batch_size_mem=self.batch_size_mem,
alpha=self.alpha,
beta=self.beta,
train_epochs=self.train_epochs,
eval_mb_size=self.eval_mb_size,
evaluator=self.eval_plugin,
plugins=plugins,
eval_every=1,
device=self.device
)
else:
self.strategy = Naive(
self.model,
self.optimizer,
criterion=self.criterion,
train_mb_size=self.train_mb_size,
train_epochs=self.train_epochs,
eval_mb_size=self.eval_mb_size,
evaluator=self.eval_plugin,
plugins=plugins,
eval_every=1,
device=self.device
)
# TRAINING LOOP
def train(self,):
print('Starting experiment...')
results = []
val_experiences_list = []
for exp in self.benchmark.valid_stream:
if isinstance(exp, Iterable):
val_experiences_list.extend(exp.dataset)
else:
val_experiences_list.append(exp.dataset)
val_experiences_list = AvalancheDataset(val_experiences_list)
if self.strategy_name == "JointTraining":
self.strategy.train(self.benchmark.train_stream, eval_streams=[self.benchmark.valid_stream])
print('Training completed')
if self.pp_calibration_mode:
# for parameters in self.strategy.model.parameters():
# print(parameters.size())
# print(parameters)
if self.pp_cal_vector_scaling:
self.strategy.model = MatrixAndVectorScaling(self.strategy.model, self.device, self.num_classes, self.num_bins, True)
elif self.pp_cal_matrix_scaling:
self.strategy.model = MatrixAndVectorScaling(self.strategy.model, self.device, self.num_classes, self.num_bins)
else:
self.strategy.model = ModelWithTemperature(self.strategy.model, self.device, self.num_bins)
self.strategy.model.calibrate(self.lrpp, self.max_iter, val_experiences_list)
# for parameters in self.strategy.model.parameters():
# print(parameters.size())
# print(parameters)
print('Computing accuracy on the whole test set')
# test also returns a dictionary which contains all the metric values
results.append(self.strategy.eval(self.benchmark.test_stream))
th.save(self.strategy.model.state_dict(), f"{self.log_dir}/model_{self.strategy_name}_{self.calibration_mode_str}.pt")
else:
buffer_val = None
# weights_pre_exp = None
# bias_pre_exp = None
# temperature_pre_exp = None
for experience_tr, experience_val in zip(self.benchmark.train_stream, self.benchmark.valid_stream):
print("############### Start of experience: ", experience_tr.current_experience)
print("Current Classes: ", experience_tr.classes_in_this_experience)
# train returns a dictionary which contains all the metric values
self.strategy.train(experience_tr, eval_streams=[experience_val])
print('Training completed')
if self.pp_calibration_mode:
if experience_tr.current_experience == 0:
if self.pp_cal_vector_scaling:
self.strategy.model = MatrixAndVectorScaling(self.strategy.model, self.device, self.num_classes, True)
elif self.pp_cal_matrix_scaling:
self.strategy.model = MatrixAndVectorScaling(self.strategy.model, self.device, self.num_classes, self.num_bins)
else:
self.strategy.model = ModelWithTemperature(self.strategy.model, self.device, self.num_bins)
experience_val_data = make_classification_dataset(experience_val.dataset)
if buffer_val and self.pp_cal_mixed_data:
buffer_length = len(experience_val_data)
indices = list(range(buffer_length))
np.random.shuffle(indices)
val_split_index = int(np.floor(0.4 * buffer_length))
new_buffer = AvalancheSubset(experience_val_data, indices[:val_split_index])
buffer_val = AvalancheConcatDataset([new_buffer, buffer_val])
else:
buffer_val = experience_val_data
# print("!!!!!!! VAL Classes: !!!!!!!", experience_val.previous_classes, experience_val.classes_in_this_experience, len(buffer_val))
self.strategy.model.calibrate(self.lrpp, self.max_iter, buffer_val)
print('Computing accuracy on the whole test set')
# test also returns a dictionary which contains all the metric values
results.append(self.strategy.eval(self.benchmark.test_stream))
# store model after each experience
th.save(
self.strategy.model.state_dict(),
f"{self.log_dir}/model_{self.strategy_name}_{self.calibration_mode_str}_exp{experience_tr.current_experience}.pt"
)
return results