-
Notifications
You must be signed in to change notification settings - Fork 64
/
train_xent.py
143 lines (122 loc) · 4.81 KB
/
train_xent.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
#!/bin/python3.6
"""
Date Created: Feb 10 2020
This is the main training script for speaker embeddings, which will evolve
over time
"""
import os
import sys
import glob
import time
import socket
import torch
import numpy as np
from train_utils import *
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
# SEEDS
torch.manual_seed(0)
np.random.seed(0)
# PARAMS, MODEL PREP
parser = getParams()
args = parser.parse_args()
print(args)
totalSteps = args.numEpochs * args.numArchives
net, optimizer, step, saveDir = prepareModel(args)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
numBatchesPerArk = int(args.numEgsPerArk/args.batchSize)
# LR SCHEDULERS
cyclic_lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer,
max_lr=args.maxLR,
cycle_momentum=False,
div_factor=5,
final_div_factor=1e+3,
total_steps=totalSteps*numBatchesPerArk,
pct_start=0.15)
criterion = nn.CrossEntropyLoss()
eps = args.noiseEps
# TRAINING
while step < totalSteps:
archiveI = step%args.numArchives + 1
archive_start_time = time.time()
ark_file = '{}/egs.{}.ark'.format(args.featDir,archiveI)
print('Reading from archive %d' %archiveI)
preFetchRatio = args.preFetchRatio
# Read with data data_loader
data_loader = nnet3EgsDL(ark_file)
par_data_loader = DataLoader(data_loader,
batch_size=preFetchRatio*args.batchSize,
shuffle=False,
num_workers=0,
drop_last=False,
pin_memory=True)
batchI, loggedBatch = 0, 0
loggingLoss = 0.0
start_time = time.time()
for _,(X, Y) in par_data_loader:
Y = Y['matrix'][0][0][0].to(device)
X = X['matrix'].to(device)
try:
assert max(Y) < args.numSpkrs and min(Y) >= 0
except:
print('Read an out of range value at iter %d' %iter)
continue
if torch.isnan(X).any():
print('Read a nan value at iter %d' %iter)
continue
accumulateStepSize = 4
preFetchBatchI = 0 # this counter within the prefetched batches only
while preFetchBatchI < int(len(Y)/args.batchSize) - accumulateStepSize:
# Accumulated gradients used
optimizer.zero_grad()
for _ in range(accumulateStepSize):
batchI += 1
preFetchBatchI += 1
# fwd + bckwd + optim
output = net(X[preFetchBatchI*args.batchSize:(preFetchBatchI+1)*args.batchSize,:,:].permute(0,2,1), eps)
loss = criterion(output, Y[preFetchBatchI*args.batchSize:(preFetchBatchI+1)*args.batchSize].squeeze())
if np.isnan(loss.item()):
print('Nan encountered at iter %d. Exiting..' %iter)
sys.exit(1)
loss.backward()
loggingLoss += loss.item()
optimizer.step() # Does the update
cyclic_lr_scheduler.step()
# Log
if batchI-loggedBatch >= args.logStepSize:
logStepTime = time.time() - start_time
print('Batch: (%d/%d) Avg Time/batch: %1.3f Avg Loss/batch: %1.3f' %(
batchI,
numBatchesPerArk,
logStepTime/(batchI-loggedBatch),
loggingLoss/(batchI-loggedBatch)))
loggingLoss = 0.0
start_time = time.time()
loggedBatch = batchI
print('Archive processing time: %1.3f' %(time.time()-archive_start_time))
# Update dropout
if 1.0*step < args.stepFrac*totalSteps:
p_drop = args.pDropMax*step/(args.stepFrac*totalSteps)
else:
p_drop = max(0,args.pDropMax*(2*step - totalSteps*(args.stepFrac+1))/(totalSteps*(args.stepFrac-1))) # fast decay
for x in net.modules():
if isinstance(x, torch.nn.Dropout):
x.p = p_drop
print('Dropout updated to %f' %p_drop)
# Save checkpoint
torch.save({
'step': step,
'archiveI':archiveI,
'model_state_dict': net.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
'args': args,
}, '{}/checkpoint_step{}.tar'.format(saveDir, step))
# Compute validation loss, update LR if using plateau rule
valAcc = computeValidAccuracy(args, saveDir)
print('Validation accuracy is %1.2f precent' %(valAcc))
# Cleanup. We always retain the last 10 models
if step > 10:
if os.path.exists('%s/checkpoint_step%d.tar' %(saveDir,step-10)):
os.remove('%s/checkpoint_step%d.tar' %(saveDir,step-10))
step += 1