


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



											'''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(_lowerCAmelCase     )
											__magic_name__ 		=			out_features
											__magic_name__ 		=			out_indices
					def   a (	self					:	int     )       ->				int:



											'''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					:	Tuple     )       ->				Tuple:



											'''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					:	List[str]  ,			_lowerCAmelCase					:	Optional[Any]  ,			_lowerCAmelCase					:	Dict  ,			_lowerCAmelCase					:	Tuple     )       ->				Optional[Any]:



											'''simple docstring'''





											__magic_name__ 		=			ResNetModel(config=_lowerCAmelCase     )
											model.to(_lowerCAmelCase     )
											model.eval()
											__magic_name__ 		=			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   a (	self					:	Tuple  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	Dict  ,			_lowerCAmelCase					:	List[str]     )       ->				Any:



											'''simple docstring'''





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



											'''simple docstring'''





											__magic_name__ 		=			ResNetBackbone(config=_lowerCAmelCase     )
											model.to(_lowerCAmelCase     )
											model.eval()
											__magic_name__ 		=			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
											__magic_name__ 		=			None
											__magic_name__ 		=			ResNetBackbone(config=_lowerCAmelCase     )
											model.to(_lowerCAmelCase     )
											model.eval()
											__magic_name__ 		=			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   a (	self					:	List[Any]     )       ->				Tuple:



											'''simple docstring'''





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







@require_torch
class     __snake_case							(      _UpperCAmelCase  ,			_UpperCAmelCase  ,			unittest.TestCase):
					SCREAMING_SNAKE_CASE_		:					Dict 				= (
					    (
					        ResNetModel,
					        ResNetForImageClassification,
					        ResNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= (
					    {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

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



											'''simple docstring'''





											__magic_name__ 		=			ResNetModelTester(self     )
											__magic_name__ 		=			ConfigTester(self  ,			config_class=_lowerCAmelCase  ,			has_text_modality=_lowerCAmelCase     )
					def   a (	self					:	List[Any]     )       ->				Optional[int]:



											'''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					:	Union[str, Any]     )       ->				List[Any]:



											'''simple docstring'''





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



											'''simple docstring'''





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



											'''simple docstring'''





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



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__ 		=			model_class(_lowerCAmelCase     )
																	__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]  ,			_lowerCAmelCase     )
					def   a (	self					:	List[Any]     )       ->				List[str]:



											'''simple docstring'''





											__magic_name__ 		=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCAmelCase     )
					def   a (	self					:	List[str]     )       ->				List[str]:



											'''simple docstring'''





											__magic_name__ 		=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_backbone(*_lowerCAmelCase     )
					def   a (	self					:	int     )       ->				Union[str, Any]:



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__ 		=			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   a (	self					:	Union[str, Any]     )       ->				Optional[Any]:



											'''simple docstring'''





											def check_hidden_states_output(_lowerCAmelCase					:	Tuple  ,			_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	Any     ):
																	__magic_name__ 		=			model_class(_lowerCAmelCase     )
																	model.to(_lowerCAmelCase     )
																	model.eval()

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

																	__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(_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]  ,			)

											__magic_name__		,			__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(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )

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

																							check_hidden_states_output(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )
					@unittest.skip(reason='ResNet does not use feedforward chunking'     )
					def   a (	self					:	Union[str, Any]     )       ->				Optional[Any]:



											'''simple docstring'''





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



											'''simple docstring'''





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







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



											'''simple docstring'''





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







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					:	List[Any]     )       ->				int:



											'''simple docstring'''





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







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



											'''simple docstring'''





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

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

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

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

											__magic_name__ 		=			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     __snake_case							(      _UpperCAmelCase  ,			unittest.TestCase):
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= (ResNetBackbone,) if is_torch_available() else ()
					SCREAMING_SNAKE_CASE_		:					List[str] 				= False
					SCREAMING_SNAKE_CASE_		:					List[Any] 				= ResNetConfig
					def   a (	self					:	Any     )       ->				str:



											'''simple docstring'''





											__magic_name__ 		=			ResNetModelTester(self     )



import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding

class     __snake_case							(      _UpperCAmelCase):
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= ["image_processor", "tokenizer"]
					SCREAMING_SNAKE_CASE_		:					Tuple 				= "AutoImageProcessor"
					SCREAMING_SNAKE_CASE_		:					Dict 				= "AutoTokenizer"
					def __init__(	self					:	List[str]  ,			_lowerCAmelCase					:	str=None  ,			_lowerCAmelCase					:	Dict=None  ,			**_lowerCAmelCase					:	List[str]     )       ->				Optional[int]:



											'''simple docstring'''





											__magic_name__ 		=			None
											if "feature_extractor" in kwargs:
																	warnings.warn(
																	    'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
																	    ' instead.'  ,			_lowerCAmelCase  ,			)
																	__magic_name__ 		=			kwargs.pop('feature_extractor'     )

											__magic_name__ 		=			image_processor if image_processor is not None else feature_extractor
											if image_processor is None:
																	raise ValueError('You have to specify an image_processor.'     )
											if tokenizer is None:
																	raise ValueError('You have to specify a tokenizer.'     )

											super().__init__(_lowerCAmelCase  ,			_lowerCAmelCase     )
											__magic_name__ 		=			self.image_processor
					def __call__(	self					:	str  ,			_lowerCAmelCase					:	Any=None  ,			_lowerCAmelCase					:	int=None  ,			_lowerCAmelCase					:	List[str]=None  ,			**_lowerCAmelCase					:	int     )       ->				int:



											'''simple docstring'''





											if text is None and images is None:
																	raise ValueError('You have to specify either text or images. Both cannot be none.'     )

											if text is not None:
																	__magic_name__ 		=			self.tokenizer(_lowerCAmelCase  ,			return_tensors=_lowerCAmelCase  ,			**_lowerCAmelCase     )

											if images is not None:
																	__magic_name__ 		=			self.image_processor(_lowerCAmelCase  ,			return_tensors=_lowerCAmelCase  ,			**_lowerCAmelCase     )

											if text is not None and images is not None:
																	__magic_name__ 		=			image_features.pixel_values
																	return encoding
											elif text is not None:
																	return encoding
											else:
																	return BatchEncoding(data=dict(**_lowerCAmelCase     )  ,			tensor_type=_lowerCAmelCase     )
					def   a (	self					:	Optional[int]  ,			*_lowerCAmelCase					:	Optional[int]  ,			**_lowerCAmelCase					:	Optional[Any]     )       ->				Optional[int]:



											'''simple docstring'''





											return self.tokenizer.batch_decode(*_lowerCAmelCase  ,			**_lowerCAmelCase     )
					def   a (	self					:	Union[str, Any]  ,			*_lowerCAmelCase					:	str  ,			**_lowerCAmelCase					:	Tuple     )       ->				int:



											'''simple docstring'''





											return self.tokenizer.decode(*_lowerCAmelCase  ,			**_lowerCAmelCase     )
					@property
					def   a (	self					:	List[Any]     )       ->				Tuple:



											'''simple docstring'''





											__magic_name__ 		=			self.tokenizer.model_input_names
											__magic_name__ 		=			self.image_processor.model_input_names
											return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names     )     )
					@property
					def   a (	self					:	Optional[Any]     )       ->				Dict:



											'''simple docstring'''





											warnings.warn(
											    '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'  ,			_lowerCAmelCase  ,			)
											return self.image_processor_class







					@property
					def   a (	self					:	Dict     )       ->				Tuple:



											'''simple docstring'''





											warnings.warn(
											    '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'  ,			_lowerCAmelCase  ,			)
											return self.image_processor

