





"""simple docstring"""




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 				_a		:






				def __init__(				self	:					List[str],				lowerCAmelCase__	:					Optional[int],				lowerCAmelCase__	:					List[str]=3,				lowerCAmelCase__	:					Tuple=3_2,				lowerCAmelCase__	:					Optional[int]=3,				lowerCAmelCase__	:					str=1_0,				lowerCAmelCase__	:					int=[1_0, 2_0, 3_0, 4_0],				lowerCAmelCase__	:					Tuple=[1, 1, 2, 1],				lowerCAmelCase__	:					Any=True,				lowerCAmelCase__	:					str=True,				lowerCAmelCase__	:					str="relu",				lowerCAmelCase__	:					str=3,				lowerCAmelCase__	:					List[Any]=None,				lowerCAmelCase__	:					Optional[Any]=["stage2", "stage3", "stage4"],				lowerCAmelCase__	:					Dict=[2, 3, 4],				)			->   int:




										'''simple docstring'''



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






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




										'''simple docstring'''



										_UpperCamelCase    :      str						     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

										_UpperCamelCase    :      List[str]						     =					None
										if self.use_labels:
																_UpperCamelCase    :      str						     =					ids_tensor([self.batch_size],				self.num_labels							)

										_UpperCamelCase    :      Dict						     =					self.get_config()

										return config, pixel_values, labels






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




										'''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        snake_case			(				self	:					List[Any],				lowerCAmelCase__	:					Tuple,				lowerCAmelCase__	:					Optional[Any],				lowerCAmelCase__	:					Any							)			->   Optional[int]:




										'''simple docstring'''



										_UpperCamelCase    :      List[str]						     =					ResNetModel(config=lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase    :      List[Any]						     =					model(lowerCAmelCase__							)
										# 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 // 3_2, self.image_size // 3_2),				)






				def        snake_case			(				self	:					Union[str, Any],				lowerCAmelCase__	:					Optional[Any],				lowerCAmelCase__	:					List[str],				lowerCAmelCase__	:					Union[str, Any]							)			->   Tuple:




										'''simple docstring'''



										_UpperCamelCase    :      int						     =					self.num_labels
										_UpperCamelCase    :      Optional[int]						     =					ResNetForImageClassification(lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase    :      int						     =					model(lowerCAmelCase__,				labels=lowerCAmelCase__							)
										self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_labels)							)






				def        snake_case			(				self	:					Dict,				lowerCAmelCase__	:					List[Any],				lowerCAmelCase__	:					int,				lowerCAmelCase__	:					Optional[Any]							)			->   int:




										'''simple docstring'''



										_UpperCamelCase    :      Union[str, Any]						     =					ResNetBackbone(config=lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase    :      List[Any]						     =					model(lowerCAmelCase__							)

										# 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
										_UpperCamelCase    :      Dict						     =					None
										_UpperCamelCase    :      List[str]						     =					ResNetBackbone(config=lowerCAmelCase__							)
										model.to(lowerCAmelCase__							)
										model.eval()
										_UpperCamelCase    :      Optional[int]						     =					model(lowerCAmelCase__							)

										# 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        snake_case			(				self	:					Optional[Any]							)			->   int:




										'''simple docstring'''



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




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

				UpperCamelCase			=					True
				UpperCamelCase			=					False
				UpperCamelCase			=					False
				UpperCamelCase			=					False
				UpperCamelCase			=					False






				def        snake_case			(				self	:					str							)			->   int:




										'''simple docstring'''



										_UpperCamelCase    :      Tuple						     =					ResNetModelTester(self							)
										_UpperCamelCase    :      Tuple						     =					ConfigTester(self,				config_class=lowerCAmelCase__,				has_text_modality=lowerCAmelCase__							)






				def        snake_case			(				self	:					int							)			->   Tuple:




										'''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        snake_case			(				self	:					Union[str, Any]							)			->   int:




										'''simple docstring'''



										return






				@unittest.skip(reason='''ResNet does not use inputs_embeds'''							)
				def        snake_case			(				self	:					Optional[int]							)			->   int:




										'''simple docstring'''



										pass






				@unittest.skip(reason='''ResNet does not support input and output embeddings'''							)
				def        snake_case			(				self	:					Optional[Any]							)			->   Optional[Any]:




										'''simple docstring'''



										pass






				def        snake_case			(				self	:					str							)			->   int:




										'''simple docstring'''



										_UpperCamelCase     ,							_UpperCamelCase    :      str						     =					self.model_tester.prepare_config_and_inputs_for_common()

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

																_UpperCamelCase    :      List[str]						     =					['''pixel_values''']
																self.assertListEqual(arg_names[:1],				lowerCAmelCase__							)






				def        snake_case			(				self	:					Any							)			->   int:




										'''simple docstring'''



										_UpperCamelCase    :      List[str]						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__							)






				def        snake_case			(				self	:					str							)			->   Dict:




										'''simple docstring'''



										_UpperCamelCase    :      Optional[Any]						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*lowerCAmelCase__							)






				def        snake_case			(				self	:					str							)			->   Tuple:




										'''simple docstring'''



										_UpperCamelCase     ,							_UpperCamelCase    :      int						     =					self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																_UpperCamelCase    :      Optional[Any]						     =					model_class(config=lowerCAmelCase__							)
																for name, module in model.named_modules():
																						if isinstance(lowerCAmelCase__,				(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        snake_case			(				self	:					Union[str, Any]							)			->   int:




										'''simple docstring'''



										def check_hidden_states_output(lowerCAmelCase__	:					List[Any],				lowerCAmelCase__	:					str,				lowerCAmelCase__	:					Optional[Any]							):
																_UpperCamelCase    :      Tuple						     =					model_class(lowerCAmelCase__							)
																model.to(lowerCAmelCase__							)
																model.eval()

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

																_UpperCamelCase    :      str						     =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																_UpperCamelCase    :      Union[str, Any]						     =					self.model_tester.num_stages
																self.assertEqual(len(lowerCAmelCase__							),				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],				)

										_UpperCamelCase     ,							_UpperCamelCase    :      Any						     =					self.model_tester.prepare_config_and_inputs_for_common()
										_UpperCamelCase    :      List[str]						     =					['''basic''', '''bottleneck''']
										for model_class in self.all_model_classes:
																for layer_type in layers_type:
																						_UpperCamelCase    :      Union[str, Any]						     =					layer_type
																						_UpperCamelCase    :      int						     =					True
																						check_hidden_states_output(lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__							)

																						# check that output_hidden_states also work using config
																						del inputs_dict["output_hidden_states"]
																						_UpperCamelCase    :      List[str]						     =					True

																						check_hidden_states_output(lowerCAmelCase__,				lowerCAmelCase__,				lowerCAmelCase__							)






				@unittest.skip(reason='''ResNet does not use feedforward chunking'''							)
				def        snake_case			(				self	:					Optional[int]							)			->   List[Any]:




										'''simple docstring'''



										pass






				def        snake_case			(				self	:					Tuple							)			->   str:




										'''simple docstring'''



										_UpperCamelCase    :      Tuple						     =					self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)






				@slow
				def        snake_case			(				self	:					Optional[Any]							)			->   str:




										'''simple docstring'''



										for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCamelCase    :      List[Any]						     =					ResNetModel.from_pretrained(lowerCAmelCase__							)
																self.assertIsNotNone(lowerCAmelCase__							)





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




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






				@cached_property
				def        snake_case			(				self	:					Any							)			->   Any:




										'''simple docstring'''



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






				@slow
				def        snake_case			(				self	:					Optional[Any]							)			->   str:




										'''simple docstring'''



										_UpperCamelCase    :      List[str]						     =					ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(lowerCAmelCase__							)

										_UpperCamelCase    :      Any						     =					self.default_image_processor
										_UpperCamelCase    :      Any						     =					prepare_img()
										_UpperCamelCase    :      Any						     =					image_processor(images=lowerCAmelCase__,				return_tensors='''pt'''							).to(lowerCAmelCase__							)

										# forward pass
										with torch.no_grad():
																_UpperCamelCase    :      Union[str, Any]						     =					model(**lowerCAmelCase__							)

										# verify the logits
										_UpperCamelCase    :      List[str]						     =					torch.Size((1, 1_0_0_0)							)
										self.assertEqual(outputs.logits.shape,				lowerCAmelCase__							)

										_UpperCamelCase    :      Tuple						     =					torch.tensor([-11.1_069, -9.7_877, -8.3_777]							).to(lowerCAmelCase__							)

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




