transformers

Форк
0
/
test_modeling_squeezebert.py 
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

17
import unittest
18

19
from transformers import SqueezeBertConfig, is_torch_available
20
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
21

22
from ...test_configuration_common import ConfigTester
23
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
24
from ...test_pipeline_mixin import PipelineTesterMixin
25

26

27
if is_torch_available():
28
    import torch
29

30
    from transformers import (
31
        SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
32
        SqueezeBertForMaskedLM,
33
        SqueezeBertForMultipleChoice,
34
        SqueezeBertForQuestionAnswering,
35
        SqueezeBertForSequenceClassification,
36
        SqueezeBertForTokenClassification,
37
        SqueezeBertModel,
38
    )
39

40

41
class SqueezeBertModelTester(object):
42
    def __init__(
43
        self,
44
        parent,
45
        batch_size=13,
46
        seq_length=7,
47
        is_training=True,
48
        use_input_mask=True,
49
        use_token_type_ids=False,
50
        use_labels=True,
51
        vocab_size=99,
52
        hidden_size=32,
53
        num_hidden_layers=2,
54
        num_attention_heads=4,
55
        intermediate_size=64,
56
        hidden_act="gelu",
57
        hidden_dropout_prob=0.1,
58
        attention_probs_dropout_prob=0.1,
59
        max_position_embeddings=512,
60
        type_vocab_size=16,
61
        type_sequence_label_size=2,
62
        initializer_range=0.02,
63
        num_labels=3,
64
        num_choices=4,
65
        scope=None,
66
        q_groups=2,
67
        k_groups=2,
68
        v_groups=2,
69
        post_attention_groups=2,
70
        intermediate_groups=4,
71
        output_groups=1,
72
    ):
73
        self.parent = parent
74
        self.batch_size = batch_size
75
        self.seq_length = seq_length
76
        self.is_training = is_training
77
        self.use_input_mask = use_input_mask
78
        self.use_token_type_ids = use_token_type_ids
79
        self.use_labels = use_labels
80
        self.vocab_size = vocab_size
81
        self.hidden_size = hidden_size
82
        self.num_hidden_layers = num_hidden_layers
83
        self.num_attention_heads = num_attention_heads
84
        self.intermediate_size = intermediate_size
85
        self.hidden_act = hidden_act
86
        self.hidden_dropout_prob = hidden_dropout_prob
87
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
88
        self.max_position_embeddings = max_position_embeddings
89
        self.type_vocab_size = type_vocab_size
90
        self.type_sequence_label_size = type_sequence_label_size
91
        self.initializer_range = initializer_range
92
        self.num_labels = num_labels
93
        self.num_choices = num_choices
94
        self.scope = scope
95
        self.q_groups = q_groups
96
        self.k_groups = k_groups
97
        self.v_groups = v_groups
98
        self.post_attention_groups = post_attention_groups
99
        self.intermediate_groups = intermediate_groups
100
        self.output_groups = output_groups
101

102
    def prepare_config_and_inputs(self):
103
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
104

105
        input_mask = None
106
        if self.use_input_mask:
107
            input_mask = random_attention_mask([self.batch_size, self.seq_length])
108

109
        sequence_labels = None
110
        token_labels = None
111
        choice_labels = None
112
        if self.use_labels:
113
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
114
            token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
115
            choice_labels = ids_tensor([self.batch_size], self.num_choices)
116

117
        config = self.get_config()
118

119
        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
120

121
    def get_config(self):
122
        return SqueezeBertConfig(
123
            embedding_size=self.hidden_size,
124
            vocab_size=self.vocab_size,
125
            hidden_size=self.hidden_size,
126
            num_hidden_layers=self.num_hidden_layers,
127
            num_attention_heads=self.num_attention_heads,
128
            intermediate_size=self.intermediate_size,
129
            hidden_act=self.hidden_act,
130
            attention_probs_dropout_prob=self.hidden_dropout_prob,
131
            attention_dropout=self.attention_probs_dropout_prob,
132
            max_position_embeddings=self.max_position_embeddings,
133
            initializer_range=self.initializer_range,
134
            q_groups=self.q_groups,
135
            k_groups=self.k_groups,
136
            v_groups=self.v_groups,
137
            post_attention_groups=self.post_attention_groups,
138
            intermediate_groups=self.intermediate_groups,
139
            output_groups=self.output_groups,
140
        )
141

142
    def create_and_check_squeezebert_model(
143
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
144
    ):
145
        model = SqueezeBertModel(config=config)
146
        model.to(torch_device)
147
        model.eval()
