



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


			'''simple docstring'''

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





					"""simple docstring"""






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

			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Any   	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

					__SCREAMING_SNAKE_CASE	:		Any   	=		None
					if self.use_labels:
							__SCREAMING_SNAKE_CASE	:		Dict   	=		ids_tensor([self.batch_size]							,					self.num_labels						)

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		self.get_config()

					return config, pixel_values, labels

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





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		str   	=		ResNetModel(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		str   	=		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 UpperCamelCase__ (							self					:			List[Any]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			Dict						):





					"""simple docstring"""






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

			def UpperCamelCase__ (							self					:			Optional[int]							,					lowerCAmelCase__					:			Optional[Any]							,					lowerCAmelCase__					:			Tuple							,					lowerCAmelCase__					:			Union[str, Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		str   	=		ResNetBackbone(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		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
					__SCREAMING_SNAKE_CASE	:		Any   	=		None
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		ResNetBackbone(config=lowerCAmelCase__						)
					model.to(lowerCAmelCase__						)
					model.eval()
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		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 UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.prepare_config_and_inputs()
					__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		config_and_inputs
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		{"""pixel_values""": pixel_values}
					return config, inputs_dict






@require_torch
class 						_UpperCamelCase  (							lowerCamelCase__   , lowerCamelCase__   , unittest.TestCase   ):


			'''simple docstring'''

			_A				:		Union[str, Any]         =		(
			    (
			        ResNetModel,
			        ResNetForImageClassification,
			        ResNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			_A				:		Dict         =		(
			    {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			_A				:		Union[str, Any]         =		True
			_A				:		Union[str, Any]         =		False
			_A				:		Optional[int]         =		False
			_A				:		List[Any]         =		False
			_A				:		Optional[int]         =		False

			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		ResNetModelTester(self						)
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		ConfigTester(self							,					config_class=lowerCAmelCase__							,					has_text_modality=lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			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 UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					return

			@unittest.skip(reason="""ResNet does not use inputs_embeds"""						)
			def UpperCamelCase__ (							self					:			int						):





					"""simple docstring"""






					pass

			@unittest.skip(reason="""ResNet does not support input and output embeddings"""						)
			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					pass

			def UpperCamelCase__ (							self					:			Dict						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.model_tester.prepare_config_and_inputs_for_common()

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

							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		["""pixel_values"""]
							self.assertListEqual(arg_names[:1]							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			Any						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			List[str]						):





					"""simple docstring"""






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

					for model_class in self.all_model_classes:
							__SCREAMING_SNAKE_CASE	:		List[str]   	=		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 UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					def check_hidden_states_output(lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Optional[int]							,					lowerCAmelCase__					:			Optional[Any]						):
							__SCREAMING_SNAKE_CASE	:		Dict   	=		model_class(lowerCAmelCase__						)
							model.to(lowerCAmelCase__						)
							model.eval()

							with torch.no_grad():
									__SCREAMING_SNAKE_CASE	:		Any   	=		model(**self._prepare_for_class(lowerCAmelCase__							,					lowerCAmelCase__						)						)

							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							__SCREAMING_SNAKE_CASE	:		int   	=		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]							,					)

					__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		self.model_tester.prepare_config_and_inputs_for_common()
					__SCREAMING_SNAKE_CASE	:		Dict   	=		["""basic""", """bottleneck"""]
					for model_class in self.all_model_classes:
							for layer_type in layers_type:
									__SCREAMING_SNAKE_CASE	:		int   	=		layer_type
									__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		True
									check_hidden_states_output(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									__SCREAMING_SNAKE_CASE	:		int   	=		True

									check_hidden_states_output(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

			@unittest.skip(reason="""ResNet does not use feedforward chunking"""						)
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






					pass

			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__						)



			@slow
			def UpperCamelCase__ (							self					:			Tuple						):





					"""simple docstring"""






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


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






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


			'''simple docstring'''

			@cached_property
			def UpperCamelCase__ (							self					:			str						):





					"""simple docstring"""






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



			@slow
			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		int   	=		ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.default_image_processor
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		prepare_img()
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		image_processor(images=lowerCAmelCase__							,					return_tensors="""pt"""						).to(lowerCAmelCase__						)

					# forward pass
					with torch.no_grad():
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		model(**lowerCAmelCase__						)

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

					__SCREAMING_SNAKE_CASE	:		Dict   	=		torch.tensor([-11.10_69, -9.78_77, -8.37_77]						).to(lowerCAmelCase__						)

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






@require_torch
class 						_UpperCamelCase  (							lowerCamelCase__   , unittest.TestCase   ):


			'''simple docstring'''

			_A				:		List[str]         =		(ResNetBackbone,) if is_torch_available() else ()
			_A				:		Any         =		False
			_A				:		Tuple         =		ResNetConfig

			def UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		str   	=		ResNetModelTester(self						)




'''simple docstring'''




import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin






class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			_A				:		int         =		['''image_processor''', '''tokenizer''']
			_A				:		Union[str, Any]         =		'''AutoImageProcessor'''
			_A				:		Optional[Any]         =		'''AutoTokenizer'''

			def __init__(							self					:			Tuple							,					lowerCAmelCase__					:			Tuple=None							,					lowerCAmelCase__					:			Union[str, Any]=None							,					**lowerCAmelCase__					:			Any						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE	:		Tuple   	=		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__							,					)
							__SCREAMING_SNAKE_CASE	:		str   	=		kwargs.pop("""feature_extractor"""						)

					__SCREAMING_SNAKE_CASE	:		Any   	=		image_processor if image_processor is not None else feature_extractor
					if image_processor is None:
							raise ValueError("""You need to specify an `image_processor`."""						)
					if tokenizer is None:
							raise ValueError("""You need to specify a `tokenizer`."""						)

					super().__init__(lowerCAmelCase__							,					lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		self.image_processor
					__SCREAMING_SNAKE_CASE	:		Dict   	=		False

			def __call__(							self					:			List[str]							,					*lowerCAmelCase__					:			List[str]							,					**lowerCAmelCase__					:			Dict						):





					"""simple docstring"""






					if self._in_target_context_manager:
							return self.current_processor(*lowerCAmelCase__							,					**lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		kwargs.pop("""images"""							,					lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		kwargs.pop("""text"""							,					lowerCAmelCase__						)
					if len(lowerCAmelCase__						) > 0:
							__SCREAMING_SNAKE_CASE	:		Tuple   	=		args[0]
							__SCREAMING_SNAKE_CASE	:		int   	=		args[1:]

					if images is None and text is None:
							raise ValueError("""You need to specify either an `images` or `text` input to process."""						)

					if images is not None:
							__SCREAMING_SNAKE_CASE	:		List[str]   	=		self.image_processor(lowerCAmelCase__							,					*lowerCAmelCase__							,					**lowerCAmelCase__						)
					if text is not None:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		self.tokenizer(lowerCAmelCase__							,					**lowerCAmelCase__						)

					if text is None:
							return inputs
					elif images is None:
							return encodings
					else:
							__SCREAMING_SNAKE_CASE	:		int   	=		encodings["""input_ids"""]
							return inputs

			def UpperCamelCase__ (							self					:			Any							,					*lowerCAmelCase__					:			Any							,					**lowerCAmelCase__					:			List[str]						):





					"""simple docstring"""






					return self.tokenizer.batch_decode(*lowerCAmelCase__							,					**lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			int							,					*lowerCAmelCase__					:			str							,					**lowerCAmelCase__					:			Dict						):





					"""simple docstring"""






					return self.tokenizer.decode(*lowerCAmelCase__							,					**lowerCAmelCase__						)

			@contextmanager
			def UpperCamelCase__ (							self					:			Union[str, Any]						):





					"""simple docstring"""






					warnings.warn(
					    """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
					    """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
					    """your images inputs, or in a separate call."""						)
					__SCREAMING_SNAKE_CASE	:		List[Any]   	=		True
					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.tokenizer
					yield
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.image_processor
					__SCREAMING_SNAKE_CASE	:		List[str]   	=		False

			@property
			def UpperCamelCase__ (							self					:			Optional[Any]						):





					"""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 UpperCamelCase__ (							self					:			List[Any]						):





					"""simple docstring"""






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