


'''simple docstring'''
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 					__lowerCAmelCase   :

						"""simple docstring"""






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






						def 				_UpperCAmelCase       (  self							:      Any	):
													A_			    =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

													A_			    =		None
													if self.use_labels:
																				A_			    =		ids_tensor([self.batch_size] ,  self.num_labels	)

													A_			    =		self.get_config()

													return config, pixel_values, labels






						def 				_UpperCAmelCase       (  self							:      Any	):
													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 				_UpperCAmelCase       (  self							:      int ,  lowerCAmelCase							:      Tuple ,  lowerCAmelCase							:      str ,  lowerCAmelCase							:      List[str]	):
													A_			    =		RegNetModel(config=lowerCAmelCase	)
													model.to(lowerCAmelCase	)
													model.eval()
													A_			    =		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 				_UpperCAmelCase       (  self							:      Union[str, Any] ,  lowerCAmelCase							:      Dict ,  lowerCAmelCase							:      List[str] ,  lowerCAmelCase							:      Optional[int]	):
													A_			    =		self.num_labels
													A_			    =		RegNetForImageClassification(lowerCAmelCase	)
													model.to(lowerCAmelCase	)
													model.eval()
													A_			    =		model(lowerCAmelCase ,  labels=lowerCAmelCase	)
													self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels)	)






						def 				_UpperCAmelCase       (  self							:      str	):
													A_			    =		self.prepare_config_and_inputs()
													A_			    =		config_and_inputs
													A_			    =		{'pixel_values': pixel_values}
													return config, inputs_dict






@require_torch
class 					__lowerCAmelCase   (   snake_case__				,			snake_case__				,			unittest.TestCase						):

						"""simple docstring"""






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

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






						def 				_UpperCAmelCase       (  self							:      str	):
													A_			    =		RegNetModelTester(self	)
													A_			    =		ConfigTester(self ,  config_class=lowerCAmelCase ,  has_text_modality=lowerCAmelCase	)






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






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






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






						def 				_UpperCAmelCase       (  self							:      Union[str, Any]	):
													A_			    =		self.model_tester.prepare_config_and_inputs_for_common()

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

																				A_			    =		['pixel_values']
																				self.assertListEqual(arg_names[:1] ,  lowerCAmelCase	)






						def 				_UpperCAmelCase       (  self							:      Dict	):
													A_			    =		self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*lowerCAmelCase	)






						def 				_UpperCAmelCase       (  self							:      Dict	):
													A_			    =		self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				A_			    =		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							:      Optional[int]	):
													def check_hidden_states_output(lowerCAmelCase							:      List[Any] ,  lowerCAmelCase							:      Union[str, Any] ,  lowerCAmelCase							:      List[Any]	):
																				A_			    =		model_class(lowerCAmelCase	)
																				model.to(lowerCAmelCase	)
																				model.eval()

																				with torch.no_grad():
																											A_			    =		model(**self._prepare_for_class(lowerCAmelCase ,  lowerCAmelCase	)	)

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

																				A_			    =		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] ,  )

													A_			    =		self.model_tester.prepare_config_and_inputs_for_common()
													A_			    =		['basic', 'bottleneck']
													for model_class in self.all_model_classes:
																				for layer_type in layers_type:
																											A_			    =		layer_type
																											A_			    =		True
																											check_hidden_states_output(lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase	)

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

																											check_hidden_states_output(lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase	)






						def 				_UpperCAmelCase       (  self							:      Optional[Any]	):
													A_			    =		self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase	)






						@slow
						def 				_UpperCAmelCase       (  self							:      List[Any]	):
													for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A_			    =		RegNetModel.from_pretrained(lowerCAmelCase	)
																				self.assertIsNotNone(lowerCAmelCase	)







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







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

						"""simple docstring"""






						@cached_property
						def 				_UpperCAmelCase       (  self							:      Optional[int]	):
													return (
													    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
													    if is_vision_available()
													    else None
													)






						@slow
						def 				_UpperCAmelCase       (  self							:      List[str]	):
													A_			    =		RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(lowerCAmelCase	)

													A_			    =		self.default_image_processor
													A_			    =		prepare_img()
													A_			    =		image_processor(images=lowerCAmelCase ,  return_tensors="pt"	).to(lowerCAmelCase	)

													# forward pass
													with torch.no_grad():
																				A_			    =		model(**lowerCAmelCase	)

													# verify the logits
													A_			    =		torch.Size((1, 10_00)	)
													self.assertEqual(outputs.logits.shape ,  lowerCAmelCase	)

													A_			    =		torch.tensor([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]	).to(lowerCAmelCase	)

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












import os
import sys

_lowercase		:  List[str]			       =os.path.join(os.path.dirname(__file__), """src""")
sys.path.append(SRC_DIR)


from transformers import (
    AutoConfig,
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForMaskedLM,
    AutoModelForQuestionAnswering,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    add_start_docstrings,
)


_lowercase		:  Optional[int]			       =[
    """torch""",
    """numpy""",
    """tokenizers""",
    """filelock""",
    """requests""",
    """tqdm""",
    """regex""",
    """sentencepiece""",
    """sacremoses""",
    """importlib_metadata""",
    """huggingface_hub""",
]


@add_start_docstrings(AutoConfig.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoConfig.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)


@add_start_docstrings(AutoTokenizer.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoTokenizer.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)


@add_start_docstrings(AutoModel.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoModel.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)


@add_start_docstrings(AutoModelForCausalLM.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoModelForCausalLM.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)


@add_start_docstrings(AutoModelForMaskedLM.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoModelForMaskedLM.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)


@add_start_docstrings(AutoModelForSequenceClassification.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoModelForSequenceClassification.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)





@add_start_docstrings(AutoModelForQuestionAnswering.__doc__						)
def 		_SCREAMING_SNAKE_CASE     ( *lowerCAmelCase__							,**lowerCAmelCase__						):
		return AutoModelForQuestionAnswering.from_pretrained(*lowerCAmelCase__							,**lowerCAmelCase__						)
