





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      UpperCamelCase_				(   UpperCamelCase__			):


							def    _snake_case     (							self			:str						)      ->      Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.config_class(**self.inputs_dict						)
									self.parent.assertTrue(hasattr(__A							, """hidden_sizes"""						)						)
									self.parent.assertTrue(hasattr(__A							, """num_encoder_blocks"""						)						)




class      UpperCamelCase_				:


							def __init__(							self			:str							, __A			:Tuple							, __A			:Union[str, Any]=13							, __A			:Optional[Any]=64							, __A			:Any=3							, __A			:List[str]=4							, __A			:Any=[2, 2, 2, 2]							, __A			:Union[str, Any]=[8, 4, 2, 1]							, __A			:List[str]=[16, 32, 64, 128]							, __A			:Dict=[1, 4, 8, 16]							, __A			:Union[str, Any]=False							, __A			:List[Any]=True							, __A			:Tuple="gelu"							, __A			:Optional[int]=0.1							, __A			:Union[str, Any]=0.0_2							, __A			:List[Any]=3							, __A			:List[Any]=None							, )      ->      Optional[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					parent
									SCREAMING_SNAKE_CASE__								=					batch_size
									SCREAMING_SNAKE_CASE__								=					image_size
									SCREAMING_SNAKE_CASE__								=					num_channels
									SCREAMING_SNAKE_CASE__								=					num_encoder_blocks
									SCREAMING_SNAKE_CASE__								=					sr_ratios
									SCREAMING_SNAKE_CASE__								=					depths
									SCREAMING_SNAKE_CASE__								=					hidden_sizes
									SCREAMING_SNAKE_CASE__								=					downsampling_rates
									SCREAMING_SNAKE_CASE__								=					is_training
									SCREAMING_SNAKE_CASE__								=					use_labels
									SCREAMING_SNAKE_CASE__								=					hidden_act
									SCREAMING_SNAKE_CASE__								=					hidden_dropout_prob
									SCREAMING_SNAKE_CASE__								=					initializer_range
									SCREAMING_SNAKE_CASE__								=					num_labels
									SCREAMING_SNAKE_CASE__								=					scope


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

									SCREAMING_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			:Optional[Any]							, __A			:Optional[Any]							, __A			:str							, __A			:Union[str, Any]						)      ->      int:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					PoolFormerModel(config=__A						)
									model.to(__A						)
									model.eval()
									SCREAMING_SNAKE_CASE__								=					model(__A						)
									SCREAMING_SNAKE_CASE__								=					SCREAMING_SNAKE_CASE__								=					self.image_size // 3_2.0
									self.parent.assertEqual(
									    result.last_hidden_state.shape							, (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)						)


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					config_and_inputs
									SCREAMING_SNAKE_CASE__								=					{"""pixel_values""": pixel_values}
									return config, inputs_dict




@require_torch
class      UpperCamelCase_				(   UpperCamelCase__ ,     UpperCamelCase__ ,     unittest.TestCase			):
							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    _snake_case     (							self			:Optional[int]						)      ->      Optional[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					PoolFormerModelTester(self						)
									SCREAMING_SNAKE_CASE__								=					PoolFormerConfigTester(self							, config_class=__A						)


							def    _snake_case     (							self			:Optional[int]						)      ->      Optional[Any]:



									"""simple docstring"""



									self.config_tester.run_common_tests()


							def    _snake_case     (							self			:Dict						)      ->      str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__A						)


							@unittest.skip("""PoolFormer does not use inputs_embeds"""						)
							def    _snake_case     (							self			:Dict						)      ->      List[Any]:



									"""simple docstring"""



									pass


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



									"""simple docstring"""



									pass


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



									"""simple docstring"""



									def check_hidden_states_output(__A			:Optional[Any]							, __A			:List[Any]							, __A			:Any						):
											SCREAMING_SNAKE_CASE__								=					model_class(__A						)
											model.to(__A						)
											model.eval()

											with torch.no_grad():
													SCREAMING_SNAKE_CASE__								=					model(**self._prepare_for_class(__A							, __A						)						)

											SCREAMING_SNAKE_CASE__								=					outputs.hidden_states

											SCREAMING_SNAKE_CASE__								=					self.model_tester.num_encoder_blocks
											self.assertEqual(len(__A						)							, __A						)

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

									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__								=					True
											check_hidden_states_output(__A							, __A							, __A						)

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

											check_hidden_states_output(__A							, __A							, __A						)


							def    _snake_case     (							self			:Optional[int]						)      ->      Tuple:



									"""simple docstring"""



									if not self.model_tester.is_training:
											return

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

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


							def    _snake_case     (							self			:Tuple						)      ->      str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.model_tester.prepare_config_and_inputs_for_common()

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

											SCREAMING_SNAKE_CASE__								=					["""pixel_values"""]
											self.assertListEqual(arg_names[:1]							, __A						)


							@slow
							def    _snake_case     (							self			:Tuple						)      ->      List[str]:



									"""simple docstring"""



									for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											SCREAMING_SNAKE_CASE__								=					PoolFormerModel.from_pretrained(__A						)
											self.assertIsNotNone(__A						)






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




@require_torch
class      UpperCamelCase_				(   unittest.TestCase			):


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					PoolFormerImageProcessor()
									SCREAMING_SNAKE_CASE__								=					PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""						).to(__A						)

									SCREAMING_SNAKE_CASE__								=					image_processor(images=prepare_img()							, return_tensors="""pt"""						).to(__A						)

									# forward pass
									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=					model(**__A						)

									# verify the logits
									SCREAMING_SNAKE_CASE__								=					torch.Size((1, 1000)						)
									self.assertEqual(outputs.logits.shape							, __A						)

									SCREAMING_SNAKE_CASE__								=					torch.tensor([-0.6_1_1_3, 0.1_6_8_5, -0.0_4_9_2]						).to(__A						)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]							, __A							, atol=1E-4						)						)






def  SCREAMING_SNAKE_CASE__							(				UpperCamelCase__:							str			):
		SCREAMING_SNAKE_CASE__								=					SCREAMING_SNAKE_CASE__								=					0
		for letter in data:
				SCREAMING_SNAKE_CASE__								=					(hash_ << 4) + ord(UpperCamelCase__			)
				SCREAMING_SNAKE_CASE__								=					hash_ & 0XF_0_0_0_0_0_0_0
				if x != 0:
						hash_ ^= x >> 24
				hash_ &= ~x
		return hash_


if __name__ == "__main__":
	import doctest

	doctest.testmod()