
"""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    _snake_case  (						_lowercase       ):






							def 							__lowercase  (					self						:			Any    ):






												"""simple docstring"""



												__a:						Union[str, Any]		    =					self.config_class(**self.inputs_dict    )
												self.parent.assertTrue(hasattr(snake_case__						, """hidden_sizes"""    )    )
												self.parent.assertTrue(hasattr(snake_case__						, """num_encoder_blocks"""    )    )






class    _snake_case  :






							def __init__(					self						:			List[str]						, snake_case__						:			List[str]						, snake_case__						:			Any=1_3						, snake_case__						:			List[Any]=6_4						, snake_case__						:			int=3						, snake_case__						:			str=4						, snake_case__						:			List[str]=[2, 2, 2, 2]						, snake_case__						:			List[str]=[8, 4, 2, 1]						, snake_case__						:			Any=[1_6, 3_2, 6_4, 1_2_8]						, snake_case__						:			str=[1, 4, 8, 1_6]						, snake_case__						:			Union[str, Any]=False						, snake_case__						:			Any=True						, snake_case__						:			Tuple="gelu"						, snake_case__						:			Dict=0.1						, snake_case__						:			int=0.02						, snake_case__						:			Optional[int]=3						, snake_case__						:			Any=None						, ):






												"""simple docstring"""



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






							def 							__lowercase  (					self						:			Any    ):






												"""simple docstring"""



												__a:						Tuple		    =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

												__a:						int		    =					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 							__lowercase  (					self						:			int						, snake_case__						:			str						, snake_case__						:			Any						, snake_case__						:			Any    ):






												"""simple docstring"""



												__a:						Any		    =					PoolFormerModel(config=snake_case__    )
												model.to(snake_case__    )
												model.eval()
												__a:						Union[str, Any]		    =					model(snake_case__    )
												__a:						List[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 							__lowercase  (					self						:			Union[str, Any]    ):






												"""simple docstring"""



												__a:						Optional[int]		    =					self.prepare_config_and_inputs()
												__a    ,				__a    ,				__a:						Any		    =					config_and_inputs
												__a:						List[Any]		    =					{"""pixel_values""": pixel_values}
												return config, inputs_dict






@require_torch
class    _snake_case  (						_lowercase ,				_lowercase ,				unittest.TestCase       ):
							SCREAMING_SNAKE_CASE		     =						(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
							SCREAMING_SNAKE_CASE		     =						(
							    {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
							    if is_torch_available()
							    else {}
							)

							SCREAMING_SNAKE_CASE		     =						False
							SCREAMING_SNAKE_CASE		     =						False
							SCREAMING_SNAKE_CASE		     =						False
							SCREAMING_SNAKE_CASE		     =						False
							SCREAMING_SNAKE_CASE		     =						False






							def 							__lowercase  (					self						:			Union[str, Any]    ):






												"""simple docstring"""



												__a:						int		    =					PoolFormerModelTester(self    )
												__a:						Union[str, Any]		    =					PoolFormerConfigTester(self						, config_class=snake_case__    )






							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												self.config_tester.run_common_tests()






							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												__a:						List[str]		    =					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*snake_case__    )






							@unittest.skip("""PoolFormer does not use inputs_embeds"""    )
							def 							__lowercase  (					self						:			Any    ):






												"""simple docstring"""



												pass






							@unittest.skip("""PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"""    )
							def 							__lowercase  (					self						:			Optional[Any]    ):






												"""simple docstring"""



												pass






							def 							__lowercase  (					self						:			str    ):






												"""simple docstring"""



												def check_hidden_states_output(snake_case__						:			Any						, snake_case__						:			Tuple						, snake_case__						:			Dict    ):
																	__a:						str		    =					model_class(snake_case__    )
																	model.to(snake_case__    )
																	model.eval()

																	with torch.no_grad():
																						__a:						Any		    =					model(**self._prepare_for_class(snake_case__						, snake_case__    )    )

																	__a:						str		    =					outputs.hidden_states

																	__a:						Optional[Any]		    =					self.model_tester.num_encoder_blocks
																	self.assertEqual(len(snake_case__    )						, 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,
																	    ]						, )

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

												for model_class in self.all_model_classes:
																	__a:						List[Any]		    =					True
																	check_hidden_states_output(snake_case__						, snake_case__						, snake_case__    )

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

																	check_hidden_states_output(snake_case__						, snake_case__						, snake_case__    )






							def 							__lowercase  (					self						:			Tuple    ):






												"""simple docstring"""



												if not self.model_tester.is_training:
																	return

												__a    ,				__a:						Tuple		    =					self.model_tester.prepare_config_and_inputs_for_common()
												__a:						Optional[Any]		    =					True

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






							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												__a    ,				__a:						Tuple		    =					self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	__a:						List[str]		    =					model_class(snake_case__    )
																	__a:						List[Any]		    =					inspect.signature(model.forward    )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	__a:						Tuple		    =					[*signature.parameters.keys()]

																	__a:						Dict		    =					["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]						, snake_case__    )






							@slow
							def 							__lowercase  (					self						:			Tuple    ):






												"""simple docstring"""



												for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	__a:						int		    =					PoolFormerModel.from_pretrained(snake_case__    )
																	self.assertIsNotNone(snake_case__    )






def     lowerCamelCase_    (	)     ->			Tuple:


					'''simple docstring'''
					__a:						Tuple		    =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
					return image




@require_torch
class    _snake_case  (						unittest.TestCase       ):






							@slow
							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												__a:						str		    =					PoolFormerImageProcessor()
												__a:						Dict		    =					PoolFormerForImageClassification.from_pretrained("""sail/poolformer_s12"""    ).to(snake_case__    )

												__a:						Any		    =					image_processor(images=prepare_img()						, return_tensors="""pt"""    ).to(snake_case__    )

												# forward pass
												with torch.no_grad():
																	__a:						List[Any]		    =					model(**snake_case__    )

												# verify the logits
												__a:						Tuple		    =					torch.Size((1, 1_0_0_0)    )
												self.assertEqual(outputs.logits.shape						, snake_case__    )

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


"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase		:						int =					logging.get_logger(__name__)

lowercase		:						Any =					{
    'facebook/regnet-y-040': 'https://huggingface.co/facebook/regnet-y-040/blob/main/config.json',
}




class    _snake_case  (						_lowercase       ):
							SCREAMING_SNAKE_CASE		     =						'''regnet'''
							SCREAMING_SNAKE_CASE		     =						['''x''', '''y''']






							def __init__(					self						:			Union[str, Any]						, snake_case__						:			Any=3						, snake_case__						:			str=3_2						, snake_case__						:			Tuple=[1_2_8, 1_9_2, 5_1_2, 1_0_8_8]						, snake_case__						:			Union[str, Any]=[2, 6, 1_2, 2]						, snake_case__						:			str=6_4						, snake_case__						:			Optional[int]="y"						, snake_case__						:			Tuple="relu"						, **snake_case__						:			str						, ):






												"""simple docstring"""



												super().__init__(**snake_case__    )
												if layer_type not in self.layer_types:
																	raise ValueError(f"""layer_type={layer_type} is not one of {','.join(self.layer_types    )}"""    )
												__a:						Any		    =					num_channels
												__a:						List[Any]		    =					embedding_size
												__a:						Optional[int]		    =					hidden_sizes
												__a:						Optional[int]		    =					depths
												__a:						Optional[Any]		    =					groups_width
												__a:						Tuple		    =					layer_type
												__a:						str		    =					hidden_act
												# always downsample in the first stage
												__a:						List[str]		    =					True
