-
Notifications
You must be signed in to change notification settings - Fork 7
/
train_multiple.py
219 lines (184 loc) · 8.03 KB
/
train_multiple.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
""" Script to train the selected model
Used to train a Multi-lingual model ( Teacher model )
Loads individual student models and then
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle
import time
import tensorflow as tf
from tqdm import tqdm
from src.MultilingualDataLoader import ProcessMultilingualDataset
from src.arguments import get_args
from src.models.GraphAttentionModel import TransGAT
from src.utils.metrics import LossLayer
from src.utils.model_utils import CustomSchedule, _set_up_dirs
from src.utils.rogue import rouge_n
# model paramteres
if __name__ == "__main__":
args = get_args()
global step
# set up dirs
(OUTPUT_DIR, EvalResultsFile,
TestResults, log_file, log_dir) = _set_up_dirs(args)
if args.enc_type == 'gat' and args.dec_type == 'transformer':
OUTPUT_DIR += '/' + args.enc_type + '_' + args.dec_type
(dataset, src_vocab, src_vocab_size, tgt_vocab,
tgt_vocab_size, MULTI_BUFFER_SIZE, steps_per_epoch, MaxSeqSize) = ProcessMultilingualDataset(args)
# Load the eval src and tgt files for evaluation
reference = open(args.eval_ref, 'r')
eval_file = open(args.eval, 'r')
model = TransGAT(args, src_vocab_size, src_vocab,
tgt_vocab_size, MaxSeqSize, tgt_vocab)
loss_layer = LossLayer(tgt_vocab_size, 0.1)
if args.decay is not None:
learning_rate = CustomSchedule(args.emb_dim, warmup_steps=args.decay_steps)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.9, beta2=0.98,
epsilon=1e-9)
else:
optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate, beta1=0.9, beta2=0.98,
epsilon=1e-9)
step = 0
# Save model parameters for future use
if os.path.isfile(log_dir + '/' + args.lang + '_model_params'):
with open(log_dir + '/' + args.lang + '_model_params', 'rb') as fp:
PARAMS = pickle.load(fp)
print('Loaded Parameters..')
else:
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
PARAMS = {
"args": args,
"src_vocab_size": src_vocab_size,
"tgt_vocab_size": tgt_vocab_size,
"step": 0
}
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction='none')
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(
name='train_accuracy')
ckpt = tf.train.Checkpoint(
model=model
)
ckpt_manager = tf.train.CheckpointManager(ckpt, OUTPUT_DIR, max_to_keep=5)
if ckpt_manager.latest_checkpoint:
ckpt.restore(ckpt_manager.latest_checkpoint)
print('Latest checkpoint restored!!')
if args.epochs is not None:
steps = args.epochs * steps_per_epoch
else:
steps = args.steps
def train_step(nodes, labels, node1, node2, targ):
with tf.GradientTape() as tape:
predictions = model(nodes, labels, node1, node2, targ, None)
predictions = model.metric_layer([predictions, targ])
batch_loss = loss_layer([predictions, targ])
gradients = tape.gradient(batch_loss, model.trainable_weights)
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
acc = model.metrics[0].result()
ppl = model.metrics[-1].result()
batch_loss = train_loss(batch_loss)
return batch_loss, acc, ppl
# Eval function
def eval_step(steps):
model.trainable = False
results = []
ref_target = []
eval_results = open(EvalResultsFile, 'w+')
for (batch, (nodes, labels,
node1, node2, target)) in tqdm(enumerate(
dataset['eval_set'].take(steps))):
predictions = model(nodes, labels, node1,
node2, targ=None, mask=None)
pred = [(predictions['outputs'].numpy().tolist())]
if args.sentencepiece == 'True':
for i in range(len(pred[0])):
sentence = (tgt_vocab.DecodeIds(list(pred[0][i])))
sentence = sentence.partition("<start>")[2].partition("<end>")[0]
eval_results.write(sentence + '\n')
ref_target.append(reference.readline())
results.append(sentence)
else:
for i in pred:
sentences = tgt_vocab.sequences_to_texts(i)
sentence = [j.partition("<start>")[2].partition("<end>")[0] for j in sentences]
for w in sentence:
eval_results.write((w + '\n'))
ref_target.append(reference.readline())
results.append(w)
rogue = (rouge_n(results, ref_target))
eval_results.close()
model.trainable = True
return rogue
# Eval function
def test_step():
model.trainable = False
results = []
ref_target = []
eval_results = open(TestResults, 'w+')
for (batch, (nodes, labels, node1, node2)) in tqdm(enumerate(
dataset['test_set'])):
predictions = model(nodes, labels, node1,
node2, targ=None, mask=None)
pred = [(predictions['outputs'].numpy().tolist())]
if args.sentencepiece == 'True':
for i in range(len(pred[0])):
sentence = (tgt_vocab.DecodeIds(list(pred[0][i])))
sentence = sentence.partition("<start>")[2].partition("<end>")[0]
eval_results.write(sentence + '\n')
ref_target.append(reference.readline())
results.append(sentence)
else:
for i in pred:
sentences = tgt_vocab.sequences_to_texts(i)
sentence = [j.partition("<start>")[2].partition("<end>")[0] for j in sentences]
for w in sentence:
eval_results.write((w + '\n'))
ref_target.append(reference.readline())
results.append(w)
rogue = (rouge_n(results, ref_target))
score = 0
eval_results.close()
model.trainable = True
return rogue, score
train_loss.reset_states()
train_accuracy.reset_states()
for (batch, (nodes, labels,
node1, node2, targ)) in tqdm(enumerate(
dataset['train_set'].repeat(-1))):
if PARAMS['step'] < steps:
start = time.time()
PARAMS['step'] += 1
if args.decay is not None:
optimizer._lr = learning_rate(tf.cast(PARAMS['step'], dtype=tf.float32))
batch_loss, acc, ppl = train_step(nodes, labels, node1, node2, targ)
if batch % 100 == 0:
print('Step {} Learning Rate {:.4f} Train Loss {:.4f} '
'Accuracy {:.4f} Perplex {:.4f}'.format(PARAMS['step'],
optimizer._lr,
train_loss.result(),
acc.numpy(),
ppl.numpy()))
print('Time {} \n'.format(time.time() - start))
# log the training results
tf.io.write_file(log_file,
f"Step {PARAMS['step']} Train Accuracy: {acc.numpy()}"
f" Loss: {train_loss.result()} Perplexity: {ppl.numpy()} \n")
if batch % args.eval_steps == 0:
rogue = eval_step(5)
print('\n' + '---------------------------------------------------------------------' + '\n')
print('Rogue {:.4f}'.format(rogue))
print('\n' + '---------------------------------------------------------------------' + '\n')
if batch % args.checkpoint == 0:
ckpt_save_path = ckpt_manager.save()
print("Saving checkpoint \n")
with open(log_dir + '/' + args.lang + '_model_params', 'wb+') as fp:
pickle.dump(PARAMS, fp)
else:
break
rogue, score = test_step()
print('\n' + '---------------------------------------------------------------------' + '\n')
print('Rogue {:.4f} BLEU {:.4f}'.format(rogue, score))
print('\n' + '---------------------------------------------------------------------' + '\n')