



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






						'''simple docstring'''







						def __init__(						self   :      Tuple						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      Any=3						,						__lowerCamelCase   :      Optional[Any]=32						,						__lowerCamelCase   :      Optional[Any]=3						,						__lowerCamelCase   :      List[Any]=10						,						__lowerCamelCase   :      Tuple=[10, 20, 30, 40]						,						__lowerCamelCase   :      Optional[Any]=[1, 1, 2, 1]						,						__lowerCamelCase   :      Dict=True						,						__lowerCamelCase   :      List[str]=True						,						__lowerCamelCase   :      Optional[Any]="relu"						,						__lowerCamelCase   :      Optional[Any]=3						,						__lowerCamelCase   :      int=None						,						__lowerCamelCase   :      Union[str, Any]=["stage2", "stage3", "stage4"]						,						__lowerCamelCase   :      List[str]=[2, 3, 4]						,						)   ->					Union[str, Any]:
									A				:       Tuple														=    parent
									A				:       Dict														=    batch_size
									A				:       List[str]														=    image_size
									A				:       int														=    num_channels
									A				:       Union[str, Any]														=    embeddings_size
									A				:       Union[str, Any]														=    hidden_sizes
									A				:       Union[str, Any]														=    depths
									A				:       Any														=    is_training
									A				:       List[str]														=    use_labels
									A				:       Tuple														=    hidden_act
									A				:       Optional[int]														=    num_labels
									A				:       List[Any]														=    scope
									A				:       int														=    len(__lowerCamelCase			)
									A				:       List[str]														=    out_features
									A				:       str														=    out_indices







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]			)   ->					List[str]:
									A				:       Optional[Any]														=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

									A				:       Any														=    self.get_config()

									return config, pixel_values, labels







						def       SCREAMING_SNAKE_CASE__		(						self   :      int			)   ->					Tuple:
									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       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      str						,						__lowerCamelCase   :      str			)   ->					int:
									A				:       Dict														=    ResNetModel(config=__lowerCamelCase			)
									model.to(__lowerCamelCase			)
									model.eval()
									A				:       Optional[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 // 32, self.image_size // 32)						,						)







						def       SCREAMING_SNAKE_CASE__		(						self   :      int						,						__lowerCamelCase   :      str						,						__lowerCamelCase   :      Any						,						__lowerCamelCase   :      List[Any]			)   ->					Optional[int]:
									A				:       Optional[Any]														=    self.num_labels
									A				:       Optional[int]														=    ResNetForImageClassification(__lowerCamelCase			)
									model.to(__lowerCamelCase			)
									model.eval()
									A				:       Union[str, Any]														=    model(__lowerCamelCase						,						labels=__lowerCamelCase			)
									self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]						,						__lowerCamelCase   :      Optional[Any]						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      int			)   ->					int:
									A				:       Optional[int]														=    ResNetBackbone(config=__lowerCamelCase			)
									model.to(__lowerCamelCase			)
									model.eval()
									A				:       Union[str, 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
									A				:       Any														=    None
									A				:       Any														=    ResNetBackbone(config=__lowerCamelCase			)
									model.to(__lowerCamelCase			)
									model.eval()
									A				:       List[str]														=    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       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					int:
									A				:       Tuple														=    self.prepare_config_and_inputs()
									A							,			A							,			A				:       Optional[int]														=    config_and_inputs
									A				:       Any														=    {"pixel_values": pixel_values}
									return config, inputs_dict







@require_torch
class 						lowerCamelCase_     (			_A    ,_A    ,unittest.TestCase    ):






						'''simple docstring'''
						a__ =	(
						    (
						        ResNetModel,
						        ResNetForImageClassification,
						        ResNetBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						a__ =	(
						    {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
						    if is_torch_available()
						    else {}
						)

						a__ =	True
						a__ =	False
						a__ =	False
						a__ =	False
						a__ =	False







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Union[str, Any]:
									A				:       Dict														=    ResNetModelTester(self			)
									A				:       int														=    ConfigTester(self						,						config_class=__lowerCamelCase						,						has_text_modality=__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Any:
									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       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]			)   ->					Tuple:
									return







						@unittest.skip(reason="ResNet does not use inputs_embeds"			)
						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Union[str, Any]:
									pass







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







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					List[str]:
									A							,			A				:       Optional[Any]														=    self.model_tester.prepare_config_and_inputs_for_common()

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

												A				:       Union[str, Any]														=    ["pixel_values"]
												self.assertListEqual(arg_names[:1]						,						__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					List[Any]:
									A				:       Optional[int]														=    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]			)   ->					int:
									A				:       Optional[int]														=    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Any:
									A							,			A				:       Union[str, Any]														=    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												A				:       Tuple														=    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       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					int:
									def check_hidden_states_output(__lowerCamelCase   :      Dict						,						__lowerCamelCase   :      str						,						__lowerCamelCase   :      Optional[Any]			):
												A				:       Optional[Any]														=    model_class(__lowerCamelCase			)
												model.to(__lowerCamelCase			)
												model.eval()

												with torch.no_grad():
															A				:       Optional[int]														=    model(**self._prepare_for_class(__lowerCamelCase						,						__lowerCamelCase			)			)

												A				:       List[Any]														=    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(__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]						,						)

									A							,			A				:       Dict														=    self.model_tester.prepare_config_and_inputs_for_common()
									A				:       int														=    ["basic", "bottleneck"]
									for model_class in self.all_model_classes:
												for layer_type in layers_type:
															A				:       Union[str, Any]														=    layer_type
															A				:       str														=    True
															check_hidden_states_output(__lowerCamelCase						,						__lowerCamelCase						,						__lowerCamelCase			)

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

															check_hidden_states_output(__lowerCamelCase						,						__lowerCamelCase						,						__lowerCamelCase			)







						@unittest.skip(reason="ResNet does not use feedforward chunking"			)
						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Optional[Any]:
									pass







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]			)   ->					Optional[int]:
									A				:       str														=    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)







						@slow
						def       SCREAMING_SNAKE_CASE__		(						self   :      Dict			)   ->					List[str]:
									for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A				:       Optional[int]														=    ResNetModel.from_pretrained(__lowerCamelCase			)
												self.assertIsNotNone(__lowerCamelCase			)







