-
Notifications
You must be signed in to change notification settings - Fork 0
/
training.py
175 lines (144 loc) · 6.86 KB
/
training.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
import datetime
import logging
import os
import pprint
from statistics import mean
import torch
import torch.nn
from torch.utils.tensorboard import SummaryWriter
from tqdm import trange
import data
import utils
from model import BachNetTrainingContinuo, BachNetTrainingMiddleParts
def train(config, data_loaders):
logging.debug('Initializing...')
# Prepare logging
date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_dir = os.path.join('.', 'runs', f'{date}')
writer = SummaryWriter(log_dir=log_dir)
logging.debug(f'Configuration:\n{pprint.pformat(config)}')
device = torch.device("cuda:0" if config.use_cuda and torch.cuda.is_available() else "cpu")
logging.debug(f'Using device: {device}')
logging.debug('Creating model...')
model_continuo = BachNetTrainingContinuo(
hidden_size=config.hidden_size,
context_radius=config.context_radius,
).to(device)
model_middle_parts = BachNetTrainingMiddleParts(
hidden_size=config.hidden_size,
context_radius=config.context_radius
).to(device)
params_continuo = [p for p in model_continuo.parameters() if p.requires_grad]
params_middleparts = [p for p in model_middle_parts.parameters() if p.requires_grad]
optimizer_continuo = torch.optim.Adam(params_continuo, lr=config.lr)
optimizer_middleparts = torch.optim.Adam(params_middleparts, lr=config.lr)
lr_scheduler_continuo = torch.optim.lr_scheduler.StepLR(
optimizer_continuo,
step_size=config.lr_step_size,
gamma=config.lr_gamma,
)
lr_scheduler_middleparts = torch.optim.lr_scheduler.StepLR(
optimizer_middleparts,
step_size=config.lr_step_size,
gamma=config.lr_gamma,
)
criterion = torch.nn.CrossEntropyLoss().to(device)
logging.debug('Training and testing...')
# for epoch in range(config.num_epochs):
for epoch in trange(config.num_epochs, unit='epoch'):
for phase in ['train', 'test']:
model_continuo.train() if phase == 'train' else model_continuo.eval()
model_middle_parts.train() if phase == 'train' else model_middle_parts.eval()
loss_lists = {
'all': [],
'bass': [],
'alto': [],
'tenor': []
}
with torch.set_grad_enabled(phase == 'train'):
for batch_idx, batch in enumerate(data_loaders[phase]):
inputs, targets = batch
# Transfer to device
inputs_for_continuo = {k: inputs[k].to(device) for k in ['soprano', 'bass', 'extra']}
inputs_for_middle_parts = {k: inputs[k].to(device) for k in
['soprano', 'alto', 'tenor', 'bass_with_context', 'extra']}
targets_continuo = {k: targets[k].to(device) for k in ['bass']}
targets_middleparts = {k: targets[k].to(device) for k in ['alto', 'tenor']}
predictions_continuo = model_continuo(inputs_for_continuo)
losses_continuo = {k: criterion(predictions_continuo[k], targets_continuo[k]) for k in
targets_continuo.keys()}
predictions_middleparts = model_middle_parts(inputs_for_middle_parts)
losses_middleparts = {k: criterion(predictions_middleparts[k], targets_middleparts[k]) for k in
targets_middleparts.keys()}
loss = sum([sum(losses_middleparts.values()), sum(losses_continuo.values())])
loss_lists['all'].append(loss.item())
for k in losses_continuo.keys():
loss_lists[k].append(losses_continuo[k].item())
for k in losses_middleparts.keys():
loss_lists[k].append(losses_middleparts[k].item())
if phase == 'train':
optimizer_continuo.zero_grad()
optimizer_middleparts.zero_grad()
sum(losses_continuo.values()).backward()
sum(losses_middleparts.values()).backward()
# loss.backward()
optimizer_continuo.step()
optimizer_middleparts.step()
# Log current loss
if batch_idx % config.log_interval == 0:
step = int((float(epoch) + (batch_idx / len(data_loaders[phase]))) * 1000)
writer.add_scalars('loss', {phase: loss.item()}, step)
writer.add_scalars('loss_per_parts', {f'{phase}_{k}': v for k, v in losses_continuo.items()},
step)
writer.add_scalars('loss_per_parts', {f'{phase}_{k}': v for k, v in losses_middleparts.items()},
step)
# Log mean loss per epoch
mean_loss_per_epoch = mean(loss_lists['all'])
writer.add_scalars('loss', {phase + '_mean': mean_loss_per_epoch}, (epoch + 1) * 1000)
writer.file_writer.flush()
lr_scheduler_continuo.step()
lr_scheduler_middleparts.step()
if config.checkpoint_interval is not None and (epoch + 1) % config.checkpoint_interval == 0:
subfolder = f'{date}' # {str(config)}
folder = os.path.join(config.checkpoint_root_dir, subfolder)
os.makedirs(folder, exist_ok=True)
fname = f'{date}_epoch={str(epoch + 1).zfill(4)}.pt'
checkpoint_path = os.path.join(folder, fname)
torch.save({
'config': config,
'state_continuo': model_continuo.state_dict(),
'state_middle_parts': model_middle_parts.state_dict(),
'epoch': epoch,
'loss_bass': mean(loss_lists['bass']),
'loss_alto': mean(loss_lists['alto']),
'loss_tenor': mean(loss_lists['tenor'])
}, checkpoint_path)
txt_file = os.path.join(folder, 'config.txt')
with open(txt_file, 'w') as f:
f.write(str(config))
writer.close()
std_config = utils.Config({
'num_epochs': 3000,
'batch_size': 8192,
'num_workers': 1,
'hidden_size': 650,
'context_radius': 32,
'time_grid': 0.25,
'lr': 0.0005,
'lr_gamma': 0.99,
'lr_step_size': 30,
'checkpoint_interval': 1,
'split': 0.05,
})
if __name__ == '__main__':
logging.basicConfig(level=logging.ERROR)
logging.debug('Loading datasets...')
data_loaders = data.get_data_loaders(
batch_size=std_config.batch_size,
num_workers=std_config.num_workers,
time_grid=std_config.time_grid,
context_radius=std_config.context_radius,
split=std_config.split,
debug=False
)
train(std_config, data_loaders)