





import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
	from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import PoolFormerImageProcessor



class       __lowerCAmelCase (    _a  ):






			def     lowerCamelCase						(self					)  ->     List[Any]:


							'''simple docstring'''



							snake_case_		:					str			    =						self.config_class(**self.inputs_dict					)
							self.parent.assertTrue(hasattr(__magic_name__      ,							'''hidden_sizes'''					)					)
							self.parent.assertTrue(hasattr(__magic_name__      ,							'''num_encoder_blocks'''					)					)




class       __lowerCAmelCase :






			def __init__(self      ,							__magic_name__      ,							__magic_name__=13      ,							__magic_name__=64      ,							__magic_name__=3      ,							__magic_name__=4      ,							__magic_name__=[2, 2, 2, 2]      ,							__magic_name__=[8, 4, 2, 1]      ,							__magic_name__=[16, 32, 64, 128]      ,							__magic_name__=[1, 4, 8, 16]      ,							__magic_name__=False      ,							__magic_name__=True      ,							__magic_name__="gelu"      ,							__magic_name__=0.1      ,							__magic_name__=0.02      ,							__magic_name__=3      ,							__magic_name__=None      ,							)  ->     Optional[Any]:


							'''simple docstring'''



							snake_case_		:					Dict			    =						parent
							snake_case_		:					Dict			    =						batch_size
							snake_case_		:					int			    =						image_size
							snake_case_		:					Optional[int]			    =						num_channels
							snake_case_		:					Union[str, Any]			    =						num_encoder_blocks
							snake_case_		:					str			    =						sr_ratios
							snake_case_		:					List[str]			    =						depths
							snake_case_		:					int			    =						hidden_sizes
							snake_case_		:					Any			    =						downsampling_rates
							snake_case_		:					Any			    =						is_training
							snake_case_		:					Dict			    =						use_labels
							snake_case_		:					Union[str, Any]			    =						hidden_act
							snake_case_		:					List[Any]			    =						hidden_dropout_prob
							snake_case_		:					Optional[Any]			    =						initializer_range
							snake_case_		:					Tuple			    =						num_labels
							snake_case_		:					Union[str, Any]			    =						scope






			def     lowerCamelCase						(self					)  ->     Any:


							'''simple docstring'''



							snake_case_		:					List[Any]			    =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

							snake_case_		:					int			    =						None
							if self.use_labels:
											snake_case_		:					List[Any]			    =						ids_tensor([self.batch_size, self.image_size, self.image_size]      ,							self.num_labels					)

							snake_case_		:					Optional[Any]			    =						PoolFormerConfig(
							    image_size=self.image_size      ,							num_channels=self.num_channels      ,							num_encoder_blocks=self.num_encoder_blocks      ,							depths=self.depths      ,							hidden_sizes=self.hidden_sizes      ,							hidden_act=self.hidden_act      ,							hidden_dropout_prob=self.hidden_dropout_prob      ,							initializer_range=self.initializer_range      ,							)

							return config, pixel_values, labels






			def     lowerCamelCase						(self      ,							__magic_name__      ,							__magic_name__      ,							__magic_name__					)  ->     Union[str, Any]:


							'''simple docstring'''



							snake_case_		:					Tuple			    =						PoolFormerModel(config=__magic_name__					)
							model.to(__magic_name__					)
							model.eval()
							snake_case_		:					Dict			    =						model(__magic_name__					)
							snake_case_		:					Optional[Any]			    =						self.image_size // 32.0
							self.parent.assertEqual(
							    result.last_hidden_state.shape      ,							(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)					)






			def     lowerCamelCase						(self					)  ->     Union[str, Any]:


							'''simple docstring'''



							snake_case_		:					Optional[Any]			    =						self.prepare_config_and_inputs()
							snake_case_    ,							snake_case_    ,							snake_case_		:					str			    =						config_and_inputs
							snake_case_		:					int			    =						{'''pixel_values''': pixel_values}
							return config, inputs_dict




