-
Notifications
You must be signed in to change notification settings - Fork 3
/
xnmt_model.py
279 lines (231 loc) · 15.4 KB
/
xnmt_model.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import os
import random
import numpy as np
import dynet_config
dynet_config.set_gpu()
dynet_config.set(mem=2048,random_seed=9)
# 1245884048
import xnmt.tee
from xnmt.modelparts.attenders import MlpAttender
from xnmt.batchers import WordSrcBatcher,InOrderBatcher,Batcher
from xnmt.modelparts.bridges import CopyBridge
from xnmt.modelparts.decoders import AutoRegressiveDecoder
from xnmt.modelparts.embedders import SimpleWordEmbedder,PretrainedSimpleWordEmbedder
from xnmt.eval.tasks import LossEvalTask, AccuracyEvalTask
from xnmt.experiments import Experiment,ExpGlobal
from xnmt.inferences import AutoRegressiveInference
from xnmt.input_readers import PlainTextReader
from xnmt.transducers.recurrent import BiLSTMSeqTransducer, UniLSTMSeqTransducer
from xnmt.modelparts.transforms import AuxNonLinear
from xnmt.modelparts.scorers import Softmax
from xnmt.optimizers import AdamTrainer
from xnmt.param_collections import ParamManager
from xnmt.persistence import save_to_file
from xnmt.train.regimens import SimpleTrainingRegimen
from xnmt.models.translators import DefaultTranslator
from xnmt.vocabs import Vocab
from xnmt.preproc import PreprocVocab,PreprocTokenize,PreprocRunner,SentencepieceTokenizer,VocabFiltererFreq
from xnmt.search_strategies import BeamSearch
from xnmt.length_norm import PolynomialNormalization
from xnmt.persistence import LoadSerialized
from vocab_builder import VocabBuilder
class Seq2SeqRunner():
def __init__(self, vocab_size=4000, model_type='unigram', min_freq=2, layers=1, layer_dim=128, alpha=0.001, epochs=1, src_embedding='SimpleWordEmbedding', dataset = 'annot', trg_embedding = None, parent_model = None, custom_emb_size = 100, dropout = 0.3 ):
self.vocab_size = vocab_size
self.model_type = model_type
self.min_freq = min_freq
self.layers = layers
self.layer_dim = layer_dim
self.alpha = alpha
self.epochs = epochs
self.src_embedding = src_embedding # used to choose pre-trained embeddings
self.dataset = dataset
self.trg_embedding = trg_embedding
self.dropout = dropout
self.train = 'conala-trainnodev'
self.dev = 'conala-dev'
self.test = 'conala-test'
if self.dataset == 'encoder':
self.train = 'encoder-train'
self.dev = 'encoder-dev'
self.test = 'encoder-test'
elif self.dataset == 'decoder':
self.train = 'decoder-train'
self.dev = 'decoder-dev'
self.test = 'decoder-test'
if self.src_embedding != 'SimpleWordEmbedding' and self.trg_embedding is None:
raise Exception ("Custom source embedding is set, please make sure to set the target embedding as well")
self.custom_emb_size = custom_emb_size
# Parent Model if transfer learning is being used
self.parent_model = parent_model
def run(self):
seed=13
random.seed(seed)
np.random.seed(seed)
EXP_DIR = os.path.dirname(__file__)
RESULTS_DIR = os.path.join(os.path.dirname(__file__),'seq2seq')
EXP = str(self.dataset)
if self.parent_model != None:
base = os.path.basename(str(self.parent_model))
file_name = os.path.splitext(base)[0]
EXP = 'parent_'+ str(file_name)+ '_child_'+ str(self.dataset)
model_file = f"{RESULTS_DIR}/results/{EXP}.mod"
log_file = f"{RESULTS_DIR}/results/{EXP}.log"
xnmt.tee.set_out_file(log_file,exp_name=EXP)
xnmt.tee.utils.dy.DynetParams().set_mem(1024) #Doesnt work figure out how to set memory
ParamManager.init_param_col()
ParamManager.param_col.model_file = model_file
builder = VocabBuilder(f"{EXP_DIR}/processed_dataset/"+self.train + '.json.seq2seq',self.min_freq)
builder.build()
pre_runner=PreprocRunner(tasks= [PreprocTokenize(in_files=[f'{EXP_DIR}/processed_dataset/'+self.train+'.snippet',
f'{EXP_DIR}/processed_dataset/'+self.train+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.dev+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.dev+'.snippet',
f'{EXP_DIR}/processed_dataset/'+self.test+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.test+'.snippet'],
out_files= [f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet',
f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.snippet',
f'{EXP_DIR}/processed_dataset/'+self.test+'.tmspm'+str(self.vocab_size)+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.test+'.tmspm'+str(self.vocab_size)+'.snippet'],
specs= [{'filenum':'all',
'tokenizers':[SentencepieceTokenizer(
hard_vocab_limit=False,
train_files= [f'{EXP_DIR}/processed_dataset/'+self.train+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.train+'.snippet'],vocab_size=self.vocab_size,
model_type= self.model_type,model_prefix= 'processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.spm')]}])
,PreprocVocab(in_files= [f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent',
f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet'],
out_files=[f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent.vocab',
f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet.vocab'],
specs=[{'filenum':'all','filters':[VocabFiltererFreq(min_freq = self.min_freq)]}])],overwrite=True)
src_vocab = Vocab(vocab_file=f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent.vocab')
trg_vocab = Vocab(vocab_file=f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet.vocab')
#trg_vocab = Vocab(vocab_file=f'{EXP_DIR}/processed_dataset/'+self.train+'.intent.vocab')
#src_vocab = Vocab(vocab_file=f'{EXP_DIR}/processed_dataset/'+self.train+'.snippet.vocab')
batcher = Batcher(batch_size=64)
# inference = AutoRegressiveInference(search_strategy= BeamSearch(beam_size= 5), post_process = 'none',src_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.intent',ref_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.snippet')
#len_norm= PolynomialNormalization(apply_during_search=True),beam_size= 5))#post_process= 'join-piece')
inference = AutoRegressiveInference(search_strategy= BeamSearch(len_norm= PolynomialNormalization(apply_during_search=True),beam_size= 5),post_process= 'join-piece')
layer_dim = self.layer_dim
if self.src_embedding == 'SimpleWordEmbedding':
model = DefaultTranslator(
src_reader=PlainTextReader(vocab=src_vocab),
trg_reader=PlainTextReader(vocab=trg_vocab),
src_embedder=SimpleWordEmbedder(emb_dim=layer_dim,vocab= src_vocab),
encoder=BiLSTMSeqTransducer(input_dim=layer_dim, hidden_dim=layer_dim, layers=self.layers),
attender=MlpAttender(hidden_dim=layer_dim, state_dim=layer_dim, input_dim=layer_dim),
trg_embedder=SimpleWordEmbedder(emb_dim=layer_dim, vocab = trg_vocab),
decoder=AutoRegressiveDecoder(input_dim=layer_dim,
rnn=UniLSTMSeqTransducer(input_dim=layer_dim, hidden_dim=layer_dim,
),
transform=AuxNonLinear(input_dim=layer_dim, output_dim=layer_dim,
aux_input_dim=layer_dim),
scorer=Softmax(vocab_size=len(trg_vocab), input_dim=layer_dim),
trg_embed_dim=layer_dim,
input_feeding= False,
bridge=CopyBridge(dec_dim=layer_dim)),
inference=inference)
else:
model = DefaultTranslator(
src_reader=PlainTextReader(vocab=src_vocab),
trg_reader=PlainTextReader(vocab=trg_vocab),
src_embedder=PretrainedSimpleWordEmbedder(filename= self.src_embedding,emb_dim=self.custom_emb_size,vocab = src_vocab),
encoder=BiLSTMSeqTransducer(input_dim=layer_dim, hidden_dim=layer_dim, layers=self.layers),
attender=MlpAttender(hidden_dim=layer_dim, state_dim=layer_dim, input_dim=layer_dim),
trg_embedder= PretrainedSimpleWordEmbedder(filename= self.trg_embedding,emb_dim=self.custom_emb_size,vocab = trg_vocab),
decoder=AutoRegressiveDecoder(input_dim=layer_dim,
rnn=UniLSTMSeqTransducer(input_dim=layer_dim, hidden_dim=layer_dim,
),
transform=AuxNonLinear(input_dim=layer_dim, output_dim=layer_dim,
aux_input_dim=layer_dim),
scorer=Softmax(vocab_size=len(trg_vocab), input_dim=layer_dim),
trg_embed_dim=layer_dim,
input_feeding= False,
bridge=CopyBridge(dec_dim=layer_dim)),
inference=inference)
#decoder = AutoRegressiveDecoder(bridge=CopyBridge(),inference=inference))
if self.parent_model is None:
train = SimpleTrainingRegimen(
name=f"{EXP}",
model=model,
batcher=WordSrcBatcher(avg_batch_size=64),
trainer=AdamTrainer(alpha=self.alpha),
patience= 3,
lr_decay= 0.5,
restart_trainer= True,
run_for_epochs=self.epochs,
src_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent',
trg_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet',
dev_tasks=[LossEvalTask(src_file=f'{EXP_DIR}/processed_dataset/'+ self.dev +'.tmspm'+str(self.vocab_size)+'.intent',
ref_file= f'{EXP_DIR}/processed_dataset/'+ self.dev +'.tmspm'+str(self.vocab_size)+'.snippet',
#src_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.intent',
#trg_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.snippet',
#dev_tasks=[LossEvalTask(src_file=f'{EXP_DIR}/processed_dataset/'+ self.dev +'.intent',
# ref_file= f'{EXP_DIR}/processed_dataset/'+ self.dev +'.snippet',
model=model,
batcher=WordSrcBatcher(avg_batch_size=64)),
AccuracyEvalTask(eval_metrics= 'bleu',
src_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.intent',
#src_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.intent',
ref_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.snippet',
hyp_file= f'{RESULTS_DIR}/results/{EXP}.dev.hyp',
model = model)])
evaluate = [AccuracyEvalTask(eval_metrics="bleu",
src_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.tmspm'+str(self.vocab_size)+'.intent',
#src_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.intent',
ref_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.snippet',
hyp_file=f"{RESULTS_DIR}/results/{EXP}.test.hyp",
inference=inference,
model=model)]
standard_experiment = Experiment(
exp_global= ExpGlobal(default_layer_dim= layer_dim, dropout= self.dropout,
log_file= log_file,model_file=model_file),
name=EXP,
model=model,
train=train,
evaluate=evaluate
)
else:
evaluate = [AccuracyEvalTask(eval_metrics="bleu",
src_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.tmspm'+str(self.vocab_size)+'.intent',
#src_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.intent',
ref_file=f'{EXP_DIR}/processed_dataset/'+self.test+'.snippet',
hyp_file=f'{RESULTS_DIR}/results/'+self.dataset+'.test.hyp',
inference=inference,
model=model)]
standard_experiment = Experiment(LoadSerialized(filename = '{EXP_DIR)/'+str(self.parent_model),overwrite=[ExpGlobal(default_layer_dim= layer_dim, dropout= self.dropout,
log_file= log_file,model_file=model_file),
]),
name=EXP,
model=model,
train=SimpleTrainingRegimen( name=f"{EXP}",
model=model,
batcher=WordSrcBatcher(avg_batch_size=64),
trainer=AdamTrainer(alpha=self.alpha),
patience= 3,
lr_decay= 0.5,
restart_trainer= True,
run_for_epochs=self.epochs,
src_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.intent',
trg_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.tmspm'+str(self.vocab_size)+'.snippet',
dev_tasks=[LossEvalTask(src_file=f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.intent',
ref_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.snippet',
#src_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.intent',
#trg_file= f'{EXP_DIR}/processed_dataset/'+self.train+'.snippet',
#dev_tasks=[LossEvalTask(src_file=f'{EXP_DIR}/processed_dataset/'+self.dev+'.intent',
#ref_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.snippet',
model=model,
batcher=WordSrcBatcher(avg_batch_size=64)),
AccuracyEvalTask(eval_metrics= 'bleu',
src_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.tmspm'+str(self.vocab_size)+'.intent',
#src_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.intent',
ref_file= f'{EXP_DIR}/processed_dataset/'+self.dev+'.snippet',
hyp_file= f'{RESULTS_DIR}/results/'+self.dataset+'.dev.hyp',
model = model)]),
evaluate=evaluate
)
# run experiment
standard_experiment(save_fct=lambda: save_to_file(model_file, standard_experiment))
exit()