transformers

Форк
0
/
test_modeling_resnet.py 
326 строк · 11.9 Кб
1
# coding=utf-8
2
# Copyright 2022 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 ResNet model. """
16

17

18
import unittest
19

20
from transformers import ResNetConfig
21
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
22
from transformers.utils import cached_property, is_torch_available, is_vision_available
23

24
from ...test_backbone_common import BackboneTesterMixin
25
from ...test_configuration_common import ConfigTester
26
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_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 ResNetBackbone, ResNetForImageClassification, ResNetModel
35
    from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST
36

37

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

41
    from transformers import AutoImageProcessor
42

43

44
class ResNetModelTester:
45
    def __init__(
46
        self,
47
        parent,
48
        batch_size=3,
49
        image_size=32,
50
        num_channels=3,
51
        embeddings_size=10,
52
        hidden_sizes=[10, 20, 30, 40],
53
        depths=[1, 1, 2, 1],
54
        is_training=True,
55
        use_labels=True,
56
        hidden_act="relu",
57
        num_labels=3,
58
        scope=None,
59
        out_features=["stage2", "stage3", "stage4"],
60
        out_indices=[2, 3, 4],
61
    ):
62
        self.parent = parent
63
        self.batch_size = batch_size
64
        self.image_size = image_size
65
        self.num_channels = num_channels
66
        self.embeddings_size = embeddings_size
67
        self.hidden_sizes = hidden_sizes
68
        self.depths = depths
69
        self.is_training = is_training
70
        self.use_labels = use_labels
71
        self.hidden_act = hidden_act
72
        self.num_labels = num_labels
73
        self.scope = scope
74
        self.num_stages = len(hidden_sizes)
75
        self.out_features = out_features
76
        self.out_indices = out_indices
77

78
    def prepare_config_and_inputs(self):
79
        pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
80

81
        labels = None
82
        if self.use_labels:
83
            labels = ids_tensor([self.batch_size], self.num_labels)
84

85
        config = self.get_config()
86

87
        return config, pixel_values, labels
88

89
    def get_config(self):
90
        return ResNetConfig(
91
            num_channels=self.num_channels,
92
            embeddings_size=self.embeddings_size,
93
            hidden_sizes=self.hidden_sizes,
94
            depths=self.depths,
95
            hidden_act=self.hidden_act,
96
            num_labels=self.num_labels,
97
            out_features=self.out_features,
98
            out_indices=self.out_indices,
99
        )
100

101
    def create_and_check_model(self, config, pixel_values, labels):
102
        model = ResNetModel(config=config)
103
        model.to(torch_device)
104
        model.eval()
105
        result = model(pixel_values)
106
        # expected last hidden states: B, C, H // 32, W // 32
107
        self.parent.assertEqual(
108
            result.last_hidden_state.shape,
109
            (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
110
        )
111

112
    def create_and_check_for_image_classification(self, config, pixel_values, labels):
113
        config.num_labels = self.num_labels
114
        model = ResNetForImageClassification(config)
115
        model.to(torch_device)
116
        model.eval()
117
        result = model(pixel_values, labels=labels)
118
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
119

120
    def create_and_check_backbone(self, config, pixel_values, labels):
121
        model = ResNetBackbone(config=config)
122
        model.to(torch_device)
123
        model.eval()
124
        result = model(pixel_values)
125

126
        # verify feature maps
127
        self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
128
        self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[1], 4, 4])
129

130
        # verify channels
131
        self.parent.assertEqual(len(model.channels), len(config.out_features))
132
        self.parent.assertListEqual(model.channels, config.hidden_sizes[1:])
133

134
        # verify backbone works with out_features=None
135
        config.out_features = None
136
        model = ResNetBackbone(config=config)
137
        model.to(torch_device)
138
        model.eval()
139
        result = model(pixel_values)
140

141
        # verify feature maps
142
        self.parent.assertEqual(len(result.feature_maps), 1)
143
        self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[-1], 1, 1])
144

145
        # verify channels
146
        self.parent.assertEqual(len(model.channels), 1)
147
        self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]])
148

149
    def prepare_config_and_inputs_for_common(self):
150
        config_and_inputs = self.prepare_config_and_inputs()
151
        config, pixel_values, labels = config_and_inputs
152
        inputs_dict = {"pixel_values": pixel_values}
153
        return config, inputs_dict
154

155

156
@require_torch
157
class ResNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
158
    """
159
    Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds,
160
    attention_mask and seq_length.
161
    """
162

163
    all_model_classes = (
164
        (
165
            ResNetModel,
166
            ResNetForImageClassification,
167
            ResNetBackbone,
168
        )
169
        if is_torch_available()
170
        else ()
171
    )
