




"""simple docstring"""





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


				'''simple docstring'''


				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										snake_case__    :   Union[str, Any]							     =   self.config_class(**self.inputs_dict )
										self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ ,'''hidden_sizes''' ) )
										self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ ,'''num_encoder_blocks''' ) )







class  __lowercase    :


				'''simple docstring'''


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

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







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


				'''simple docstring'''


				_lowerCAmelCase		     =(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
				_lowerCAmelCase		     =(
				    {"feature-extraction": PoolFormerModel, "image-classification": PoolFormerForImageClassification}
				    if is_torch_available()
				    else {}
				)

				_lowerCAmelCase		     =False
				_lowerCAmelCase		     =False
				_lowerCAmelCase		     =False
				_lowerCAmelCase		     =False
				_lowerCAmelCase		     =False

				def  _lowerCamelCase   (				self				:       Dict ):
										snake_case__    :   List[Any]							     =   PoolFormerModelTester(self )
										snake_case__    :   Optional[Any]							     =   PoolFormerConfigTester(self ,config_class=SCREAMING_SNAKE_CASE_ )

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										self.config_tester.run_common_tests()

				def  _lowerCamelCase   (				self				:       Any ):
										snake_case__    :   Union[str, Any]							     =   self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )

				@unittest.skip('''PoolFormer does not use inputs_embeds''' )
				def  _lowerCamelCase   (				self				:       int ):
										pass

				@unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods''' )
				def  _lowerCamelCase   (				self				:       Dict ):
										pass

				def  _lowerCamelCase   (				self				:       Dict ):
										def check_hidden_states_output(SCREAMING_SNAKE_CASE_				:       str ,SCREAMING_SNAKE_CASE_				:       Any ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
																snake_case__    :   Dict							     =   model_class(SCREAMING_SNAKE_CASE_ )
																model.to(SCREAMING_SNAKE_CASE_ )
																model.eval()

																with torch.no_grad():
																						snake_case__    :   Optional[Any]							     =   model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) )

																snake_case__    :   Dict							     =   outputs.hidden_states

																snake_case__    :   Dict							     =   self.model_tester.num_encoder_blocks
																self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,SCREAMING_SNAKE_CASE_ )

																# 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__    :   Optional[int]							     =   self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																snake_case__    :   Union[str, Any]							     =   True
																check_hidden_states_output(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																snake_case__    :   Union[str, Any]							     =   True

																check_hidden_states_output(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )

				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										if not self.model_tester.is_training:
																return

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

										for model_class in self.all_model_classes:
																if model_class in get_values(SCREAMING_SNAKE_CASE_ ):
																						continue
																snake_case__    :   Any							     =   model_class(SCREAMING_SNAKE_CASE_ )
																model.to(SCREAMING_SNAKE_CASE_ )
																model.train()
																snake_case__    :   Optional[int]							     =   self._prepare_for_class(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,return_labels=SCREAMING_SNAKE_CASE_ )
																snake_case__    :   int							     =   model(**SCREAMING_SNAKE_CASE_ ).loss
																loss.backward()

				def  _lowerCamelCase   (				self				:       Any ):
										snake_case__     ,		snake_case__    :   int							     =   self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																snake_case__    :   Tuple							     =   model_class(SCREAMING_SNAKE_CASE_ )
																snake_case__    :   List[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] ,SCREAMING_SNAKE_CASE_ )





				@slow
				def  _lowerCamelCase   (				self				:       Dict ):
										for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																snake_case__    :   Optional[Any]							     =   PoolFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
																self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )







def 						lowerCAmelCase							(	):
						'''simple docstring'''


						snake_case__    :   int							     =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
						return image

@require_torch
class  __lowercase    (     unittest.TestCase		):


				'''simple docstring'''


				@slow
				def  _lowerCamelCase   (				self				:       Any ):
										snake_case__    :   Optional[Any]							     =   PoolFormerImageProcessor()
										snake_case__    :   int							     =   PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12''' ).to(SCREAMING_SNAKE_CASE_ )

										snake_case__    :   int							     =   image_processor(images=prepare_img() ,return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ )

										# forward pass
										with torch.no_grad():
																snake_case__    :   Optional[int]							     =   model(**SCREAMING_SNAKE_CASE_ )

										# verify the logits
										snake_case__    :   Optional[int]							     =   torch.Size((1, 1_0_0_0) )
										self.assertEqual(outputs.logits.shape ,SCREAMING_SNAKE_CASE_ )

										snake_case__    :   List[str]							     =   torch.tensor([-0.6113, 0.1685, -0.0492] ).to(SCREAMING_SNAKE_CASE_ )
										self.assertTrue(torch.allclose(outputs.logits[0, :3] ,SCREAMING_SNAKE_CASE_ ,atol=1E-4 ) )








"""simple docstring"""





class  __lowercase    :


				'''simple docstring'''


				class  __lowercase    :


								'''simple docstring'''


								_lowerCAmelCase		     ="_prev", "_data", "_next"

								def __init__(				self				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       int ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ,SCREAMING_SNAKE_CASE_				:       Any ):
														snake_case__    :   Any							     =   link_p
														snake_case__    :   List[str]							     =   element
														snake_case__    :   str							     =   link_n





								def  _lowerCamelCase   (				self				:       Optional[Any] ):
														return (
														    F''' Prev -> {self._prev is not None}, Next -> {self._next is not None}'''
														)







				def __init__(				self				:       Any ):
										snake_case__    :   int							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Optional[int]							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Union[str, Any]							     =   self._trailer
										snake_case__    :   Union[str, Any]							     =   self._header
										snake_case__    :   Any							     =   0

				def __len__(				self				:       str ):
										return self._size

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										return self.__len__() == 0

				def  _lowerCamelCase   (				self				:       Any ,SCREAMING_SNAKE_CASE_				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       List[str] ,SCREAMING_SNAKE_CASE_				:       Dict ):
										# Create new_node by setting it's prev.link -> header
										# setting it's next.link -> trailer
										snake_case__    :   Dict							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Any							     =   new_node
										snake_case__    :   str							     =   new_node
										self._size += 1
										return self





				def  _lowerCamelCase   (				self				:       Union[str, Any] ,SCREAMING_SNAKE_CASE_				:       Dict ):
										snake_case__    :   Union[str, Any]							     =   node._prev
										snake_case__    :   Union[str, Any]							     =   node._next

										snake_case__    :   List[Any]							     =   successor
										snake_case__    :   Dict							     =   predecessor
										self._size -= 1
										snake_case__    :   Dict							     =   node._data
										snake_case__    :   List[str]							     =   None
										del node
										return temp







class  __lowercase    (     _DoublyLinkedBase		):


				'''simple docstring'''


				def  _lowerCamelCase   (				self				:       Optional[int] ):
										if self.is_empty():
																raise Exception('''List is empty''' )
										return self._header._next._data

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										if self.is_empty():
																raise Exception('''List is empty''' )
										return self._trailer._prev._data

				def  _lowerCamelCase   (				self				:       Any ,SCREAMING_SNAKE_CASE_				:       Dict ):
										return self._insert(self._header ,SCREAMING_SNAKE_CASE_ ,self._header._next )

				def  _lowerCamelCase   (				self				:       Dict ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										return self._insert(self._trailer._prev ,SCREAMING_SNAKE_CASE_ ,self._trailer )

				def  _lowerCamelCase   (				self				:       Optional[int] ):
										if self.is_empty():
																raise IndexError('''remove_first from empty list''' )
										return self._delete(self._header._next )





				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										if self.is_empty():
																raise IndexError('''remove_first from empty list''' )
										return self._delete(self._trailer._prev )


