


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     __snake_case							:
     def __init__(	self					:	Dict  ,			_lowerCAmelCase					:	List[Any]  ,			_lowerCAmelCase					:	List[Any]=3  ,			_lowerCAmelCase					:	Tuple=3_2  ,			_lowerCAmelCase					:	str=3  ,			_lowerCAmelCase					:	Any=1_0  ,			_lowerCAmelCase					:	List[str]=[1_0, 2_0, 3_0, 4_0]  ,			_lowerCAmelCase					:	Optional[Any]=[1, 1, 2, 1]  ,			_lowerCAmelCase					:	Dict=True  ,			_lowerCAmelCase					:	int=True  ,			_lowerCAmelCase					:	Dict="relu"  ,			_lowerCAmelCase					:	Any=3  ,			_lowerCAmelCase					:	Union[str, Any]=None  ,			_lowerCAmelCase					:	int=["stage2", "stage3", "stage4"]  ,			_lowerCAmelCase					:	Union[str, Any]=[2, 3, 4]  ,			)       ->				Union[str, Any]:



           '''simple docstring'''





           __magic_name__ 		=			parent
           __magic_name__ 		=			batch_size
           __magic_name__ 		=			image_size
           __magic_name__ 		=			num_channels
           __magic_name__ 		=			embeddings_size
           __magic_name__ 		=			hidden_sizes
           __magic_name__ 		=			depths
           __magic_name__ 		=			is_training
           __magic_name__ 		=			use_labels
           __magic_name__ 		=			hidden_act
           __magic_name__ 		=			num_labels
           __magic_name__ 		=			scope
           __magic_name__ 		=			len(_A     )
           __magic_name__ 		=			out_features
           __magic_name__ 		=			out_indices
     def   a (	self					:	Optional[int]     )       ->				str:



           '''simple docstring'''





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

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

           __magic_name__ 		=			self.get_config()

           return config, pixel_values, labels
     def   a (	self					:	Optional[Any]     )       ->				Optional[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   a (	self					:	Dict  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	Optional[int]  ,			_lowerCAmelCase					:	List[Any]     )       ->				str:



           '''simple docstring'''





           __magic_name__ 		=			ResNetModel(config=_A     )
           model.to(_A     )
           model.eval()
           __magic_name__ 		=			model(_A     )
           # 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   a (	self					:	Optional[int]  ,			_lowerCAmelCase					:	int  ,			_lowerCAmelCase					:	int  ,			_lowerCAmelCase					:	int     )       ->				Optional[Any]:



           '''simple docstring'''





           __magic_name__ 		=			self.num_labels
           __magic_name__ 		=			ResNetForImageClassification(_A     )
           model.to(_A     )
           model.eval()
           __magic_name__ 		=			model(_A  ,			labels=_A     )
           self.parent.assertEqual(result.logits.shape  ,			(self.batch_size, self.num_labels)     )
     def   a (	self					:	Any  ,			_lowerCAmelCase					:	List[str]  ,			_lowerCAmelCase					:	int  ,			_lowerCAmelCase					:	List[Any]     )       ->				int:



           '''simple docstring'''





           __magic_name__ 		=			ResNetBackbone(config=_A     )
           model.to(_A     )
           model.eval()
           __magic_name__ 		=			model(_A     )

           # 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
           __magic_name__ 		=			None
           __magic_name__ 		=			ResNetBackbone(config=_A     )
           model.to(_A     )
           model.eval()
           __magic_name__ 		=			model(_A     )

           # 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   a (	self					:	Any     )       ->				Any:



           '''simple docstring'''





           __magic_name__ 		=			self.prepare_config_and_inputs()
           __magic_name__ 		=			config_and_inputs
           __magic_name__ 		=			{'pixel_values': pixel_values}
           return config, inputs_dict







@require_torch
class     __snake_case							(      lowercase__  ,			lowercase__  ,			unittest.TestCase):
     SCREAMING_SNAKE_CASE_		:					Tuple 				= (
         (
             ResNetModel,
             ResNetForImageClassification,
             ResNetBackbone,
         )
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE_		:					Any 				= (
         {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE_		:					int 				= True
     SCREAMING_SNAKE_CASE_		:					Dict 				= False
     SCREAMING_SNAKE_CASE_		:					Tuple 				= False
     SCREAMING_SNAKE_CASE_		:					str 				= False
     SCREAMING_SNAKE_CASE_		:					List[Any] 				= False
     def   a (	self					:	Tuple     )       ->				Union[str, Any]:



           '''simple docstring'''





           __magic_name__ 		=			ResNetModelTester(self     )
           __magic_name__ 		=			ConfigTester(self  ,			config_class=_A  ,			has_text_modality=_A     )
     def   a (	self					:	Optional[int]     )       ->				str:



           '''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   a (	self					:	Optional[Any]     )       ->				Tuple:



           '''simple docstring'''





           return
     @unittest.skip(reason='ResNet does not use inputs_embeds'     )
     def   a (	self					:	int     )       ->				Tuple:



           '''simple docstring'''





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



           '''simple docstring'''





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



           '''simple docstring'''





           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

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

                 __magic_name__ 		=			['pixel_values']
                 self.assertListEqual(arg_names[:1]  ,			_A     )
     def   a (	self					:	str     )       ->				int:



           '''simple docstring'''





           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_A     )
     def   a (	self					:	str     )       ->				Dict:



           '''simple docstring'''





           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*_A     )
     def   a (	self					:	Dict     )       ->				int:



           '''simple docstring'''





           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 __magic_name__ 		=			model_class(config=_A     )
                 for name, module in model.named_modules():
                       if isinstance(_A  ,			(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   a (	self					:	Any     )       ->				List[str]:



           '''simple docstring'''





           def check_hidden_states_output(_lowerCAmelCase					:	Optional[Any]  ,			_lowerCAmelCase					:	Optional[Any]  ,			_lowerCAmelCase					:	str     ):
                 __magic_name__ 		=			model_class(_A     )
                 model.to(_A     )
                 model.eval()

                 with torch.no_grad():
                       __magic_name__ 		=			model(**self._prepare_for_class(_A  ,			_A     )     )

                 __magic_name__ 		=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 __magic_name__ 		=			self.model_tester.num_stages
                 self.assertEqual(len(_A     )  ,			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]  ,			)

           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()
           __magic_name__ 		=			['basic', 'bottleneck']
           for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                       __magic_name__ 		=			layer_type
                       __magic_name__ 		=			True
                       check_hidden_states_output(_A  ,			_A  ,			_A     )

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

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



           '''simple docstring'''





           pass
     def   a (	self					:	int     )       ->				Tuple:



           '''simple docstring'''





           __magic_name__ 		=			self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_A     )







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



           '''simple docstring'''





           for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __magic_name__ 		=			ResNetModel.from_pretrained(_A     )
                 self.assertIsNotNone(_A     )







def 							UpperCamelCase_  (				)->      Dict:




      '''simple docstring'''
      __magic_name__ 		=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
      return image

@require_torch
@require_vision
class     __snake_case							(      unittest.TestCase):
     @cached_property
     def   a (	self					:	Tuple     )       ->				List[Any]:



           '''simple docstring'''





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







     @slow
     def   a (	self					:	Any     )       ->				Tuple:



           '''simple docstring'''





           __magic_name__ 		=			ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(_A     )

           __magic_name__ 		=			self.default_image_processor
           __magic_name__ 		=			prepare_img()
           __magic_name__ 		=			image_processor(images=_A  ,			return_tensors='pt'     ).to(_A     )

           # forward pass
           with torch.no_grad():
                 __magic_name__ 		=			model(**_A     )

           # verify the logits
           __magic_name__ 		=			torch.Size((1, 1_0_0_0)     )
           self.assertEqual(outputs.logits.shape  ,			_A     )

           __magic_name__ 		=			torch.tensor([-11.1069, -9.7877, -8.3777]     ).to(_A     )

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







@require_torch
class     __snake_case							(      lowercase__  ,			unittest.TestCase):
     SCREAMING_SNAKE_CASE_		:					Tuple 				= (ResNetBackbone,) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE_		:					int 				= False
     SCREAMING_SNAKE_CASE_		:					Optional[Any] 				= ResNetConfig
     def   a (	self					:	Union[str, Any]     )       ->				str:



           '''simple docstring'''





           __magic_name__ 		=			ResNetModelTester(self     )





def 							UpperCamelCase_  (				__snake_case			:						list[int]     )->      tuple[int, int]:




						'''simple docstring'''
						# base case
						if len(__snake_case     ) == 1:
												return a[0], a[0]
						else:
												# split A into half.
												__magic_name__ 		=			a[: len(__snake_case     ) // 2]
												__magic_name__ 		=			a[len(__snake_case     ) // 2 :]

												# 2 sub problems, 1/2 of original size.
												__magic_name__		,			__magic_name__ 		=			max_difference(__snake_case     )
												__magic_name__		,			__magic_name__ 		=			max_difference(__snake_case     )

												# get min of first and max of second
												# linear time
												__magic_name__ 		=			min(__snake_case     )
												__magic_name__ 		=			max(__snake_case     )

												# 3 cases, either (small1, big1),
												# (min_first, max_second), (small2, big2)
												# constant comparisons
												if biga - smalla > max_second - min_first and biga - smalla > biga - smalla:
																		return smalla, biga
												elif biga - smalla > max_second - min_first:
																		return smalla, biga
												else:
																		return min_first, max_second


if __name__ == "__main__":
					import doctest

					doctest.testmod()

