





import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
					from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor



class      _SCREAMING_SNAKE_CASE		:







	'''simple docstring'''

	def __init__(self       :     Optional[int] ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Tuple=3 ,				UpperCAmelCase_       :     Any=32 ,				UpperCAmelCase_       :     Optional[Any]=3 ,				UpperCAmelCase_       :     str=10 ,				UpperCAmelCase_       :     Any=[10, 20, 30, 40] ,				UpperCAmelCase_       :     str=[1, 1, 2, 1] ,				UpperCAmelCase_       :     Tuple=True ,				UpperCAmelCase_       :     Union[str, Any]=True ,				UpperCAmelCase_       :     List[str]="relu" ,				UpperCAmelCase_       :     Optional[Any]=3 ,				UpperCAmelCase_       :     Dict=None ,				) ->Optional[Any]:



			'''simple docstring'''



			lowerCamelCase__:   List[str]    						=parent
			lowerCamelCase__:   Tuple    						=batch_size
			lowerCamelCase__:   Optional[Any]    						=image_size
			lowerCamelCase__:   Any    						=num_channels
			lowerCamelCase__:   Tuple    						=embeddings_size
			lowerCamelCase__:   Union[str, Any]    						=hidden_sizes
			lowerCamelCase__:   str    						=depths
			lowerCamelCase__:   List[Any]    						=is_training
			lowerCamelCase__:   List[Any]    						=use_labels
			lowerCamelCase__:   Optional[int]    						=hidden_act
			lowerCamelCase__:   Any    						=num_labels
			lowerCamelCase__:   Union[str, Any]    						=scope
			lowerCamelCase__:   int    						=len(UpperCAmelCase_)

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Any:



			'''simple docstring'''



			lowerCamelCase__:   int    						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

			lowerCamelCase__:   str    						=self.get_config()

			return config, pixel_values, labels

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



			'''simple docstring'''



			return RegNetConfig(
			    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 ,				)

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any] ,				UpperCAmelCase_       :     List[Any] ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Dict) ->int:



			'''simple docstring'''



			lowerCamelCase__:   Tuple    						=RegNetModel(config=UpperCAmelCase_)
			model.to(UpperCAmelCase_)
			model.eval()
			lowerCamelCase__:   List[Any]    						=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 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int] ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     str ,				UpperCAmelCase_       :     Any) ->List[Any]:



			'''simple docstring'''



			lowerCamelCase__:   List[str]    						=self.num_labels
			lowerCamelCase__:   int    						=RegNetForImageClassification(UpperCAmelCase_)
			model.to(UpperCAmelCase_)
			model.eval()
			lowerCamelCase__:   List[str]    						=model(UpperCAmelCase_ ,				labels=UpperCAmelCase_)
			self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels))







	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->Tuple:



			'''simple docstring'''



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