@require_torch
class 				_a		(   _lowerCAmelCase			,       unittest.TestCase       ):
				UpperCamelCase			=					(ResNetBackbone,) if is_torch_available() else ()
				UpperCamelCase			=					False
				UpperCamelCase			=					ResNetConfig






				def        snake_case			(				self	:					Any							)			->   Tuple:




										'''simple docstring'''



										_UpperCamelCase    :      List[str]						     =					ResNetModelTester(self							)










"""simple docstring"""




UpperCamelCase_     =1_000





def  a_       (							_lowercase     ):
						return x * x





def  a_       (							_lowercase ,		_lowercase ,		_lowercase ,		_lowercase = 4     ):
						assert callable(
						    _lowercase     ), F"""the function(object) passed should be callable your input : {function}"""
						assert isinstance(_lowercase ,		(float, int)     ), F"""a should be float or integer your input : {a}"""
						assert isinstance(function(_lowercase     ) ,		(float, int)     ), (
						    "the function should return integer or float return type of your function, "
						    F"""{type(_lowercase     )}"""
						)
						assert isinstance(_lowercase ,		(float, int)     ), F"""b should be float or integer your input : {b}"""
						assert (
						    isinstance(_lowercase ,		_lowercase     ) and precision > 0
						), F"""precision should be positive integer your input : {precision}"""

						# just applying the formula of simpson for approximate integration written in
						# mentioned article in first comment of this file and above this function

						_UpperCamelCase    :      str						     =					(b - a) / N_STEPS
						_UpperCamelCase    :      Dict						     =					function(_lowercase     ) + function(_lowercase     )

						for i in range(1 ,		_lowercase     ):
												_UpperCamelCase    :      List[Any]						     =					a + h * i
												result += function(_lowercase     ) * (4 if i % 2 else 2)

						result *= h / 3
						return round(_lowercase ,		_lowercase     )


if __name__ == "__main__":
						import doctest

						doctest.testmod()



