-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_only_sum.py
197 lines (175 loc) · 7.07 KB
/
train_only_sum.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
from dataset.create_ds import check_dataset
from dataset.load_ds import load_data, nMNIST
from models.model import CUSTOM_OPERATION, ALIGNED_CUSTOM_OPERATION, ADDITION_JOINT, ADDITION_SPLIT
import torch
from argparse import Namespace
import os
from tqdm import tqdm
import numpy as np
args = Namespace()
args.data_location = 'C:/Users/debryu/Desktop/VS_CODE/HOME/ML/data/'
args.data_folder = 'custom_task'
args.num_epochs = 1000000
args.batch_size = 128
args.num_workers = 1
args.eval_check = 10
args.file_name = 'das_summation_dataset_no_interventions'
args.sequence_len = 2
args.lr_joint = 1e-3
args.lr_split = 1e-3
args.patience = 3
args.train_examples = 10000
args.test_examples = 10000
args.model_save_path = "C:/Users/debryu/Desktop/VS_CODE/HOME/ML/data/models/"
args.saved_model_name = 'entangled'
args.custom_task = False
n_digits=10
args.num_images = args.sequence_len
args.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dataset_dimensions= {f'{args.file_name}_train':args.train_examples, f'{args.file_name}_test': args.test_examples}
data_folder = os.path.join(args.data_location, args.data_folder)
def sum_calculator(concepts: torch.Tensor):
'''Calculate the sum of the labels'''
sum = concepts[:,0] + concepts[:,1]
return sum
def accuracy(model,dl):
'''Calculate the accuracy of the MNIST addition model'''
correct = 0
total = 0
for imgs,labels,concepts in dl:
if model.model_type == 'only_sum_joint':
out, _,_,_,_,_,_ = model(imgs.to(args.device))
else:
out, _,_,_,_,_ = model(imgs.to(args.device))
pred_output = torch.argmax(out,dim=-1)
i_labels = labels.to(args.device)
correct += torch.sum(pred_output == i_labels)
total += len(i_labels)
print(f"Accuracy: {correct/total}")
return correct/total
def train_split(train_dl,test_dl,args):
'''Train the split model for simple MNIST addition task'''
model = ADDITION_SPLIT(args = args)
model = model.to(args.device)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr_split)
learning_rate_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
patience = 0
max_lr_decrease = 5
best_accuracy = 0
model.train()
lr_decrease = 0
for epoch in range(args.num_epochs):
train_losses = []
for imgs,labels,concepts in tqdm(train_dl):
sum = sum_calculator(concepts)
#rhs = rhs.type(torch.LongTensor).to(args.device)
sum = sum.type(torch.LongTensor).to(args.device)
out, _,_,_,_,_ = model(imgs.to(args.device))
loss = criterion(out, sum)
train_losses.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_losses.append(loss.item())
print(f"Epoch {epoch} loss: {np.mean(train_losses)}")
if epoch % args.eval_check == 0:
eval_losses = []
model.eval()
for imgs,labels,concepts in test_dl:
# Concepts size: batch_size x 4
sum = sum_calculator(concepts)
#rhs = rhs.type(torch.LongTensor).to(args.device)
sum = sum.type(torch.LongTensor).to(args.device)
out, _,_,_,_,_ = model(imgs.to(args.device))
loss = criterion(out, sum)
eval_losses.append(loss.item())
avg_loss = np.mean(eval_losses)
print(f"Epoch {epoch} test loss: {avg_loss}")
acc = accuracy(model, test_dl)
if acc > best_accuracy:
patience = 0
best_accuracy = acc
torch.save(model.state_dict(), args.model_save_path + args.file_name + f"_best_{args.saved_model_name}_{epoch}.pt")
else:
patience += 1
if patience > args.patience:
print("Decreasing LR")
learning_rate_scheduler.step()
lr_decrease += 1
patience = 0
if lr_decrease > max_lr_decrease:
break
def train_joint(train_dl,test_dl,args):
'''Train the joint model for simple MNIST addition task'''
model = ADDITION_JOINT(args = args)
model = model.to(args.device)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr_joint)
learning_rate_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
patience = 0
max_lr_decrease = 6
best_accuracy = 0
model.train()
lr_decrease = 0
for epoch in range(args.num_epochs):
train_losses = []
for imgs,labels,concepts in tqdm(train_dl):
sum = sum_calculator(concepts)
sum = sum.type(torch.LongTensor).to(args.device)
out,_,_,_,_,_,_ = model(imgs.to(args.device))
loss = criterion(out, sum)
train_losses.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_losses.append(loss.item())
print(f"Epoch {epoch} loss: {np.mean(train_losses)}")
if epoch % args.eval_check == 0:
eval_losses = []
model.eval()
for imgs,labels,concepts in test_dl:
# Concepts size: batch_size x 4
sum = sum_calculator(concepts)
#rhs = rhs.type(torch.LongTensor).to(args.device)
sum = sum.type(torch.LongTensor).to(args.device)
out,_,_,_,_,_,_ = model(imgs.to(args.device))
loss = criterion(out, sum)
eval_losses.append(loss.item())
avg_loss = np.mean(eval_losses)
print(f"Epoch {epoch} test loss: {avg_loss}")
acc = accuracy(model, test_dl)
if acc > best_accuracy:
patience = 0
best_accuracy = acc
torch.save(model.state_dict(), args.model_save_path + args.file_name + f"_best_{args.saved_model_name}_{epoch}.pt")
else:
patience += 1
if patience > args.patience:
print("Decreasing LR")
learning_rate_scheduler.step()
lr_decrease += 1
patience = 0
if lr_decrease > max_lr_decrease:
break
def main():
# Check whether dataset exists, if not build it
check_dataset(n_digits, args.sequence_len, data_folder, args.file_name, dataset_dimensions, custom_task=args.custom_task)
train_ds,test_ds = load_data(data_file=args.file_name, data_folder=data_folder, args=args)
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=args.batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=args.batch_size, shuffle=False)
'''
Train the disentangled model
The digit images are passed separately to the encoder
which ideally should encode the number
'''
#args.saved_model_name = 'disentangled'
#train_split(train_dl,test_dl,args)
'''
Train the entangled model
The digit images are passed as a single image with double the size to a different encoder
'''
args.saved_model_name = 'entangled'
train_joint(train_dl,test_dl,args)
if __name__ == '__main__':
main()