transformers

Форк
0
/
test_modeling_vitdet.py 
302 строки · 11.1 Кб
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 ViTDet model. """
16

17

18
import unittest
19

20
from transformers import VitDetConfig
21
from transformers.testing_utils import is_flaky, require_torch, torch_device
22
from transformers.utils import is_torch_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 VitDetBackbone, VitDetModel
35

36

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

76
        self.num_patches_one_direction = self.image_size // self.patch_size
77
        self.seq_length = (self.image_size // self.patch_size) ** 2
78

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

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

86
        config = self.get_config()
87

88
        return config, pixel_values, labels
89

90
    def get_config(self):
91
        return VitDetConfig(
92
            image_size=self.image_size,
93
            pretrain_image_size=self.image_size,
94
            patch_size=self.patch_size,
95
            num_channels=self.num_channels,
96
            hidden_size=self.hidden_size,
97
            num_hidden_layers=self.num_hidden_layers,
98
            num_attention_heads=self.num_attention_heads,
99
            intermediate_size=self.intermediate_size,
100
            hidden_act=self.hidden_act,
101
            hidden_dropout_prob=self.hidden_dropout_prob,
102
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
103
            is_decoder=False,
104
            initializer_range=self.initializer_range,
105
        )
106

107
    def create_and_check_model(self, config, pixel_values, labels):
108
        model = VitDetModel(config=config)
109
        model.to(torch_device)
110
        model.eval()
111
        result = model(pixel_values)
112
        self.parent.assertEqual(
113
            result.last_hidden_state.shape,
114
            (self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction),
115
        )
116

117
    def create_and_check_backbone(self, config, pixel_values, labels):
118
        model = VitDetBackbone(config=config)
119
        model.to(torch_device)
120
        model.eval()
121
        result = model(pixel_values)
122

123
        # verify hidden states
124
        self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
125
        self.parent.assertListEqual(
126
            list(result.feature_maps[0].shape),
127
            [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction],
128
        )
129

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

134
        # verify backbone works with out_features=None
135
        config.out_features = None
136
        model = VitDetBackbone(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(
144
            list(result.feature_maps[0].shape),
145
            [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction],
146
        )
147

148
        # verify channels
149
        self.parent.assertEqual(len(model.channels), 1)
150
        self.parent.assertListEqual(model.channels, [config.hidden_size])
151

152
    def prepare_config_and_inputs_for_common(self):
153
        config_and_inputs = self.prepare_config_and_inputs()
154
        config, pixel_values, labels = config_and_inputs
155
        inputs_dict = {"pixel_values": pixel_values}
156
        return config, inputs_dict
157

158

159
@require_torch
160
class VitDetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
161
    """
162
    Here we also overwrite some of the tests of test_modeling_common.py, as VitDet does not use input_ids, inputs_embeds,
163
    attention_mask and seq_length.
164
    """
165

166
    all_model_classes = (VitDetModel, VitDetBackbone) if is_torch_available() else ()
167
    pipeline_model_mapping = {"feature-extraction": VitDetModel} if is_torch_available() else {}
168

169
    fx_compatible = False
170
    test_pruning = False
171
    test_resize_embeddings = False
172
    test_head_masking = False
173

174
    def setUp(self):
175
        self.model_tester = VitDetModelTester(self)
176
        self.config_tester = ConfigTester(self, config_class=VitDetConfig, has_text_modality=False, hidden_size=37)
177

178
    @is_flaky(max_attempts=3, description="`torch.nn.init.trunc_normal_` is flaky.")
179
    def test_initialization(self):
180
        super().test_initialization()
181

182
    # TODO: Fix me (once this model gets more usage)
183
    @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.")
184
    def test_cpu_offload(self):
185
        super().test_cpu_offload()
186

187
    # TODO: Fix me (once this model gets more usage)
188
    @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.")
189
    def test_disk_offload_bin(self):
190
        super().test_disk_offload()
191

192
    @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.")
193
    def test_disk_offload_safetensors(self):
194
        super().test_disk_offload()
195

196
    # TODO: Fix me (once this model gets more usage)
197
    @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.")
198
    def test_model_parallelism(self):
199
        super().test_model_parallelism()
200

201
    def test_config(self):
202
        self.config_tester.run_common_tests()
203

204
    @unittest.skip(reason="VitDet does not use inputs_embeds")
205
    def test_inputs_embeds(self):
206
        pass
207

208
    def test_model_common_attributes(self):
209
        config, _ = self.model_tester.prepare_config_and_inputs_for_common()
210

211
        for model_class in self.all_model_classes:
212
            model = model_class(config)
213
            self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
214
            x = model.get_output_embeddings()
215
            self.assertTrue(x is None or isinstance(x, nn.Linear))
216

217
    def test_model(self):
218
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
219
        self.model_tester.create_and_check_model(*config_and_inputs)
220

221
    def test_backbone(self):
222
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
223
        self.model_tester.create_and_check_backbone(*config_and_inputs)
224

225
    def test_hidden_states_output(self):
226
        def check_hidden_states_output(inputs_dict, config, model_class):
227
            model = model_class(config)
228
            model.to(torch_device)
229
            model.eval()
230

231
            with torch.no_grad():
232
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))
233

234
            hidden_states = outputs.hidden_states
235

236
            expected_num_stages = self.model_tester.num_hidden_layers
237
            self.assertEqual(len(hidden_states), expected_num_stages + 1)
238

239
            # VitDet's feature maps are of shape (batch_size, num_channels, height, width)
240
            self.assertListEqual(
241
                list(hidden_states[0].shape[-2:]),
242
                [
243
                    self.model_tester.num_patches_one_direction,
244
                    self.model_tester.num_patches_one_direction,
245
                ],
246
            )
247

248
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
249

250
        for model_class in self.all_model_classes:
251
            inputs_dict["output_hidden_states"] = True
252
            check_hidden_states_output(inputs_dict, config, model_class)
253

254
            # check that output_hidden_states also work using config
255
            del inputs_dict["output_hidden_states"]
256
            config.output_hidden_states = True
257

258
            check_hidden_states_output(inputs_dict, config, model_class)
259

260
    # overwrite since VitDet only supports retraining gradients of hidden states
261
    def test_retain_grad_hidden_states_attentions(self):
262
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
263
        config.output_hidden_states = True
264
        config.output_attentions = self.has_attentions
265

266
        # no need to test all models as different heads yield the same functionality
267
        model_class = self.all_model_classes[0]
268
        model = model_class(config)
269
        model.to(torch_device)
270

271
        inputs = self._prepare_for_class(inputs_dict, model_class)
272

273
        outputs = model(**inputs)
274

275
        output = outputs[0]
276

277
        # Encoder-/Decoder-only models
278
        hidden_states = outputs.hidden_states[0]
279
        hidden_states.retain_grad()
280

281
        output.flatten()[0].backward(retain_graph=True)
282

283
        self.assertIsNotNone(hidden_states.grad)
284

285
    @unittest.skip(reason="VitDet does not support feedforward chunking")
286
    def test_feed_forward_chunking(self):
287
        pass
288

289
    @unittest.skip(reason="VitDet does not have standalone checkpoints since it used as backbone in other models")
290
    def test_model_from_pretrained(self):
291
        pass
292

293

294
@require_torch
295
class VitDetBackboneTest(unittest.TestCase, BackboneTesterMixin):
296
    all_model_classes = (VitDetBackbone,) if is_torch_available() else ()
297
    config_class = VitDetConfig
298

299
    has_attentions = False
300

301
    def setUp(self):
302
        self.model_tester = VitDetModelTester(self)
303

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

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

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

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