transformers

Форк
0
/
test_modeling_beit.py 
557 строк · 21.1 Кб
1
# coding=utf-8
2
# Copyright 2021 The HuggingFace Inc. 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
""" Testing suite for the PyTorch BEiT model. """
16

17

18
import unittest
19

20
from datasets import load_dataset
21
from packaging import version
22

23
from transformers import BeitConfig
24
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
25
from transformers.utils import cached_property, is_torch_available, is_vision_available
26

27
from ...test_backbone_common import BackboneTesterMixin
28
from ...test_configuration_common import ConfigTester
29
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
30
from ...test_pipeline_mixin import PipelineTesterMixin
31

32

33
if is_torch_available():
34
    import torch
35
    from torch import nn
36

37
    from transformers import (
38
        BeitBackbone,
39
        BeitForImageClassification,
40
        BeitForMaskedImageModeling,
41
        BeitForSemanticSegmentation,
42
        BeitModel,
43
    )
44
    from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
45
    from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST
46

47

48
if is_vision_available():
49
    import PIL
50
    from PIL import Image
51

52
    from transformers import BeitImageProcessor
53

54

55
class BeitModelTester:
56
    def __init__(
57
        self,
58
        parent,
59
        vocab_size=100,
60
        batch_size=13,
61
        image_size=30,
62
        patch_size=2,
63
        num_channels=3,
64
        is_training=True,
65
        use_labels=True,
66
        hidden_size=32,
67
        num_hidden_layers=4,
68
        num_attention_heads=4,
69
        intermediate_size=37,
70
        hidden_act="gelu",
71
        hidden_dropout_prob=0.1,
72
        attention_probs_dropout_prob=0.1,
73
        type_sequence_label_size=10,
74
        initializer_range=0.02,
75
        num_labels=3,
76
        scope=None,
77
        out_indices=[1, 2, 3, 4],
78
        out_features=["stage1", "stage2", "stage3", "stage4"],
79
    ):
80
        self.parent = parent
81
        self.vocab_size = vocab_size
82
        self.batch_size = batch_size
83
        self.image_size = image_size
84
        self.patch_size = patch_size
85
        self.num_channels = num_channels
86
        self.is_training = is_training
87
        self.use_labels = use_labels
88
        self.hidden_size = hidden_size
89
        self.num_hidden_layers = num_hidden_layers
90
        self.num_attention_heads = num_attention_heads
91
        self.intermediate_size = intermediate_size
92
        self.hidden_act = hidden_act
93
        self.hidden_dropout_prob = hidden_dropout_prob
94
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
95
        self.type_sequence_label_size = type_sequence_label_size
96
        self.initializer_range = initializer_range
97
        self.scope = scope
98
        self.out_indices = out_indices
99
        self.out_features = out_features
100
        self.num_labels = num_labels
101

102
        # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
103
        num_patches = (image_size // patch_size) ** 2
104
        self.seq_length = num_patches + 1
105

106
    def prepare_config_and_inputs(self):
107
        pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
108

109
        labels = None
110
        pixel_labels = None
111
        if self.use_labels:
112
            labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
113
            pixel_labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
114

115
        config = self.get_config()
116

117
        return config, pixel_values, labels, pixel_labels
118

119
    def get_config(self):
120
        return BeitConfig(
121
            vocab_size=self.vocab_size,
122
            image_size=self.image_size,
123
            patch_size=self.patch_size,
124
            num_channels=self.num_channels,
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
            hidden_dropout_prob=self.hidden_dropout_prob,
131
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
132
            is_decoder=False,
133
            initializer_range=self.initializer_range,
134
            out_indices=self.out_indices,
135
            out_features=self.out_features,
136
        )
137

138
    def create_and_check_model(self, config, pixel_values, labels, pixel_labels):
139
        model = BeitModel(config=config)
140
        model.to(torch_device)
141
        model.eval()
142
        result = model(pixel_values)
143
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
144

145
    def create_and_check_backbone(self, config, pixel_values, labels, pixel_labels):
146
        model = BeitBackbone(config=config)
147
        model.to(torch_device)
148
        model.eval()
149
        result = model(pixel_values)
150

151
        # verify hidden states
152
        self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
153
        expected_height = expected_width = self.image_size // config.patch_size
154
        self.parent.assertListEqual(
155
            list(result.feature_maps[0].shape), [self.batch_size, self.hidden_size, expected_height, expected_width]
156
        )
157

158
        # verify channels
159
        self.parent.assertEqual(len(model.channels), len(config.out_features))
160

161
        # verify backbone works with out_features=None
162
        config.out_features = None
163
        model = BeitBackbone(config=config)
164
        model.to(torch_device)
165
        model.eval()
166
        result = model(pixel_values)
167

168
        # verify feature maps
169
        self.parent.assertEqual(len(result.feature_maps), 1)
170
        self.parent.assertListEqual(
171
            list(result.feature_maps[0].shape), [self.batch_size, self.hidden_size, expected_height, expected_width]
172
        )
173

174
        # verify channels
175
        self.parent.assertEqual(len(model.channels), 1)
176

177
    def create_and_check_for_masked_lm(self, config, pixel_values, labels, pixel_labels):
178
        model = BeitForMaskedImageModeling(config=config)
179
        model.to(torch_device)
180
        model.eval()
181
        result = model(pixel_values)
182
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length - 1, self.vocab_size))
183

