-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrainer.py
196 lines (149 loc) · 6.09 KB
/
trainer.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
import os
import time
import torch
import random
import numpy as np
from tqdm import tqdm
import torch.nn as nn
from util import epoch_time
import torch.optim as optim
from model.neural_network import RandomlyWiredNeuralNetwork
from data.data_util import fetch_dataloader, test_voc, test_imagenet
SEED = 981126
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
class Trainer:
def __init__(self, num_epoch, lr,
batch_size, num_node,
p, k, m, channel,
in_channels, path,
graph_mode, dataset,
is_small_regime,
checkpoint_path, load):
super(Trainer, self).__init__()
self.params = {'num_epoch': num_epoch,
'batch_size': batch_size,
'lr': lr,
'node_num': num_node,
'p': p,
'k': k,
'm': m,
'in_channels': in_channels,
'channel': channel,
'classes': 21 if dataset == 'voc' else 1000,
'graph_mode': graph_mode,
'load': load,
'path': path,
'dataset': dataset,
'is_small_regime': is_small_regime,
'checkpoint_path': checkpoint_path
}
self.device = torch.device(
'cuda' if torch.cuda.is_available() else 'cpu')
self.train_data, self.val_data, self.test_data = fetch_dataloader(
self.params['dataset'],
self.params['path'],
self.params['batch_size'])
self.rwnn = RandomlyWiredNeuralNetwork(
self.params['channel'],
self.params['in_channels'],
self.params['p'],
self.params['k'],
self.params['m'],
self.params['graph_mode'],
self.params['classes'],
self.params['node_num'],
self.params['checkpoint_path'],
self.params['load'],
self.params['is_small_regime']
).to(self.device)
self.optimizer = optim.SGD(
self.rwnn.parameters(), self.params['lr'], 0.9, weight_decay=5e-5)
self.best_loss = float('inf')
self.step_num = 0
if load:
checkpoint = torch.load(os.path.join(
self.params['checkpoint_path'], 'train.tar'))
self.rwnn.load_state_dict(checkpoint['model_state_dict'])
self.optimizer.load_state_dict(
checkpoint['optimizer_state_dict'])
self.epoch = checkpoint['epoch']
self.best_loss = checkpoint['best_loss']
self.scheduler = checkpoint['scheduler']
self.step_num = checkpoint['step_num']
else:
self.epoch = 0
self.scheduler = optim.lr_scheduler.CosineAnnealingLR(
self.optimizer, self.params['num_epoch'])
self.criterion = nn.CrossEntropyLoss()
pytorch_total_params = sum(p.numel() for p in self.rwnn.parameters())
print(f"Number of parameters {pytorch_total_params}")
def train(self):
print("\nbegin training...")
for epoch in range(self.epoch, self.params['num_epoch']):
print(
f"\nEpoch: {epoch+1} out of {self.params['num_epoch']}, step: {self.step_num}")
start_time = time.perf_counter()
epoch_loss, step = train_loop(
self.train_data, self.rwnn, self.optimizer, self.criterion, self.device)
val_loss = val_loop(self.val_data, self.rwnn,
self.criterion, self.device)
if val_loss < self.best_loss:
self.best_loss = val_loss
with open(os.path.join(self.params['checkpoint_path'], 'best_model.txt'), 'w') as f:
f.write(
f"epoch: {epoch+1}, 'validation loss: {val_loss}, step: {self.step_num}")
torch.save(
self.rwnn,
os.path.join(self.params['checkpoint_path'], 'best.pt'))
if (epoch + 1) % 15 == 0:
if self.params['dataset'] == 'voc':
test_voc(self.test_data, self.rwnn, self.device)
self.step_num += step
self.scheduler.step()
end_time = time.perf_counter()
minutes, seconds, time_left_min, time_left_sec = epoch_time(
end_time-start_time, epoch, self.params['num_epoch'])
torch.save({
'epoch': epoch,
'model_state_dict': self.rwnn.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'best_loss': self.best_loss,
'scheduler': self.scheduler,
'step_num': self.step_num
}, os.path.join(self.params['checkpoint_path'], 'train.tar'))
print(
f"Train_loss: {round(epoch_loss, 3)} - Val_loss: {round(val_loss, 3)}")
print(
f"Epoch time: {minutes}m {seconds}s - Time left for training: {time_left_min}m {time_left_sec}s")
def train_loop(train_iter, model, optimizer, criterion, device):
epoch_loss = 0
step_num = 0
model.train()
print("Training...")
for src, tgt in tqdm(train_iter):
src = src.to(device)
tgt = tgt.to(device)
optimizer.zero_grad()
logits = model(src)
loss = criterion(logits, tgt)
loss.backward()
optimizer.step()
step_num += 1
epoch_loss += loss.item()
return epoch_loss / len(train_iter), step_num
def val_loop(val_iter, model, criterion, device):
model.eval()
val_loss = 0
with torch.no_grad():
print("Validating...")
for src, tgt in tqdm(val_iter):
src = src.to(device)
tgt = tgt.to(device)
logits = model(src)
loss = criterion(logits, tgt)
val_loss += loss.item()
return val_loss / len(val_iter)