172
    pipeline_model_mapping = (
173
        {"image-feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
174
        if is_torch_available()
175
        else {}
176
    )
177

178
    fx_compatible = True
179
    test_pruning = False
180
    test_resize_embeddings = False
181
    test_head_masking = False
182
    has_attentions = False
183

184
    def setUp(self):
185
        self.model_tester = ResNetModelTester(self)
186
        self.config_tester = ConfigTester(self, config_class=ResNetConfig, has_text_modality=False)
187

188
    def test_config(self):
189
        self.create_and_test_config_common_properties()
190
        self.config_tester.create_and_test_config_to_json_string()
191
        self.config_tester.create_and_test_config_to_json_file()
192
        self.config_tester.create_and_test_config_from_and_save_pretrained()
193
        self.config_tester.create_and_test_config_with_num_labels()
194
        self.config_tester.check_config_can_be_init_without_params()
195
        self.config_tester.check_config_arguments_init()
196

197
    def create_and_test_config_common_properties(self):
198
        return
199

200
    @unittest.skip(reason="ResNet does not use inputs_embeds")
201
    def test_inputs_embeds(self):
202
        pass
203

204
    @unittest.skip(reason="ResNet does not support input and output embeddings")
205
    def test_model_common_attributes(self):
206
        pass
207

208
    def test_model(self):
209
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
210
        self.model_tester.create_and_check_model(*config_and_inputs)
211

212
    def test_backbone(self):
213
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
214
        self.model_tester.create_and_check_backbone(*config_and_inputs)
215

216
    def test_initialization(self):
217
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
218

219
        for model_class in self.all_model_classes:
220
            model = model_class(config=config)
221
            for name, module in model.named_modules():
222
                if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
223
                    self.assertTrue(
224
                        torch.all(module.weight == 1),
225
                        msg=f"Parameter {name} of model {model_class} seems not properly initialized",
226
                    )
227
                    self.assertTrue(
228
                        torch.all(module.bias == 0),
229
                        msg=f"Parameter {name} of model {model_class} seems not properly initialized",
230
                    )
231

232
    def test_hidden_states_output(self):
233
        def check_hidden_states_output(inputs_dict, config, model_class):
234
            model = model_class(config)
235
            model.to(torch_device)
236
            model.eval()
237

238
            with torch.no_grad():
239
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))
240

241
            hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
242

243
            expected_num_stages = self.model_tester.num_stages
244
            self.assertEqual(len(hidden_states), expected_num_stages + 1)
245

246
            # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
247
            self.assertListEqual(
248
                list(hidden_states[0].shape[-2:]),
249
                [self.model_tester.image_size // 4, self.model_tester.image_size // 4],
250
            )
251

252
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
253
        layers_type = ["basic", "bottleneck"]
254
        for model_class in self.all_model_classes:
255
            for layer_type in layers_type:
256
                config.layer_type = layer_type
257
                inputs_dict["output_hidden_states"] = True
258
                check_hidden_states_output(inputs_dict, config, model_class)
259

260
                # check that output_hidden_states also work using config
261
                del inputs_dict["output_hidden_states"]
262
                config.output_hidden_states = True
263

264
                check_hidden_states_output(inputs_dict, config, model_class)
265

266
    @unittest.skip(reason="ResNet does not use feedforward chunking")
267
    def test_feed_forward_chunking(self):
268
        pass
269

270
    def test_for_image_classification(self):
271
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
272
        self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
273

274
    @slow
275
    def test_model_from_pretrained(self):
276
        for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
277
            model = ResNetModel.from_pretrained(model_name)
278
            self.assertIsNotNone(model)
279

280

281
# We will verify our results on an image of cute cats
282
def prepare_img():
283
    image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
284
    return image
285

286

287
@require_torch
288
@require_vision
289
class ResNetModelIntegrationTest(unittest.TestCase):
290
    @cached_property
291
    def default_image_processor(self):
292
        return (
293
            AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
294
            if is_vision_available()
295
            else None
296
        )
297

298
    @slow
299
    def test_inference_image_classification_head(self):
300
        model = ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(torch_device)
301

302
        image_processor = self.default_image_processor
303
        image = prepare_img()
304
        inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
305

306
        # forward pass
307
        with torch.no_grad():
308
            outputs = model(**inputs)
309

310
        # verify the logits
311
        expected_shape = torch.Size((1, 1000))
312
        self.assertEqual(outputs.logits.shape, expected_shape)
313

314
        expected_slice = torch.tensor([-11.1069, -9.7877, -8.3777]).to(torch_device)
315

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

318

319
@require_torch
320
class ResNetBackboneTest(BackboneTesterMixin, unittest.TestCase):
321
    all_model_classes = (ResNetBackbone,) if is_torch_available() else ()
322
    has_attentions = False
323
    config_class = ResNetConfig
324

325
    def setUp(self):
326
        self.model_tester = ResNetModelTester(self)
327

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

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

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

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