transformers

Форк
0
/
test_modeling_funnel.py 
525 строк · 19.5 Кб
1
# coding=utf-8
2
# Copyright 2020 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 FunnelConfig, FunnelTokenizer, is_torch_available
20
from transformers.models.auto import get_values
21
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
22

23
from ...test_configuration_common import ConfigTester
24
from ...test_modeling_common import ModelTesterMixin, ids_tensor
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
        FunnelBaseModel,
34
        FunnelForMaskedLM,
35
        FunnelForMultipleChoice,
36
        FunnelForPreTraining,
37
        FunnelForQuestionAnswering,
38
        FunnelForSequenceClassification,
39
        FunnelForTokenClassification,
40
        FunnelModel,
41
    )
42

43

44
class FunnelModelTester:
45
    """You can also import this e.g, from .test_modeling_funnel import FunnelModelTester"""
46

47
    def __init__(
48
        self,
49
        parent,
50
        batch_size=13,
51
        seq_length=7,
52
        is_training=True,
53
        use_input_mask=True,
54
        use_token_type_ids=True,
55
        use_labels=True,
56
        vocab_size=99,
57
        block_sizes=[1, 1, 2],
58
        num_decoder_layers=1,
59
        d_model=32,
60
        n_head=4,
61
        d_head=8,
62
        d_inner=37,
63
        hidden_act="gelu_new",
64
        hidden_dropout=0.1,
65
        attention_dropout=0.1,
66
        activation_dropout=0.0,
67
        max_position_embeddings=512,
68
        type_vocab_size=3,
69
        initializer_std=0.02,  # Set to a smaller value, so we can keep the small error threshold (1e-5) in the test
70
        num_labels=3,
71
        num_choices=4,
72
        scope=None,
73
        base=False,
74
    ):
75
        self.parent = parent
76
        self.batch_size = batch_size
77
        self.seq_length = seq_length
78
        self.is_training = is_training
79
        self.use_input_mask = use_input_mask
80
        self.use_token_type_ids = use_token_type_ids
81
        self.use_labels = use_labels
82
        self.vocab_size = vocab_size
83
        self.block_sizes = block_sizes
84
        self.num_decoder_layers = num_decoder_layers
85
        self.d_model = d_model
86
        self.n_head = n_head
87
        self.d_head = d_head
88
        self.d_inner = d_inner
89
        self.hidden_act = hidden_act
90
        self.hidden_dropout = hidden_dropout
91
        self.attention_dropout = attention_dropout
92
        self.activation_dropout = activation_dropout
93
        self.max_position_embeddings = max_position_embeddings
94
        self.type_vocab_size = type_vocab_size
95
        self.type_sequence_label_size = 2
96
        self.num_labels = num_labels
97
        self.num_choices = num_choices
98
        self.scope = scope
99
        self.initializer_std = initializer_std
100

101
        # Used in the tests to check the size of the first attention layer
102
        self.num_attention_heads = n_head
103
        # Used in the tests to check the size of the first hidden state
104
        self.hidden_size = self.d_model
105
        # Used in the tests to check the number of output hidden states/attentions
106
        self.num_hidden_layers = sum(self.block_sizes) + (0 if base else self.num_decoder_layers)
107
        # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
108
        # the last hidden state of the first block (which is the first hidden state of the decoder).
109
        if not base:
110
            self.expected_num_hidden_layers = self.num_hidden_layers + 2
111

112
    def prepare_config_and_inputs(self):
113
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
114

115
        input_mask = None
116
        if self.use_input_mask:
117
            input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
118

119
        token_type_ids = None
120
        if self.use_token_type_ids:
121
            token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
122

123
        sequence_labels = None
124
        token_labels = None
125
        choice_labels = None
126
        if self.use_labels:
127
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
128
            token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
129
            choice_labels = ids_tensor([self.batch_size], self.num_choices)
130
            fake_token_labels = ids_tensor([self.batch_size, self.seq_length], 1)
131

