transformers

Форк
0
/
test_modeling_flax_beit.py 
294 строки · 11.1 Кб
1
# Copyright 2021 The HuggingFace Team. All rights reserved.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

15
import inspect
16
import unittest
17

18
import numpy as np
19

20
from transformers import BeitConfig
21
from transformers.testing_utils import require_flax, require_vision, slow
22
from transformers.utils import cached_property, is_flax_available, is_vision_available
23

24
from ...test_configuration_common import ConfigTester
25
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor
26

27

28
if is_flax_available():
29
    import jax
30

31
    from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel
32

33
if is_vision_available():
34
    from PIL import Image
35

36
    from transformers import BeitImageProcessor
37

38

39
class FlaxBeitModelTester(unittest.TestCase):
40
    def __init__(
41
        self,
42
        parent,
43
        vocab_size=100,
44
        batch_size=13,
45
        image_size=30,
46
        patch_size=2,
47
        num_channels=3,
48
        is_training=True,
49
        use_labels=True,
50
        hidden_size=32,
51
        num_hidden_layers=2,
52
        num_attention_heads=4,
53
        intermediate_size=37,
54
        hidden_act="gelu",
55
        hidden_dropout_prob=0.1,
56
        attention_probs_dropout_prob=0.1,
57
        type_sequence_label_size=10,
58
        initializer_range=0.02,
59
        num_labels=3,
60
    ):
61
        self.parent = parent
62
        self.vocab_size = vocab_size
63
        self.batch_size = batch_size
64
        self.image_size = image_size
65
        self.patch_size = patch_size
66
        self.num_channels = num_channels
67
        self.is_training = is_training
68
        self.use_labels = use_labels
69
        self.hidden_size = hidden_size
70
        self.num_hidden_layers = num_hidden_layers
71
        self.num_attention_heads = num_attention_heads
72
        self.intermediate_size = intermediate_size
73
        self.hidden_act = hidden_act
74
        self.hidden_dropout_prob = hidden_dropout_prob
75
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
76
        self.type_sequence_label_size = type_sequence_label_size
77
        self.initializer_range = initializer_range
78

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

83
    def prepare_config_and_inputs(self):
84
        pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
85

86
        labels = None
87
        if self.use_labels:
88
            labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
89

90
        config = BeitConfig(
91
            vocab_size=self.vocab_size,
92
            image_size=self.image_size,
93
            patch_size=self.patch_size,
94
            num_channels=self.num_channels,
95
            hidden_size=self.hidden_size,
96
            num_hidden_layers=self.num_hidden_layers,
97
            num_attention_heads=self.num_attention_heads,
98
            intermediate_size=self.intermediate_size,
99
            hidden_act=self.hidden_act,
100
            hidden_dropout_prob=self.hidden_dropout_prob,
101
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
102
            is_decoder=False,
103
            initializer_range=self.initializer_range,
104
        )
105

106
        return config, pixel_values, labels
107

108
    def create_and_check_model(self, config, pixel_values, labels):
109
        model = FlaxBeitModel(config=config)
110
        result = model(pixel_values)
111
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
112

113
    def create_and_check_for_masked_lm(self, config, pixel_values, labels):
114
        model = FlaxBeitForMaskedImageModeling(config=config)
115
        result = model(pixel_values)
116
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length - 1, self.vocab_size))
117

118
    def create_and_check_for_image_classification(self, config, pixel_values, labels):
119
        config.num_labels = self.type_sequence_label_size
120
        model = FlaxBeitForImageClassification(config=config)
121
        result = model(pixel_values)
122
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
123

124
        # test greyscale images
125
        config.num_channels = 1
126
        model = FlaxBeitForImageClassification(config)
127

128
        pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
129
        result = model(pixel_values)
130

131
    def prepare_config_and_inputs_for_common(self):
132
        config_and_inputs = self.prepare_config_and_inputs()
133
        (
134
            config,
135
            pixel_values,
136
            labels,
137
        ) = config_and_inputs
138
        inputs_dict = {"pixel_values": pixel_values}
139
        return config, inputs_dict
140

141

