

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 			snake_case_     (	__A      ):







			'''simple docstring'''

			def        snake_case__(  self				:       Optional[Any]							)   ->Tuple:
									snake_case_     =			self.config_class(**self.inputs_dict							)
									self.parent.assertTrue(hasattr(_UpperCamelCase							,     '''hidden_sizes'''							)							)
									self.parent.assertTrue(hasattr(_UpperCamelCase							,     '''num_encoder_blocks'''							)							)






class 			snake_case_     :







			'''simple docstring'''

			def __init__(  self				:       Tuple							,     _UpperCamelCase				:       Dict							,     _UpperCamelCase				:       Dict=1_3							,     _UpperCamelCase				:       Union[str, Any]=6_4							,     _UpperCamelCase				:       Optional[Any]=3							,     _UpperCamelCase				:       Any=4							,     _UpperCamelCase				:       Tuple=[2, 2, 2, 2]							,     _UpperCamelCase				:       Tuple=[8, 4, 2, 1]							,     _UpperCamelCase				:       Tuple=[1_6, 3_2, 6_4, 1_2_8]							,     _UpperCamelCase				:       Any=[1, 4, 8, 1_6]							,     _UpperCamelCase				:       Tuple=False							,     _UpperCamelCase				:       Optional[int]=True							,     _UpperCamelCase				:       List[str]="gelu"							,     _UpperCamelCase				:       Dict=0.1							,     _UpperCamelCase				:       Tuple=0.02							,     _UpperCamelCase				:       str=3							,     _UpperCamelCase				:       Tuple=None							,     )   ->int:
									snake_case_     =			parent
									snake_case_     =			batch_size
									snake_case_     =			image_size
									snake_case_     =			num_channels
									snake_case_     =			num_encoder_blocks
									snake_case_     =			sr_ratios
									snake_case_     =			depths
									snake_case_     =			hidden_sizes
									snake_case_     =			downsampling_rates
									snake_case_     =			is_training
									snake_case_     =			use_labels
									snake_case_     =			hidden_act
									snake_case_     =			hidden_dropout_prob
									snake_case_     =			initializer_range
									snake_case_     =			num_labels
									snake_case_     =			scope







			def        snake_case__(  self				:       Tuple							)   ->int:
									snake_case_     =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

									snake_case_     =			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        snake_case__(  self				:       Tuple							,     _UpperCamelCase				:       Dict							,     _UpperCamelCase				:       List[str]							,     _UpperCamelCase				:       int							)   ->int:
									snake_case_     =			PoolFormerModel(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_     =			model(_UpperCamelCase							)
									snake_case_     =			snake_case_     =			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        snake_case__(  self				:       Any							)   ->Dict:
									snake_case_     =			self.prepare_config_and_inputs()
									snake_case_,					snake_case_,					snake_case_     =			config_and_inputs
									snake_case_     =			{'''pixel_values''': pixel_values}
									return config, inputs_dict






@require_torch
class 			snake_case_     (	__A			, __A			, unittest.TestCase      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     Tuple		    =       (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
			SCREAMING_SNAKE_CASE  :     List[Any]		    =       (
			    {"feature-extraction": PoolFormerModel, "image-classification": PoolFormerForImageClassification}
			    if is_torch_available()
			    else {}
			)

			SCREAMING_SNAKE_CASE  :     List[Any]		    =       False
			SCREAMING_SNAKE_CASE  :     Optional[Any]		    =       False
			SCREAMING_SNAKE_CASE  :     Dict		    =       False
			SCREAMING_SNAKE_CASE  :     Tuple		    =       False
			SCREAMING_SNAKE_CASE  :     Any		    =       False







			def        snake_case__(  self				:       Union[str, Any]							)   ->List[str]:
									snake_case_     =			PoolFormerModelTester(self							)
									snake_case_     =			PoolFormerConfigTester(self							,     config_class=_UpperCamelCase							)







			def        snake_case__(  self				:       Any							)   ->str:
									self.config_tester.run_common_tests()







			def        snake_case__(  self				:       List[str]							)   ->Dict:
									snake_case_     =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase							)







			@unittest.skip('''PoolFormer does not use inputs_embeds'''							)
			def        snake_case__(  self				:       Union[str, Any]							)   ->Optional[int]:
									pass







			@unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''							)
			def        snake_case__(  self				:       Tuple							)   ->Optional[Any]:
									pass







			def        snake_case__(  self				:       Dict							)   ->Optional[Any]:
									def check_hidden_states_output(_UpperCamelCase				:       Optional[int]							,     _UpperCamelCase				:       int							,     _UpperCamelCase				:       int							):
															snake_case_     =			model_class(_UpperCamelCase							)
															model.to(_UpperCamelCase							)
															model.eval()

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

															snake_case_     =			outputs.hidden_states

															snake_case_     =			self.model_tester.num_encoder_blocks
															self.assertEqual(len(_UpperCamelCase							)							,     _UpperCamelCase							)

															# 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_     =			self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															snake_case_     =			True
															check_hidden_states_output(_UpperCamelCase							,     _UpperCamelCase							,     _UpperCamelCase							)

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

															check_hidden_states_output(_UpperCamelCase							,     _UpperCamelCase							,     _UpperCamelCase							)







			def        snake_case__(  self				:       Tuple							)   ->Tuple:
									if not self.model_tester.is_training:
															return

									snake_case_,					snake_case_     =			self.model_tester.prepare_config_and_inputs_for_common()
									snake_case_     =			True

									for model_class in self.all_model_classes:
															if model_class in get_values(_UpperCamelCase							):
																					continue
															snake_case_     =			model_class(_UpperCamelCase							)
															model.to(_UpperCamelCase							)
															model.train()
															snake_case_     =			self._prepare_for_class(_UpperCamelCase							,     _UpperCamelCase							,     return_labels=_UpperCamelCase							)
															snake_case_     =			model(**_UpperCamelCase							).loss
															loss.backward()







			def        snake_case__(  self				:       List[Any]							)   ->Optional[Any]:
									snake_case_,					snake_case_     =			self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case_     =			['''pixel_values''']
															self.assertListEqual(arg_names[:1]							,     _UpperCamelCase							)







			@slow
			def        snake_case__(  self				:       Union[str, Any]							)   ->Optional[int]:
									for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_     =			PoolFormerModel.from_pretrained(_UpperCamelCase							)
															self.assertIsNotNone(_UpperCamelCase							)






def 						__SCREAMING_SNAKE_CASE      ():
						snake_case_     =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
						return image





@require_torch
class 			snake_case_     (	unittest.TestCase      ):







			'''simple docstring'''

			@slow
			def        snake_case__(  self				:       Optional[Any]							)   ->Dict:
									snake_case_     =			PoolFormerImageProcessor()
									snake_case_     =			PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''							).to(_UpperCamelCase							)

									snake_case_     =			image_processor(images=prepare_img()							,     return_tensors='''pt'''							).to(_UpperCamelCase							)

									# forward pass
									with torch.no_grad():
															snake_case_     =			model(**_UpperCamelCase							)

									# verify the logits
									snake_case_     =			torch.Size((1, 1_0_0_0)							)
									self.assertEqual(outputs.logits.shape							,     _UpperCamelCase							)

									snake_case_     =			torch.tensor([-0.6113, 0.1685, -0.0492]							).to(_UpperCamelCase							)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]							,     _UpperCamelCase							,     atol=1e-4							)							)


import warnings

from .generation import GenerationMixin





class 			snake_case_     (	__A      ):







			'''simple docstring'''

			warnings.warn(
			    "Importing `GenerationMixin` from `src/transformers/generation_utils.py` is deprecated and will "
			    "be removed in Transformers v5. Import as `from transformers import GenerationMixin` instead."			, __A			, )