@require_torch
class       __lowerCAmelCase (    _a,  _a,  unittest.TestCase  ):
			lowerCamelCase_  :  Optional[int]     =   (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
			lowerCamelCase_  :  Optional[int]     =   (
			    {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
			    if is_torch_available()
			    else {}
			)

			lowerCamelCase_  :  Optional[int]     =   False
			lowerCamelCase_  :  Optional[int]     =   False
			lowerCamelCase_  :  List[Any]     =   False
			lowerCamelCase_  :  Union[str, Any]     =   False
			lowerCamelCase_  :  Dict     =   False






			def     lowerCamelCase						(self					)  ->     List[str]:


							'''simple docstring'''



							snake_case_		:					Union[str, Any]			    =						PoolFormerModelTester(self					)
							snake_case_		:					Optional[int]			    =						PoolFormerConfigTester(self      ,							config_class=__magic_name__					)






			def     lowerCamelCase						(self					)  ->     Optional[int]:


							'''simple docstring'''



							self.config_tester.run_common_tests()






			def     lowerCamelCase						(self					)  ->     List[Any]:


							'''simple docstring'''



							snake_case_		:					Optional[Any]			    =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__magic_name__					)






			@unittest.skip('''PoolFormer does not use inputs_embeds'''					)
			def     lowerCamelCase						(self					)  ->     Dict:


							'''simple docstring'''



							pass






			@unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''					)
			def     lowerCamelCase						(self					)  ->     List[str]:


							'''simple docstring'''



							pass






			def     lowerCamelCase						(self					)  ->     Optional[Any]:


							'''simple docstring'''



							def check_hidden_states_output(__magic_name__      ,							__magic_name__      ,							__magic_name__					):
											snake_case_		:					Union[str, Any]			    =						model_class(__magic_name__					)
											model.to(__magic_name__					)
											model.eval()

											with torch.no_grad():
															snake_case_		:					Tuple			    =						model(**self._prepare_for_class(__magic_name__      ,							__magic_name__					)					)

											snake_case_		:					List[Any]			    =						outputs.hidden_states

											snake_case_		:					Dict			    =						self.model_tester.num_encoder_blocks
											self.assertEqual(len(__magic_name__					)      ,							__magic_name__					)

											# verify the first hidden states (first block)
											self.assertListEqual(
											    list(hidden_states[0].shape[-3:]					)      ,							[
											        self.model_tester.hidden_sizes[0],
											        self.model_tester.image_size // 4,
											        self.model_tester.image_size // 4,
											    ]      ,							)

							snake_case_    ,							snake_case_		:					List[str]			    =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											snake_case_		:					Optional[int]			    =						True
											check_hidden_states_output(__magic_name__      ,							__magic_name__      ,							__magic_name__					)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											snake_case_		:					int			    =						True

											check_hidden_states_output(__magic_name__      ,							__magic_name__      ,							__magic_name__					)






			def     lowerCamelCase						(self					)  ->     int:


							'''simple docstring'''



							if not self.model_tester.is_training:
											return

							snake_case_    ,							snake_case_		:					Any			    =						self.model_tester.prepare_config_and_inputs_for_common()
							snake_case_		:					Union[str, Any]			    =						True

							for model_class in self.all_model_classes:
											if model_class in get_values(__magic_name__					):
															continue
											snake_case_		:					List[str]			    =						model_class(__magic_name__					)
											model.to(__magic_name__					)
											model.train()
											snake_case_		:					Optional[int]			    =						self._prepare_for_class(__magic_name__      ,							__magic_name__      ,							return_labels=__magic_name__					)
											snake_case_		:					Tuple			    =						model(**__magic_name__					).loss
											loss.backward()






			def     lowerCamelCase						(self					)  ->     Optional[int]:


							'''simple docstring'''



							snake_case_    ,							snake_case_		:					Any			    =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											snake_case_		:					Optional[int]			    =						model_class(__magic_name__					)
											snake_case_		:					Optional[Any]			    =						inspect.signature(model.forward					)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											snake_case_		:					List[Any]			    =						[*signature.parameters.keys()]

											snake_case_		:					List[Any]			    =						['''pixel_values''']
											self.assertListEqual(arg_names[:1]      ,							__magic_name__					)






			@slow
			def     lowerCamelCase						(self					)  ->     Dict:


							'''simple docstring'''



							for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											snake_case_		:					Dict			    =						PoolFormerModel.from_pretrained(__magic_name__					)
											self.assertIsNotNone(__magic_name__					)






def   lowerCamelCase_		(       )	->		List[str]:






				"""simple docstring"""


				snake_case_		:					Optional[int]			    =						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
				return image





@require_torch
class       __lowerCAmelCase (    unittest.TestCase  ):






			@slow
			def     lowerCamelCase						(self					)  ->     List[Any]:


							'''simple docstring'''



							snake_case_		:					Optional[Any]			    =						PoolFormerImageProcessor()
							snake_case_		:					Optional[Any]			    =						PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''					).to(__magic_name__					)

							snake_case_		:					str			    =						image_processor(images=prepare_img()      ,							return_tensors='''pt'''					).to(__magic_name__					)

							# forward pass
							with torch.no_grad():
											snake_case_		:					Optional[Any]			    =						model(**__magic_name__					)

							# verify the logits
							snake_case_		:					Dict			    =						torch.Size((1, 1000)					)
							self.assertEqual(outputs.logits.shape      ,							__magic_name__					)

							snake_case_		:					int			    =						torch.tensor([-0.6_113, 0.1_685, -0.0_492]					).to(__magic_name__					)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,							__magic_name__      ,							atol=1e-4					)					)







import warnings

from ...utils import logging
from .image_processing_mobilenet_va import MobileNetVaImageProcessor


lowerCAmelCase_												=       logging.get_logger(__name__)



class       __lowerCAmelCase (    _a  ):






			def __init__(self      ,							*__magic_name__      ,							**__magic_name__					)  ->     None:


							'''simple docstring'''



							warnings.warn(
							    '''The class MobileNetV2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
							    ''' Please use MobileNetV2ImageProcessor instead.'''      ,							__magic_name__      ,							)
							super().__init__(*__magic_name__      ,							**__magic_name__					)