184
    def create_and_check_for_image_classification(self, config, pixel_values, labels, pixel_labels):
185
        config.num_labels = self.type_sequence_label_size
186
        model = BeitForImageClassification(config)
187
        model.to(torch_device)
188
        model.eval()
189
        result = model(pixel_values, labels=labels)
190
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
191

192
        # test greyscale images
193
        config.num_channels = 1
194
        model = BeitForImageClassification(config)
195
        model.to(torch_device)
196
        model.eval()
197

198
        pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
199
        result = model(pixel_values, labels=labels)
200
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
201

202
    def create_and_check_for_semantic_segmentation(self, config, pixel_values, labels, pixel_labels):
203
        config.num_labels = self.num_labels
204
        model = BeitForSemanticSegmentation(config)
205
        model.to(torch_device)
206
        model.eval()
207
        result = model(pixel_values)
208
        self.parent.assertEqual(
209
            result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
210
        )
211
        result = model(pixel_values, labels=pixel_labels)
212
        self.parent.assertEqual(
213
            result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
214
        )
215

216
    def prepare_config_and_inputs_for_common(self):
217
        config_and_inputs = self.prepare_config_and_inputs()
218
        config, pixel_values, labels, pixel_labels = config_and_inputs
219
        inputs_dict = {"pixel_values": pixel_values}
220
        return config, inputs_dict
221

222

223
@require_torch
224
class BeitModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
225
    """
226
    Here we also overwrite some of the tests of test_modeling_common.py, as BEiT does not use input_ids, inputs_embeds,
227
    attention_mask and seq_length.
228
    """
229

230
    all_model_classes = (
231
        (
232
            BeitModel,
233
            BeitForImageClassification,
234
            BeitForMaskedImageModeling,
235
            BeitForSemanticSegmentation,
236
            BeitBackbone,
237
        )
238
        if is_torch_available()
239
        else ()
240
    )
241
    pipeline_model_mapping = (
242
        {
243
            "image-feature-extraction": BeitModel,
244
            "image-classification": BeitForImageClassification,
245
            "image-segmentation": BeitForSemanticSegmentation,
246
        }
247
        if is_torch_available()
248
        else {}
249
    )
250

251
    test_pruning = False
252
    test_resize_embeddings = False
253
    test_head_masking = False
254

255
    def setUp(self):
256
        self.model_tester = BeitModelTester(self)
257
        self.config_tester = ConfigTester(self, config_class=BeitConfig, has_text_modality=False, hidden_size=37)
258

259
    def test_config(self):
260
        self.config_tester.run_common_tests()
261

262
    @unittest.skip(reason="BEiT does not use inputs_embeds")
263
    def test_inputs_embeds(self):
264
        pass
265

266
    @require_torch_multi_gpu