def 						UpperCAmelCase (    ):
			A				:       Optional[Any]														=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
			return image

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






						'''simple docstring'''







						@cached_property
						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					List[Any]:
									return (
									    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
									    if is_vision_available()
									    else None
									)







						@slow
						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]			)   ->					Tuple:
									A				:       Tuple														=    ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(__lowerCamelCase			)

									A				:       Optional[Any]														=    self.default_image_processor
									A				:       List[str]														=    prepare_img()
									A				:       Tuple														=    image_processor(images=__lowerCamelCase						,						return_tensors="pt"			).to(__lowerCamelCase			)

									# forward pass
									with torch.no_grad():
												A				:       str														=    model(**__lowerCamelCase			)

									# verify the logits
									A				:       str														=    torch.Size((1, 10_00)			)
									self.assertEqual(outputs.logits.shape						,						__lowerCamelCase			)

									A				:       List[str]														=    torch.tensor([-11.1069, -9.7877, -8.3777]			).to(__lowerCamelCase			)

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







@require_torch
class 						lowerCamelCase_     (			_A    ,unittest.TestCase    ):






						'''simple docstring'''
						a__ =	(ResNetBackbone,) if is_torch_available() else ()
						a__ =	False
						a__ =	ResNetConfig







						def       SCREAMING_SNAKE_CASE__		(						self   :      int			)   ->					Dict:
									A				:       Any														=    ResNetModelTester(self			)




def 						UpperCAmelCase (    _lowerCamelCase     ):
			return "".join(chr(ord(_lowerCamelCase     ) + 32     ) if "A" <= char <= "Z" else char for char in word     )


if __name__ == "__main__":
							from doctest import testmod

							testmod()