142
@require_flax
143
class FlaxBeitModelTest(FlaxModelTesterMixin, unittest.TestCase):
144
    all_model_classes = (
145
        (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
146
    )
147

148
    def setUp(self) -> None:
149
        self.model_tester = FlaxBeitModelTester(self)
150
        self.config_tester = ConfigTester(self, config_class=BeitConfig, has_text_modality=False, hidden_size=37)
151

152
    def test_config(self):
153
        self.config_tester.run_common_tests()
154

155
    # We need to override this test because Beit's forward signature is different than text models.
156
    def test_forward_signature(self):
157
        config, _ = self.model_tester.prepare_config_and_inputs_for_common()
158

159
        for model_class in self.all_model_classes:
160
            model = model_class(config)
161
            signature = inspect.signature(model.__call__)
162
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
163
            arg_names = [*signature.parameters.keys()]
164

165
            expected_arg_names = ["pixel_values"]
166
            self.assertListEqual(arg_names[:1], expected_arg_names)
167

168
    # We need to override this test because Beit expects pixel_values instead of input_ids
169
    def test_jit_compilation(self):
170
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
171

172
        for model_class in self.all_model_classes:
173
            with self.subTest(model_class.__name__):
174
                prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
175
                model = model_class(config)
176

177
                @jax.jit
178
                def model_jitted(pixel_values, **kwargs):
179
                    return model(pixel_values=pixel_values, **kwargs)
180

181
                with self.subTest("JIT Enabled"):
182
                    jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple()
183

184
                with self.subTest("JIT Disabled"):
185
                    with jax.disable_jit():
186
                        outputs = model_jitted(**prepared_inputs_dict).to_tuple()
187

188
                self.assertEqual(len(outputs), len(jitted_outputs))
189
                for jitted_output, output in zip(jitted_outputs, outputs):
190
                    self.assertEqual(jitted_output.shape, output.shape)
191

192
    def test_model(self):
193
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
194
        self.model_tester.create_and_check_model(*config_and_inputs)
195

196
    def test_for_masked_lm(self):
197
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
198
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
199

200
    def test_for_image_classification(self):
201
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
202
        self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
203

204
    @slow
205
    def test_model_from_pretrained(self):
206
        for model_class_name in self.all_model_classes:
207
            model = model_class_name.from_pretrained("microsoft/beit-base-patch16-224")
208
            outputs = model(np.ones((1, 3, 224, 224)))
209
            self.assertIsNotNone(outputs)
210

211

212
# We will verify our results on an image of cute cats
213
def prepare_img():
214
    image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
215
    return image
216

217

218
@require_vision
219
@require_flax
220
class FlaxBeitModelIntegrationTest(unittest.TestCase):
221
    @cached_property
222
    def default_image_processor(self):
223
        return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224") if is_vision_available() else None
224

225
    @slow
226
    def test_inference_masked_image_modeling_head(self):
227
        model = FlaxBeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
228

229
        image_processor = self.default_image_processor
230
        image = prepare_img()
231
        pixel_values = image_processor(images=image, return_tensors="np").pixel_values
232

233
        # prepare bool_masked_pos
234
        bool_masked_pos = np.ones((1, 196), dtype=bool)
235

236
        # forward pass
237
        outputs = model(pixel_values=pixel_values, bool_masked_pos=bool_masked_pos)
238
        logits = outputs.logits
239

240
        # verify the logits
241
        expected_shape = (1, 196, 8192)
242
        self.assertEqual(logits.shape, expected_shape)
243

244
        expected_slice = np.array(
245
            [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]
246
        )
247

248
        self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3], expected_slice, atol=1e-2))
249

250
    @slow
251
    def test_inference_image_classification_head_imagenet_1k(self):
252
        model = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224")
253

254
        image_processor = self.default_image_processor
255
        image = prepare_img()
256
        inputs = image_processor(images=image, return_tensors="np")
257

258
        # forward pass
259
        outputs = model(**inputs)
260
        logits = outputs.logits
261

262
        # verify the logits
263
        expected_shape = (1, 1000)
264
        self.assertEqual(logits.shape, expected_shape)
265

266
        expected_slice = np.array([-1.2385, -1.0987, -1.0108])
267

268
        self.assertTrue(np.allclose(logits[0, :3], expected_slice, atol=1e-4))
269

270
        expected_class_idx = 281
271
        self.assertEqual(logits.argmax(-1).item(), expected_class_idx)
272

273
    @slow
274
    def test_inference_image_classification_head_imagenet_22k(self):
275
        model = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k")
276

277
        image_processor = self.default_image_processor
278
        image = prepare_img()
279
        inputs = image_processor(images=image, return_tensors="np")
280

281
        # forward pass
282
        outputs = model(**inputs)
283
        logits = outputs.logits
284

285
        # verify the logits
286
        expected_shape = (1, 21841)
287
        self.assertEqual(logits.shape, expected_shape)
288

289
        expected_slice = np.array([1.6881, -0.2787, 0.5901])
290

291
        self.assertTrue(np.allclose(logits[0, :3], expected_slice, atol=1e-4))
292

293
        expected_class_idx = 2396
294
        self.assertEqual(logits.argmax(-1).item(), expected_class_idx)
295

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

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

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

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