267
    @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`")
268
    def test_multi_gpu_data_parallel_forward(self):
269
        pass
270

271
    @unittest.skip(reason="BEiT does not support feedforward chunking yet")
272
    def test_feed_forward_chunking(self):
273
        pass
274

275
    def test_model_common_attributes(self):
276
        config, _ = self.model_tester.prepare_config_and_inputs_for_common()
277

278
        for model_class in self.all_model_classes:
279
            model = model_class(config)
280
            self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
281
            x = model.get_output_embeddings()
282
            self.assertTrue(x is None or isinstance(x, nn.Linear))
283

284
    def test_model(self):
285
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
286
        self.model_tester.create_and_check_model(*config_and_inputs)
287

288
    def test_backbone(self):
289
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
290
        self.model_tester.create_and_check_backbone(*config_and_inputs)
291

292
    def test_for_masked_lm(self):
293
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
294
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
295

296
    def test_for_image_classification(self):
297
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
298
        self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
299

300
    def test_for_semantic_segmentation(self):
301
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
302
        self.model_tester.create_and_check_for_semantic_segmentation(*config_and_inputs)
303

304
    def test_training(self):
305
        if not self.model_tester.is_training:
306
            return
307

308
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
309
        config.return_dict = True
310

311
        for model_class in self.all_model_classes:
312
            # we don't test BeitForMaskedImageModeling
313
            if model_class.__name__ in [
314
                *MODEL_MAPPING_NAMES.values(),
315
                *MODEL_FOR_BACKBONE_MAPPING_NAMES.values(),
316
                "BeitForMaskedImageModeling",
317
            ]:
318
                continue
319

320
            model = model_class(config)
321
            model.to(torch_device)
322
            model.train()
323
            inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
324
            loss = model(**inputs).loss
325
            loss.backward()
326

327
    def test_training_gradient_checkpointing(self):
328
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
329
        if not self.model_tester.is_training:
330
            return
331

332
        config.use_cache = False
333
        config.return_dict = True
334

335
        for model_class in self.all_model_classes:
336
            # we don't test BeitForMaskedImageModeling
337
            if (
338
                model_class.__name__
339
                in [
340
                    *MODEL_MAPPING_NAMES.values(),
341
                    *MODEL_FOR_BACKBONE_MAPPING_NAMES.values(),
342
                    "BeitForMaskedImageModeling",
343
                ]
344
                or not model_class.supports_gradient_checkpointing
345
            ):
346
                continue
347

348
            model = model_class(config)
349
            model.gradient_checkpointing_enable()
350
            model.to(torch_device)
351
            model.train()
352
            inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
353
            loss = model(**inputs).loss
354
            loss.backward()
355

356
    @unittest.skip(
357
        reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
358
    )
359
    def test_training_gradient_checkpointing_use_reentrant(self):
360
        pass
361

362
    @unittest.skip(
363
        reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
364
    )
365
    def test_training_gradient_checkpointing_use_reentrant_false(self):
366
        pass
367

368
    def test_initialization(self):
369
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
370

371
        configs_no_init = _config_zero_init(config)
372
        for model_class in self.all_model_classes:
373
            model = model_class(config=configs_no_init)
374
            for name, param in model.named_parameters():
375
                # we skip lambda parameters as these require special initial values
376
                # determined by config.layer_scale_init_value
377
                if "lambda" in name:
378
                    continue
379
                if param.requires_grad:
380
                    self.assertIn(
381
                        ((param.data.mean() * 1e9).round() / 1e9).item(),
382
                        [0.0, 1.0],
383
                        msg=f"Parameter {name} of model {model_class} seems not properly initialized",
384
                    )
385

386
    @slow
387
    def test_model_from_pretrained(self):
388
        for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
389
            model = BeitModel.from_pretrained(model_name)
390
            self.assertIsNotNone(model)
391

392

393
# We will verify our results on an image of cute cats
394
def prepare_img():
395
    image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
396
    return image
397

398

399
@require_torch
400
@require_vision
401
class BeitModelIntegrationTest(unittest.TestCase):
402
    @cached_property
403
    def default_image_processor(self):
404
        return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224") if is_vision_available() else None
405

406
    @slow
407
    def test_inference_masked_image_modeling_head(self):
408
        model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k").to(torch_device)
409

410
        image_processor = self.default_image_processor
411
        image = prepare_img()
412
        pixel_values = image_processor(images=image, return_tensors="pt").pixel_values.to(torch_device)
413

414
        # prepare bool_masked_pos
415
        bool_masked_pos = torch.ones((1, 196), dtype=torch.bool).to(torch_device)
416

417
        # forward pass
418
        with torch.no_grad():
419
            outputs = model(pixel_values=pixel_values, bool_masked_pos=bool_masked_pos)
420
        logits = outputs.logits
421

422
        # verify the logits
423
        expected_shape = torch.Size((1, 196, 8192))
424
        self.assertEqual(logits.shape, expected_shape)
425

426
        expected_slice = torch.tensor(
427
            [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]
428
        ).to(torch_device)
429

430
        self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3], expected_slice, atol=1e-2))
431

432
    @slow
433
    def test_inference_image_classification_head_imagenet_1k(self):
434
        model = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224").to(torch_device)
435

436
        image_processor = self.default_image_processor
437
        image = prepare_img()
438
        inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
439

440
        # forward pass
441
        with torch.no_grad():
442
            outputs = model(**inputs)
443
        logits = outputs.logits
444

445
        # verify the logits
446
        expected_shape = torch.Size((1, 1000))
447
        self.assertEqual(logits.shape, expected_shape)
448

449
        expected_slice = torch.tensor([-1.2385, -1.0987, -1.0108]).to(torch_device)
450

451
        self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
452

453
        expected_class_idx = 281
454
        self.assertEqual(logits.argmax(-1).item(), expected_class_idx)
455

456
    @slow
457
    def test_inference_image_classification_head_imagenet_22k(self):
458
        model = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k").to(
459
            torch_device
460
        )
461

462
        image_processor = self.default_image_processor
463
        image = prepare_img()
464
        inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
465

466
        # forward pass
467
        with torch.no_grad():
468
            outputs = model(**inputs)
469
        logits = outputs.logits
470

471
        # verify the logits
472
        expected_shape = torch.Size((1, 21841))
473
        self.assertEqual(logits.shape, expected_shape)
474

475
        expected_slice = torch.tensor([1.6881, -0.2787, 0.5901]).to(torch_device)
476

477
        self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
478

479
        expected_class_idx = 2396
480
        self.assertEqual(logits.argmax(-1).item(), expected_class_idx)
481

482
    @slow
483
    def test_inference_semantic_segmentation(self):
484
        model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
485
        model = model.to(torch_device)
486

487
        image_processor = BeitImageProcessor(do_resize=True, size=640, do_center_crop=False)
488

489
        ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
490
        image = Image.open(ds[0]["file"])
491
        inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
492

493
        # forward pass
494
        with torch.no_grad():
495
            outputs = model(**inputs)
496
        logits = outputs.logits
497

498
        # verify the logits
499
        expected_shape = torch.Size((1, 150, 160, 160))
500
        self.assertEqual(logits.shape, expected_shape)
501

502
        is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0")
503

504
        if is_pillow_less_than_9:
505
            expected_slice = torch.tensor(
506
                [
507
                    [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
508
                    [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
509
                    [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
510
                ],
511
                device=torch_device,
512
            )
513
        else:
514
            expected_slice = torch.tensor(
515
                [
516
                    [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
517
                    [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
518
                    [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
519
                ],
520
                device=torch_device,
521
            )
522

523
        self.assertTrue(torch.allclose(logits[0, :3, :3, :3], expected_slice, atol=1e-4))
524

525
    @slow
526
    def test_post_processing_semantic_segmentation(self):
527
        model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
528
        model = model.to(torch_device)
529

530
        image_processor = BeitImageProcessor(do_resize=True, size=640, do_center_crop=False)
531

532
        ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
533
        image = Image.open(ds[0]["file"])
534
        inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
535

536
        # forward pass
537
        with torch.no_grad():
538
            outputs = model(**inputs)
539

540
        outputs.logits = outputs.logits.detach().cpu()
541

542
        segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs, target_sizes=[(500, 300)])
543
        expected_shape = torch.Size((500, 300))
544
        self.assertEqual(segmentation[0].shape, expected_shape)
545

546
        segmentation = image_processor.post_process_semantic_segmentation(outputs=outputs)
547
        expected_shape = torch.Size((160, 160))
548
        self.assertEqual(segmentation[0].shape, expected_shape)
549

550

551
@require_torch
552
class BeitBackboneTest(unittest.TestCase, BackboneTesterMixin):
553
    all_model_classes = (BeitBackbone,) if is_torch_available() else ()
554
    config_class = BeitConfig
555

556
    def setUp(self):
557
        self.model_tester = BeitModelTester(self)
558

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

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

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

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