






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    ,     lowerCAmelCase__    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=32    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=10    ,     lowerCAmelCase__=[10, 20, 30, 40]    ,     lowerCAmelCase__=[1, 1, 2, 1]    ,     lowerCAmelCase__=True    ,     lowerCAmelCase__=True    ,     lowerCAmelCase__="relu"    ,     lowerCAmelCase__=3    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=["stage2", "stage3", "stage4"]    ,     lowerCAmelCase__=[2, 3, 4]    ,     )							->   Optional[Any]:
							__magic_name__    :     Optional[Any]								=      parent
							__magic_name__    :     str								=      batch_size
							__magic_name__    :     List[str]								=      image_size
							__magic_name__    :     Dict								=      num_channels
							__magic_name__    :     int								=      embeddings_size
							__magic_name__    :     Any								=      hidden_sizes
							__magic_name__    :     Union[str, Any]								=      depths
							__magic_name__    :     List[Any]								=      is_training
							__magic_name__    :     Dict								=      use_labels
							__magic_name__    :     Any								=      hidden_act
							__magic_name__    :     Tuple								=      num_labels
							__magic_name__    :     List[Any]								=      scope
							__magic_name__    :     Union[str, Any]								=      len(lowerCAmelCase__				)
							__magic_name__    :     List[Any]								=      out_features
							__magic_name__    :     List[Any]								=      out_indices
	def     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     str								=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

							__magic_name__    :     Dict								=      None
							if self.use_labels:
													__magic_name__    :     List[str]								=      ids_tensor([self.batch_size]    ,     self.num_labels				)

							__magic_name__    :     Optional[Any]								=      self.get_config()

							return config, pixel_values, labels
	def     __magic_name__       (       self				)							->   str:
							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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   Tuple:
							__magic_name__    :     Any								=      ResNetModel(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Tuple								=      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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   List[str]:
							__magic_name__    :     Optional[Any]								=      self.num_labels
							__magic_name__    :     int								=      ResNetForImageClassification(lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     Dict								=      model(lowerCAmelCase__    ,     labels=lowerCAmelCase__				)
							self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)				)
	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)							->   Optional[int]:
							__magic_name__    :     Any								=      ResNetBackbone(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     List[str]								=      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__    :     Any								=      None
							__magic_name__    :     Union[str, Any]								=      ResNetBackbone(config=lowerCAmelCase__				)
							model.to(lowerCAmelCase__				)
							model.eval()
							__magic_name__    :     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     __magic_name__       (       self				)							->   Optional[Any]:
							__magic_name__    :     Union[str, Any]								=      self.prepare_config_and_inputs()
							__magic_name__    :     Tuple								=      config_and_inputs
							__magic_name__    :     List[Any]								=      {'''pixel_values''': pixel_values}
							return config, inputs_dict





@require_torch
class  snake_case__      (							A_		,						A_		,						unittest.TestCase   ):
	lowercase__		:  Union[str, Any]							   =					(
	    (
	        ResNetModel,
	        ResNetForImageClassification,
	        ResNetBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__		:  Optional[int]							   =					(
	    {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	lowercase__		:  int							   =					True
	lowercase__		:  Optional[Any]							   =					False
	lowercase__		:  Optional[int]							   =					False
	lowercase__		:  Any							   =					False
	lowercase__		:  str							   =					False
	def     __magic_name__       (       self				)							->   List[str]:
							__magic_name__    :     Union[str, Any]								=      ResNetModelTester(self				)
							__magic_name__    :     List[Any]								=      ConfigTester(self    ,     config_class=lowerCAmelCase__    ,     has_text_modality=lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Dict:
							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     __magic_name__       (       self				)							->   int:
							return
	@unittest.skip(reason="""ResNet does not use inputs_embeds"""				)
	def     __magic_name__       (       self				)							->   Tuple:
							pass
	@unittest.skip(reason="""ResNet does not support input and output embeddings"""				)
	def     __magic_name__       (       self				)							->   Optional[int]:
							pass
	def     __magic_name__       (       self				)							->   Optional[Any]:
							__magic_name__    :     Union[str, Any]								=      self.model_tester.prepare_config_and_inputs_for_common()

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

													__magic_name__    :     Any								=      ['''pixel_values''']
													self.assertListEqual(arg_names[:1]    ,     lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Tuple:
							__magic_name__    :     List[str]								=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     Any								=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   List[Any]:
							__magic_name__    :     int								=      self.model_tester.prepare_config_and_inputs_for_common()

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



							def check_hidden_states_output(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				):
													__magic_name__    :     str								=      model_class(lowerCAmelCase__				)
													model.to(lowerCAmelCase__				)
													model.eval()

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

													__magic_name__    :     Optional[int]								=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													__magic_name__    :     Dict								=      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__    :     Union[str, Any]								=      self.model_tester.prepare_config_and_inputs_for_common()
							__magic_name__    :     Union[str, Any]								=      ['''basic''', '''bottleneck''']
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			__magic_name__    :     List[Any]								=      layer_type
																			__magic_name__    :     Union[str, Any]								=      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__    :     Dict								=      True

																			check_hidden_states_output(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)
	@unittest.skip(reason="""ResNet does not use feedforward chunking"""				)
	def     __magic_name__       (       self				)							->   str:
							pass
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     Optional[Any]								=      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__				)







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



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



def 					UpperCamelCase		( ):






						"""simple docstring"""







						__magic_name__    :     List[Any]								=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
						return image





@require_torch
@require_vision
class  snake_case__      (							unittest.TestCase   ):
	@cached_property
	def     __magic_name__       (       self				)							->   Dict:
							return (
							    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
							    if is_vision_available()
							    else None
							)







	@slow
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     Any								=      ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(lowerCAmelCase__				)

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

							# forward pass
							with torch.no_grad():
													__magic_name__    :     Optional[int]								=      model(**lowerCAmelCase__				)

							# verify the logits
							__magic_name__    :     Optional[int]								=      torch.Size((1, 10_00)				)
							self.assertEqual(outputs.logits.shape    ,     lowerCAmelCase__				)

							__magic_name__    :     Optional[int]								=      torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]				).to(lowerCAmelCase__				)

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





@require_torch
class  snake_case__      (							A_		,						unittest.TestCase   ):
	lowercase__		:  List[Any]							   =					(ResNetBackbone,) if is_torch_available() else ()
	lowercase__		:  Optional[int]							   =					False
	lowercase__		:  int							   =					ResNetConfig
	def     __magic_name__       (       self				)							->   Any:
							__magic_name__    :     Optional[int]								=      ResNetModelTester(self				)








def 					UpperCamelCase		( _A				):






						"""simple docstring"""







						return 1 if input_a == 0 else 0

def 					UpperCamelCase		( ):






						"""simple docstring"""







						assert not_gate(0				) == 1
						assert not_gate(1				) == 0


if __name__ == "__main__":
		print(not_gate(0))
		print(not_gate(1))
