-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
executable file
·204 lines (145 loc) · 6.78 KB
/
utils.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
'''Helper functions.
'''
import os
import glob
import torch
from pathlib import Path
def load_checkpoint(model_save_folder,
model_name,
mae_model,
load_checkpoint_epoch=None,
logger=None):
'''Loads either the latest model (if load_checkpoint_val is None) or loads the specific checkpoint.
'''
try:
checkpoint = None
if not load_checkpoint_epoch is None:
checkpoint = torch.load(f"{model_save_folder.rstrip('/')}/{model_name}-checkpoint-ep-{load_checkpoint_epoch}.pth.tar")
else:
checkpoint = torch.load(f"{model_save_folder.rstrip('/')}/{model_name}-latest.pth.tar")
mae_model.load_state_dict(checkpoint['mae_model']) #load the weights into the model
epoch = checkpoint['epoch']
if not logger is None:
logger.info(f"Checkpoint from epoch {epoch} is successfully loaded! Extracting the parameters to load to individual model/variabels now...")
except Exception as err:
if not logger is None:
logger.error(f"Error loading the model! {err}")
else:
print(err)
epoch = 0
return mae_model, epoch
def save_checkpoint(model_save_folder,
model_name,
mae_model,
scaler,
epoch,
loss,
N_models_to_keep,
logger=None,
):
'''Save model checkpoint.
'''
save_dict = {
'mae_model': mae_model.state_dict(),
'scaler': scaler,
'epoch': epoch, #useful for resuming training from the last epoch. And also to initialize the optimizer module's step.
'loss' : loss #record purposes.
}
try:
Path(f"{model_save_folder}").mkdir(parents=True, exist_ok=True) #create directory if doesn't exist.yy
torch.save(save_dict, f"{model_save_folder.rstrip('/')}/{model_name}-checkpoint-ep-{epoch}.pth.tar")
torch.save(save_dict, f"{model_save_folder.rstrip('/')}/{model_name}-latest.pth.tar")
if not logger is None:
logger.info(f"Model checkpoint save for epoch {epoch} is successful!")
#remove the unwanted models.
remove_old_models(N_models_to_keep=N_models_to_keep, model_save_folder=model_save_folder)
except Exception as err:
if not logger is None:
logger.error(f"Model checkpoint save for epoch {epoch} has failed! {err}")
else:
print(err)
return None
def remove_old_models(N_models_to_keep, model_save_folder):
'''Remove the old saved models based on the given paramters.
'''
all_models = []
for x in glob.glob(f'{model_save_folder.rstrip("/")}/**'):
all_models.append(x)
if len(all_models) > N_models_to_keep:
all_models.sort(key=lambda x: os.path.getctime(x)) #sorts the files based on their creation time.
unwanted_models = all_models[:-1*N_models_to_keep]
if len(unwanted_models) != 0:
#delete the old models.
for x in unwanted_models:
os.remove(x)
return None
def load_encoder_checkpoint(model_save_folder,
mae_model_name,
encoder_model,
load_checkpoint_epoch=None,
logger=None):
'''Loads only the encoder part of the MAE network for downstream purposes.
'''
try:
checkpoint = None
if not load_checkpoint_epoch is None:
checkpoint = torch.load(f"{model_save_folder.rstrip('/')}/{mae_model_name}-checkpoint-ep-{load_checkpoint_epoch}.pth.tar")
else:
checkpoint = torch.load(f"{model_save_folder.rstrip('/')}/{mae_model_name}-latest.pth.tar")
#to only load the patch embedding layers and the encoder transformer blocks into the new encoder model.
filtered_state_dict = {}
for k, v in checkpoint['mae_model'].items():
if 'encoder_transformer_blocks' in k or 'patch_embed' in k or 'encoder_norm' in k:
filtered_state_dict[k[7:]] = v #for some reason the keys here starts with 'module' while the new encoder model does not. So the 7: is to remove the 'module'.
encoder_model.load_state_dict(filtered_state_dict, strict=True) #load the weights into the model
epoch = checkpoint['epoch']
if not logger is None:
logger.info(f"Checkpoint from epoch {epoch} is successfully loaded! Extracting the parameters to load to individual model/variabels now...")
except Exception as err:
if not logger is None:
logger.error(f"Error loading the model! {err}")
else:
print(err)
epoch = 0
return encoder_model, epoch
def save_both_model_checkpoint(model_save_folder,
model_name,
pretrained_model,
finetuned_model,
scaler,
epoch,
loss,
N_models_to_keep,
logger=None,
):
'''Save both the pretrained and finetuned (downstream) model.
'''
save_dict = {
'pretrained_model': pretrained_model.state_dict(),
'finetuned_model': finetuned_model.state_dict(),
'scaler': scaler,
'epoch': epoch, #useful for resuming training from the last epoch. And also to initialize the optimizer module's step.
'loss' : loss #record purposes.
}
try:
Path(f"{model_save_folder}").mkdir(parents=True, exist_ok=True) #create directory if doesn't exist.yy
torch.save(save_dict, f"{model_save_folder.rstrip('/')}/{model_name}-checkpoint-ep-{epoch}.pth.tar")
torch.save(save_dict, f"{model_save_folder.rstrip('/')}/{model_name}-latest.pth.tar")
if not logger is None:
logger.info(f"Model checkpoint save for epoch {epoch} is successful!")
#remove the unwanted models.
remove_old_models(N_models_to_keep=N_models_to_keep, model_save_folder=model_save_folder)
except Exception as err:
if not logger is None:
logger.error(f"Model checkpoint save for epoch {epoch} has failed! {err}")
else:
print(err)
return None
def calculate_accuracy(predicted, target):
'''Calculates the accuracy of the prediction.
'''
num_data = target.size()[0]
predicted = torch.argmax(predicted, dim=1)
correct_pred = torch.sum(predicted == target)
accuracy = (correct_pred/num_data)*100
return accuracy.item()