

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor






class 	__magic_name__    :





			def __init__(		self					,  __snake_case					,  __snake_case=3					,  __snake_case=32					,  __snake_case=3					,  __snake_case=10					,  __snake_case=[10, 20, 30, 40]					,  __snake_case=[1, 1, 2, 1]					,  __snake_case=True					,  __snake_case=True					,  __snake_case="relu"					,  __snake_case=3					,  __snake_case=None					,  )   -> Tuple:




						'''simple docstring'''
						__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(__snake_case					)





			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						__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 		__magic_name__    (		self					)   -> List[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 		__magic_name__    (		self					,  __snake_case					,  __snake_case					,  __snake_case					)   -> Optional[int]:




						'''simple docstring'''
						__a        =TFRegNetModel(config=__snake_case					)
						__a        =model(__snake_case					,  training=__snake_case					)
						# 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					,  __snake_case					,  __snake_case					,  __snake_case					)   -> int:




						'''simple docstring'''
						__a        =self.num_labels
						__a        =TFRegNetForImageClassification(__snake_case					)
						__a        =model(__snake_case					,  labels=__snake_case					,  training=__snake_case					)
						self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels)					)





			def 		__magic_name__    (		self					)   -> Dict:




						'''simple docstring'''
						__a        =self.prepare_config_and_inputs()
						__a      ,    __a      ,    __a        =config_and_inputs
						__a        ={'pixel_values': pixel_values}
						return config, inputs_dict






@require_tf
class 	__magic_name__    (			lowerCAmelCase_  ,    lowerCAmelCase_  ,    unittest.TestCase      ):
			SCREAMING_SNAKE_CASE							   =						(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
			SCREAMING_SNAKE_CASE							   =						(
			    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False





			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''
						__a        =TFRegNetModelTester(self					)
						__a        =ConfigTester(self					,  config_class=__snake_case					,  has_text_modality=__snake_case					)





			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''
						return





			@unittest.skip(reason='RegNet does not use inputs_embeds'					)
			def 		__magic_name__    (		self					)   -> Dict:




						'''simple docstring'''
						pass





			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('GPU'					)					) == 0					,  reason='TF does not support backprop for grouped convolutions on CPU.'					,  )
			@slow
			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''
						super().test_keras_fit()





			@unittest.skip(reason='RegNet does not support input and output embeddings'					)
			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''
						pass





			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()

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

									__a        =['pixel_values']
									self.assertListEqual(arg_names[:1]					,  __snake_case					)





			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						__a        =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__snake_case					)





			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						def check_hidden_states_output(__snake_case					,  __snake_case					,  __snake_case					):
									__a        =model_class(__snake_case					)
									__a        =model(**self._prepare_for_class(__snake_case					,  __snake_case					)					,  training=__snake_case					)

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

									__a        =self.model_tester.num_stages
									self.assertEqual(len(__snake_case					)					,  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      ,    __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(__snake_case					,  __snake_case					,  __snake_case					)

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

												check_hidden_states_output(__snake_case					,  __snake_case					,  __snake_case					)





			def 		__magic_name__    (		self					)   -> int:




						'''simple docstring'''
						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()

						def check_equivalence(__snake_case					,  __snake_case					,  __snake_case					,  __snake_case={}					):
									__a        =model(__snake_case					,  return_dict=__snake_case					,  **__snake_case					)
									__a        =model(__snake_case					,  return_dict=__snake_case					,  **__snake_case					).to_tuple()

									def recursive_check(__snake_case					,  __snake_case					):
												if isinstance(__snake_case					,  (List, Tuple)					):
															for tuple_iterable_value, dict_iterable_value in zip(__snake_case					,  __snake_case					):
																		recursive_check(__snake_case					,  __snake_case					)
												elif tuple_object is None:
															return
												else:
															self.assertTrue(
															    all(tf.equal(__snake_case					,  __snake_case					)					)					,  msg=(
															        'Tuple and dict output are not equal. Difference:'
															        f' {tf.math.reduce_max(tf.abs(tuple_object - dict_object					)					)}'
															    )					,  )

												recursive_check(__snake_case					,  __snake_case					)

						for model_class in self.all_model_classes:
									__a        =model_class(__snake_case					)

									__a        =self._prepare_for_class(__snake_case					,  __snake_case					)
									__a        =self._prepare_for_class(__snake_case					,  __snake_case					)
									check_equivalence(__snake_case					,  __snake_case					,  __snake_case					)

									__a        =self._prepare_for_class(__snake_case					,  __snake_case					,  return_labels=__snake_case					)
									__a        =self._prepare_for_class(__snake_case					,  __snake_case					,  return_labels=__snake_case					)
									check_equivalence(__snake_case					,  __snake_case					,  __snake_case					)

									__a        =self._prepare_for_class(__snake_case					,  __snake_case					)
									__a        =self._prepare_for_class(__snake_case					,  __snake_case					)
									check_equivalence(__snake_case					,  __snake_case					,  __snake_case					,  {'output_hidden_states': True}					)

									__a        =self._prepare_for_class(__snake_case					,  __snake_case					,  return_labels=__snake_case					)
									__a        =self._prepare_for_class(__snake_case					,  __snake_case					,  return_labels=__snake_case					)
									check_equivalence(__snake_case					,  __snake_case					,  __snake_case					,  {'output_hidden_states': True}					)





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




						'''simple docstring'''
						__a        =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__snake_case					)





			@slow
			def 		__magic_name__    (		self					)   -> str:




						'''simple docstring'''
						for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__a        =TFRegNetModel.from_pretrained(__snake_case					)
									self.assertIsNotNone(__snake_case					)






