




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__							(_UpperCamelCase       ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(				self    :					int							) ->					List[Any]:
							a   =      self.config_class(**self.inputs_dict							)
							self.parent.assertTrue(hasattr(__lowerCamelCase ,				"hidden_sizes"							)							)
							self.parent.assertTrue(hasattr(__lowerCamelCase ,				"num_encoder_blocks"							)							)




class    snake_case__							:
				"""simple docstring"""



				def __init__(				self    :					Union[str, Any] ,				__lowerCamelCase    :					Tuple ,				__lowerCamelCase    :					Tuple=13 ,				__lowerCamelCase    :					str=64 ,				__lowerCamelCase    :					Optional[Any]=3 ,				__lowerCamelCase    :					int=4 ,				__lowerCamelCase    :					str=[2, 2, 2, 2] ,				__lowerCamelCase    :					Union[str, Any]=[8, 4, 2, 1] ,				__lowerCamelCase    :					Dict=[16, 32, 64, 1_28] ,				__lowerCamelCase    :					List[Any]=[1, 4, 8, 16] ,				__lowerCamelCase    :					Any=False ,				__lowerCamelCase    :					Optional[Any]=True ,				__lowerCamelCase    :					str="gelu" ,				__lowerCamelCase    :					str=0.1 ,				__lowerCamelCase    :					Optional[Any]=0.02 ,				__lowerCamelCase    :					Optional[int]=3 ,				__lowerCamelCase    :					List[str]=None ,				) ->					Tuple:
							a   =      parent
							a   =      batch_size
							a   =      image_size
							a   =      num_channels
							a   =      num_encoder_blocks
							a   =      sr_ratios
							a   =      depths
							a   =      hidden_sizes
							a   =      downsampling_rates
							a   =      is_training
							a   =      use_labels
							a   =      hidden_act
							a   =      hidden_dropout_prob
							a   =      initializer_range
							a   =      num_labels
							a   =      scope





				def 							__UpperCAmelCase							(				self    :					Optional[int]							) ->					Tuple:
							a   =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

							a   =      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 							__UpperCAmelCase							(				self    :					Optional[Any] ,				__lowerCamelCase    :					List[Any] ,				__lowerCamelCase    :					Dict ,				__lowerCamelCase    :					int							) ->					Any:
							a   =      PoolFormerModel(config=__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a   =      model(__lowerCamelCase							)
							a   =      a   =      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 							__UpperCAmelCase							(				self    :					List[str]							) ->					Optional[Any]:
							a   =      self.prepare_config_and_inputs()
							a   ,		a   ,		a   =      config_and_inputs
							a   =      {"pixel_values": pixel_values}
							return config, inputs_dict




@require_torch
class    snake_case__							(_UpperCamelCase   ,	_UpperCamelCase   ,	unittest.TestCase       ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_	:							List[str]										= (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_	:							str										= False
				SCREAMING_SNAKE_CASE_	:							Any										= False
				SCREAMING_SNAKE_CASE_	:							List[Any]										= False
				SCREAMING_SNAKE_CASE_	:							List[Any]										= False
				SCREAMING_SNAKE_CASE_	:							List[str]										= False





				def 							__UpperCAmelCase							(				self    :					Dict							) ->					int:
							a   =      PoolFormerModelTester(self							)
							a   =      PoolFormerConfigTester(self ,				config_class=__lowerCamelCase							)





				def 							__UpperCAmelCase							(				self    :					List[str]							) ->					Optional[int]:
							self.config_tester.run_common_tests()





				def 							__UpperCAmelCase							(				self    :					Optional[Any]							) ->					Optional[int]:
							a   =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowerCamelCase							)





				@unittest.skip("PoolFormer does not use inputs_embeds"							)
				def 							__UpperCAmelCase							(				self    :					Dict							) ->					Union[str, Any]:
							pass





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





				def 							__UpperCAmelCase							(				self    :					Any							) ->					Tuple:
							def check_hidden_states_output(__lowerCamelCase    :					Optional[int] ,				__lowerCamelCase    :					int ,				__lowerCamelCase    :					List[str]							):
										a   =      model_class(__lowerCamelCase							)
										model.to(__lowerCamelCase							)
										model.eval()

										with torch.no_grad():
													a   =      model(**self._prepare_for_class(__lowerCamelCase ,				__lowerCamelCase							)							)

										a   =      outputs.hidden_states

										a   =      self.model_tester.num_encoder_blocks
										self.assertEqual(len(__lowerCamelCase							) ,				__lowerCamelCase							)

										# 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,
										    ] ,				)

							a   ,		a   =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a   =      True
										check_hidden_states_output(__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase							)

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

										check_hidden_states_output(__lowerCamelCase ,				__lowerCamelCase ,				__lowerCamelCase							)





				def 							__UpperCAmelCase							(				self    :					Optional[Any]							) ->					int:
							if not self.model_tester.is_training:
										return

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

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





				def 							__UpperCAmelCase							(				self    :					Dict							) ->					Dict:
							a   ,		a   =      self.model_tester.prepare_config_and_inputs_for_common()

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

										a   =      ["pixel_values"]
										self.assertListEqual(arg_names[:1] ,				__lowerCamelCase							)





				@slow
				def 							__UpperCAmelCase							(				self    :					List[str]							) ->					Union[str, Any]:
							for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a   =      PoolFormerModel.from_pretrained(__lowerCamelCase							)
										self.assertIsNotNone(__lowerCamelCase							)




def       __magic_name__    (			):






			'''simple docstring'''







			a   =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
			return image






@require_torch
class    snake_case__							(unittest.TestCase       ):
				"""simple docstring"""



				@slow
				def 							__UpperCAmelCase							(				self    :					Optional[int]							) ->					int:
							a   =      PoolFormerImageProcessor()
							a   =      PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"							).to(__lowerCamelCase							)

							a   =      image_processor(images=prepare_img() ,				return_tensors="pt"							).to(__lowerCamelCase							)

							# forward pass
							with torch.no_grad():
										a   =      model(**__lowerCamelCase							)

							# verify the logits
							a   =      torch.Size((1, 10_00)							)
							self.assertEqual(outputs.logits.shape ,				__lowerCamelCase							)

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












import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin




class    snake_case__							(_UpperCamelCase       ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_	:							List[Any]										= ["""image_processor""", """tokenizer"""]
				SCREAMING_SNAKE_CASE_	:							List[Any]										= """AutoImageProcessor"""
				SCREAMING_SNAKE_CASE_	:							Dict										= """AutoTokenizer"""





				def __init__(				self    :					int ,				__lowerCamelCase    :					Dict=None ,				__lowerCamelCase    :					int=None ,				**__lowerCamelCase    :					Optional[Any]							) ->					str:
							a   =      None
							if "feature_extractor" in kwargs:
										warnings.warn(
										    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
										    " instead." ,				__lowerCamelCase ,				)
										a   =      kwargs.pop("feature_extractor"							)

							a   =      image_processor if image_processor is not None else feature_extractor
							if image_processor is None:
										raise ValueError("You need to specify an `image_processor`."							)
							if tokenizer is None:
										raise ValueError("You need to specify a `tokenizer`."							)

							super().__init__(__lowerCamelCase ,				__lowerCamelCase							)
							a   =      self.image_processor
							a   =      False





				def __call__(				self    :					Any ,				*__lowerCamelCase    :					int ,				**__lowerCamelCase    :					Optional[int]							) ->					int:
							# For backward compatibility
							if self._in_target_context_manager:
										return self.current_processor(*__lowerCamelCase ,				**__lowerCamelCase							)

							a   =      kwargs.pop("images" ,				__lowerCamelCase							)
							a   =      kwargs.pop("text" ,				__lowerCamelCase							)
							if len(__lowerCamelCase							) > 0:
										a   =      args[0]
										a   =      args[1:]

							if images is None and text is None:
										raise ValueError("You need to specify either an `images` or `text` input to process."							)

							if images is not None:
										a   =      self.image_processor(__lowerCamelCase ,				*__lowerCamelCase ,				**__lowerCamelCase							)
							if text is not None:
										a   =      self.tokenizer(__lowerCamelCase ,				**__lowerCamelCase							)

							if text is None:
										return inputs
							elif images is None:
										return encodings
							else:
										a   =      encodings["input_ids"]
										return inputs





				def 							__UpperCAmelCase							(				self    :					Union[str, Any] ,				*__lowerCamelCase    :					str ,				**__lowerCamelCase    :					str							) ->					Optional[Any]:
							return self.tokenizer.batch_decode(*__lowerCamelCase ,				**__lowerCamelCase							)





				def 							__UpperCAmelCase							(				self    :					Optional[Any] ,				*__lowerCamelCase    :					Union[str, Any] ,				**__lowerCamelCase    :					Any							) ->					str:
							return self.tokenizer.decode(*__lowerCamelCase ,				**__lowerCamelCase							)





				@contextmanager
				def 							__UpperCAmelCase							(				self    :					Any							) ->					Optional[int]:
							warnings.warn(
							    "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
							    "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
							    "your images inputs, or in a separate call."							)
							a   =      True
							a   =      self.tokenizer
							yield
							a   =      self.image_processor
							a   =      False





				@property
				def 							__UpperCAmelCase							(				self    :					Dict							) ->					Optional[Any]:
							warnings.warn(
							    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." ,				__lowerCamelCase ,				)
							return self.image_processor_class





				@property
				def 							__UpperCAmelCase							(				self    :					int							) ->					Union[str, Any]:
							warnings.warn(
							    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." ,				__lowerCamelCase ,				)
							return self.image_processor






