-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
249 lines (232 loc) · 10.6 KB
/
main.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import torch
from utils import DatasetLoader,init_weights,OneCycle
import random, math, os, pickle, sys
import numpy as np
from tqdm import tqdm
from models.CNNBasic import CNNBasic
from models.Resnet18 import ResNet18
from models.VGG import VGG
from torchvision.transforms import RandomRotation
# Load config file
params = {'weight_decay_rate' : 1e-7,
'cyc_size' : 70,
'max_lr' : 5e-3,
'low_lr' : 1e-5,
'dec_scale' : 1,
'batch_size' : 32,
'tot_epochs' : 90,
'beta_weight' : 1,
'heterogeneous' : False,
'reflection' : True,
'mode' : 'R4',
'ratio' : [32,8,2,1],
'mplc_kernel_size' : [8,4,2,1],
'dataset' : 'rot_tim',
'model' : 'Resnet18',
'training' : True,
'save_dir':'ien_training'}
# Check if cuda available
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("Using",device,"for training...")
# Determining ChannelsMaxPool Layer characteristics
if params["heterogeneous"]:
mplc_kernel_size = params["mplc_kernel_size"]
if sum(mplc_kernel_size)==7 or sum(mplc_kernel_size)==14:
ratio = [8,2,1]
elif sum(mplc_kernel_size)==15:
ratio = [32,8,2,1]
else:
ratio = None
if params["reflection"] or params["mode"]=="R8":
mplc_kernel_size = 8
elif params["mode"]=="R4":
mplc_kernel_size = 4
else:
raise NameError("Only R4 and R8 modes are allowed")
# Loading dataset and model
print("loading",params["dataset"],"Dataset and",params["model"],"Model...")
if params["dataset"]=="rot_mnist":
if params["model"]=="BasicCNN":
model = CNNBasic(10,ratio,mplc_kernel_size).to(device)
model.apply(init_weights)
num_layers = 6
dataset = DatasetLoader(params["dataset"],params["batch_size"],params["training"])
else:
raise RuntimeError("Only BasicCNN is allowed with",params["dataset"])
elif params["dataset"]=="rot_tim":
if params["reflection"]:
dataset_dir = "ImageNet-rot-ref-masked/"
else:
dataset_dir = "ImageNet-rot-masked/"
if params["model"]=="VGG":
model = VGG(100, ratio, mplc_kernel_size).to(device)
num_layers = 8
dataset = DatasetLoader(dataset_dir,params["batch_size"],params["training"])
elif params["model"]=="Resnet18":
model = ResNet18(100, ratio, mplc_kernel_size).to(device)
num_layers = 4
dataset = DatasetLoader(dataset_dir,params["batch_size"],params["training"],resize=65)
else:
raise RuntimeError("Only VGG and Resnet18 are allowed with",params["dataset"])
else:
raise NameError("Dataset",params["dataset"],"is not available. Choose from: rot_mnist or rot_tim")
# setting up training parameters
classification_loss = torch.nn.CrossEntropyLoss()
equivariance_loss = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=params['low_lr'], weight_decay=params['weight_decay_rate'])
onecycle = OneCycle(math.ceil(dataset['train_size']/params['batch_size'])*params['cyc_size'], params['max_lr'], params['low_lr'], params['dec_scale'])
all_rotations = None
if params["mode"]=="R8" or (params["heterogeneous"] and params["mplc_kernel_size"][0]==8):
all_rotations = [(RandomRotation((x,x)),RandomRotation((-x,-x))) for x in range(45,360,45)]
# Training Loop
best_val_acc = 0
for epoch in range(params['tot_epochs']):
model.train()
running_loss1 = 0.0
running_loss2 = [0.0]*num_layers
running_corrects = 0
print("Epoch",epoch,": Starting training...")
for i,(inputs, labels) in enumerate(tqdm(dataset["train_loader"])):
inputs = inputs.to(device)
labels = labels.to(device)
tbs = labels.shape[0]
if all_rotations:
aug_rot = random.choices(all_rotations,k=tbs)
else:
aug_rot = random.choices(range(0,4),k=tbs) #(1,4)
if params["reflection"]:
aug_ref = random.choices(range(0,3),k=tbs)
for i in range(tbs):
if all_rotations:
augmented_input = aug_rot[i][0](inputs[i])
else:
augmented_input = torch.rot90(inputs[i], aug_rot[i], [-2, -1])
if params["reflection"]:
if aug_ref[i]==1:
augmented_input = torch.flip(augmented_input, (-2,))
elif aug_ref[i]==2:
augmented_input = torch.flip(augmented_input, (-1,))
inputs = torch.cat((inputs,augmented_input.unsqueeze(0)),0)
optimizer.zero_grad()
if epoch<params['cyc_size']:
lr = onecycle.calc()
for g in optimizer.param_groups:
g['lr'] = lr
outputs, temparr = model(inputs)
loss2 = []
for j in range(num_layers):
augmented_temp = temparr[j][tbs]
if params["reflection"]:
if aug_ref[0]==1:
augmented_temp = torch.flip(augmented_temp, (-2,))
elif aug_ref[0]==2:
augmented_temp = torch.flip(augmented_temp, (-1,))
if all_rotations:
augmented_temp = aug_rot[0][1](augmented_temp)
else:
augmented_temp = torch.rot90(augmented_temp, -aug_rot[0], [-2,-1])
temp_rot = augmented_temp.unsqueeze(0)
for i in range(1,tbs):
augmented_temp = temparr[j][tbs+i]
if params["reflection"]:
if aug_ref[i]==1:
augmented_temp = torch.flip(augmented_temp, (-2,))
elif aug_ref[i]==2:
augmented_temp = torch.flip(augmented_temp, (-1,))
if all_rotations:
augmented_temp = aug_rot[i][1](augmented_temp)
else:
augmented_temp = torch.rot90(augmented_temp, -aug_rot[i], [-2,-1])
temp_rot = torch.cat((temp_rot, augmented_temp.unsqueeze(0)),0)
loss2.append(equivariance_loss(temparr[j][:tbs],temp_rot))
labels = torch.cat((labels,labels))
_, preds = torch.max(outputs, 1)
loss1 = classification_loss(outputs, labels)
for i in range(num_layers):
loss1+=(params['beta_weight']*loss2[i])
loss1.backward()
optimizer.step()
running_loss1 += loss1.item() * inputs.size(0)
for i in range(num_layers):
running_loss2[i] += loss2[i].item() * tbs
running_corrects += torch.sum(preds == labels.data)
sys.stdout.flush()
train_class_loss = running_loss1 / (dataset['train_size']*2)
train_equi_loss = [running_loss2[i] / (dataset['train_size']) for i in range(num_layers)]
train_acc = running_corrects.double() / (dataset['train_size']*2)
train_tot_loss = train_class_loss + sum(train_equi_loss)
### Validation
print("Epoch",epoch,": Starting Validation...")
model.eval()
with torch.no_grad():
val_running_loss1 = 0.0
val_running_loss2 = [0.0]*num_layers
val_running_corrects = 0
for i,(inputs, labels) in enumerate(tqdm(dataset['test_loader'])):
inputs = inputs.to(device)
labels = labels.to(device)
tbs = labels.shape[0]
if all_rotations:
aug_rot = random.choices(all_rotations,k=tbs)
else:
aug_rot = random.choices(range(0,4),k=tbs) #(1,4)
if params["reflection"]:
aug_ref = random.choices(range(0,3),k=tbs)
for i in range(tbs):
if all_rotations:
augmented_input = aug_rot[i][0](inputs[i])
else:
augmented_input = torch.rot90(inputs[i], aug_rot[i], [-2, -1])
if params["reflection"]:
if aug_ref[i]==1:
augmented_input = torch.flip(augmented_input, (-2,))
elif aug_ref[i]==2:
augmented_input = torch.flip(augmented_input, (-1,))
inputs = torch.cat((inputs,augmented_input.unsqueeze(0)),0)
outputs, temparr = model(inputs)
_, preds = torch.max(outputs, 1)
loss2 = []
for j in range(num_layers):
augmented_temp = temparr[j][tbs]
if params["reflection"]:
if aug_ref[0]==1:
augmented_temp = torch.flip(augmented_temp, (-2,))
elif aug_ref[0]==2:
augmented_temp = torch.flip(augmented_temp, (-1,))
if all_rotations:
augmented_temp = aug_rot[0][1](augmented_temp)
else:
augmented_temp = torch.rot90(augmented_temp, -aug_rot[0], [-2,-1])
temp_rot = augmented_temp.unsqueeze(0)
for i in range(1,tbs):
augmented_temp = temparr[j][tbs+i]
if params["reflection"]:
if aug_ref[i]==1:
augmented_temp = torch.flip(augmented_temp, (-2,))
elif aug_ref[i]==2:
augmented_temp = torch.flip(augmented_temp, (-1,))
if all_rotations:
augmented_temp = aug_rot[i][1](augmented_temp)
else:
augmented_temp = torch.rot90(augmented_temp, -aug_rot[i], [-2,-1])
temp_rot = torch.cat((temp_rot, augmented_temp.unsqueeze(0)),0)
loss2.append(equivariance_loss(temparr[j][:tbs],temp_rot).item())
_, preds = torch.max(outputs, 1)
labels = torch.cat((labels,labels))
loss1 = classification_loss(outputs, labels)
val_running_loss1 += loss1.item() * inputs.size(0)
for i in range(num_layers):
val_running_loss2[i] += (loss2[i] * tbs)
val_running_corrects += torch.sum(preds == labels.data)
val_class_loss = val_running_loss1 / (dataset['test_size']*2)
val_equi_loss = [val_running_loss2[i] / dataset['test_size'] for i in range(num_layers)]
val_acc = val_running_corrects.double() / (dataset['test_size']*2)
val_tot_loss = val_class_loss + sum(val_equi_loss)
if not os.path.exists(params['save_dir']):
os.mkdir(params['save_dir'])
print(f"Epoch {epoch}: Train Acc {train_acc}, Train Total Loss {train_tot_loss}, Class Loss {train_class_loss}, Equi Loss {train_equi_loss} | ; | Val Acc {val_acc}, Val Total Loss {val_tot_loss}, Class Loss {val_class_loss}, Equi Loss {val_equi_loss}")
torch.save(model.state_dict(),params['save_dir']+"/last_model_weights.ckpt")
torch.save(optimizer.state_dict(),params['save_dir']+"/last_adam_settings.ckpt")
if val_acc>best_val_acc:
best_val_acc = val_acc
torch.save(model.state_dict(),params['save_dir']+"/best_model_weights.ckpt")