transformers
293 строки · 10.7 Кб
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 SwiftFormer model. """
16
17
18import copy
19import unittest
20
21from transformers import PretrainedConfig, SwiftFormerConfig
22from transformers.testing_utils import (
23require_torch,
24require_vision,
25slow,
26torch_device,
27)
28from transformers.utils import cached_property, is_torch_available, is_vision_available
29
30from ...test_configuration_common import ConfigTester
31from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
32from ...test_pipeline_mixin import PipelineTesterMixin
33
34
35if is_torch_available():
36import torch
37from torch import nn
38
39from transformers import SwiftFormerForImageClassification, SwiftFormerModel
40from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
41
42
43if is_vision_available():
44from PIL import Image
45
46from transformers import ViTImageProcessor
47
48
49class SwiftFormerModelTester:
50def __init__(
51self,
52parent,
53batch_size=13,
54num_channels=3,
55is_training=True,
56use_labels=True,
57hidden_dropout_prob=0.1,
58attention_probs_dropout_prob=0.1,
59image_size=224,
60num_labels=3,
61layer_depths=[1, 1, 1, 1],
62embed_dims=[16, 16, 32, 32],
63):
64self.parent = parent
65self.batch_size = batch_size
66self.num_channels = num_channels
67self.is_training = is_training
68self.use_labels = use_labels
69self.hidden_dropout_prob = hidden_dropout_prob
70self.attention_probs_dropout_prob = attention_probs_dropout_prob
71self.num_labels = num_labels
72self.image_size = image_size
73self.layer_depths = layer_depths
74self.embed_dims = embed_dims
75
76def prepare_config_and_inputs(self):
77pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
78
79labels = None
80if self.use_labels:
81labels = ids_tensor([self.batch_size], self.num_labels)
82
83config = self.get_config()
84
85return config, pixel_values, labels
86
87def get_config(self):
88return SwiftFormerConfig(
89depths=self.layer_depths,
90embed_dims=self.embed_dims,
91mlp_ratio=4,
92downsamples=[True, True, True, True],
93hidden_act="gelu",
94num_labels=self.num_labels,
95down_patch_size=3,
96down_stride=2,
97down_pad=1,
98drop_rate=0.0,
99drop_path_rate=0.0,
100use_layer_scale=True,
101layer_scale_init_value=1e-5,
102)
103
104def create_and_check_model(self, config, pixel_values, labels):
105model = SwiftFormerModel(config=config)
106model.to(torch_device)
107model.eval()
108result = model(pixel_values)
109self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.embed_dims[-1], 7, 7))
110
111def create_and_check_for_image_classification(self, config, pixel_values, labels):
112config.num_labels = self.num_labels
113model = SwiftFormerForImageClassification(config)
114model.to(torch_device)
115model.eval()
116result = model(pixel_values, labels=labels)
117self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
118
119model = SwiftFormerForImageClassification(config)
120model.to(torch_device)
121model.eval()
122
123pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
124result = model(pixel_values)
125self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
126
127def prepare_config_and_inputs_for_common(self):
128(config, pixel_values, labels) = self.prepare_config_and_inputs()
129inputs_dict = {"pixel_values": pixel_values}
130return config, inputs_dict
131
132
133@require_torch
134class SwiftFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
135"""
136Here we also overwrite some of the tests of test_modeling_common.py, as SwiftFormer does not use input_ids, inputs_embeds,
137attention_mask and seq_length.
138"""
139
140all_model_classes = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
141pipeline_model_mapping = (
142{"image-feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
143if is_torch_available()
144else {}
145)
146
147fx_compatible = False
148test_pruning = False
149test_resize_embeddings = False
150test_head_masking = False
151has_attentions = False
152
153def setUp(self):
154self.model_tester = SwiftFormerModelTester(self)
155self.config_tester = ConfigTester(
156self,
157config_class=SwiftFormerConfig,
158has_text_modality=False,
159hidden_size=37,
160num_attention_heads=12,
161num_hidden_layers=12,
162)
163
164def test_config(self):
165self.config_tester.run_common_tests()
166
167@unittest.skip(reason="SwiftFormer does not use inputs_embeds")
168def test_inputs_embeds(self):
169pass
170
171def test_model_common_attributes(self):
172config, _ = self.model_tester.prepare_config_and_inputs_for_common()
173
174for model_class in self.all_model_classes:
175model = model_class(config)
176x = model.get_output_embeddings()
177self.assertTrue(x is None or isinstance(x, nn.Linear))
178
179def test_model(self):
180config_and_inputs = self.model_tester.prepare_config_and_inputs()
181self.model_tester.create_and_check_model(*config_and_inputs)
182
183def test_for_image_classification(self):
184config_and_inputs = self.model_tester.prepare_config_and_inputs()
185self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
186
187@slow
188def test_model_from_pretrained(self):
189for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
190model = SwiftFormerModel.from_pretrained(model_name)
191self.assertIsNotNone(model)
192
193@unittest.skip(reason="SwiftFormer does not output attentions")
194def test_attention_outputs(self):
195pass
196
197def test_hidden_states_output(self):
198def check_hidden_states_output(inputs_dict, config, model_class):
199model = model_class(config)
200model.to(torch_device)
201model.eval()
202
203with torch.no_grad():
204outputs = model(**self._prepare_for_class(inputs_dict, model_class))
205
206hidden_states = outputs.hidden_states
207
208expected_num_stages = 8
209self.assertEqual(len(hidden_states), expected_num_stages) # TODO
210
211# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
212# with the width and height being successively divided by 2, after every 2 blocks
213for i in range(len(hidden_states)):
214self.assertEqual(
215hidden_states[i].shape,
216torch.Size(
217[
218self.model_tester.batch_size,
219self.model_tester.embed_dims[i // 2],
220(self.model_tester.image_size // 4) // 2 ** (i // 2),
221(self.model_tester.image_size // 4) // 2 ** (i // 2),
222]
223),
224)
225
226config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
227
228for model_class in self.all_model_classes:
229inputs_dict["output_hidden_states"] = True
230check_hidden_states_output(inputs_dict, config, model_class)
231
232# check that output_hidden_states also work using config
233del inputs_dict["output_hidden_states"]
234config.output_hidden_states = True
235
236check_hidden_states_output(inputs_dict, config, model_class)
237
238def test_initialization(self):
239def _config_zero_init(config):
240configs_no_init = copy.deepcopy(config)
241for key in configs_no_init.__dict__.keys():
242if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
243setattr(configs_no_init, key, 1e-10)
244if isinstance(getattr(configs_no_init, key, None), PretrainedConfig):
245no_init_subconfig = _config_zero_init(getattr(configs_no_init, key))
246setattr(configs_no_init, key, no_init_subconfig)
247return configs_no_init
248
249config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
250
251configs_no_init = _config_zero_init(config)
252for model_class in self.all_model_classes:
253model = model_class(config=configs_no_init)
254for name, param in model.named_parameters():
255if param.requires_grad:
256self.assertIn(
257((param.data.mean() * 1e9) / 1e9).round().item(),
258[0.0, 1.0],
259msg=f"Parameter {name} of model {model_class} seems not properly initialized",
260)
261
262
263# We will verify our results on an image of cute cats
264def prepare_img():
265image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
266return image
267
268
269@require_torch
270@require_vision
271class SwiftFormerModelIntegrationTest(unittest.TestCase):
272@cached_property
273def default_image_processor(self):
274return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs") if is_vision_available() else None
275
276@slow
277def test_inference_image_classification_head(self):
278model = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs").to(torch_device)
279
280image_processor = self.default_image_processor
281image = prepare_img()
282inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
283
284# forward pass
285with torch.no_grad():
286outputs = model(**inputs)
287
288# verify the logits
289expected_shape = torch.Size((1, 1000))
290self.assertEqual(outputs.logits.shape, expected_shape)
291
292expected_slice = torch.tensor([[-2.1703e00, 2.1107e00, -2.0811e00]]).to(torch_device)
293self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
294