-
Notifications
You must be signed in to change notification settings - Fork 2
/
chordVAE_train.py
220 lines (206 loc) · 9.97 KB
/
chordVAE_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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
Created on Fri Oct 29 17:28:18 2022
@author: Shulei Ji
"""
import torch
import torch.nn as nn
import random
import pickle
import os
import time
import math
import datetime
import numpy as np
from pytorchtools import EarlyStopping
from models.chordVAE_givenMelody import chordVAE
from utils import list2tensor
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(torch.cuda.is_available())
print("device: ",device)
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def train(melody,chord,valence,step,allStep):
coefficient = (1 / allStep) * step
P_coefficient=(1 / allStep) * step*0.05
s_p=torch.nn.functional.one_hot(valence.narrow(1,0,1),num_classes=5).float()
S_B=torch.nn.functional.one_hot(valence.narrow(1,1,valence.shape[1]-1),num_classes=5).float()
KL_loss,b_KL_loss,root,type=VAE(melody,chord,s_p,S_B)
GT_chords=chord.narrow(1,1,chord.shape[1]-1)
_, GT_type = GT_chords.narrow(-1, 0, 7).topk(1)
_, GT_root = GT_chords.narrow(-1, 7, 41).topk(1)
GT_type=GT_type.squeeze(-1)
GT_root=GT_root.squeeze(-1)
l = 0
for k in range(12):
l += criterion(type[k], GT_type[k])
l += criterion(root[k], GT_root[k])
reconstruction_loss = l/12
Piece_KL_loss = P_coefficient * KL_loss
Bar_KL_loss = coefficient * b_KL_loss
loss_update=reconstruction_loss+Piece_KL_loss+Bar_KL_loss
loss_record=reconstruction_loss+KL_loss+b_KL_loss
return loss_update,loss_record.item(),reconstruction_loss.item(),KL_loss.item(),b_KL_loss.item()
start_time=time.time()
def timeSince(since):
now=time.time()
s=now-since
h=math.floor(s/3600)
s-=h*3600
m=math.floor(s/60)
s-=m*60
return '%dh_%dm_%ds' % (h, m, s)
def trainIter(train_melody,train_chord,train_valence,test_melody,test_chord,test_valence,Epoch):
model_path = "./save_models/chordVAE_scratch_"+dataset +"/"
if not os.path.exists(model_path):
os.makedirs(model_path)
log_path = './logs/chordVAE_scratch_'+dataset +'.log'
if not os.path.exists(log_path):
os.makedirs(log_path)
f = open(log_path, 'a')
f.write('\nbatch_size: %.6d lr: %.6f' % (batch_size,learning_rate))
f.close()
train_length = len(train_melody)
test_length = len(test_melody)
max_test_loss = 1000
lr = learning_rate
step=0
allStep = train_length * 100
for epoch in range(0,Epoch):
f = open(log_path, 'a')
print("-----------------------------epoch ", epoch, "------------------------------")
f.write('\n-----------------------------epoch %d------------------------------' % (epoch))
train_total_loss=0
rl_total=0;kl_total=0;P_kl_total=0
temp_total_loss = 0;temp_rl_loss = 0
temp_Pkl=0;temp_kl=0
train_start_idx=0
VAE.train()
i=0
while i < train_length:
loss_update = 0
mem=0
for j in range(batch_size // 12):
if i + j >= train_length:
break
melody, chord, valence = train_melody[i + j], train_chord[i + j], train_valence[i + j]
if melody.shape[1]>1500:
continue
mem+=melody.shape[1]
if mem>1500:
optimizer.zero_grad()
loss_update.backward()
nn.utils.clip_grad_norm_(VAE.parameters(),2)
optimizer.step()
loss_update=0
chord_prefix=torch.zeros([chord.shape[0],1,48]).to(device)
chord_prefix[:,:,0]=1;chord_prefix[:,:,-1]=1;
chord = torch.cat((chord_prefix, chord), dim=1)
loss_back,loss,rl,P_kl,kl=train(melody,chord,valence,step,allStep)
step+=1
loss_update+=loss_back
temp_total_loss+=loss*12
train_total_loss+=loss*12
rl_total+=rl*12;kl_total+=kl*12;P_kl_total+=P_kl*12
temp_rl_loss+=rl*12;temp_kl+=kl*12;temp_Pkl+=P_kl*12
train_start_idx+=12
i = i + j + 1
if loss_update!=0:
optimizer.zero_grad()
loss_update.backward()
nn.utils.clip_grad_norm_(VAE.parameters(), 2)
optimizer.step()
if train_start_idx%(print_every)==0:
print('epoch train:%d, %s(%d %d%%) total: %.6f rl: %.6f Pkl: %.6f kl: %.6f' % (
epoch, timeSince(start_time), train_start_idx, train_start_idx / (train_length * 12) * 100,
temp_total_loss/print_every,temp_rl_loss /print_every,temp_Pkl/print_every,temp_kl/print_every))
f.write('\nepoch train:%d, %s(%d %d%%) total: %.6f rl: %.6f Pkl: %.6f kl: %.6f' % (
epoch, timeSince(start_time), train_start_idx, train_start_idx / (train_length * 12) * 100,
temp_total_loss/print_every,temp_rl_loss /print_every,temp_Pkl/print_every,temp_kl/print_every))
print("--------------------------------------------------------------")
temp_total_loss = 0
temp_rl_loss=0
temp_Pkl=0
temp_kl=0
test_start_idx = 0
test_total_loss= 0
rl_total_test=0;kl_total_test=0;P_kl_total_test=0
VAE.eval()
for i in range(test_length):
melody, chord, valence = test_melody[i], test_chord[i], test_valence[i]
if melody.shape[1]>1500:
continue
chord_prefix = torch.zeros([chord.shape[0], 1, 48]).to(device)
chord_prefix[:, :, 0] = 1;chord_prefix[:, :, -1] = 1
chord = torch.cat((chord_prefix, chord), dim=1)
_,loss,rl,P_kl,kl=train(melody,chord,valence,step,allStep)
test_total_loss+=loss*test_batch_size
rl_total_test+=rl*test_batch_size;kl_total_test+=kl*test_batch_size;P_kl_total_test+=P_kl*test_batch_size
test_start_idx+=test_batch_size
print('epoch: %d, time: %s, \ntrain loss: %.6f, test loss: %.6f, \nrl_train: %.6f, rl_test: %.6f, \n'
'kl_train: %.6f,kl_test: %.6f, \nP_kl_train: %.6f, P_kl_test: %.6f, \nlearning rate: %.6f'
% (epoch, timeSince(start_time), train_total_loss / train_start_idx,test_total_loss/test_start_idx,
rl_total/train_start_idx,rl_total_test/test_start_idx,kl_total/train_start_idx,kl_total_test/test_start_idx,
P_kl_total/train_start_idx,P_kl_total_test/test_start_idx,lr))
f.write('\nepoch: %d, time: %s, \ntrain loss: %.6f, test loss: %.6f, \nrl_train: %.6f, rl_test: %.6f, \n'
'kl_train: %.6f,kl_test: %.6f, \nP_kl_train: %.6f, P_kl_test: %.6f, \nlearning rate: %.6f'
% (epoch, timeSince(start_time), train_total_loss / train_start_idx,test_total_loss/test_start_idx,
rl_total/train_start_idx,rl_total_test/test_start_idx,kl_total/train_start_idx,kl_total_test/test_start_idx,
P_kl_total/train_start_idx,P_kl_total_test/test_start_idx,lr))
train_average = train_total_loss / train_start_idx
test_average = test_total_loss / test_start_idx
early_stopping(test_average, VAE)
if early_stopping.early_stop:
print("------------Early Stopping-------------")
break
if test_average < max_test_loss:
print("epoch: %d save min test loss model-->test loss: %.6f" % (epoch, test_average))
f.write('\nepoch: %d save min test loss model-->test loss: %.6f' % (epoch, test_average))
model_save_path = model_path + "chordVAE_" + dataset + "_epoch" + str(epoch) + "_min_" + str(round(test_average,4)) + ".pth"
state = {'model': VAE.state_dict(), 'optimizer': optimizer.state_dict(), 'epoch': epoch}
torch.save(state, model_save_path)
max_test_loss = test_average
else:
if epoch%5==0:
model_save_path = model_path + "chordVAE_" + dataset + "_epoch" + str(epoch) + "_" + str(round(test_average,4)) + ".pth"
state = {'model': VAE.state_dict(), 'optimizer': optimizer.state_dict(), 'epoch': epoch}
torch.save(state, model_save_path)
f.close()
if __name__ == '__main__':
################################### configuration
setup_seed(13)
dataset = "NMD"
batch_size = 24
test_batch_size=12
patience = 20
Epoch = 200
VAE = chordVAE(N=3,h=4,m_size=8,c_size=48,d_ff=256,hidden_size=256,latent_size=128,dropout=0.2).to(device)
criterion = nn.NLLLoss().to(device)
learning_rate = 3e-4
optimizer = torch.optim.Adam(VAE.parameters(), lr=learning_rate)
early_stopping = EarlyStopping(patience, verbose=True)
print_every = 1020
################################# extract data
file = open("./data/"+dataset+"_melody_train.data", 'rb')
train_melody = pickle.load(file)
file = open("./data/"+dataset+"_chord_train.data", 'rb')
train_chord = pickle.load(file)
file = open("./data/"+dataset+"_chord_train_valence.data", 'rb')
train_valence = pickle.load(file)
print(len(train_melody),len(train_chord),len(train_valence))
file = open("./data/"+dataset+"_melody_test.data", 'rb')
test_melody = pickle.load(file)
file = open("./data/"+dataset+"_chord_test.data", 'rb')
test_chord = pickle.load(file)
file = open("./data/"+dataset+"_chord_test_valence.data", 'rb')
test_valence = pickle.load(file)
print(len(test_melody),len(test_chord),len(test_valence))
train_melody, train_chord, train_valence = list2tensor(train_melody, train_chord, train_valence, device)
print(len(train_melody), len(train_chord), len(train_valence))
test_melody, test_chord, test_valence = list2tensor(test_melody, test_chord, test_valence, device)
print(len(test_melody), len(test_chord), len(test_valence))
################################# begin train
trainIter(train_melody,train_chord,train_valence,test_melody,test_chord,test_valence,Epoch)