132
        config = self.get_config()
133

134
        return (
135
            config,
136
            input_ids,
137
            token_type_ids,
138
            input_mask,
139
            sequence_labels,
140
            token_labels,
141
            choice_labels,
142
            fake_token_labels,
143
        )
144

145
    def get_config(self):
146
        return FunnelConfig(
147
            vocab_size=self.vocab_size,
148
            block_sizes=self.block_sizes,
149
            num_decoder_layers=self.num_decoder_layers,
150
            d_model=self.d_model,
151
            n_head=self.n_head,
152
            d_head=self.d_head,
153
            d_inner=self.d_inner,
154
            hidden_act=self.hidden_act,
155
            hidden_dropout=self.hidden_dropout,
156
            attention_dropout=self.attention_dropout,
157
            activation_dropout=self.activation_dropout,
158
            max_position_embeddings=self.max_position_embeddings,
159
            type_vocab_size=self.type_vocab_size,
160
            initializer_std=self.initializer_std,
161
        )
162

163
    def create_and_check_model(
164
        self,
165
        config,
166
        input_ids,
167
        token_type_ids,
168
        input_mask,
169
        sequence_labels,
170
        token_labels,
171
        choice_labels,
172
        fake_token_labels,
173
    ):
174
        model = FunnelModel(config=config)
175
        model.to(torch_device)
176
        model.eval()
177
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
178
        result = model(input_ids, token_type_ids=token_type_ids)
179
        result = model(input_ids)
180
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
181

182
        model.config.truncate_seq = False
183
        result = model(input_ids)
184
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
185

186
        model.config.separate_cls = False
187
        result = model(input_ids)
188
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
189

190
    def create_and_check_base_model(
191
        self,
192
        config,
193
        input_ids,
194
        token_type_ids,
195
        input_mask,
196
        sequence_labels,
197
        token_labels,
198
        choice_labels,
199
        fake_token_labels,
200
    ):
201
        model = FunnelBaseModel(config=config)
202
        model.to(torch_device)
203
        model.eval()
204
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
205
        result = model(input_ids, token_type_ids=token_type_ids)
206
        result = model(input_ids)
207
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
208

209
        model.config.truncate_seq = False
210
        result = model(input_ids)
211
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 3, self.d_model))
212

213
        model.config.separate_cls = False
214
        result = model(input_ids)
215
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
216

217
    def create_and_check_for_pretraining(
218
        self,
219
        config,
220
        input_ids,
221
        token_type_ids,
222
        input_mask,
223
        sequence_labels,
224
        token_labels,
225
        choice_labels,
226
        fake_token_labels,
227
    ):
228
        config.num_labels = self.num_labels
229
        model = FunnelForPreTraining(config=config)
230
        model.to(torch_device)
231
        model.eval()
232
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=fake_token_labels)
233
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length))
234

235
    def create_and_check_for_masked_lm(
236
        self,
237
        config,
238
        input_ids,
239
        token_type_ids,
240
        input_mask,
241
        sequence_labels,
242
        token_labels,
243
        choice_labels,
244
        fake_token_labels,
245
    ):
246
        model = FunnelForMaskedLM(config=config)
247
        model.to(torch_device)
248
        model.eval()
249
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
250
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
251

252
    def create_and_check_for_sequence_classification(
253
        self,
254
        config,
255
        input_ids,
256
        token_type_ids,
257
        input_mask,
258
        sequence_labels,
259
        token_labels,
260
        choice_labels,
261
        fake_token_labels,
262
    ):
263
        config.num_labels = self.num_labels
264
        model = FunnelForSequenceClassification(config)
265
        model.to(torch_device)
266
        model.eval()
267
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
268
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
269

270
    def create_and_check_for_multiple_choice(
271
        self,
272
        config,
273
        input_ids,
274
        token_type_ids,
275
        input_mask,
276
        sequence_labels,
277
        token_labels,
278
        choice_labels,
279
        fake_token_labels,
280
    ):
