






'''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  _SCREAMING_SNAKE_CASE				:


			'''simple docstring'''





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

									'''simple docstring'''







									UpperCamelCase__       =			parent
									UpperCamelCase__       =			batch_size
									UpperCamelCase__       =			image_size
									UpperCamelCase__       =			num_channels
									UpperCamelCase__       =			embeddings_size
									UpperCamelCase__       =			hidden_sizes
									UpperCamelCase__       =			depths
									UpperCamelCase__       =			is_training
									UpperCamelCase__       =			use_labels
									UpperCamelCase__       =			hidden_act
									UpperCamelCase__       =			num_labels
									UpperCamelCase__       =			scope
									UpperCamelCase__       =			len(lowercase      )
									UpperCamelCase__       =			out_features
									UpperCamelCase__       =			out_indices






			def 					A   ( self				:    Any      )				->     List[str]:

									'''simple docstring'''







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

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

									UpperCamelCase__       =			self.get_config()

									return config, pixel_values, labels






			def 					A   ( self				:    str      )				->     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				:    str			,   lowercase				:    Optional[int]			,   lowercase				:    Union[str, Any]			,   lowercase				:    Optional[int]      )				->     int:

									'''simple docstring'''







									UpperCamelCase__       =			ResNetModel(config=lowercase      )
									model.to(lowercase      )
									model.eval()
									UpperCamelCase__       =			model(lowercase      )
									# 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]			,   lowercase				:    str			,   lowercase				:    Optional[int]			,   lowercase				:    Any      )				->     List[Any]:

									'''simple docstring'''







									UpperCamelCase__       =			self.num_labels
									UpperCamelCase__       =			ResNetForImageClassification(lowercase      )
									model.to(lowercase      )
									model.eval()
									UpperCamelCase__       =			model(lowercase			,   labels=lowercase      )
									self.parent.assertEqual(result.logits.shape			,   (self.batch_size, self.num_labels)      )






			def 					A   ( self				:    str			,   lowercase				:    Optional[int]			,   lowercase				:    List[Any]			,   lowercase				:    Union[str, Any]      )				->     Optional[Any]:

									'''simple docstring'''







									UpperCamelCase__       =			ResNetBackbone(config=lowercase      )
									model.to(lowercase      )
									model.eval()
									UpperCamelCase__       =			model(lowercase      )

									# 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__       =			None
									UpperCamelCase__       =			ResNetBackbone(config=lowercase      )
									model.to(lowercase      )
									model.eval()
									UpperCamelCase__       =			model(lowercase      )

									# 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				:    Optional[Any]      )				->     List[str]:

									'''simple docstring'''







									UpperCamelCase__       =			self.prepare_config_and_inputs()
									UpperCamelCase__     , UpperCamelCase__     , UpperCamelCase__       =			config_and_inputs
									UpperCamelCase__       =			{"""pixel_values""": pixel_values}
									return config, inputs_dict
@require_torch
class  _SCREAMING_SNAKE_CASE				(		SCREAMING_SNAKE_CASE							,SCREAMING_SNAKE_CASE							,unittest.TestCase						):


			'''simple docstring'''





			__a				:				Dict         =       (
			    (
			        ResNetModel,
			        ResNetForImageClassification,
			        ResNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			__a				:				str         =       (
			    {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			__a				:				Dict         =       True
			__a				:				int         =       False
			__a				:				Any         =       False
			__a				:				Union[str, Any]         =       False
			__a				:				int         =       False






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

									'''simple docstring'''







									UpperCamelCase__       =			ResNetModelTester(self      )
									UpperCamelCase__       =			ConfigTester(self			,   config_class=lowercase			,   has_text_modality=lowercase      )






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

									'''simple docstring'''







									return






			@unittest.skip(reason="""ResNet does not use inputs_embeds"""      )
			def 					A   ( self				:    List[str]      )				->     Optional[int]:

									'''simple docstring'''







									pass






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

									'''simple docstring'''







									pass






			def 					A   ( self				:    Any      )				->     List[Any]:

									'''simple docstring'''







									UpperCamelCase__     , UpperCamelCase__       =			self.model_tester.prepare_config_and_inputs_for_common()

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

															UpperCamelCase__       =			["""pixel_values"""]
															self.assertListEqual(arg_names[:1]			,   lowercase      )






			def 					A   ( self				:    Optional[Any]      )				->     str:

									'''simple docstring'''







									UpperCamelCase__       =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase      )






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

									'''simple docstring'''







									UpperCamelCase__       =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*lowercase      )






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

									'''simple docstring'''







									UpperCamelCase__     , UpperCamelCase__       =			self.model_tester.prepare_config_and_inputs_for_common()

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

									'''simple docstring'''







									def check_hidden_states_output(lowercase				:    Dict			,   lowercase				:    Union[str, Any]			,   lowercase				:    Union[str, Any]      ):
															UpperCamelCase__       =			model_class(lowercase      )
															model.to(lowercase      )
															model.eval()

															with torch.no_grad():
																					UpperCamelCase__       =			model(**self._prepare_for_class(lowercase			,   lowercase      )      )

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

															UpperCamelCase__       =			self.model_tester.num_stages
															self.assertEqual(len(lowercase      )			,   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__       =			self.model_tester.prepare_config_and_inputs_for_common()
									UpperCamelCase__       =			["""basic""", """bottleneck"""]
									for model_class in self.all_model_classes:
															for layer_type in layers_type:
																					UpperCamelCase__       =			layer_type
																					UpperCamelCase__       =			True
																					check_hidden_states_output(lowercase			,   lowercase			,   lowercase      )

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

																					check_hidden_states_output(lowercase			,   lowercase			,   lowercase      )






			@unittest.skip(reason="""ResNet does not use feedforward chunking"""      )
			def 					A   ( self				:    str      )				->     List[str]:

									'''simple docstring'''







									pass






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

									'''simple docstring'''







									UpperCamelCase__       =			self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowercase      )







			@slow
			def 					A   ( self				:    Optional[int]      )				->     List[Any]:

									'''simple docstring'''







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







def 						__magic_name__(			):
						'''simple docstring'''





						UpperCamelCase__       =			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
						return image
@require_torch
@require_vision
class  _SCREAMING_SNAKE_CASE				(		unittest.TestCase						):


			'''simple docstring'''





			@cached_property
			def 					A   ( self				:    int      )				->     str:

									'''simple docstring'''







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







			@slow
			def 					A   ( self				:    Any      )				->     int:

									'''simple docstring'''







									UpperCamelCase__       =			ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      ).to(lowercase      )

									UpperCamelCase__       =			self.default_image_processor
									UpperCamelCase__       =			prepare_img()
									UpperCamelCase__       =			image_processor(images=lowercase			,   return_tensors="""pt"""      ).to(lowercase      )

									# forward pass
									with torch.no_grad():
															UpperCamelCase__       =			model(**lowercase      )

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

									UpperCamelCase__       =			torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]      ).to(lowercase      )

									self.assertTrue(torch.allclose(outputs.logits[0, :3]			,   lowercase			,   atol=1e-4      )      )
@require_torch
class  _SCREAMING_SNAKE_CASE				(		SCREAMING_SNAKE_CASE							,unittest.TestCase						):


			'''simple docstring'''





			__a				:				str         =       (ResNetBackbone,) if is_torch_available() else ()
			__a				:				int         =       False
			__a				:				Any         =       ResNetConfig






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

									'''simple docstring'''







									UpperCamelCase__       =			ResNetModelTester(self      )








'''simple docstring'''


lowerCamelCase_					:			List[Any]     						=				{0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]}

lowerCamelCase_					:			Tuple     						=				{0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []}







def 						__magic_name__(			_A    ,   _A    ,   _A       ):
						'''simple docstring'''





						UpperCamelCase__       =			True
						UpperCamelCase__       =			[]

						for neighbour in graph[vert]:
												if not visited[neighbour]:
																		connected_verts += dfs(_A    ,   _A    ,   _A       )

						return [vert, *connected_verts]







def 						__magic_name__(			_A       ):
						'''simple docstring'''





						UpperCamelCase__       =			len(_A       )
						UpperCamelCase__       =			graph_size * [False]
						UpperCamelCase__       =			[]

						for i in range(_A       ):
												if not visited[i]:
																		UpperCamelCase__       =			dfs(_A    ,   _A    ,   _A       )
																		components_list.append(_A       )

						return components_list


if __name__ == "__main__":
					import doctest

					doctest.testmod()
