-
Notifications
You must be signed in to change notification settings - Fork 8
/
run.py
236 lines (195 loc) · 7.32 KB
/
run.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
import torch
import os
import numpy as np
import copy
#from src.runner.test import test
import datetime
import ml_collections
import yaml
from CIFAR10.utils import model_path, EarlyStopping
import argparse
import sys
def train_CIFAR10(
model, dataloader, config, test_loader
):
# Training parameters
epochs = config.epochs
device = config.device
# clip = config.clip
# Save best performing weights
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
best_loss = 999
# iterate over epochs
print(model)
optimizer = torch.optim.Adam(
model.parameters(),
lr=config.lr,
weight_decay=config.weight_decay,
)
lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(
optimizer,
gamma=config.gamma)
criterion = torch.nn.CrossEntropyLoss()
counter = 0
# wandb.watch(model, criterion, log="all", log_freq=1)
for epoch in range(epochs):
print("Epoch {}/{}".format(epoch + 1, epochs))
print("-" * 30)
# Print current learning rate
for param_group in optimizer.param_groups:
print("Learning Rate: {}".format(param_group["lr"]))
print("-" * 30)
# Each epoch consist of training and validation
for phase in ["train", "validation"]:
if phase == "train":
model.train()
else:
model.eval()
# Accumulate accuracy and loss
running_loss = 0
running_corrects = 0
total = 0
# iterate over data
for inputs, labels in dataloader[phase]:
_, in_channels, x, y = inputs.shape
inputs = inputs.view(-1, in_channels, x * y)
if config.length != None:
inputs = inputs[:, :, :config.length]
else:
pass
inputs = inputs.permute(0, 2, 1).to(device)
labels = labels.to(device)
optimizer.zero_grad()
train = phase == "train"
with torch.set_grad_enabled(train):
# FwrdPhase:
# inputs = torch.dropout(inputs, config.dropout_in, train)
outputs = model(inputs)
loss = criterion(outputs, labels)
# Regularization:
_, preds = torch.max(outputs, 1)
# BwrdPhase:
if phase == "train":
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += (preds == labels).sum().item()
total += labels.size(0)
# statistics of the epoch
epoch_loss = running_loss / total
epoch_acc = running_corrects / total
print("{} Loss: {:.4f} Acc: {:.4f}".format(
phase, epoch_loss, epoch_acc))
print(datetime.datetime.now())
# If better validation accuracy, replace best weights and compute the test performance
if phase == "validation" and epoch_acc >= best_acc:
# Updates to the weights will not happen if the accuracy is equal but loss does not diminish
if (epoch_acc == best_acc) and (epoch_loss > best_loss):
pass
else:
best_acc = epoch_acc
best_loss = epoch_loss
best_model_wts = copy.deepcopy(model.state_dict())
# Clean CUDA Memory
del inputs, outputs, labels
torch.cuda.empty_cache()
# Perform test and log results
test_acc = best_acc
if phase == "validation":
torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, 'min').step(metrics=best_loss)
EarlyStopping(patience=30)(val_acc=best_acc)
if counter > config.patience:
break
else:
lr_scheduler.step()
print()
lr_scheduler.step()
print()
# Report best results
print("Best Val Acc: {:.4f}".format(best_acc))
# Load best model weights
model.load_state_dict(best_model_wts)
torch.save(model.state_dict(), config.path)
# Return model and histories
return model
def test_CIFAR10(model, test_loader, config):
# send model to device
device = config.device
model.eval()
model.to(device)
# Summarize results
correct = 0
total = 0
with torch.no_grad():
# Iterate through data
for inputs, labels in test_loader:
_, in_channels, x, y = inputs.shape
inputs = inputs.view(-1, in_channels, x * y)
inputs = inputs.permute(0, 2, 1).to(device)
labels = labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
# Print results
test_acc = correct / total
print(
"Accuracy of the network on the {} test samples: {}".format(
total, (100 * test_acc)
)
)
return test_acc
def main(config):
# print(config)
os.environ["CUDA_VISIBLE_DEVICES"] = config.gpu_id
print(os.environ["CUDA_VISIBLE_DEVICES"])
# Set the seed
# torch.manual_seed(config.seed)
# np.random.seed(config.seed)
# initialize weight and bias
# Place here your API key.
if (config.device ==
"cuda" and torch.cuda.is_available()):
config.update({"device": "cuda:0"}, allow_val_change=True)
else:
config.update({"device": "cpu"}, allow_val_change=True)
torch.cuda.set_per_process_memory_fraction(0.5, 0)
from CIFAR10.models import get_model
model = get_model(config)
# Define transforms and create dataloaders
from CIFAR10.dataloader import get_dataset
dataloaders, test_loader = get_dataset(config, num_workers=4)
# Create model directory and instantiate config.path
model_path(config)
if config.pretrained:
# Load model state dict
model.module.load_state_dict(torch.load(config.path), strict=False)
# Train the model
if config.train:
# Print arguments (Sanity check)
print(config)
# Train the model
import datetime
print(datetime.datetime.now())
train_CIFAR10(model, dataloaders, config, test_loader)
# Select test function
test_acc = test_CIFAR10(model, test_loader, config)
return test_acc
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='LSTM_DEV',
help='choose from LSTM, LSTM_DEV,EXPRNN')
args = parser.parse_args()
if args.model == 'LSTM_DEV':
with open('CIFAR10/configs/train_lstm_dev.yaml') as file:
config = ml_collections.ConfigDict(yaml.safe_load(file))
elif args.model == 'LSTM':
with open('CIFAR10/configs/train_lstm.yaml') as file:
config = ml_collections.ConfigDict(yaml.safe_load(file))
elif args.model == 'EXPRNN':
with open('CIFAR10/configs/train_exprnn.yaml') as file:
config = ml_collections.ConfigDict(yaml.safe_load(file))
main(config=config)