transformers
261 строка · 10.2 Кб
1# coding=utf-8
2# Copyright 2020 The HuggingFace Team. All rights reserved.
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
17from __future__ import annotations
18
19import unittest
20
21from transformers import DistilBertConfig, is_tf_available
22from transformers.testing_utils import require_tf, slow
23
24from ...test_configuration_common import ConfigTester
25from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
26from ...test_pipeline_mixin import PipelineTesterMixin
27
28
29if is_tf_available():
30import tensorflow as tf
31
32from transformers.models.distilbert.modeling_tf_distilbert import (
33TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
34TFDistilBertForMaskedLM,
35TFDistilBertForMultipleChoice,
36TFDistilBertForQuestionAnswering,
37TFDistilBertForSequenceClassification,
38TFDistilBertForTokenClassification,
39TFDistilBertModel,
40)
41
42
43class TFDistilBertModelTester:
44def __init__(
45self,
46parent,
47):
48self.parent = parent
49self.batch_size = 13
50self.seq_length = 7
51self.is_training = True
52self.use_input_mask = True
53self.use_token_type_ids = False
54self.use_labels = True
55self.vocab_size = 99
56self.hidden_size = 32
57self.num_hidden_layers = 2
58self.num_attention_heads = 4
59self.intermediate_size = 37
60self.hidden_act = "gelu"
61self.hidden_dropout_prob = 0.1
62self.attention_probs_dropout_prob = 0.1
63self.max_position_embeddings = 512
64self.type_vocab_size = 16
65self.type_sequence_label_size = 2
66self.initializer_range = 0.02
67self.num_labels = 3
68self.num_choices = 4
69self.scope = None
70
71def prepare_config_and_inputs(self):
72input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
73
74input_mask = None
75if self.use_input_mask:
76input_mask = random_attention_mask([self.batch_size, self.seq_length])
77
78sequence_labels = None
79token_labels = None
80choice_labels = None
81if self.use_labels:
82sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
83token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
84choice_labels = ids_tensor([self.batch_size], self.num_choices)
85
86config = DistilBertConfig(
87vocab_size=self.vocab_size,
88dim=self.hidden_size,
89n_layers=self.num_hidden_layers,
90n_heads=self.num_attention_heads,
91hidden_dim=self.intermediate_size,
92hidden_act=self.hidden_act,
93dropout=self.hidden_dropout_prob,
94attention_dropout=self.attention_probs_dropout_prob,
95max_position_embeddings=self.max_position_embeddings,
96initializer_range=self.initializer_range,
97)
98
99return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
100
101def create_and_check_distilbert_model(
102self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
103):
104model = TFDistilBertModel(config=config)
105inputs = {"input_ids": input_ids, "attention_mask": input_mask}
106
107result = model(inputs)
108
109inputs = [input_ids, input_mask]
110
111result = model(inputs)
112
113self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
114
115def create_and_check_distilbert_for_masked_lm(
116self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
117):
118model = TFDistilBertForMaskedLM(config=config)
119inputs = {"input_ids": input_ids, "attention_mask": input_mask}
120result = model(inputs)
121self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
122
123def create_and_check_distilbert_for_question_answering(
124self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
125):
126model = TFDistilBertForQuestionAnswering(config=config)
127inputs = {
128"input_ids": input_ids,
129"attention_mask": input_mask,
130}
131result = model(inputs)
132self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
133self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
134
135def create_and_check_distilbert_for_sequence_classification(
136self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
137):
138config.num_labels = self.num_labels
139model = TFDistilBertForSequenceClassification(config)
140inputs = {"input_ids": input_ids, "attention_mask": input_mask}
141result = model(inputs)
142self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
143
144def create_and_check_distilbert_for_multiple_choice(
145self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
146):
147config.num_choices = self.num_choices
148model = TFDistilBertForMultipleChoice(config)
149multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
150multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
151inputs = {
152"input_ids": multiple_choice_inputs_ids,
153"attention_mask": multiple_choice_input_mask,
154}
155result = model(inputs)
156self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
157
158def create_and_check_distilbert_for_token_classification(
159self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
160):
161config.num_labels = self.num_labels
162model = TFDistilBertForTokenClassification(config)
163inputs = {"input_ids": input_ids, "attention_mask": input_mask}
164result = model(inputs)
165self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
166
167def prepare_config_and_inputs_for_common(self):
168config_and_inputs = self.prepare_config_and_inputs()
169(config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
170inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
171return config, inputs_dict
172
173
174@require_tf
175class TFDistilBertModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
176all_model_classes = (
177(
178TFDistilBertModel,
179TFDistilBertForMaskedLM,
180TFDistilBertForQuestionAnswering,
181TFDistilBertForSequenceClassification,
182TFDistilBertForTokenClassification,
183TFDistilBertForMultipleChoice,
184)
185if is_tf_available()
186else None
187)
188pipeline_model_mapping = (
189{
190"feature-extraction": TFDistilBertModel,
191"fill-mask": TFDistilBertForMaskedLM,
192"question-answering": TFDistilBertForQuestionAnswering,
193"text-classification": TFDistilBertForSequenceClassification,
194"token-classification": TFDistilBertForTokenClassification,
195"zero-shot": TFDistilBertForSequenceClassification,
196}
197if is_tf_available()
198else {}
199)
200test_head_masking = False
201test_onnx = False
202
203def setUp(self):
204self.model_tester = TFDistilBertModelTester(self)
205self.config_tester = ConfigTester(self, config_class=DistilBertConfig, dim=37)
206
207def test_config(self):
208self.config_tester.run_common_tests()
209
210def test_distilbert_model(self):
211config_and_inputs = self.model_tester.prepare_config_and_inputs()
212self.model_tester.create_and_check_distilbert_model(*config_and_inputs)
213
214def test_for_masked_lm(self):
215config_and_inputs = self.model_tester.prepare_config_and_inputs()
216self.model_tester.create_and_check_distilbert_for_masked_lm(*config_and_inputs)
217
218def test_for_question_answering(self):
219config_and_inputs = self.model_tester.prepare_config_and_inputs()
220self.model_tester.create_and_check_distilbert_for_question_answering(*config_and_inputs)
221
222def test_for_sequence_classification(self):
223config_and_inputs = self.model_tester.prepare_config_and_inputs()
224self.model_tester.create_and_check_distilbert_for_sequence_classification(*config_and_inputs)
225
226def test_for_multiple_choice(self):
227config_and_inputs = self.model_tester.prepare_config_and_inputs()
228self.model_tester.create_and_check_distilbert_for_multiple_choice(*config_and_inputs)
229
230def test_for_token_classification(self):
231config_and_inputs = self.model_tester.prepare_config_and_inputs()
232self.model_tester.create_and_check_distilbert_for_token_classification(*config_and_inputs)
233
234@slow
235def test_model_from_pretrained(self):
236for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]):
237model = TFDistilBertModel.from_pretrained(model_name)
238self.assertIsNotNone(model)
239
240
241@require_tf
242class TFDistilBertModelIntegrationTest(unittest.TestCase):
243@slow
244def test_inference_masked_lm(self):
245model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
246input_ids = tf.constant([[0, 1, 2, 3, 4, 5]])
247output = model(input_ids)[0]
248
249expected_shape = [1, 6, 768]
250self.assertEqual(output.shape, expected_shape)
251
252expected_slice = tf.constant(
253[
254[
255[0.19261885, -0.13732955, 0.4119799],
256[0.22150156, -0.07422661, 0.39037204],
257[0.22756018, -0.0896414, 0.3701467],
258]
259]
260)
261tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=1e-4)
262