-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_callbacks.py
224 lines (156 loc) · 6.66 KB
/
train_callbacks.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
import logging
import numpy as np
import torch
import torch.nn as nn
from torch import optim
#from tqdm import tqdm_notebook as tqdm
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from forward.simple_model import SimpleLayerModel, SimpleLayerDataset
from utils.data_vis import plot_speeds, plot_amplitudes
class Callback():
def __init__(self): pass
def on_train_begin(self,s): pass
def on_train_end(self,s): pass
def on_epoch_begin(self,s): pass
def on_epoch_end(self,s): pass
def on_batch_begin(self,s): pass
def on_batch_end(self,s): pass
def on_val_begin(self,s): pass
def on_val_end(self,s): pass
class TBWriter(Callback):
def on_train_begin(self,s):
self.writer = SummaryWriter(comment=f'LR_{s.lr}_BS_{s.batch_size}')
def on_train_end(self,s):
self.writer.close()
def on_batch_end(self,s):
self.writer.add_scalar('Loss/train', s.batch_loss, s.global_step)
lr = s.optimizer.param_groups[0]['lr']
self.writer.add_scalar('LR',lr,s.global_step)
def on_val_end(self,s):
amps_plot = plot_amplitudes(s.current_X)
self.writer.add_images('images', amps_plot, s.global_step)
speeds_plot = plot_speeds(s.current_Y.detach().cpu().numpy()[0],
s.current_Y_pred.detach().cpu().numpy()[0])
self.writer.add_images('speeds', speeds_plot, s.global_step)
class TrainState():
def __init__(self,
model,
train_dataset,
val_dataset,
n_epochs = 5,
lr=0.1,
batch_size = 1,
n_subbatches = 1,
val_interval = 500,
save_dir = None,
device = None,
optimizer = None,
criterion = None,
):
if not device:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if not optimizer:
optimizer = optim.RMSprop(net.parameters(), lr=lr, weight_decay=1e-8)
if not criterion:
criterion = nn.MSELoss()
self.model = model
self.train_dataset = train_dataset
self.val_dataset = val_dataset
self.train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=5, pin_memory=True, worker_init_fn=lambda x: np.random.seed())
self.val_loader = DataLoader(val_dataset, batch_size=batch_size, num_workers=5, pin_memory=True)
self.n_train = len(train_dataset)
self.n_val = len(val_dataset)
self.n_epochs = n_epochs
self.lr = lr
self.batch_size = batch_size
self.n_subbatches = n_subbatches
self.val_interval = val_interval
self.save_dir = None
self.device = device
self.optimizer = optimizer
self.criterion = criterion
# State
self.batch_num = 0
self.global_step = 0
self.epoch_loss = 0
self.val_loss = 0
self.batch_loss = 0
self.current_X = None
self.current_Y = None
self.current_Y_pred = None
def train_net(
state,
callbacks
):
s = state
model = s.model
criterion = s.criterion
optimizer = s.optimizer
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logging.info(f'Network:\n'
f'\t{model.n_channels} input channels\n')
logging.info(f'''Starting training:
Epochs: {s.n_epochs}
Batch size: {s.batch_size}
Learning rate: {s.lr}
Training size: {s.n_train}
Validation size: {s.n_val}
Device: {s.device.type}
''')
model.to(device=s.device)
# faster convolutions, but more memory
# cudnn.benchmark = True
model.train()
# Train Start Callback
for c in callbacks: c.on_train_begin(s)
for epoch in range(s.n_epochs):
# Epoch Begin Callback
for c in callbacks: c.on_epoch_begin(s)
loss = 0
with tqdm(total=np.ceil(s.n_train/s.batch_size), desc=f'Epoch {epoch + 1}/{s.n_epochs}', unit='img') as pbar:
for (k,batch) in enumerate(s.train_loader):
# Batch Begin Callback
for c in callbacks: c.on_batch_begin(s)
assert batch['X'].shape[1] == model.n_channels, \
f'Network has been defined with {net.n_channels} input channels, ' \
f'but loaded amplitudes have {imgs.shape[1]} channels. Please check that ' \
'the net is configured correctly.'
X = batch['X'].to(device=s.device, dtype=torch.float32)
Y = batch['Y'].to(device=s.device, dtype=torch.float32)
Y_pred = model(X)
s.current_X = X
s.current_Y = Y
s.current_Y_pred = Y_pred
loss += criterion(Y_pred, Y)
if k % s.n_subbatches == 0:
s.epoch_loss += loss.item()
s.batch_loss = loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss = 0
pbar.set_postfix(**{'loss (batch)': s.batch_loss})
# Batch End Callbacks
for c in callbacks: c.on_batch_end(s)
pbar.update()
s.global_step += 1
if s.global_step % s.val_interval == 1:
#val_score = eval_net(net, val_loader, device, n_val)
#net.train()
#logging.info('Validation cross entropy: {}'.format(val_score))
#writer.add_scalar('Loss/test', val_score, global_step)
for c in callbacks: c.on_val_end(s)
# Epoch End Callback
for c in callbacks: c.on_epoch_end(s)
if s.save_dir:
try:
os.mkdir(s.save_dir)
except OSError:
pass
torch.save(net.state_dict(),
s.save_dir + f'CP_epoch{epoch + 1}.pth')
logging.info(f'Checkpoint {epoch + 1} saved !')
# Train End Callback
for c in callbacks: c.on_train_end(s)