transformers

Форк
0
/
test_modeling_albert.py 
345 строк · 14.1 Кб
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

17
import unittest
18

19
from transformers import AlbertConfig, is_torch_available
20
from transformers.models.auto import get_values
21
from transformers.testing_utils import require_torch, slow, torch_device
22

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

27

28
if is_torch_available():
29
    import torch
30

31
    from transformers import (
32
        MODEL_FOR_PRETRAINING_MAPPING,
33
        AlbertForMaskedLM,
34
        AlbertForMultipleChoice,
35
        AlbertForPreTraining,
36
        AlbertForQuestionAnswering,
37
        AlbertForSequenceClassification,
38
        AlbertForTokenClassification,
39
        AlbertModel,
40
    )
41
    from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
42

43

44
class AlbertModelTester:
45
    def __init__(
46
        self,
47
        parent,
48
        batch_size=13,
49
        seq_length=7,
50
        is_training=True,
51
        use_input_mask=True,
52
        use_token_type_ids=True,
53
        use_labels=True,
54
        vocab_size=99,
55
        embedding_size=16,
56
        hidden_size=36,
57
        num_hidden_layers=2,
58
        # this needs to be the same as `num_hidden_layers`!
59
        num_hidden_groups=2,
60
        num_attention_heads=6,
61
        intermediate_size=37,
62
        hidden_act="gelu",
63
        hidden_dropout_prob=0.1,
64
        attention_probs_dropout_prob=0.1,
65
        max_position_embeddings=512,
66
        type_vocab_size=16,
67
        type_sequence_label_size=2,
68
        initializer_range=0.02,
69
        num_labels=3,
70
        num_choices=4,
71
        scope=None,
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.embedding_size = embedding_size
82
        self.hidden_size = hidden_size
83
        self.num_hidden_layers = num_hidden_layers
84
        self.num_hidden_groups = num_hidden_groups
85
        self.num_attention_heads = num_attention_heads
86
        self.intermediate_size = intermediate_size
87
        self.hidden_act = hidden_act
88
        self.hidden_dropout_prob = hidden_dropout_prob
89
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
90
        self.max_position_embeddings = max_position_embeddings
91
        self.type_vocab_size = type_vocab_size
92
        self.type_sequence_label_size = type_sequence_label_size
93
        self.initializer_range = initializer_range
94
        self.num_labels = num_labels
95
        self.num_choices = num_choices
96
        self.scope = scope
97

98
    def prepare_config_and_inputs(self):
99
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
100

101
        input_mask = None
102
        if self.use_input_mask:
103
            input_mask = random_attention_mask([self.batch_size, self.seq_length])
104

105
        token_type_ids = None
106
        if self.use_token_type_ids:
107
            token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
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, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
120

121
    def get_config(self):
122
        return AlbertConfig(
123
            vocab_size=self.vocab_size,
124
            hidden_size=self.hidden_size,
125
            num_hidden_layers=self.num_hidden_layers,
126
            num_attention_heads=self.num_attention_heads,
127
            intermediate_size=self.intermediate_size,
128
            hidden_act=self.hidden_act,
129
            hidden_dropout_prob=self.hidden_dropout_prob,
130
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
131
            max_position_embeddings=self.max_position_embeddings,
132
            type_vocab_size=self.type_vocab_size,
133
            initializer_range=self.initializer_range,
134
            num_hidden_groups=self.num_hidden_groups,
135
        )
136

137
    def create_and_check_model(
138
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
139
    ):
140
        model = AlbertModel(config=config)
141
        model.to(torch_device)
142
        model.eval()
143
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
144
        result = model(input_ids, token_type_ids=token_type_ids)
145
        result = model(input_ids)
146
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
147
        self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
148

149
    def create_and_check_for_pretraining(
150
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
151
    ):
152
        model = AlbertForPreTraining(config=config)
153
        model.to(torch_device)
154
        model.eval()
155
        result = model(
156
            input_ids,
157
            attention_mask=input_mask,
158
            token_type_ids=token_type_ids,
159
            labels=token_labels,
160
            sentence_order_label=sequence_labels,
161
        )
162
        self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
163
        self.parent.assertEqual(result.sop_logits.shape, (self.batch_size, config.num_labels))
164

165
    def create_and_check_for_masked_lm(
166
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
167
    ):
168
        model = AlbertForMaskedLM(config=config)
169
        model.to(torch_device)
170
        model.eval()
171
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
172
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
173

174
    def create_and_check_for_question_answering(
175
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
176
    ):
177
        model = AlbertForQuestionAnswering(config=config)
178
        model.to(torch_device)
179
        model.eval()
180
        result = model(
181
            input_ids,
182
            attention_mask=input_mask,
183
            token_type_ids=token_type_ids,
184
            start_positions=sequence_labels,
185
            end_positions=sequence_labels,
186
        )
187
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
188
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
189

190
    def create_and_check_for_sequence_classification(
191
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
192
    ):
193
        config.num_labels = self.num_labels
194
        model = AlbertForSequenceClassification(config)
195
        model.to(torch_device)
196
        model.eval()
197
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
198
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
199

200
    def create_and_check_for_token_classification(
201
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
202
    ):
203
        config.num_labels = self.num_labels
204
        model = AlbertForTokenClassification(config=config)
205
        model.to(torch_device)
206
        model.eval()
207
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
208
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
209

210
    def create_and_check_for_multiple_choice(
211
        self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
212
    ):
213
        config.num_choices = self.num_choices
214
        model = AlbertForMultipleChoice(config=config)
215
        model.to(torch_device)
216
        model.eval()
217
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
218
        multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
219
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
220
        result = model(
221
            multiple_choice_inputs_ids,
222
            attention_mask=multiple_choice_input_mask,
223
            token_type_ids=multiple_choice_token_type_ids,
224
            labels=choice_labels,
225
        )
226
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
227

228
    def prepare_config_and_inputs_for_common(self):
229
        config_and_inputs = self.prepare_config_and_inputs()
230
        (
231
            config,
232
            input_ids,
233
            token_type_ids,
234
            input_mask,
235
            sequence_labels,
236
            token_labels,
237
            choice_labels,
238
        ) = config_and_inputs
239
        inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
240
        return config, inputs_dict
241

242

243
@require_torch
244
class AlbertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
245
    all_model_classes = (
246
        (
247
            AlbertModel,
248
            AlbertForPreTraining,
249
            AlbertForMaskedLM,
250
            AlbertForMultipleChoice,
251
            AlbertForSequenceClassification,
252
            AlbertForTokenClassification,
253
            AlbertForQuestionAnswering,
254
        )
255
        if is_torch_available()
256
        else ()
257
    )
258
    pipeline_model_mapping = (
259
        {
260
            "feature-extraction": AlbertModel,
261
            "fill-mask": AlbertForMaskedLM,
262
            "question-answering": AlbertForQuestionAnswering,
263
            "text-classification": AlbertForSequenceClassification,
264
            "token-classification": AlbertForTokenClassification,
265
            "zero-shot": AlbertForSequenceClassification,
266
        }
267
        if is_torch_available()
268
        else {}
269
    )
270
    fx_compatible = True
271

272
    # special case for ForPreTraining model
273
    def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
274
        inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
275

276
        if return_labels:
277
            if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
278
                inputs_dict["labels"] = torch.zeros(
279
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
280
                )
281
                inputs_dict["sentence_order_label"] = torch.zeros(
282
                    self.model_tester.batch_size, dtype=torch.long, device=torch_device
283
                )
284
        return inputs_dict
285

286
    def setUp(self):
287
        self.model_tester = AlbertModelTester(self)
288
        self.config_tester = ConfigTester(self, config_class=AlbertConfig, hidden_size=37)
289

290
    def test_config(self):
291
        self.config_tester.run_common_tests()
292

293
    def test_model(self):
294
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
295
        self.model_tester.create_and_check_model(*config_and_inputs)
296

297
    def test_for_pretraining(self):
298
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
299
        self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
300

301
    def test_for_masked_lm(self):
302
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
303
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
304

305
    def test_for_multiple_choice(self):
306
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
307
        self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
308

309
    def test_for_question_answering(self):
310
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
311
        self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
312

313
    def test_for_sequence_classification(self):
314
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
315
        self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
316

317
    def test_model_various_embeddings(self):
318
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
319
        for type in ["absolute", "relative_key", "relative_key_query"]:
320
            config_and_inputs[0].position_embedding_type = type
321
            self.model_tester.create_and_check_model(*config_and_inputs)
322

323
    @slow
324
    def test_model_from_pretrained(self):
325
        for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
326
            model = AlbertModel.from_pretrained(model_name)
327
            self.assertIsNotNone(model)
328

329

330
@require_torch
331
class AlbertModelIntegrationTest(unittest.TestCase):
332
    @slow
333
    def test_inference_no_head_absolute_embedding(self):
334
        model = AlbertModel.from_pretrained("albert/albert-base-v2")
335
        input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
336
        attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
337
        with torch.no_grad():
338
            output = model(input_ids, attention_mask=attention_mask)[0]
339
        expected_shape = torch.Size((1, 11, 768))
340
        self.assertEqual(output.shape, expected_shape)
341
        expected_slice = torch.tensor(
342
            [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]
343
        )
344

345
        self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
346

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

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

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

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