148
        result = model(input_ids, input_mask)
149
        result = model(input_ids)
150
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
151

152
    def create_and_check_squeezebert_for_masked_lm(
153
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
154
    ):
155
        model = SqueezeBertForMaskedLM(config=config)
156
        model.to(torch_device)
157
        model.eval()
158
        result = model(input_ids, attention_mask=input_mask, labels=token_labels)
159
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
160

161
    def create_and_check_squeezebert_for_question_answering(
162
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
163
    ):
164
        model = SqueezeBertForQuestionAnswering(config=config)
165
        model.to(torch_device)
166
        model.eval()
167
        result = model(
168
            input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels
169
        )
170
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
171
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
172

173
    def create_and_check_squeezebert_for_sequence_classification(
174
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
175
    ):
176
        config.num_labels = self.num_labels
177
        model = SqueezeBertForSequenceClassification(config)
178
        model.to(torch_device)
179
        model.eval()
180
        result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
181
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
182

183
    def create_and_check_squeezebert_for_token_classification(
184
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
185
    ):
186
        config.num_labels = self.num_labels
187
        model = SqueezeBertForTokenClassification(config=config)
188
        model.to(torch_device)
189
        model.eval()
190

191
        result = model(input_ids, attention_mask=input_mask, labels=token_labels)
192
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
193

194
    def create_and_check_squeezebert_for_multiple_choice(
195
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
196
    ):
197
        config.num_choices = self.num_choices
198
        model = SqueezeBertForMultipleChoice(config=config)
199
        model.to(torch_device)
200
        model.eval()
201
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
202
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
203
        result = model(
204
            multiple_choice_inputs_ids,
205
            attention_mask=multiple_choice_input_mask,
206
            labels=choice_labels,
207
        )
208
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
209

210
    def prepare_config_and_inputs_for_common(self):
211
        config_and_inputs = self.prepare_config_and_inputs()
212
        (config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
213
        inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
214
        return config, inputs_dict
215

216

217
@require_torch
218
class SqueezeBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
219
    all_model_classes = (
220
        (
221
            SqueezeBertModel,
222
            SqueezeBertForMaskedLM,
223
            SqueezeBertForMultipleChoice,
224
            SqueezeBertForQuestionAnswering,
225
            SqueezeBertForSequenceClassification,
226
            SqueezeBertForTokenClassification,
227
        )
228
        if is_torch_available()
229
        else None
230
    )
231
    pipeline_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
        }
240
        if is_torch_available()
241
        else {}
242
    )
243
    test_pruning = False
244
    test_resize_embeddings = True
245
    test_head_masking = False
246

247
    def setUp(self):
248
        self.model_tester = SqueezeBertModelTester(self)
249
        self.config_tester = ConfigTester(self, config_class=SqueezeBertConfig, dim=37)
250

251
    def test_config(self):
252
        self.config_tester.run_common_tests()
253

254
    def test_squeezebert_model(self):
255
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
256
        self.model_tester.create_and_check_squeezebert_model(*config_and_inputs)
257

258
    def test_for_masked_lm(self):
259
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
260
        self.model_tester.create_and_check_squeezebert_for_masked_lm(*config_and_inputs)
261

262
    def test_for_question_answering(self):
263
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
264
        self.model_tester.create_and_check_squeezebert_for_question_answering(*config_and_inputs)
265

266
    def test_for_sequence_classification(self):
267
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
268
        self.model_tester.create_and_check_squeezebert_for_sequence_classification(*config_and_inputs)
269

270
    def test_for_token_classification(self):
271
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
272
        self.model_tester.create_and_check_squeezebert_for_token_classification(*config_and_inputs)
273

274
    def test_for_multiple_choice(self):
275
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
276
        self.model_tester.create_and_check_squeezebert_for_multiple_choice(*config_and_inputs)
277

278
    @slow
279
    def test_model_from_pretrained(self):
280
        for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
281
            model = SqueezeBertModel.from_pretrained(model_name)
282
            self.assertIsNotNone(model)
283

284

285
@require_sentencepiece
286
@require_tokenizers
287
@require_torch
288
class SqueezeBertModelIntegrationTest(unittest.TestCase):
289
    @slow
290
    def test_inference_classification_head(self):
291
        model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli")
292

293
        input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]])
294
        output = model(input_ids)[0]
295
        expected_shape = torch.Size((1, 3))
296
        self.assertEqual(output.shape, expected_shape)
297
        expected_tensor = torch.tensor([[0.6401, -0.0349, -0.6041]])
298
        self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4))
299

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.