forked from lingyongyan/Neural-Machine-Translation
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtrain.py
168 lines (139 loc) · 5.81 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
import sys
import argparse
import etl
import helpers
import random
import time
import torch
import torch.nn as nn
import torch.optim as optim
from attention_decoder import AttentionDecoderRNN
from encoder import EncoderRNN
from language import Language
# Parse argument for language to train
parser = argparse.ArgumentParser()
parser.add_argument('--attn_model', type=str, help='attention type: dot, general, concat')
parser.add_argument('--embedding_size', type=int)
parser.add_argument('--hidden_size', type=int)
parser.add_argument('--n_layers', type=int)
parser.add_argument('--dropout', type=float)
parser.add_argument('--teacher_forcing_ratio', type=float, default=0.5)
parser.add_argument('--clip', type=float, default=5.0)
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--n_epochs', type=int)
parser.add_argument('--plot_every', type=int)
parser.add_argument('--print_every', type=int)
parser.add_argument('--language', type=str, help='specific which language.')
parser.add_argument('--input', type=str, help='src -> tgt')
parser.add_argument('--device', type=str, help='cpu or cuda')
parser.add_argument('--seed', type=str, help='random seed')
args = parser.parse_args()
print(sys.argv)
torch.random.manual_seed(args.seed)
device = torch.device(args.device)
print('device: ', device)
helpers.validate_language(args.language)
def train(input, target, encoder, decoder, encoder_opt, decoder_opt, criterion):
# Initialize optimizers and loss
encoder_opt.zero_grad()
decoder_opt.zero_grad()
loss = 0
# Get input and target seq lengths
target_length = target.size()[0]
# Run through encoder
encoder_hidden = encoder.init_hidden(device)
encoder_outputs, encoder_hidden = encoder(input, encoder_hidden)
# Prepare input and output variables
decoder_input = torch.LongTensor([0]).to(device)
decoder_context = torch.zeros(1, 1, decoder.hidden_size).to(device)
decoder_hidden = encoder_hidden
# Scheduled sampling
use_teacher_forcing = random.random() < args.teacher_forcing_ratio
if use_teacher_forcing:
# Feed target as the next input
for di in range(target_length):
decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,
decoder_context,
decoder_hidden,
encoder_outputs)
loss += criterion(decoder_output, target[di])
decoder_input = target[di]
else:
# Use previous prediction as next input
for di in range(target_length):
decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input,
decoder_context,
decoder_hidden,
encoder_outputs)
# decoder_output: [1, tgt_vocab_size]
loss += criterion(decoder_output, target[di])
topv, topi = decoder_output.data.topk(1, dim=1)
decoder_input = topi
if topi.item() == Language.eos_token:
break
# Backpropagation
loss.backward()
# print(list(encoder.parameters()))
# print(args.clip)
_ = nn.utils.clip_grad_norm_(encoder.parameters(), args.clip)
_ = nn.utils.clip_grad_norm_(decoder.parameters(), args.clip)
encoder_opt.step()
decoder_opt.step()
return loss.item() / target_length
input_lang, output_lang, pairs = etl.prepare_data(args.language)
# Initialize models
encoder = EncoderRNN(
input_lang.n_words,
args.embedding_size,
args.hidden_size,
args.n_layers,
args.dropout
)
decoder = AttentionDecoderRNN(
output_lang.n_words,
args.embedding_size,
args.hidden_size,
args.attn_model,
args.n_layers,
args.dropout
)
# Move models to device
encoder = encoder.to(device)
decoder = decoder.to(device)
# Initialize optimizers and criterion
encoder_optimizer = optim.Adam(encoder.parameters(), lr=args.lr)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=args.lr)
criterion = nn.NLLLoss()
# Keep track of time elapsed and running averages
start = time.time()
plot_losses = []
print_loss_total = 0 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
# Begin training
for epoch in range(1, args.n_epochs + 1):
# Get training data for this cycle
training_pair = etl.tensor_from_pair(random.choice(pairs), input_lang, output_lang)
input = training_pair[0]
target = training_pair[1]
# Run the train step
loss = train(input, target, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)
# Keep track of loss
print_loss_total += loss
plot_loss_total += loss
if epoch == 0:
continue
if epoch % args.print_every == 0:
print_loss_avg = print_loss_total / args.print_every
print_loss_total = 0
time_since = helpers.time_since(start, epoch / args.n_epochs)
print('%s (%d %d%%) %.4f' % (time_since, epoch, epoch / args.n_epochs * 100, print_loss_avg))
if epoch % args.plot_every == 0:
plot_loss_avg = plot_loss_total / args.plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
# Save our models
torch.save(encoder.state_dict(), './data/encoder_params_{}'.format(args.language))
torch.save(decoder.state_dict(), './data/decoder_params_{}'.format(args.language))
torch.save(decoder.attention.state_dict(), './data/attention_params_{}'.format(args.language))
# Plot loss
helpers.show_plot(plot_losses)