@require_torch
class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							unittest.TestCase					):







	'''simple docstring'''
	lowercase_	=    (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
	lowercase_	=    (
	    {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	lowercase_	=    False
	lowercase_	=    False
	lowercase_	=    False
	lowercase_	=    False

	def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->Any:



			'''simple docstring'''



			lowerCamelCase__:   Optional[int]    						=RegNetModelTester(self)
			lowerCamelCase__:   str    						=ConfigTester(self ,				config_class=UpperCAmelCase_ ,				has_text_modality=UpperCAmelCase_)

	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[Any]) ->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 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->List[str]:



			'''simple docstring'''



			return

	@unittest.skip(reason="RegNet does not use inputs_embeds")
	def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Any:



			'''simple docstring'''



			pass

	@unittest.skip(reason="RegNet does not support input and output embeddings")
	def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->List[Any]:



			'''simple docstring'''



			pass

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->List[str]:



			'''simple docstring'''



			lowerCamelCase__:   Optional[Any]    						=self.model_tester.prepare_config_and_inputs_for_common()

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

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

	def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->Any:



			'''simple docstring'''



			lowerCamelCase__:   Optional[int]    						=self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*UpperCAmelCase_)

	def 							SCREAMING_SNAKE_CASE_      (self       :     List[str]) ->Any:



			'''simple docstring'''



			lowerCamelCase__:   Optional[Any]    						=self.model_tester.prepare_config_and_inputs_for_common()

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



			'''simple docstring'''



			def check_hidden_states_output(UpperCAmelCase_       :     Union[str, Any] ,				UpperCAmelCase_       :     List[str] ,				UpperCAmelCase_       :     Dict):
					lowerCamelCase__:   Tuple    						=model_class(UpperCAmelCase_)
					model.to(UpperCAmelCase_)
					model.eval()

					with torch.no_grad():
							lowerCamelCase__:   List[str]    						=model(**self._prepare_for_class(UpperCAmelCase_ ,				UpperCAmelCase_))

					lowerCamelCase__:   List[str]    						=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

					lowerCamelCase__:   Optional[int]    						=self.model_tester.num_stages
					self.assertEqual(len(UpperCAmelCase_) ,				expected_num_stages + 1)

					# RegNet'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 // 2, self.model_tester.image_size // 2] ,				)

			lowerCamelCase__:   Tuple    						=self.model_tester.prepare_config_and_inputs_for_common()
			lowerCamelCase__:   Any    						=["basic", "bottleneck"]
			for model_class in self.all_model_classes:
					for layer_type in layers_type:
							lowerCamelCase__:   Any    						=layer_type
							lowerCamelCase__:   int    						=True
							check_hidden_states_output(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

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

							check_hidden_states_output(UpperCAmelCase_ ,				UpperCAmelCase_ ,				UpperCAmelCase_)

	def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->List[str]:



			'''simple docstring'''



			lowerCamelCase__:   Any    						=self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)







	@slow
	def 							SCREAMING_SNAKE_CASE_      (self       :     str) ->int:



			'''simple docstring'''



			for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					lowerCamelCase__:   Union[str, Any]    						=RegNetModel.from_pretrained(UpperCAmelCase_)
					self.assertIsNotNone(UpperCAmelCase_)





def   lowerCAmelCase_				( )  ->	Dict:







		"""simple docstring"""





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






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







	'''simple docstring'''

	@cached_property
	def 							SCREAMING_SNAKE_CASE_      (self       :     int) ->Tuple:



			'''simple docstring'''



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







	@slow
	def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->List[Any]:



			'''simple docstring'''



			lowerCamelCase__:   Dict    						=RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(UpperCAmelCase_)

			lowerCamelCase__:   Tuple    						=self.default_image_processor
			lowerCamelCase__:   str    						=prepare_img()
			lowerCamelCase__:   List[str]    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

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

			# verify the logits
			lowerCamelCase__:   Union[str, Any]    						=torch.Size((1, 1_000))
			self.assertEqual(outputs.logits.shape ,				UpperCAmelCase_)

			lowerCamelCase__:   Any    						=torch.tensor([-0.4180, -1.5051, -3.4836]).to(UpperCAmelCase_)

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








import os
import sys
import unittest


__A             =       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import get_test_info  # noqa: E402
from get_test_info import (  # noqa: E402
    get_model_to_test_mapping,
    get_model_to_tester_mapping,
    get_test_to_tester_mapping,
)


__A             =       os.path.join("tests", "models", "bert", "test_modeling_bert.py")
__A             =       os.path.join("tests", "models", "blip", "test_modeling_blip.py")



class      _SCREAMING_SNAKE_CASE		(			unittest.TestCase					):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->str:



   '''simple docstring'''



   lowerCamelCase__:   List[str]    						=get_test_to_tester_mapping(UpperCAmelCase_)
   lowerCamelCase__:   List[str]    						=get_test_to_tester_mapping(UpperCAmelCase_)

   lowerCamelCase__:   List[Any]    						={"BertModelTest": "BertModelTester"}

   lowerCamelCase__:   Optional[int]    						={
       "BlipModelTest": "BlipModelTester",
       "BlipTextImageModelTest": "BlipTextImageModelsModelTester",
       "BlipTextModelTest": "BlipTextModelTester",
       "BlipTextRetrievalModelTest": "BlipTextRetrievalModelTester",
       "BlipVQAModelTest": "BlipVQAModelTester",
       "BlipVisionModelTest": "BlipVisionModelTester",
   }

   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)
   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[Any]) ->str:



   '''simple docstring'''



   lowerCamelCase__:   str    						=get_model_to_test_mapping(UpperCAmelCase_)
   lowerCamelCase__:   int    						=get_model_to_test_mapping(UpperCAmelCase_)

   lowerCamelCase__:   Tuple    						={
       "BertForMaskedLM": ["BertModelTest"],
       "BertForMultipleChoice": ["BertModelTest"],
       "BertForNextSentencePrediction": ["BertModelTest"],
       "BertForPreTraining": ["BertModelTest"],
       "BertForQuestionAnswering": ["BertModelTest"],
       "BertForSequenceClassification": ["BertModelTest"],
       "BertForTokenClassification": ["BertModelTest"],
       "BertLMHeadModel": ["BertModelTest"],
       "BertModel": ["BertModelTest"],
   }

   lowerCamelCase__:   Any    						={
       "BlipForConditionalGeneration": ["BlipTextImageModelTest"],
       "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTest"],
       "BlipForQuestionAnswering": ["BlipVQAModelTest"],
       "BlipModel": ["BlipModelTest"],
       "BlipTextModel": ["BlipTextModelTest"],
       "BlipVisionModel": ["BlipVisionModelTest"],
   }

   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)
   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)







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



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=get_model_to_tester_mapping(UpperCAmelCase_)
   lowerCamelCase__:   Optional[Any]    						=get_model_to_tester_mapping(UpperCAmelCase_)

   lowerCamelCase__:   Any    						={
       "BertForMaskedLM": ["BertModelTester"],
       "BertForMultipleChoice": ["BertModelTester"],
       "BertForNextSentencePrediction": ["BertModelTester"],
       "BertForPreTraining": ["BertModelTester"],
       "BertForQuestionAnswering": ["BertModelTester"],
       "BertForSequenceClassification": ["BertModelTester"],
       "BertForTokenClassification": ["BertModelTester"],
       "BertLMHeadModel": ["BertModelTester"],
       "BertModel": ["BertModelTester"],
   }

   lowerCamelCase__:   Optional[Any]    						={
       "BlipForConditionalGeneration": ["BlipTextImageModelsModelTester"],
       "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTester"],
       "BlipForQuestionAnswering": ["BlipVQAModelTester"],
       "BlipModel": ["BlipModelTester"],
       "BlipTextModel": ["BlipTextModelTester"],
       "BlipVisionModel": ["BlipVisionModelTester"],
   }

   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)
   self.assertEqual(get_test_info.to_json(UpperCAmelCase_) ,				UpperCAmelCase_)

