
import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 torch import nn

					from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
					from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor

class     _SCREAMING_SNAKE_CASE							:





				def __init__(		self :		Any					,      snake_case_ :		Dict					,      snake_case_ :		str=3					,      snake_case_ :		Tuple=32					,      snake_case_ :		Optional[Any]=3					,      snake_case_ :		Union[str, Any]=10					,      snake_case_ :		Any=[10, 20, 30, 40]					,      snake_case_ :		Any=[1, 1, 2, 1]					,      snake_case_ :		Dict=True					,      snake_case_ :		Union[str, Any]=True					,      snake_case_ :		List[str]="relu"					,      snake_case_ :		Optional[Any]=3					,      snake_case_ :		Tuple=None					,      snake_case_ :		Any=["stage2", "stage3", "stage4"]					,      snake_case_ :		List[str]=[2, 3, 4]					,      ):


								"""simple docstring"""

								A     :  Optional[int]   =				parent
								A     :  Optional[int]   =				batch_size
								A     :  str   =				image_size
								A     :  Optional[Any]   =				num_channels
								A     :  Union[str, Any]   =				embeddings_size
								A     :  Optional[Any]   =				hidden_sizes
								A     :  int   =				depths
								A     :  int   =				is_training
								A     :  Any   =				use_labels
								A     :  Optional[int]   =				hidden_act
								A     :  str   =				num_labels
								A     :  int   =				scope
								A     :  List[str]   =				len(snake_case_							)
								A     :  Dict   =				out_features
								A     :  List[Any]   =				out_indices





				def        _UpperCAmelCase						(		self :		Any							):


								"""simple docstring"""

								A     :  Any   =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

								A     :  Optional[Any]   =				None
								if self.use_labels:
												A     :  Optional[int]   =				ids_tensor([self.batch_size]					,      self.num_labels							)

								A     :  Tuple   =				self.get_config()

								return config, pixel_values, labels





				def        _UpperCAmelCase						(		self :		str							):


								"""simple docstring"""

								return ResNetConfig(
								    num_channels=self.num_channels					,      embeddings_size=self.embeddings_size					,      hidden_sizes=self.hidden_sizes					,      depths=self.depths					,      hidden_act=self.hidden_act					,      num_labels=self.num_labels					,      out_features=self.out_features					,      out_indices=self.out_indices					,      )





				def        _UpperCAmelCase						(		self :		List[Any]					,      snake_case_ :		List[Any]					,      snake_case_ :		Any					,      snake_case_ :		int							):


								"""simple docstring"""

								A     :  Dict   =				ResNetModel(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  int   =				model(snake_case_							)
								# expected last hidden states: B, C, H // 32, W // 32
								self.parent.assertEqual(
								    result.last_hidden_state.shape					,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)					,      )





				def        _UpperCAmelCase						(		self :		Dict					,      snake_case_ :		List[Any]					,      snake_case_ :		Optional[int]					,      snake_case_ :		Any							):


								"""simple docstring"""

								A     :  Tuple   =				self.num_labels
								A     :  Dict   =				ResNetForImageClassification(snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Any   =				model(snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)							)





				def        _UpperCAmelCase						(		self :		Dict					,      snake_case_ :		Tuple					,      snake_case_ :		str					,      snake_case_ :		Optional[int]							):


								"""simple docstring"""

								A     :  str   =				ResNetBackbone(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  str   =				model(snake_case_							)

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps							)					,      len(config.out_features							)							)
								self.parent.assertListEqual(list(result.feature_maps[0].shape							)					,      [self.batch_size, self.hidden_sizes[1], 4, 4]							)

								# verify channels
								self.parent.assertEqual(len(model.channels							)					,      len(config.out_features							)							)
								self.parent.assertListEqual(model.channels					,      config.hidden_sizes[1:]							)

								# verify backbone works with out_features=None
								A     :  List[Any]   =				None
								A     :  List[Any]   =				ResNetBackbone(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Union[str, Any]   =				model(snake_case_							)

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps							)					,      1							)
								self.parent.assertListEqual(list(result.feature_maps[0].shape							)					,      [self.batch_size, self.hidden_sizes[-1], 1, 1]							)

								# verify channels
								self.parent.assertEqual(len(model.channels							)					,      1							)
								self.parent.assertListEqual(model.channels					,      [config.hidden_sizes[-1]]							)






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


								"""simple docstring"""

								A     :  str   =				self.prepare_config_and_inputs()
								A ,       A ,       A     :  int   =				config_and_inputs
								A     :  List[Any]   =				{'''pixel_values''': pixel_values}
								return config, inputs_dict