def        UpperCamelCase_(							):




			"""simple docstring"""






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






@require_tf
@require_vision
class 	__magic_name__    (			unittest.TestCase      ):





			@cached_property
			def 		__magic_name__    (		self					)   -> int:




						'''simple docstring'''
						return (
						    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
						    if is_vision_available()
						    else None
						)





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




						'''simple docstring'''
						__a        =TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

						__a        =self.default_image_processor
						__a        =prepare_img()
						__a        =image_processor(images=__snake_case					,  return_tensors='tf'					)

						# forward pass
						__a        =model(**__snake_case					,  training=__snake_case					)

						# verify the logits
						__a        =tf.TensorShape((1, 1000)					)
						self.assertEqual(outputs.logits.shape					,  __snake_case					)

						__a        =tf.constant([-0.4180, -1.5051, -3.4836]					)

						tf.debugging.assert_near(outputs.logits[0, :3]					,  __snake_case					,  atol=1e-4					)









from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase					:			Tuple  				=			logging.get_logger(__name__)

_lowerCAmelCase					:			Union[str, Any]  				=			{"ctrl": "https://huggingface.co/ctrl/resolve/main/config.json"}






class 	__magic_name__    (			lowerCAmelCase_      ):
			SCREAMING_SNAKE_CASE							   =						'ctrl'
			SCREAMING_SNAKE_CASE							   =						['past_key_values']
			SCREAMING_SNAKE_CASE							   =						{
			    'max_position_embeddings': 'n_positions',
			    'hidden_size': 'n_embd',
			    'num_attention_heads': 'n_head',
			    'num_hidden_layers': 'n_layer',
			}





			def __init__(		self					,  __snake_case=24_6534					,  __snake_case=256					,  __snake_case=1280					,  __snake_case=8192					,  __snake_case=48					,  __snake_case=16					,  __snake_case=0.1					,  __snake_case=0.1					,  __snake_case=1e-6					,  __snake_case=0.02					,  __snake_case=True					,  **__snake_case					,  )   -> Union[str, Any]:




						'''simple docstring'''
						__a        =vocab_size
						__a        =n_positions
						__a        =n_embd
						__a        =n_layer
						__a        =n_head
						__a        =dff
						__a        =resid_pdrop
						__a        =embd_pdrop
						__a        =layer_norm_epsilon
						__a        =initializer_range

						__a        =use_cache

						super().__init__(**__snake_case					)






