



'''simple docstring'''




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





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





	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		List[str]							     =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

								UpperCAmelCase     :		List[str]							     =		self.get_config()
								return config, pixel_values, labels





	def  _lowercase(  self    )			->			Optional[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  _lowercase(  self		,		A		,		A		,		A    )			->			List[Any]:
								UpperCAmelCase     :		List[Any]							     =		TFRegNetModel(config=SCREAMING_SNAKE_CASE_    )
								UpperCAmelCase     :		List[Any]							     =		model(SCREAMING_SNAKE_CASE_		,		training=SCREAMING_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  _lowercase(  self		,		A		,		A		,		A    )			->			List[Any]:
								UpperCAmelCase     :		int							     =		self.num_labels
								UpperCAmelCase     :		int							     =		TFRegNetForImageClassification(SCREAMING_SNAKE_CASE_    )
								UpperCAmelCase     :		Dict							     =		model(SCREAMING_SNAKE_CASE_		,		labels=SCREAMING_SNAKE_CASE_		,		training=SCREAMING_SNAKE_CASE_    )
								self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.num_labels)    )






	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		str							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     :		Tuple							     =		config_and_inputs
								UpperCAmelCase     :		Optional[Any]							     =		{'pixel_values': pixel_values}
								return config, inputs_dict




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

	lowercase          = False
	lowercase          = False
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		List[Any]							     =		TFRegNetModelTester(self    )
								UpperCAmelCase     :		Tuple							     =		ConfigTester(self		,		config_class=SCREAMING_SNAKE_CASE_		,		has_text_modality=SCREAMING_SNAKE_CASE_    )





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





	@unittest.skip(reason="""RegNet does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			str:
								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  _lowercase(  self    )			->			Dict:
								super().test_keras_fit()





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





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Optional[int]							     =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		int							     =		model_class(SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		Dict							     =		inspect.signature(model.call    )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCAmelCase     :		List[Any]							     =		[*signature.parameters.keys()]

															UpperCAmelCase     :		Any							     =		['pixel_values']
															self.assertListEqual(arg_names[:1]		,		SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			Optional[Any]:
								UpperCAmelCase     :		Dict							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			str:
								def check_hidden_states_output(A		,		A		,		A    ):
															UpperCAmelCase     :		List[Any]							     =		model_class(SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		Union[str, Any]							     =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )		,		training=SCREAMING_SNAKE_CASE_    )

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

															UpperCAmelCase     :		Union[str, Any]							     =		self.model_tester.num_stages
															self.assertEqual(len(SCREAMING_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]		,		)

								UpperCAmelCase     :		List[Any]							     =		self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase     :		Optional[int]							     =		['basic', 'bottleneck']
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						UpperCAmelCase     :		str							     =		layer_type
																						UpperCAmelCase     :		List[str]							     =		True
																						check_hidden_states_output(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )

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

																						check_hidden_states_output(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		int							     =		self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(A		,		A		,		A		,		A={}    ):
															UpperCAmelCase     :		Optional[Any]							     =		model(SCREAMING_SNAKE_CASE_		,		return_dict=SCREAMING_SNAKE_CASE_		,		**SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		List[Any]							     =		model(SCREAMING_SNAKE_CASE_		,		return_dict=SCREAMING_SNAKE_CASE_		,		**SCREAMING_SNAKE_CASE_    ).to_tuple()

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

																						recursive_check(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )

								for model_class in self.all_model_classes:
															UpperCAmelCase     :		Union[str, Any]							     =		model_class(SCREAMING_SNAKE_CASE_    )

															UpperCAmelCase     :		List[Any]							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		Union[str, Any]							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )
															check_equivalence(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )

															UpperCAmelCase     :		Optional[int]							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		str							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															check_equivalence(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )

															UpperCAmelCase     :		Tuple							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		int							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_    )
															check_equivalence(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		{"""output_hidden_states""": True}    )

															UpperCAmelCase     :		List[Any]							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															UpperCAmelCase     :		Any							     =		self._prepare_for_class(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		return_labels=SCREAMING_SNAKE_CASE_    )
															check_equivalence(SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		SCREAMING_SNAKE_CASE_		,		{"""output_hidden_states""": True}    )





	def  _lowercase(  self    )			->			Any:
								UpperCAmelCase     :		List[str]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_    )






	@slow
	def  _lowercase(  self    )			->			Optional[int]:
								for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		int							     =		TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE_    )
															self.assertIsNotNone(SCREAMING_SNAKE_CASE_    )




def       __lowerCamelCase  (					)      ->			List[str]:
							UpperCAmelCase     :		Optional[Any]							     =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
							return image


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





	@cached_property
	def  _lowercase(  self    )			->			Dict:
								return (
								    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
								    if is_vision_available()
								    else None
								)






	@slow
	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		int							     =		TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

								UpperCAmelCase     :		Tuple							     =		self.default_image_processor
								UpperCAmelCase     :		Dict							     =		prepare_img()
								UpperCAmelCase     :		Union[str, Any]							     =		image_processor(images=SCREAMING_SNAKE_CASE_		,		return_tensors="""tf"""    )

								# forward pass
								UpperCAmelCase     :		List[str]							     =		model(**SCREAMING_SNAKE_CASE_		,		training=SCREAMING_SNAKE_CASE_    )

								# verify the logits
								UpperCAmelCase     :		Optional[Any]							     =		tf.TensorShape((1, 1000)    )
								self.assertEqual(outputs.logits.shape		,		SCREAMING_SNAKE_CASE_    )

								UpperCAmelCase     :		List[Any]							     =		tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]    )

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






"""simple docstring"""







from typing import List, Optional, Union

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


lowercase__		:				Union[str, Any]          =	logging.get_logger(__name__)

lowercase__		:				List[str]          =	{
    """huggingface/informer-tourism-monthly""": (
        """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"""
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}







class       UpperCamelCase__   (	lowercase_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     """informer"""
      _SCREAMING_SNAKE_CASE  				=     {
          """hidden_size""": """d_model""",
          """num_attention_heads""": """encoder_attention_heads""",
          """num_hidden_layers""": """encoder_layers""",
      }



      def __init__(      self				:      Any    ,			SCREAMING_SNAKE_CASE_				:      Optional[int] = None    ,			SCREAMING_SNAKE_CASE_				:      Optional[int] = None    ,			SCREAMING_SNAKE_CASE_				:      str = "student_t"    ,			SCREAMING_SNAKE_CASE_				:      str = "nll"    ,			SCREAMING_SNAKE_CASE_				:      int = 1    ,			SCREAMING_SNAKE_CASE_				:      List[int] = None    ,			SCREAMING_SNAKE_CASE_				:      Optional[Union[str, bool]] = "mean"    ,			SCREAMING_SNAKE_CASE_				:      int = 0    ,			SCREAMING_SNAKE_CASE_				:      int = 0    ,			SCREAMING_SNAKE_CASE_				:      int = 0    ,			SCREAMING_SNAKE_CASE_				:      int = 0    ,			SCREAMING_SNAKE_CASE_				:      Optional[List[int]] = None    ,			SCREAMING_SNAKE_CASE_				:      Optional[List[int]] = None    ,			SCREAMING_SNAKE_CASE_				:      int = 6_4    ,			SCREAMING_SNAKE_CASE_				:      int = 3_2    ,			SCREAMING_SNAKE_CASE_				:      int = 3_2    ,			SCREAMING_SNAKE_CASE_				:      int = 2    ,			SCREAMING_SNAKE_CASE_				:      int = 2    ,			SCREAMING_SNAKE_CASE_				:      int = 2    ,			SCREAMING_SNAKE_CASE_				:      int = 2    ,			SCREAMING_SNAKE_CASE_				:      bool = True    ,			SCREAMING_SNAKE_CASE_				:      str = "gelu"    ,			SCREAMING_SNAKE_CASE_				:      float = 0.05    ,			SCREAMING_SNAKE_CASE_				:      float = 0.1    ,			SCREAMING_SNAKE_CASE_				:      float = 0.1    ,			SCREAMING_SNAKE_CASE_				:      float = 0.1    ,			SCREAMING_SNAKE_CASE_				:      float = 0.1    ,			SCREAMING_SNAKE_CASE_				:      int = 1_0_0    ,			SCREAMING_SNAKE_CASE_				:      float = 0.02    ,			SCREAMING_SNAKE_CASE_				:      str=True    ,			SCREAMING_SNAKE_CASE_				:      str = "prob"    ,			SCREAMING_SNAKE_CASE_				:      int = 5    ,			SCREAMING_SNAKE_CASE_				:      bool = True    ,			**SCREAMING_SNAKE_CASE_				:      int    ,			):
        # time series specific configuration
        lowerCAmelCase_   :				Dict								= prediction_length
        lowerCAmelCase_   :				List[str]								= context_length or prediction_length
        lowerCAmelCase_   :				List[Any]								= distribution_output
        lowerCAmelCase_   :				int								= loss
        lowerCAmelCase_   :				Optional[int]								= input_size
        lowerCAmelCase_   :				Tuple								= num_time_features
        lowerCAmelCase_   :				List[str]								= lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
        lowerCAmelCase_   :				int								= scaling
        lowerCAmelCase_   :				List[Any]								= num_dynamic_real_features
        lowerCAmelCase_   :				Union[str, Any]								= num_static_real_features
        lowerCAmelCase_   :				Optional[int]								= num_static_categorical_features

        # set cardinality
        if cardinality and num_static_categorical_features > 0:
          if len(SCREAMING_SNAKE_CASE_       ) != num_static_categorical_features:
            raise ValueError(
                'The cardinality should be a list of the same length as `num_static_categorical_features`'       )
          lowerCAmelCase_   :				str								= cardinality
        else:
          lowerCAmelCase_   :				Any								= [0]

        # set embedding_dimension
        if embedding_dimension and num_static_categorical_features > 0:
          if len(SCREAMING_SNAKE_CASE_       ) != num_static_categorical_features:
            raise ValueError(
                'The embedding dimension should be a list of the same length as `num_static_categorical_features`'       )
          lowerCAmelCase_   :				Optional[int]								= embedding_dimension
        else:
          lowerCAmelCase_   :				Union[str, Any]								= [min(5_0    ,			(cat + 1) // 2       ) for cat in self.cardinality]

        lowerCAmelCase_   :				Optional[int]								= num_parallel_samples

        # Transformer architecture configuration
        lowerCAmelCase_   :				Any								= input_size * len(self.lags_sequence       ) + self._number_of_features
        lowerCAmelCase_   :				Any								= d_model
        lowerCAmelCase_   :				Union[str, Any]								= encoder_attention_heads
        lowerCAmelCase_   :				Optional[Any]								= decoder_attention_heads
        lowerCAmelCase_   :				Any								= encoder_ffn_dim
        lowerCAmelCase_   :				List[str]								= decoder_ffn_dim
        lowerCAmelCase_   :				Optional[Any]								= encoder_layers
        lowerCAmelCase_   :				Tuple								= decoder_layers

        lowerCAmelCase_   :				Optional[int]								= dropout
        lowerCAmelCase_   :				Dict								= attention_dropout
        lowerCAmelCase_   :				int								= activation_dropout
        lowerCAmelCase_   :				Dict								= encoder_layerdrop
        lowerCAmelCase_   :				str								= decoder_layerdrop

        lowerCAmelCase_   :				Union[str, Any]								= activation_function
        lowerCAmelCase_   :				Union[str, Any]								= init_std

        lowerCAmelCase_   :				Union[str, Any]								= use_cache

        # Informer
        lowerCAmelCase_   :				Optional[int]								= attention_type
        lowerCAmelCase_   :				Any								= sampling_factor
        lowerCAmelCase_   :				int								= distil

        super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE_    ,			**SCREAMING_SNAKE_CASE_       )





      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        return (
            sum(self.embedding_dimension       )
            + self.num_dynamic_real_features
            + self.num_time_features
            + self.num_static_real_features
            + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
        )





