

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




			"""simple docstring"""







			def __init__( self  :     str   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Optional[Any]=3   ,						lowerCAmelCase__  :     Any=32   ,						lowerCAmelCase__  :     List[Any]=3   ,						lowerCAmelCase__  :     int=10   ,						lowerCAmelCase__  :     str=[10, 20, 30, 40]   ,						lowerCAmelCase__  :     Tuple=[1, 1, 2, 1]   ,						lowerCAmelCase__  :     List[str]=True   ,						lowerCAmelCase__  :     List[Any]=True   ,						lowerCAmelCase__  :     int="relu"   ,						lowerCAmelCase__  :     List[str]=3   ,						lowerCAmelCase__  :     Dict=None   ,						):
									SCREAMING_SNAKE_CASE_: Any  		=       parent
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       batch_size
									SCREAMING_SNAKE_CASE_: str  		=       image_size
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       num_channels
									SCREAMING_SNAKE_CASE_: List[str]  		=       embeddings_size
									SCREAMING_SNAKE_CASE_: str  		=       hidden_sizes
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       depths
									SCREAMING_SNAKE_CASE_: Tuple  		=       is_training
									SCREAMING_SNAKE_CASE_: Dict  		=       use_labels
									SCREAMING_SNAKE_CASE_: List[str]  		=       hidden_act
									SCREAMING_SNAKE_CASE_: Dict  		=       num_labels
									SCREAMING_SNAKE_CASE_: str  		=       scope
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       len(lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       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        _SCREAMING_SNAKE_CASE			( self  :     str):
									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  :     int   ,						lowerCAmelCase__  :     Any   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       RegNetModel(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: List[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 // 32, self.image_size // 32)   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple   ,						lowerCAmelCase__  :     str   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Dict  		=       self.num_labels
									SCREAMING_SNAKE_CASE_: List[str]  		=       RegNetForImageClassification(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: Any  		=       model(lowerCAmelCase__   ,						labels=lowerCAmelCase__)
									self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.num_labels))




			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       config_and_inputs
									SCREAMING_SNAKE_CASE_: Any  		=       {"pixel_values": pixel_values}
									return config, inputs_dict







@require_torch
class   __lowercase				( UpperCAmelCase_		,       UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							str										=     (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
			_UpperCAmelCase   :							int										=     (
			    {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			_UpperCAmelCase   :							Dict										=     False
			_UpperCAmelCase   :							str										=     False
			_UpperCAmelCase   :							List[Any]										=     False
			_UpperCAmelCase   :							List[Any]										=     False



			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       RegNetModelTester(self)
									SCREAMING_SNAKE_CASE_: Dict  		=       ConfigTester(self   ,						config_class=lowerCAmelCase__   ,						has_text_modality=lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									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  :     Any):
									return



			@unittest.skip(reason="RegNet does not use inputs_embeds")
			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									pass



			@unittest.skip(reason="RegNet does not support input and output embeddings")
			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       self.model_tester.prepare_config_and_inputs_for_common()

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

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



			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									SCREAMING_SNAKE_CASE_: int  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_: Optional[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        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									def check_hidden_states_output(lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Optional[int]):
															SCREAMING_SNAKE_CASE_: Tuple  		=       model_class(lowerCAmelCase__)
															model.to(lowerCAmelCase__)
															model.eval()

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

															SCREAMING_SNAKE_CASE_: Tuple  		=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															SCREAMING_SNAKE_CASE_: List[Any]  		=       self.model_tester.num_stages
															self.assertEqual(len(lowerCAmelCase__)   ,						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]   ,						)

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

																					check_hidden_states_output(lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__)




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       RegNetModel.from_pretrained(lowerCAmelCase__)
															self.assertIsNotNone(lowerCAmelCase__)







def 			A_      (    ):
						SCREAMING_SNAKE_CASE_: str  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
						return image



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




			"""simple docstring"""







			@cached_property
			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									return (
									    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
									    if is_vision_available()
									    else None
									)




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.default_image_processor
									SCREAMING_SNAKE_CASE_: Any  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: 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_: Union[str, Any]  		=       torch.Size((1, 1000))
									self.assertEqual(outputs.logits.shape   ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: int  		=       torch.tensor([-0.4180, -1.5051, -3.4836]).to(lowerCAmelCase__)

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









from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
						if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")):
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline
else:
						from .pipeline_unclip import UnCLIPPipeline
						from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline
						from .text_proj import UnCLIPTextProjModel






