transformers

Форк
0
/
test_modeling_mgp_str.py 
262 строки · 9.6 Кб
1
# coding=utf-8
2
# Copyright 2023 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 MGP-STR model. """
16

17
import unittest
18

19
import requests
20

21
from transformers import MgpstrConfig
22
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
23
from transformers.utils import is_torch_available, is_vision_available
24

25
from ...test_configuration_common import ConfigTester
26
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
27
from ...test_pipeline_mixin import PipelineTesterMixin
28

29

30
if is_torch_available():
31
    import torch
32
    from torch import nn
33

34
    from transformers import MgpstrForSceneTextRecognition, MgpstrModel
35

36

37
if is_vision_available():
38
    from PIL import Image
39

40
    from transformers import MgpstrProcessor
41

42

43
class MgpstrModelTester:
44
    def __init__(
45
        self,
46
        parent,
47
        is_training=False,
48
        batch_size=13,
49
        image_size=(32, 128),
50
        patch_size=4,
51
        num_channels=3,
52
        max_token_length=27,
53
        num_character_labels=38,
54
        num_bpe_labels=99,
55
        num_wordpiece_labels=99,
56
        hidden_size=32,
57
        num_hidden_layers=2,
58
        num_attention_heads=4,
59
        mlp_ratio=4.0,
60
        patch_embeds_hidden_size=257,
61
        output_hidden_states=None,
62
    ):
63
        self.parent = parent
64
        self.is_training = is_training
65
        self.batch_size = batch_size
66
        self.image_size = image_size
67
        self.patch_size = patch_size
68
        self.num_channels = num_channels
69
        self.max_token_length = max_token_length
70
        self.num_character_labels = num_character_labels
71
        self.num_bpe_labels = num_bpe_labels
72
        self.num_wordpiece_labels = num_wordpiece_labels
73
        self.hidden_size = hidden_size
74
        self.num_hidden_layers = num_hidden_layers
75
        self.num_attention_heads = num_attention_heads
76
        self.mlp_ratio = mlp_ratio
77
        self.patch_embeds_hidden_size = patch_embeds_hidden_size
78
        self.output_hidden_states = output_hidden_states
79

80
    def prepare_config_and_inputs(self):
81
        pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]])
82
        config = self.get_config()
83
        return config, pixel_values
84

85
    def get_config(self):
86
        return MgpstrConfig(
87
            image_size=self.image_size,
88
            patch_size=self.patch_size,
89
            num_channels=self.num_channels,
90
            max_token_length=self.max_token_length,
91
            num_character_labels=self.num_character_labels,
92
            num_bpe_labels=self.num_bpe_labels,
93
            num_wordpiece_labels=self.num_wordpiece_labels,
94
            hidden_size=self.hidden_size,
95
            num_hidden_layers=self.num_hidden_layers,
96
            num_attention_heads=self.num_attention_heads,
97
            mlp_ratio=self.mlp_ratio,
98
            output_hidden_states=self.output_hidden_states,
99
        )
100

101
    def create_and_check_model(self, config, pixel_values):
102
        model = MgpstrForSceneTextRecognition(config)
103
        model.to(torch_device)
104
        model.eval()
105
        with torch.no_grad():
106
            generated_ids = model(pixel_values)
107
        self.parent.assertEqual(
108
            generated_ids[0][0].shape, (self.batch_size, self.max_token_length, self.num_character_labels)
109
        )
110

111
    def prepare_config_and_inputs_for_common(self):
112
        config_and_inputs = self.prepare_config_and_inputs()
113
        config, pixel_values = config_and_inputs
114
        inputs_dict = {"pixel_values": pixel_values}
115
        return config, inputs_dict
116

117

