-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
196 lines (151 loc) · 7.69 KB
/
train.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 logging
import hydra
import torch
import torchvision
import numpy as np
import torch.nn as nn
from omegaconf import DictConfig
from torch.utils.tensorboard import SummaryWriter
from src.model.evaluate import eval_model
from src.model.model import PieceClassifier
from src.model.dataset import PiecesDataset
from src.utils.transforms import parse_config_transforms
from src.consts import TRAIN_CONFIG_PATH, TRAIN_CONFIG_NAME
from src.visualization.train_progress_visualization import plot_learning_curves
@hydra.main(config_path=TRAIN_CONFIG_PATH, config_name=TRAIN_CONFIG_NAME, version_base='1.2')
def train(config: DictConfig) -> (str, torch.utils.data.DataLoader, torch.utils.data.DataLoader):
"""A train script for the model over the chess pieces dataset
Args:
config: hydra config manager
Returns:
model_path: path to the saved model
train_loader: train loader which was used to train the model
test_loader: test loader with test data
"""
batch_size = config.hyperparams.train.batch_size
num_workers = config.hyperparams.train.num_workers
lr = config.hyperparams.train.lr
num_epochs = config.hyperparams.train.num_epochs
print_interval = config.hyperparams.train.print_interval
minibatch_size = config.hyperparams.train.minibatch_size
shuffle_data = config.hyperparams.train.shuffle_data
model_path = config.paths.model_paths.model_path
plots_dirname = config.paths.plot_paths.plot_dirname
current_run_path = hydra.core.hydra_config.HydraConfig.get()['runtime']['output_dir']
plots_path = os.path.join(current_run_path, plots_dirname)
os.makedirs(plots_path, exist_ok=True)
log = logging.getLogger(__name__)
tb_writer = SummaryWriter()
images_dir_path = config.paths.data_paths.image_dir_path
train_labels_path = config.paths.data_paths.train_json_path
vel_labels_path = config.paths.data_paths.val_json_path
is_minibatch = minibatch_size > 0
transforms = parse_config_transforms(config.transforms)
train_dataset = PiecesDataset(images_dir_path=images_dir_path,
labels_path=train_labels_path,
transforms=transforms)
val_dataset = PiecesDataset(images_dir_path=images_dir_path,
labels_path=vel_labels_path,
transforms=transforms)
if is_minibatch:
train_dataset = torch.utils.data.ConcatDataset([train_dataset, val_dataset])
eval_train_loader = get_subset_dataloader(dataset=train_dataset,
subset_ratio=config.hyperparams.train.eval_train_size)
val_loader = None
eval_val_loader = None
else:
eval_train_loader = get_subset_dataloader(dataset=train_dataset,
subset_ratio=config.hyperparams.train.eval_train_size)
eval_val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size,
shuffle=shuffle_data, num_workers=num_workers)
train_size = len(train_dataset) * batch_size
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size,
shuffle=shuffle_data, num_workers=num_workers)
model = PieceClassifier(in_channels=config.model_params.in_channels,
hidden_dim=config.model_params.hidden_dim,
out_channels=config.model_params.out_channels,
num_classes=config.model_params.num_classes)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
log.info('Starting training')
epoch_losses = []
epoch_train_accuracies = []
epoch_val_accuracies = []
for epoch in range(num_epochs):
epoch_loss = 0.0
interval_loss = 0.0
model.train()
for iter_num, data in enumerate(train_loader):
images, label = data
images, label = images.to(device), label.to(device)
output_scores = model(images)
loss = criterion(output_scores, label)
loss.backward()
optimizer.step()
optimizer.zero_grad()
label.detach().cpu()
images.detach().cpu()
interval_loss += loss.item()
epoch_loss += loss.item()
if iter_num % print_interval == 0:
img_grid = torchvision.utils.make_grid(images)
tb_writer.add_image(f'Epoch {epoch} batch {iter_num}', img_grid)
if iter_num > 0:
log.info(f'epoch: {epoch}, iteration: {iter_num}, loss: '
f'{interval_loss / (print_interval * batch_size):.3f}')
interval_loss = 0.0
if 0 < minibatch_size == iter_num:
break
epoch_train_accuracy, epoch_train_loss = eval_model(model, criterion, eval_train_loader, device=device,
state='train', epoch_num=epoch, tb_writer=tb_writer)
epoch_val_accuracy, epoch_val_loss = eval_model(model, criterion, eval_val_loader, device=device, state='val',
epoch_num=epoch, tb_writer=tb_writer)
tb_writer.add_scalars('Balanced class accuracy',
{'train': epoch_train_accuracy,
'val': epoch_val_accuracy},
global_step=epoch)
tb_writer.add_scalars('Loss',
{'train': epoch_train_loss,
'val': epoch_val_loss},
global_step=epoch)
epoch_train_accuracies.append(epoch_train_accuracy)
if not is_minibatch:
epoch_val_accuracies.append(epoch_val_accuracy)
epoch_loss = epoch_loss / train_size
epoch_losses.append(epoch_loss)
log.info(f'epoch {epoch} loss: {epoch_loss:.3f}\n')
tb_writer.flush()
if is_minibatch:
plot_learning_curves(epoch_losses, epoch_train_accuracies, plots_path=plots_path)
else:
plot_learning_curves(epoch_losses, epoch_train_accuracies, epoch_val_accuracies, plots_path=plots_path)
log.info('Finished training\n')
if not is_minibatch:
eval_model(model=model, criterion=criterion, loader=val_loader,
device=device, state='val', log=log, tb_writer=tb_writer)
model_dir_path = os.path.join(current_run_path, os.path.dirname(model_path))
if not os.path.exists(model_dir_path):
os.mkdir(model_dir_path)
torch_model_path = os.path.join(current_run_path, model_path)
log.info(f'Saving model to {torch_model_path}')
torch.save(model.state_dict(), torch_model_path)
tb_writer.close()
def get_subset_dataloader(dataset: torch.utils.data.Dataset, subset_ratio: float) -> torch.utils.data.DataLoader:
"""Creates a DataLoader based on a subset of the dataset
Args:
dataset: the full dataset
subset_ratio: the percentage of data that should be sampled into the subset (without repetitions)
Returns:
subset_loader: DataLoader over the subset of the given dataset
"""
subset_size = int(subset_ratio * len(dataset))
random_indices = np.random.choice(np.arange(len(dataset)), size=subset_size, replace=False)
subset = torch.utils.data.Subset(dataset, random_indices)
subset_loader = torch.utils.data.DataLoader(subset, batch_size=subset_size)
return subset_loader
# tensorboard --logdir=src/model/runs
if __name__ == "__main__":
train()