281
        config.num_choices = self.num_choices
282
        model = FunnelForMultipleChoice(config=config)
283
        model.to(torch_device)
284
        model.eval()
285
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
286
        multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
287
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
288
        result = model(
289
            multiple_choice_inputs_ids,
290
            attention_mask=multiple_choice_input_mask,
291
            token_type_ids=multiple_choice_token_type_ids,
292
            labels=choice_labels,
293
        )
294
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
295

296
    def create_and_check_for_token_classification(
297
        self,
298
        config,
299
        input_ids,
300
        token_type_ids,
301
        input_mask,
302
        sequence_labels,
303
        token_labels,
304
        choice_labels,
305
        fake_token_labels,
306
    ):
307
        config.num_labels = self.num_labels
308
        model = FunnelForTokenClassification(config=config)
309
        model.to(torch_device)
310
        model.eval()
311
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
312
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
313

314
    def create_and_check_for_question_answering(
315
        self,
316
        config,
317
        input_ids,
318
        token_type_ids,
319
        input_mask,
320
        sequence_labels,
321
        token_labels,
322
        choice_labels,
323
        fake_token_labels,
324
    ):
325
        model = FunnelForQuestionAnswering(config=config)
326
        model.to(torch_device)
327
        model.eval()
328
        result = model(
329
            input_ids,
330
            attention_mask=input_mask,
331
            token_type_ids=token_type_ids,
332
            start_positions=sequence_labels,
333
            end_positions=sequence_labels,
334
        )
335
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
336
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
337

338
    def prepare_config_and_inputs_for_common(self):
339
        config_and_inputs = self.prepare_config_and_inputs()
340
        (
341
            config,
342
            input_ids,
343
            token_type_ids,
344
            input_mask,
345
            sequence_labels,
346
            token_labels,
347
            choice_labels,
348
            fake_token_labels,
349
        ) = config_and_inputs
350
        inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
351
        return config, inputs_dict
352

353

354
@require_torch
355
class FunnelModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
356
    test_head_masking = False
357
    test_pruning = False
358
    all_model_classes = (
359
        (
360
            FunnelModel,
361
            FunnelForMaskedLM,
362
            FunnelForPreTraining,
363
            FunnelForQuestionAnswering,
364
            FunnelForTokenClassification,
365
        )
366
        if is_torch_available()
367
        else ()
368
    )
369
    pipeline_model_mapping = (
370
        {
371
            "feature-extraction": (FunnelBaseModel, FunnelModel),
372
            "fill-mask": FunnelForMaskedLM,
373
            "question-answering": FunnelForQuestionAnswering,
374
            "text-classification": FunnelForSequenceClassification,
375
            "token-classification": FunnelForTokenClassification,
376
            "zero-shot": FunnelForSequenceClassification,
377
        }
378
        if is_torch_available()
379
        else {}
380
    )
381

382
    # special case for ForPreTraining model
383
    def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
384
        inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
385

386
        if return_labels:
387
            if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