118
@require_torch
119
class MgpstrModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
120
    all_model_classes = (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
121
    pipeline_model_mapping = (
122
        {"feature-extraction": MgpstrForSceneTextRecognition, "image-feature-extraction": MgpstrModel}
123
        if is_torch_available()
124
        else {}
125
    )
126
    fx_compatible = False
127

128
    test_pruning = False
129
    test_resize_embeddings = False
130
    test_head_masking = False
131
    test_attention_outputs = False
132

133
    def setUp(self):
134
        self.model_tester = MgpstrModelTester(self)
135
        self.config_tester = ConfigTester(self, config_class=MgpstrConfig, has_text_modality=False)
136

137
    def test_config(self):
138
        self.config_tester.run_common_tests()
139

140
    def test_model(self):
141
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
142
        self.model_tester.create_and_check_model(*config_and_inputs)
143

144
    @unittest.skip(reason="MgpstrModel does not use inputs_embeds")
145
    def test_inputs_embeds(self):
146
        pass
147

148
    def test_model_common_attributes(self):
149
        config, _ = self.model_tester.prepare_config_and_inputs_for_common()
150

151
        for model_class in self.all_model_classes:
152
            model = model_class(config)
153
            self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
154
            x = model.get_output_embeddings()
155
            self.assertTrue(x is None or isinstance(x, nn.Linear))
156

157
    @unittest.skip(reason="MgpstrModel does not support feedforward chunking")
158
    def test_feed_forward_chunking(self):
159
        pass
160

161
    def test_gradient_checkpointing_backward_compatibility(self):
162
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
163

164
        for model_class in self.all_model_classes:
165
            if not model_class.supports_gradient_checkpointing:
166
                continue
167

168
            config.gradient_checkpointing = True
169
            model = model_class(config)
170
            self.assertTrue(model.is_gradient_checkpointing)
171

172
    def test_hidden_states_output(self):
173
        def check_hidden_states_output(inputs_dict, config, model_class):
174
            model = model_class(config)
175
            model.to(torch_device)
176
            model.eval()
177

178
            with torch.no_grad():
179
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))
180

181
            hidden_states = outputs.hidden_states
182

183
            expected_num_layers = getattr(
184
                self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
185
            )
186
            self.assertEqual(len(hidden_states), expected_num_layers)
187

188
            self.assertListEqual(
189
                list(hidden_states[0].shape[-2:]),
190
                [self.model_tester.patch_embeds_hidden_size, self.model_tester.hidden_size],
191
            )
192

193
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
194

195
        for model_class in self.all_model_classes:
196
            inputs_dict["output_hidden_states"] = True
197
            check_hidden_states_output(inputs_dict, config, model_class)
198

199
            # check that output_hidden_states also work using config
200
            del inputs_dict["output_hidden_states"]
201
            config.output_hidden_states = True
202

203
            check_hidden_states_output(inputs_dict, config, model_class)
204

205
    # override as the `logit_scale` parameter initilization is different for MgpstrModel
206
    def test_initialization(self):
207
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
208

209
        configs_no_init = _config_zero_init(config)
210
        for model_class in self.all_model_classes:
211
            model = model_class(config=configs_no_init)
212
            for name, param in model.named_parameters():
213
                if isinstance(param, (nn.Linear, nn.Conv2d, nn.LayerNorm)):
214
                    if param.requires_grad:
215
                        self.assertIn(
216
                            ((param.data.mean() * 1e9).round() / 1e9).item(),
217
                            [0.0, 1.0],
218
                            msg=f"Parameter {name} of model {model_class} seems not properly initialized",
219
                        )
220

221
    @unittest.skip(reason="Retain_grad is tested in individual model tests")
222
    def test_retain_grad_hidden_states_attentions(self):
223
        pass
224

225

226
# We will verify our results on an image from the IIIT-5k dataset
227
def prepare_img():
228
    url = "https://i.postimg.cc/ZKwLg2Gw/367-14.png"
229
    im = Image.open(requests.get(url, stream=True).raw).convert("RGB")
230
    return im
231

232

233
@require_vision
234
@require_torch
235
class MgpstrModelIntegrationTest(unittest.TestCase):
236
    @slow
237
    def test_inference(self):
238
        model_name = "alibaba-damo/mgp-str-base"
239
        model = MgpstrForSceneTextRecognition.from_pretrained(model_name).to(torch_device)
240
        processor = MgpstrProcessor.from_pretrained(model_name)
241

242
        image = prepare_img()
243
        inputs = processor(images=image, return_tensors="pt").pixel_values.to(torch_device)
244

245
        # forward pass
246
        with torch.no_grad():
247
            outputs = model(inputs)
248

249
        # verify the logits
250
        self.assertEqual(outputs.logits[0].shape, torch.Size((1, 27, 38)))
251

252
        out_strs = processor.batch_decode(outputs.logits)
253
        expected_text = "ticket"
254

255
        self.assertEqual(out_strs["generated_text"][0], expected_text)
256

257
        expected_slice = torch.tensor(
258
            [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]],
259
            device=torch_device,
260
        )
261

262
        self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4], expected_slice, atol=1e-4))
263

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

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

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

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