transformers
298 строк · 11.9 Кб
1# coding=utf-8
2# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
17import unittest
18
19from transformers import SqueezeBertConfig, is_torch_available
20from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
21
22from ...test_configuration_common import ConfigTester
23from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
24from ...test_pipeline_mixin import PipelineTesterMixin
25
26
27if is_torch_available():
28import torch
29
30from transformers import (
31SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
32SqueezeBertForMaskedLM,
33SqueezeBertForMultipleChoice,
34SqueezeBertForQuestionAnswering,
35SqueezeBertForSequenceClassification,
36SqueezeBertForTokenClassification,
37SqueezeBertModel,
38)
39
40
41class SqueezeBertModelTester(object):
42def __init__(
43self,
44parent,
45batch_size=13,
46seq_length=7,
47is_training=True,
48use_input_mask=True,
49use_token_type_ids=False,
50use_labels=True,
51vocab_size=99,
52hidden_size=32,
53num_hidden_layers=2,
54num_attention_heads=4,
55intermediate_size=64,
56hidden_act="gelu",
57hidden_dropout_prob=0.1,
58attention_probs_dropout_prob=0.1,
59max_position_embeddings=512,
60type_vocab_size=16,
61type_sequence_label_size=2,
62initializer_range=0.02,
63num_labels=3,
64num_choices=4,
65scope=None,
66q_groups=2,
67k_groups=2,
68v_groups=2,
69post_attention_groups=2,
70intermediate_groups=4,
71output_groups=1,
72):
73self.parent = parent
74self.batch_size = batch_size
75self.seq_length = seq_length
76self.is_training = is_training
77self.use_input_mask = use_input_mask
78self.use_token_type_ids = use_token_type_ids
79self.use_labels = use_labels
80self.vocab_size = vocab_size
81self.hidden_size = hidden_size
82self.num_hidden_layers = num_hidden_layers
83self.num_attention_heads = num_attention_heads
84self.intermediate_size = intermediate_size
85self.hidden_act = hidden_act
86self.hidden_dropout_prob = hidden_dropout_prob
87self.attention_probs_dropout_prob = attention_probs_dropout_prob
88self.max_position_embeddings = max_position_embeddings
89self.type_vocab_size = type_vocab_size
90self.type_sequence_label_size = type_sequence_label_size
91self.initializer_range = initializer_range
92self.num_labels = num_labels
93self.num_choices = num_choices
94self.scope = scope
95self.q_groups = q_groups
96self.k_groups = k_groups
97self.v_groups = v_groups
98self.post_attention_groups = post_attention_groups
99self.intermediate_groups = intermediate_groups
100self.output_groups = output_groups
101
102def prepare_config_and_inputs(self):
103input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
104
105input_mask = None
106if self.use_input_mask:
107input_mask = random_attention_mask([self.batch_size, self.seq_length])
108
109sequence_labels = None
110token_labels = None
111choice_labels = None
112if self.use_labels:
113sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
114token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
115choice_labels = ids_tensor([self.batch_size], self.num_choices)
116
117config = self.get_config()
118
119return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
120
121def get_config(self):
122return SqueezeBertConfig(
123embedding_size=self.hidden_size,
124vocab_size=self.vocab_size,
125hidden_size=self.hidden_size,
126num_hidden_layers=self.num_hidden_layers,
127num_attention_heads=self.num_attention_heads,
128intermediate_size=self.intermediate_size,
129hidden_act=self.hidden_act,
130attention_probs_dropout_prob=self.hidden_dropout_prob,
131attention_dropout=self.attention_probs_dropout_prob,
132max_position_embeddings=self.max_position_embeddings,
133initializer_range=self.initializer_range,
134q_groups=self.q_groups,
135k_groups=self.k_groups,
136v_groups=self.v_groups,
137post_attention_groups=self.post_attention_groups,
138intermediate_groups=self.intermediate_groups,
139output_groups=self.output_groups,
140)
141
142def create_and_check_squeezebert_model(
143self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
144):
145model = SqueezeBertModel(config=config)
146model.to(torch_device)
147model.eval()
148result = model(input_ids, input_mask)
149result = model(input_ids)
150self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
151
152def create_and_check_squeezebert_for_masked_lm(
153self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
154):
155model = SqueezeBertForMaskedLM(config=config)
156model.to(torch_device)
157model.eval()
158result = model(input_ids, attention_mask=input_mask, labels=token_labels)
159self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
160
161def create_and_check_squeezebert_for_question_answering(
162self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
163):
164model = SqueezeBertForQuestionAnswering(config=config)
165model.to(torch_device)
166model.eval()
167result = model(
168input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels
169)
170self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
171self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
172
173def create_and_check_squeezebert_for_sequence_classification(
174self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
175):
176config.num_labels = self.num_labels
177model = SqueezeBertForSequenceClassification(config)
178model.to(torch_device)
179model.eval()
180result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
181self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
182
183def create_and_check_squeezebert_for_token_classification(
184self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
185):
186config.num_labels = self.num_labels
187model = SqueezeBertForTokenClassification(config=config)
188model.to(torch_device)
189model.eval()
190
191result = model(input_ids, attention_mask=input_mask, labels=token_labels)
192self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
193
194def create_and_check_squeezebert_for_multiple_choice(
195self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
196):
197config.num_choices = self.num_choices
198model = SqueezeBertForMultipleChoice(config=config)
199model.to(torch_device)
200model.eval()
201multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
202multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
203result = model(
204multiple_choice_inputs_ids,
205attention_mask=multiple_choice_input_mask,
206labels=choice_labels,
207)
208self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
209
210def prepare_config_and_inputs_for_common(self):
211config_and_inputs = self.prepare_config_and_inputs()
212(config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
213inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
214return config, inputs_dict
215
216
217@require_torch
218class SqueezeBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
219all_model_classes = (
220(
221SqueezeBertModel,
222SqueezeBertForMaskedLM,
223SqueezeBertForMultipleChoice,
224SqueezeBertForQuestionAnswering,
225SqueezeBertForSequenceClassification,
226SqueezeBertForTokenClassification,
227)
228if is_torch_available()
229else None
230)
231pipeline_model_mapping = (
232{
233"feature-extraction": SqueezeBertModel,
234"fill-mask": SqueezeBertForMaskedLM,
235"question-answering": SqueezeBertForQuestionAnswering,
236"text-classification": SqueezeBertForSequenceClassification,
237"token-classification": SqueezeBertForTokenClassification,
238"zero-shot": SqueezeBertForSequenceClassification,
239}
240if is_torch_available()
241else {}
242)
243test_pruning = False
244test_resize_embeddings = True
245test_head_masking = False
246
247def setUp(self):
248self.model_tester = SqueezeBertModelTester(self)
249self.config_tester = ConfigTester(self, config_class=SqueezeBertConfig, dim=37)
250
251def test_config(self):
252self.config_tester.run_common_tests()
253
254def test_squeezebert_model(self):
255config_and_inputs = self.model_tester.prepare_config_and_inputs()
256self.model_tester.create_and_check_squeezebert_model(*config_and_inputs)
257
258def test_for_masked_lm(self):
259config_and_inputs = self.model_tester.prepare_config_and_inputs()
260self.model_tester.create_and_check_squeezebert_for_masked_lm(*config_and_inputs)
261
262def test_for_question_answering(self):
263config_and_inputs = self.model_tester.prepare_config_and_inputs()
264self.model_tester.create_and_check_squeezebert_for_question_answering(*config_and_inputs)
265
266def test_for_sequence_classification(self):
267config_and_inputs = self.model_tester.prepare_config_and_inputs()
268self.model_tester.create_and_check_squeezebert_for_sequence_classification(*config_and_inputs)
269
270def test_for_token_classification(self):
271config_and_inputs = self.model_tester.prepare_config_and_inputs()
272self.model_tester.create_and_check_squeezebert_for_token_classification(*config_and_inputs)
273
274def test_for_multiple_choice(self):
275config_and_inputs = self.model_tester.prepare_config_and_inputs()
276self.model_tester.create_and_check_squeezebert_for_multiple_choice(*config_and_inputs)
277
278@slow
279def test_model_from_pretrained(self):
280for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
281model = SqueezeBertModel.from_pretrained(model_name)
282self.assertIsNotNone(model)
283
284
285@require_sentencepiece
286@require_tokenizers
287@require_torch
288class SqueezeBertModelIntegrationTest(unittest.TestCase):
289@slow
290def test_inference_classification_head(self):
291model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli")
292
293input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]])
294output = model(input_ids)[0]
295expected_shape = torch.Size((1, 3))
296self.assertEqual(output.shape, expected_shape)
297expected_tensor = torch.tensor([[0.6401, -0.0349, -0.6041]])
298self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4))
299