forked from facebookresearch/pytext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseq2seq_model_tests.py
258 lines (229 loc) · 9.62 KB
/
seq2seq_model_tests.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
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reservedimport unittest
import unittest
import torch
from pytext.common.constants import Stage
from pytext.data import Batcher
from pytext.data.data import Data
from pytext.data.sources.data_source import Gazetteer
from pytext.data.sources.tsv import TSVDataSource
from pytext.data.tensorizers import (
ByteTokenTensorizer,
GazetteerTensorizer,
TokenTensorizer,
initialize_tensorizers,
)
from pytext.models.embeddings import (
ContextualTokenEmbedding,
DictEmbedding,
WordEmbedding,
)
from pytext.models.seq_models.rnn_encoder import LSTMSequenceEncoder
from pytext.models.seq_models.rnn_encoder_decoder import RNNModel
from pytext.models.seq_models.seq2seq_model import Seq2SeqModel
# @dep //pytext/utils:utils_lib
from pytext.utils.test import import_tests_module
tests_module = import_tests_module()
TEST_FILE_NAME = tests_module.test_file("seq2seq_model_unit.tsv")
def get_tensorizers(add_dict_feat=False, add_contextual_feat=False):
schema = {"source_sequence": str, "dict_feat": Gazetteer, "target_sequence": str}
data_source = TSVDataSource.from_config(
TSVDataSource.Config(
train_filename=TEST_FILE_NAME,
field_names=["source_sequence", "dict_feat", "target_sequence"],
),
schema,
)
src_tensorizer = TokenTensorizer.from_config(
TokenTensorizer.Config(
column="source_sequence", add_eos_token=True, add_bos_token=True
)
)
tgt_tensorizer = TokenTensorizer.from_config(
TokenTensorizer.Config(
column="target_sequence", add_eos_token=True, add_bos_token=True
)
)
tensorizers = {"src_seq_tokens": src_tensorizer, "trg_seq_tokens": tgt_tensorizer}
initialize_tensorizers(tensorizers, data_source.train)
if add_dict_feat:
tensorizers["dict_feat"] = GazetteerTensorizer.from_config(
GazetteerTensorizer.Config(
text_column="source_sequence", dict_column="dict_feat"
)
)
initialize_tensorizers(
{"dict_feat": tensorizers["dict_feat"]}, data_source.train
)
if add_contextual_feat:
tensorizers["contextual_token_embedding"] = ByteTokenTensorizer.from_config(
ByteTokenTensorizer.Config(column="source_sequence")
)
initialize_tensorizers(
{"contextual_token_embedding": tensorizers["contextual_token_embedding"]},
data_source.train,
)
return tensorizers
# Smoke tests that call torchscriptify and execute the model for all the cases.
# This should at least make sure we're testing end to end.
class Seq2SeqModelExportTests(unittest.TestCase):
def test_tokens(self):
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
),
get_tensorizers(),
)
model.eval()
ts_model = model.torchscriptify()
res = ts_model(["call", "mom"])
assert res is not None
def test_tokens_contextual(self):
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
inputs=Seq2SeqModel.Config.ModelInput(
contextual_token_embedding=ByteTokenTensorizer.Config()
),
contextual_token_embedding=ContextualTokenEmbedding.Config(embed_dim=7),
encoder_decoder=RNNModel.Config(
encoder=LSTMSequenceEncoder.Config(embed_dim=519)
),
),
get_tensorizers(add_contextual_feat=True),
)
model.eval()
ts_model = model.torchscriptify()
res = ts_model(["call", "mom"], contextual_token_embedding=[0.42] * (7 * 2))
assert res is not None
def test_tokens_dictfeat(self):
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
inputs=Seq2SeqModel.Config.ModelInput(
dict_feat=GazetteerTensorizer.Config(text_column="source_sequence")
),
encoder_decoder=RNNModel.Config(
encoder=LSTMSequenceEncoder.Config(embed_dim=612)
),
dict_embedding=DictEmbedding.Config(),
),
get_tensorizers(add_dict_feat=True),
)
model.eval()
ts_model = model.torchscriptify()
res = ts_model(["call", "mom"], (["call", "mom"], [0.42, 0.17], [4, 3]))
assert res is not None
def test_tokens_dictfeat_contextual(self):
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
inputs=Seq2SeqModel.Config.ModelInput(
dict_feat=GazetteerTensorizer.Config(text_column="source_sequence"),
contextual_token_embedding=ByteTokenTensorizer.Config(),
),
encoder_decoder=RNNModel.Config(
encoder=LSTMSequenceEncoder.Config(embed_dim=619)
),
dict_embedding=DictEmbedding.Config(),
contextual_token_embedding=ContextualTokenEmbedding.Config(embed_dim=7),
),
get_tensorizers(add_dict_feat=True, add_contextual_feat=True),
)
model.eval()
ts_model = model.torchscriptify()
res = ts_model(
["call", "mom"], (["call", "mom"], [0.42, 0.17], [4, 3]), [0.42] * (7 * 2)
)
assert res is not None
# Seq2SeqModel has restrictions on what can happen during evaluation, since
# sequence generation has the opportunity to affect the underlying model.
class Seq2SeqModelEvalTests(unittest.TestCase):
def test_force_predictions_on_eval(self):
tensorizers = get_tensorizers()
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
),
tensorizers,
)
# Get sample inputs using a data source.
schema = {
"source_sequence": str,
"dict_feat": Gazetteer,
"target_sequence": str,
}
data = Data.from_config(
Data.Config(
source=TSVDataSource.Config(
train_filename=TEST_FILE_NAME,
field_names=["source_sequence", "dict_feat", "target_sequence"],
)
),
schema,
tensorizers,
)
data.batcher = Batcher(1, 1, 1)
raw_batch, batch = next(iter(data.batches(Stage.TRAIN, load_early=True)))
inputs = model.arrange_model_inputs(batch)
# Verify that model does not run sequence generation on prediction.
outputs = model(*inputs)
pred = model.get_pred(outputs, {"stage": Stage.EVAL})
self.assertEqual(pred, (None, None))
# Verify that attempting to set force_eval_predictions is correctly
# accounted for.
model.force_eval_predictions = True
with self.assertRaises(AssertionError):
_ = model.get_pred(outputs, {"stage": Stage.EVAL})
def test_reset_incremental_states(self):
"""
This test might seem trivial. However, interacting with the scripted
sequence generator crosses the Torchscript boundary, which can lead
to weird behavior. If the incremental states don't get properly
reset, the model will produce garbage _after_ the first call, which
is a pain to debug when you only catch it after training.
"""
tensorizers = get_tensorizers()
# Avoid numeric issues with quantization by setting a known seed.
torch.manual_seed(42)
model = Seq2SeqModel.from_config(
Seq2SeqModel.Config(
source_embedding=WordEmbedding.Config(embed_dim=512),
target_embedding=WordEmbedding.Config(embed_dim=512),
),
tensorizers,
)
# Get sample inputs using a data source.
schema = {
"source_sequence": str,
"dict_feat": Gazetteer,
"target_sequence": str,
}
data = Data.from_config(
Data.Config(
source=TSVDataSource.Config(
train_filename=TEST_FILE_NAME,
field_names=["source_sequence", "dict_feat", "target_sequence"],
)
),
schema,
tensorizers,
)
data.batcher = Batcher(1, 1, 1)
raw_batch, batch = next(iter(data.batches(Stage.TRAIN, load_early=True)))
inputs = model.arrange_model_inputs(batch)
model.eval()
outputs = model(*inputs)
pred, scores = model.get_pred(outputs, {"stage": Stage.TEST})
# Verify that the incremental states reset correctly.
decoder = model.sequence_generator.beam_search.decoder_ens
decoder.reset_incremental_states()
self.assertDictEqual(decoder.incremental_states, {"0": {}})
# Verify that the model returns the same predictions.
new_pred, new_scores = model.get_pred(outputs, {"stage": Stage.TEST})
self.assertEqual(new_scores, scores)