388
                inputs_dict["labels"] = torch.zeros(
389
                    (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
390
                )
391
        return inputs_dict
392

393
    def setUp(self):
394
        self.model_tester = FunnelModelTester(self)
395
        self.config_tester = ConfigTester(self, config_class=FunnelConfig)
396

397
    def test_config(self):
398
        self.config_tester.run_common_tests()
399

400
    def test_model(self):
401
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
402
        self.model_tester.create_and_check_model(*config_and_inputs)
403

404
    def test_for_pretraining(self):
405
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
406
        self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
407

408
    def test_for_masked_lm(self):
409
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
410
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
411

412
    def test_for_token_classification(self):
413
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
414
        self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
415

416
    def test_for_question_answering(self):
417
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
418
        self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
419

420
    # overwrite from test_modeling_common
421
    def _mock_init_weights(self, module):
422
        if hasattr(module, "weight") and module.weight is not None:
423
            module.weight.data.fill_(3)
424
        if hasattr(module, "bias") and module.bias is not None:
425
            module.bias.data.fill_(3)
426

427
        for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
428
            if hasattr(module, param) and getattr(module, param) is not None:
429
                weight = getattr(module, param)
430
                weight.data.fill_(3)
431

432

433
@require_torch
434
class FunnelBaseModelTest(ModelTesterMixin, unittest.TestCase):
435
    test_head_masking = False
436
    test_pruning = False
437
    all_model_classes = (
438
        (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
439
    )
440

441
    def setUp(self):
442
        self.model_tester = FunnelModelTester(self, base=True)
443
        self.config_tester = ConfigTester(self, config_class=FunnelConfig)
444

445
    def test_config(self):
446
        self.config_tester.run_common_tests()
447

448
    def test_base_model(self):
449
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
450
        self.model_tester.create_and_check_base_model(*config_and_inputs)
451

452
    def test_for_sequence_classification(self):
453
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
454
        self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
455

456
    def test_for_multiple_choice(self):
457
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
458
        self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
459

460
    # overwrite from test_modeling_common
461
    def test_training(self):
462
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
463
        config.return_dict = True
464

465
        for model_class in self.all_model_classes:
466
            if model_class.__name__ == "FunnelBaseModel":
467
                continue
468
            model = model_class(config)
469
            model.to(torch_device)
470
            model.train()
471
            inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
472
            loss = model(**inputs).loss
473
            loss.backward()
474

475
    # overwrite from test_modeling_common
476
    def _mock_init_weights(self, module):
477
        if hasattr(module, "weight") and module.weight is not None:
478
            module.weight.data.fill_(3)
479
        if hasattr(module, "bias") and module.bias is not None:
480
            module.bias.data.fill_(3)
481

482
        for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
483
            if hasattr(module, param) and getattr(module, param) is not None:
484
                weight = getattr(module, param)
485
                weight.data.fill_(3)
486

487

488
@require_torch
489
@require_sentencepiece
490
@require_tokenizers
491
class FunnelModelIntegrationTest(unittest.TestCase):
492
    def test_inference_tiny_model(self):
493
        batch_size = 13
494
        sequence_length = 7
495
        input_ids = torch.arange(0, batch_size * sequence_length).long().reshape(batch_size, sequence_length)
496
        lengths = [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
497
        token_type_ids = torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths])
498

499
        model = FunnelModel.from_pretrained("sgugger/funnel-random-tiny")
500
        output = model(input_ids, token_type_ids=token_type_ids)[0].abs()
501

502
        expected_output_sum = torch.tensor(2344.8352)
503
        expected_output_mean = torch.tensor(0.8052)
504
        self.assertTrue(torch.allclose(output.sum(), expected_output_sum, atol=1e-4))
505
        self.assertTrue(torch.allclose(output.mean(), expected_output_mean, atol=1e-4))
506

507
        attention_mask = torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]])
508
        output = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)[0].abs()
509

510
        expected_output_sum = torch.tensor(2343.8425)
511
        expected_output_mean = torch.tensor(0.8049)
512
        self.assertTrue(torch.allclose(output.sum(), expected_output_sum, atol=1e-4))
513
        self.assertTrue(torch.allclose(output.mean(), expected_output_mean, atol=1e-4))
514

515
    @slow
516
    def test_inference_model(self):
517
        tokenizer = FunnelTokenizer.from_pretrained("huggingface/funnel-small")
518
        model = FunnelModel.from_pretrained("huggingface/funnel-small")
519
        inputs = tokenizer("Hello! I am the Funnel Transformer model.", return_tensors="pt")
520
        output = model(**inputs)[0]
521

522
        expected_output_sum = torch.tensor(235.7246)
523
        expected_output_mean = torch.tensor(0.0256)
524
        self.assertTrue(torch.allclose(output.sum(), expected_output_sum, atol=1e-4))
525
        self.assertTrue(torch.allclose(output.mean(), expected_output_mean, atol=1e-4))
526

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

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

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

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