




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







							def __init__(    self   :	int   ,     __UpperCAmelCase   :	int   ,     __UpperCAmelCase   :	List[Any]=3   ,     __UpperCAmelCase   :	List[Any]=32   ,     __UpperCAmelCase   :	List[str]=3   ,     __UpperCAmelCase   :	Union[str, Any]=10   ,     __UpperCAmelCase   :	str=[10, 20, 30, 40]   ,     __UpperCAmelCase   :	int=[1, 1, 2, 1]   ,     __UpperCAmelCase   :	Optional[int]=True   ,     __UpperCAmelCase   :	Union[str, Any]=True   ,     __UpperCAmelCase   :	str="relu"   ,     __UpperCAmelCase   :	Optional[int]=3   ,     __UpperCAmelCase   :	Union[str, Any]=None   ,     __UpperCAmelCase   :	str=["stage2", "stage3", "stage4"]   ,     __UpperCAmelCase   :	Optional[int]=[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(__UpperCAmelCase				)
										UpperCamelCase_     				= out_features
										UpperCamelCase_     				= out_indices







							def        lowercase__							(    self   :	Tuple				)		->					Optional[Any]:

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

										"""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        lowercase__							(    self   :	Dict   ,     __UpperCAmelCase   :	Any   ,     __UpperCAmelCase   :	List[Any]   ,     __UpperCAmelCase   :	Tuple				)		->					Dict:

										"""simple docstring"""



										UpperCamelCase_     				= ResNetModel(config=__UpperCAmelCase				)
										model.to(__UpperCAmelCase				)
										model.eval()
										UpperCamelCase_     				= model(__UpperCAmelCase				)
										# 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        lowercase__							(    self   :	Optional[int]   ,     __UpperCAmelCase   :	Optional[Any]   ,     __UpperCAmelCase   :	int   ,     __UpperCAmelCase   :	List[str]				)		->					Tuple:

										"""simple docstring"""



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







							def        lowercase__							(    self   :	Tuple   ,     __UpperCAmelCase   :	Union[str, Any]   ,     __UpperCAmelCase   :	Any   ,     __UpperCAmelCase   :	Optional[int]				)		->					Dict:

										"""simple docstring"""



										UpperCamelCase_     				= ResNetBackbone(config=__UpperCAmelCase				)
										model.to(__UpperCAmelCase				)
										model.eval()
										UpperCamelCase_     				= model(__UpperCAmelCase				)

										# 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=__UpperCAmelCase				)
										model.to(__UpperCAmelCase				)
										model.eval()
										UpperCamelCase_     				= model(__UpperCAmelCase				)

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

										"""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     A					(				lowerCamelCase_  ,						lowerCamelCase_  ,						unittest.TestCase       ):
							_SCREAMING_SNAKE_CASE  :		int			  =       (
							    (
							        ResNetModel,
							        ResNetForImageClassification,
							        ResNetBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							_SCREAMING_SNAKE_CASE  :		int			  =       (
							    {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
							    if is_torch_available()
							    else {}
							)

							_SCREAMING_SNAKE_CASE  :		Any			  =       True
							_SCREAMING_SNAKE_CASE  :		Optional[Any]			  =       False
							_SCREAMING_SNAKE_CASE  :		Dict			  =       False
							_SCREAMING_SNAKE_CASE  :		Optional[int]			  =       False
							_SCREAMING_SNAKE_CASE  :		Tuple			  =       False







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

										"""simple docstring"""



										UpperCamelCase_     				= ResNetModelTester(self				)
										UpperCamelCase_     				= ConfigTester(self   ,     config_class=__UpperCAmelCase   ,     has_text_modality=__UpperCAmelCase				)







							def        lowercase__							(    self   :	Optional[Any]				)		->					Dict:

										"""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        lowercase__							(    self   :	str				)		->					Dict:

										"""simple docstring"""



										return







							@unittest.skip(reason='ResNet does not use inputs_embeds'				)
							def        lowercase__							(    self   :	List[Any]				)		->					Optional[Any]:

										"""simple docstring"""



										pass







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

										"""simple docstring"""



										pass







							def        lowercase__							(    self   :	int				)		->					Tuple:

										"""simple docstring"""



										UpperCamelCase_				,   UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													UpperCamelCase_     				= model_class(__UpperCAmelCase				)
													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]   ,     __UpperCAmelCase				)







							def        lowercase__							(    self   :	Any				)		->					Optional[Any]:

										"""simple docstring"""



										UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__UpperCAmelCase				)







							def        lowercase__							(    self   :	Tuple				)		->					List[str]:

										"""simple docstring"""



										UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*__UpperCAmelCase				)







							def        lowercase__							(    self   :	Any				)		->					Optional[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=__UpperCAmelCase				)
													for name, module in model.named_modules():
																if isinstance(__UpperCAmelCase   ,     (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        lowercase__							(    self   :	Union[str, Any]				)		->					List[str]:

										"""simple docstring"""



										def check_hidden_states_output(__UpperCAmelCase   :	str   ,     __UpperCAmelCase   :	int   ,     __UpperCAmelCase   :	Union[str, Any]				):
													UpperCamelCase_     				= model_class(__UpperCAmelCase				)
													model.to(__UpperCAmelCase				)
													model.eval()

													with torch.no_grad():
																UpperCamelCase_     				= model(**self._prepare_for_class(__UpperCAmelCase   ,     __UpperCAmelCase				)				)

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

													UpperCamelCase_     				= self.model_tester.num_stages
													self.assertEqual(len(__UpperCAmelCase				)   ,     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(__UpperCAmelCase   ,     __UpperCAmelCase   ,     __UpperCAmelCase				)

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

																check_hidden_states_output(__UpperCAmelCase   ,     __UpperCAmelCase   ,     __UpperCAmelCase				)







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

										"""simple docstring"""



										pass







							def        lowercase__							(    self   :	str				)		->					str:

										"""simple docstring"""



										UpperCamelCase_     				= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase				)







							@slow
							def        lowercase__							(    self   :	Any				)		->					Optional[Any]:

										"""simple docstring"""



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







def  a_		(							)	->			List[Any]:

			'''simple docstring'''


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




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







							@cached_property
							def        lowercase__							(    self   :	Optional[int]				)		->					Dict:

										"""simple docstring"""



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







							@slow
							def        lowercase__							(    self   :	Union[str, Any]				)		->					int:

										"""simple docstring"""



										UpperCamelCase_     				= ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(__UpperCAmelCase				)

										UpperCamelCase_     				= self.default_image_processor
										UpperCamelCase_     				= prepare_img()
										UpperCamelCase_     				= image_processor(images=__UpperCAmelCase   ,     return_tensors='pt'				).to(__UpperCAmelCase				)

										# forward pass
										with torch.no_grad():
													UpperCamelCase_     				= model(**__UpperCAmelCase				)

										# verify the logits
										UpperCamelCase_     				= torch.Size((1, 1000)				)
										self.assertEqual(outputs.logits.shape   ,     __UpperCAmelCase				)

										UpperCamelCase_     				= torch.tensor([-11.1_069, -9.7_877, -8.3_777]				).to(__UpperCAmelCase				)

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







@require_torch
class     A					(				lowerCamelCase_  ,						unittest.TestCase       ):
							_SCREAMING_SNAKE_CASE  :		Dict			  =       (ResNetBackbone,) if is_torch_available() else ()
							_SCREAMING_SNAKE_CASE  :		str			  =       False
							_SCREAMING_SNAKE_CASE  :		Any			  =       ResNetConfig







							def        lowercase__							(    self   :	Tuple				)		->					str:

										"""simple docstring"""



										UpperCamelCase_     				= ResNetModelTester(self				)






from functools import partial
from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload

import torch
import torch.nn as nn
import torch.types




def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			torch.Tensor:

			'''simple docstring'''


			if not inplace:
						UpperCamelCase_     				= ma + ma
			else:
						ma += ma

			return ma




def  a_		(							__snake_case     ,		__snake_case					)	->			torch.Tensor:

			'''simple docstring'''


			UpperCamelCase_     				= -1 * len(__snake_case					)
			UpperCamelCase_     				= list(range(len(tensor.shape[:zero_index]					)					)					)
			return tensor.permute(first_inds + [zero_index + i for i in inds]					)




def  a_		(							__snake_case     ,		__snake_case					)	->			torch.Tensor:

			'''simple docstring'''


			return t.reshape(t.shape[:-no_dims] + (-1,)					)




def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case     ,		__snake_case = 1E-4					)	->			torch.Tensor:

			'''simple docstring'''


			UpperCamelCase_     				= mask.expand(*value.shape					)
			return torch.sum(mask * value     ,		dim=__snake_case					) / (eps + torch.sum(__snake_case     ,		dim=__snake_case					))




def  a_		(							__snake_case     ,		__snake_case = 2.31_25     ,		__snake_case = 21.68_75     ,		__snake_case = 6_4					)	->			torch.Tensor:

			'''simple docstring'''


			UpperCamelCase_     				= torch.linspace(__snake_case     ,		__snake_case     ,		no_bins - 1     ,		device=pts.device					)
			UpperCamelCase_     				= torch.sqrt(torch.sum((pts.unsqueeze(-2					) - pts.unsqueeze(-3					)) ** 2     ,		dim=-1					)					)
			return torch.bucketize(__snake_case     ,		__snake_case					)




def  a_		(							__snake_case     ,		__snake_case					)	->			dict:

			'''simple docstring'''


			UpperCamelCase_     				= dicts[0]
			UpperCamelCase_     				= {}
			for k, v in first.items():
						UpperCamelCase_     				= [d[k] for d in dicts]
						if isinstance(__snake_case     ,		__snake_case					):
									UpperCamelCase_     				= dict_multimap(__snake_case     ,		__snake_case					)
						else:
									UpperCamelCase_     				= fn(__snake_case					)

			return new_dict




def  a_		(							__snake_case     ,		__snake_case					)	->			torch.Tensor:

			'''simple docstring'''


			UpperCamelCase_     				= v_bins.view(((1,) * len(x.shape					)) + (len(__snake_case					),)					)
			UpperCamelCase_     				= x[..., None] - reshaped_bins
			UpperCamelCase_     				= torch.argmin(torch.abs(__snake_case					)     ,		dim=-1					)
			return nn.functional.one_hot(__snake_case     ,		num_classes=len(__snake_case					)					).float()




def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case = 0     ,		__snake_case = 0					)	->			torch.Tensor:

			'''simple docstring'''


			UpperCamelCase_     				= []
			for i, s in enumerate(data.shape[:no_batch_dims]					):
						UpperCamelCase_     				= torch.arange(__snake_case					)
						UpperCamelCase_     				= r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape					) - i - 1)))					)
						ranges.append(__snake_case					)

			UpperCamelCase_     				= [slice(__snake_case					) for _ in range(len(data.shape					) - no_batch_dims					)]
			UpperCamelCase_     				= inds
			ranges.extend(__snake_case					)
			# Matt note: Editing this to get around the behaviour of using a list as an array index changing
			# in recent Numpy versions
			return data[tuple(__snake_case					)]


__a			:	List[Any]							     =		TypeVar("""T""")




def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			Dict[Any, Union[dict, list, tuple, Any]]:

			'''simple docstring'''


			UpperCamelCase_     				= {}
			for k, v in dic.items():
						if isinstance(__snake_case     ,		__snake_case					):
									UpperCamelCase_     				= dict_map(__snake_case     ,		__snake_case     ,		__snake_case					)
						else:
									UpperCamelCase_     				= tree_map(__snake_case     ,		__snake_case     ,		__snake_case					)

			return new_dict




@overload
def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			Any:

			'''simple docstring'''


			...




@overload
def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			dict:

			'''simple docstring'''


			...




@overload
def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			list:

			'''simple docstring'''


			...




@overload
def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			tuple:

			'''simple docstring'''


			...




def  a_		(							__snake_case     ,		__snake_case     ,		__snake_case					)	->			Any:

			'''simple docstring'''


			if isinstance(__snake_case     ,		__snake_case					):
						return dict_map(__snake_case     ,		__snake_case     ,		__snake_case					)
			elif isinstance(__snake_case     ,		__snake_case					):
						return [tree_map(__snake_case     ,		__snake_case     ,		__snake_case					) for x in tree]
			elif isinstance(__snake_case     ,		__snake_case					):
						return tuple(tree_map(__snake_case     ,		__snake_case     ,		__snake_case					) for x in tree					)
			elif isinstance(__snake_case     ,		__snake_case					):
						return fn(__snake_case					)
			else:
						print(type(__snake_case					)					)
						raise ValueError('Not supported'					)





__a			:	Tuple							     =		partial(tree_map, leaf_type=torch.Tensor)