@require_torch
class     _SCREAMING_SNAKE_CASE							(		snake_case,    snake_case,    unittest.TestCase							):
				lowerCamelCase_       =     (
				    (
				        ResNetModel,
				        ResNetForImageClassification,
				        ResNetBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				lowerCamelCase_       =     (
				    {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
				    if is_torch_available()
				    else {}
				)

				lowerCamelCase_       =     True
				lowerCamelCase_       =     False
				lowerCamelCase_       =     False
				lowerCamelCase_       =     False
				lowerCamelCase_       =     False





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


								"""simple docstring"""

								A     :  Dict   =				ResNetModelTester(self							)
								A     :  str   =				ConfigTester(self					,      config_class=snake_case_					,      has_text_modality=snake_case_							)





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


								"""simple docstring"""

								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()





				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								return





				@unittest.skip(reason='''ResNet does not use inputs_embeds'''							)
				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								pass





				@unittest.skip(reason='''ResNet does not support input and output embeddings'''							)
				def        _UpperCAmelCase						(		self :		Union[str, Any]							):


								"""simple docstring"""

								pass





				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

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

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

												A     :  Optional[int]   =				['''pixel_values''']
												self.assertListEqual(arg_names[:1]					,      snake_case_							)





				def        _UpperCAmelCase						(		self :		List[str]							):


								"""simple docstring"""

								A     :  Tuple   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case_							)





				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								A     :  Tuple   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*snake_case_							)





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


								"""simple docstring"""

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

								for model_class in self.all_model_classes:
												A     :  Optional[int]   =				model_class(config=snake_case_							)
												for name, module in model.named_modules():
																if isinstance(snake_case_					,      (nn.BatchNormad, nn.GroupNorm)							):
																				self.assertTrue(
																				    torch.all(module.weight == 1							)					,      msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""					,      )
																				self.assertTrue(
																				    torch.all(module.bias == 0							)					,      msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""					,      )





				def        _UpperCAmelCase						(		self :		Dict							):


								"""simple docstring"""

								def check_hidden_states_output(snake_case_ :		Union[str, Any]					,      snake_case_ :		Dict					,      snake_case_ :		Optional[Any]							):
												A     :  Optional[Any]   =				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     :  Dict   =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												A     :  Union[str, Any]   =				self.model_tester.num_stages
												self.assertEqual(len(snake_case_							)					,      expected_num_stages + 1							)

												# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
												self.assertListEqual(
												    list(hidden_states[0].shape[-2:]							)					,      [self.model_tester.image_size // 4, self.model_tester.image_size // 4]					,      )

								A ,       A     :  int   =				self.model_tester.prepare_config_and_inputs_for_common()
								A     :  str   =				['''basic''', '''bottleneck''']
								for model_class in self.all_model_classes:
												for layer_type in layers_type:
																A     :  int   =				layer_type
																A     :  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     :  List[str]   =				True

																check_hidden_states_output(snake_case_					,      snake_case_					,      snake_case_							)





				@unittest.skip(reason='''ResNet does not use feedforward chunking'''							)
				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

								pass





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								A     :  Tuple   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*snake_case_							)






				@slow
				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

								for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A     :  Dict   =				ResNetModel.from_pretrained(snake_case_							)
												self.assertIsNotNone(snake_case_							)





def 							_lowerCamelCase			(					):



				'''simple docstring'''







				A     :  List[Any]   =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
				return image

@require_torch
@require_vision
class     _SCREAMING_SNAKE_CASE							(		unittest.TestCase							):





				@cached_property
				def        _UpperCAmelCase						(		self :		Any							):


								"""simple docstring"""

								return (
								    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
								    if is_vision_available()
								    else None
								)






				@slow
				def        _UpperCAmelCase						(		self :		str							):


								"""simple docstring"""

								A     :  Optional[Any]   =				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(snake_case_							)

								A     :  Optional[int]   =				self.default_image_processor
								A     :  Optional[Any]   =				prepare_img()
								A     :  Dict   =				image_processor(images=snake_case_					,      return_tensors='''pt'''							).to(snake_case_							)

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

								# verify the logits
								A     :  int   =				torch.Size((1, 1000)							)
								self.assertEqual(outputs.logits.shape					,      snake_case_							)

								A     :  List[str]   =				torch.tensor([-11.10_69, -9.78_77, -8.37_77]							).to(snake_case_							)

								self.assertTrue(torch.allclose(outputs.logits[0, :3]					,      snake_case_					,      atol=1E-4							)							)



@require_torch
class     _SCREAMING_SNAKE_CASE							(		snake_case,    unittest.TestCase							):
				lowerCamelCase_       =     (ResNetBackbone,) if is_torch_available() else ()
				lowerCamelCase_       =     False
				lowerCamelCase_       =     ResNetConfig





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								A     :  str   =				ResNetModelTester(self							)

UpperCamelCase_  =	{
    "0": 1,
    "1": 1,
    "2": 2,
    "3": 6,
    "4": 24,
    "5": 1_20,
    "6": 7_20,
    "7": 50_40,
    "8": 4_03_20,
    "9": 36_28_80,
}

UpperCamelCase_  =	{1_45: 1_45}

UpperCamelCase_  =	{
    1_45: 0,
    1_69: 3,
    3_63_01: 3,
    14_54: 3,
    8_71: 2,
    4_53_61: 2,
    8_72: 2,
}





def 							_lowerCamelCase			(					lowerCamelCase_:  int		):



				'''simple docstring'''







				if n in CACHE_SUM_DIGIT_FACTORIALS:
								return CACHE_SUM_DIGIT_FACTORIALS[n]
				A     :  Tuple   =				sum(DIGIT_FACTORIALS[let] for let in str(lowerCamelCase_		)		)
				A     :  Dict   =				ret
				return ret





def 							_lowerCamelCase			(					lowerCamelCase_:  int				,	lowerCamelCase_:  set | None = None		):



				'''simple docstring'''







				A     :  Optional[int]   =				previous or set()
				if n in CHAIN_LENGTH_CACHE:
								return CHAIN_LENGTH_CACHE[n]
				A     :  Dict   =				sum_digit_factorials(lowerCamelCase_		)
				if next_number in previous:
								A     :  Optional[int]   =				0
								return 0
				else:
								previous.add(lowerCamelCase_		)
								A     :  str   =				1 + chain_length(lowerCamelCase_				,	lowerCamelCase_		)
								A     :  Any   =				ret
								return ret





def 							_lowerCamelCase			(					lowerCamelCase_:  int = 60				,	lowerCamelCase_:  int = 100_0000		):



				'''simple docstring'''







				return sum(1 for i in range(1				,	lowerCamelCase_		) if chain_length(lowerCamelCase_		) == num_terms		)


if __name__ == "__main__":
					print(F'''{solution() = }''')