forked from Stonesjtu/Pytorch-NCE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
203 lines (173 loc) · 6.46 KB
/
main.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
#!/usr/bin/env python
import sys
import time
import math
from tqdm import tqdm
import torch
import torch.optim as optim
import torch.autograd as autograd
import data
from model import RNNModel
from nce import NCELoss
from utils import process_data, build_unigram_noise, setup_parser, setup_logger
from generic_model import GenModel
from index_gru import IndexGRU
from index_linear import IndexLinear
parser = setup_parser()
args = parser.parse_args()
logger = setup_logger('pt-nce-%s' % args.save)
logger.info(args)
# Set the random seed manually for reproducibility.
torch.manual_seed(args.seed)
if torch.cuda.is_available():
if not args.cuda:
logger.warning('You have a CUDA device, so you should probably run with --cuda')
else:
torch.cuda.manual_seed(args.seed)
#################################################################
# Load data
#################################################################
corpus = data.Corpus(
path=args.data,
vocab_path=args.vocab,
batch_size=args.batch_size,
shuffle=True,
pin_memory=args.cuda,
)
eval_batch_size = 1
################################################################## Build the criterion and model, setup the NCE and index_module
#################################################################
ntoken = len(corpus.train.dataset.dictionary)
logger.info('Vocabulary size is {}'.format(ntoken))
# noise for soise sampling in NCE
noise = build_unigram_noise(
torch.FloatTensor(corpus.train.dataset.dictionary.idx2count)
)
if args.index_module == 'linear':
index_module = IndexLinear(args.nhid, ntoken)
criterion = NCELoss(
index_module=index_module,
noise=noise,
noise_ratio=args.noise_ratio,
norm_term=args.norm_term,
)
criterion.nce_mode(args.nce)
model = RNNModel(
ntoken, args.emsize, args.nhid, args.nlayers,
criterion=criterion, dropout=args.dropout,
)
sep_target=True
elif args.index_module == 'gru':
logger.warning('Falling into one layer GRU due to indx_GRU supporting')
index_gru = IndexGRU(ntoken, args.nhid, args.nhid, args.dropout)
nce_criterion = NCELoss(
index_module=index_gru,
noise=noise,
noise_ratio=args.noise_ratio,
norm_term=args.norm_term,
)
model = GenModel(
criterion=nce_criterion,
)
sep_target=False
else:
logger.error('The index module [%s] is not supported yet' % args.index_module)
raise(NotImplementedError('index module not supported'))
if args.cuda:
model.cuda()
logger.info('model definition:\n %s', model)
#################################################################
# Training code
#################################################################
def train(model, data_source, lr=1.0, weight_decay=1e-5, momentum=0.9):
optimizer = optim.SGD(
params=model.parameters(),
lr=lr,
momentum=momentum,
weight_decay=weight_decay
)
# Turn on training mode which enables dropout.
model.train()
model.criterion.nce_mode(args.nce)
total_loss = 0
pbar = tqdm(data_source, desc='Training PPL: ....')
for num_batch, data_batch in enumerate(pbar):
optimizer.zero_grad()
data, target, length = process_data(data_batch, cuda=args.cuda, sep_target=sep_target)
loss = model(data, target, length)
loss.backward()
# `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)
optimizer.step()
total_loss += loss.data[0]
if num_batch % args.log_interval == 0 and num_batch > 0:
if args.prof:
break
cur_loss = total_loss / args.log_interval
ppl = math.exp(cur_loss)
logger.debug(
'| epoch {:3d} | {:5d}/{:5d} batches '
'| lr {:02.2f} | loss {:5.2f} | ppl {:8.2f}'.format(
epoch, num_batch, len(corpus.train),
lr, cur_loss, ppl
)
)
pbar.set_description('Training PPL %.1f' % ppl)
total_loss = 0
def evaluate(model, data_source, cuda=args.cuda):
# Turn on evaluation mode which disables dropout.
model.eval()
# GRU does not support ce mode right now
if sep_target:
model.criterion.disable_nce()
eval_loss = 0
total_length = 0
data_source.batch_size = eval_batch_size
for data_batch in data_source:
data, target, length = process_data(data_batch, cuda=cuda, eval=True, sep_target=sep_target)
loss = model(data, target, length)
cur_length = length.sum()
eval_loss += loss.data[0] * cur_length
total_length += cur_length
return math.exp(eval_loss/total_length)
if __name__ == '__main__':
lr = args.lr
best_val_ppl = None
if args.train:
# At any point you can hit Ctrl + C to break out of training early.
try:
# Loop over epochs.
for epoch in range(1, args.epochs + 1):
epoch_start_time = time.time()
train(model, corpus.train, lr=lr, weight_decay=args.weight_decay)
if args.prof:
break
val_ppl = evaluate(model, corpus.valid)
logger.info(
'| end of epoch {:3d} | time: {:5.2f}s |'
'valid ppl {:8.2f}'.format(
epoch,
(time.time() - epoch_start_time),
val_ppl)
)
with open(args.save+'.epoch_{}'.format(epoch), 'wb') as f:
torch.save(model, f)
# Save the model if the validation loss is the best we've seen so far.
if not best_val_ppl or val_ppl < best_val_ppl:
with open(args.save, 'wb') as f:
torch.save(model, f)
best_val_ppl = val_ppl
else:
# Anneal the learning rate if no improvement has been seen in the
# validation dataset.
lr /= args.lr_decay
except KeyboardInterrupt:
logger.warning('Exiting from training early')
else:
# Load the best saved model.
with open(args.save, 'rb') as f:
model = torch.load(f)
# Run on test data.
test_ppl = evaluate(model, corpus.test)
logger.warning('| End of training | test ppl {:8.2f}'.format(test_ppl))
sys.stdout.flush()