

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




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




	def        lowerCAmelCase_       (     self						:     Dict							):
		__A :			int		    =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

		__A :			Optional[Any]		    =			None
		if self.use_labels:
			__A :			List[Any]		    =			ids_tensor([self.batch_size]					,      self.num_labels							)

		__A :			int		    =			self.get_config()
		return config, pixel_values, labels




	def        lowerCAmelCase_       (     self						:     int							):
		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        lowerCAmelCase_       (     self						:     str					,      __A						:     Optional[Any]					,      __A						:     Tuple					,      __A						:     List[str]							):
		__A :			List[Any]		    =			TFRegNetModel(config=__A							)
		__A :			int		    =			model(__A					,      training=__A							)
		# 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        lowerCAmelCase_       (     self						:     Dict					,      __A						:     str					,      __A						:     Tuple					,      __A						:     List[Any]							):
		__A :			Optional[Any]		    =			self.num_labels
		__A :			Optional[int]		    =			TFRegNetForImageClassification(__A							)
		__A :			List[Any]		    =			model(__A					,      labels=__A					,      training=__A							)
		self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)							)




	def        lowerCAmelCase_       (     self						:     str							):
		__A :			int		    =			self.prepare_config_and_inputs()
		__A    ,				__A    ,				__A :			List[Any]		    =			config_and_inputs
		__A :			str		    =			{"""pixel_values""": pixel_values}
		return config, inputs_dict






@require_tf
class      lowerCamelCase_      (	_lowercase						,      _lowercase						,      unittest.TestCase	):
	_lowercase		:   Optional[Any]     					=				(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
	_lowercase		:   Tuple     					=				(
	    {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	_lowercase		:   Union[str, Any]     					=				False
	_lowercase		:   Any     					=				False
	_lowercase		:   Optional[int]     					=				False
	_lowercase		:   Optional[Any]     					=				False
	_lowercase		:   Union[str, Any]     					=				False




	def        lowerCAmelCase_       (     self						:     Dict							):
		__A :			Tuple		    =			TFRegNetModelTester(self							)
		__A :			int		    =			ConfigTester(self					,      config_class=__A					,      has_text_modality=__A							)




	def        lowerCAmelCase_       (     self						:     List[str]							):
		return




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




	@unittest.skip(reason="""RegNet does not support input and output embeddings"""							)
	def        lowerCAmelCase_       (     self						:     Optional[int]							):
		pass




	def        lowerCAmelCase_       (     self						:     str							):
		__A    ,				__A :			Union[str, Any]		    =			self.model_tester.prepare_config_and_inputs_for_common()

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

			__A :			Any		    =			["""pixel_values"""]
			self.assertListEqual(arg_names[:1]					,      __A							)




	def        lowerCAmelCase_       (     self						:     Any							):
		__A :			Any		    =			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*__A							)




	def        lowerCAmelCase_       (     self						:     List[str]							):
		def check_hidden_states_output(__A						:     Optional[int]					,      __A						:     str					,      __A						:     str							):
			__A :			Tuple		    =			model_class(__A							)
			__A :			List[str]		    =			model(**self._prepare_for_class(__A					,      __A							)					,      training=__A							)

			__A :			List[Any]		    =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

			__A :			int		    =			self.model_tester.num_stages
			self.assertEqual(len(__A							)					,      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 :			List[Any]		    =			self.model_tester.prepare_config_and_inputs_for_common()
		__A :			List[Any]		    =			["""basic""", """bottleneck"""]
		for model_class in self.all_model_classes:
			for layer_type in layers_type:
				__A :			List[Any]		    =			layer_type
				__A :			Optional[int]		    =			True
				check_hidden_states_output(__A					,      __A					,      __A							)

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

				check_hidden_states_output(__A					,      __A					,      __A							)




	def        lowerCAmelCase_       (     self						:     Dict							):
		__A    ,				__A :			Any		    =			self.model_tester.prepare_config_and_inputs_for_common()

		def check_equivalence(__A						:     int					,      __A						:     Any					,      __A						:     List[Any]					,      __A						:     Any={}							):
			__A :			List[str]		    =			model(__A					,      return_dict=__A					,      **__A							)
			__A :			Tuple		    =			model(__A					,      return_dict=__A					,      **__A							).to_tuple()

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

				recursive_check(__A					,      __A							)

		for model_class in self.all_model_classes:
			__A :			Optional[int]		    =			model_class(__A							)

			__A :			Optional[Any]		    =			self._prepare_for_class(__A					,      __A							)
			__A :			Tuple		    =			self._prepare_for_class(__A					,      __A							)
			check_equivalence(__A					,      __A					,      __A							)

			__A :			Dict		    =			self._prepare_for_class(__A					,      __A					,      return_labels=__A							)
			__A :			List[Any]		    =			self._prepare_for_class(__A					,      __A					,      return_labels=__A							)
			check_equivalence(__A					,      __A					,      __A							)

			__A :			int		    =			self._prepare_for_class(__A					,      __A							)
			__A :			Optional[int]		    =			self._prepare_for_class(__A					,      __A							)
			check_equivalence(__A					,      __A					,      __A					,      {"""output_hidden_states""": True}							)

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




	def        lowerCAmelCase_       (     self						:     List[str]							):
		__A :			Union[str, Any]		    =			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*__A							)




	@slow
	def        lowerCAmelCase_       (     self						:     int							):
		for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__A :			List[str]		    =			TFRegNetModel.from_pretrained(__A							)
			self.assertIsNotNone(__A							)






def 							__SCREAMING_SNAKE_CASE     (   )					->				List[str]:
	__A :			Dict		    =			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
	return image







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




	@cached_property
	def        lowerCAmelCase_       (     self						:     Union[str, Any]							):
		return (
		    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
		    if is_vision_available()
		    else None
		)




	@slow
	def        lowerCAmelCase_       (     self						:     str							):
		__A :			Union[str, Any]		    =			TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

		__A :			Tuple		    =			self.default_image_processor
		__A :			str		    =			prepare_img()
		__A :			Optional[int]		    =			image_processor(images=__A					,      return_tensors="""tf"""							)

		# forward pass
		__A :			Any		    =			model(**__A					,      training=__A							)

		# verify the logits
		__A :			List[str]		    =			tf.TensorShape((1, 1000)							)
		self.assertEqual(outputs.logits.shape					,      __A							)

		__A :			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]					,      __A					,      atol=1e-4							)








from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCAmelCase_							:					int		 =   {
    '''configuration_informer''': [
        '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''InformerConfig''',
    ],
}

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			UpperCAmelCase_							:					List[str]		 =   [
			    '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
			    '''InformerForPrediction''',
			    '''InformerModel''',
			    '''InformerPreTrainedModel''',
			]


if TYPE_CHECKING:
			from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_informer import (
						    INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
						    InformerForPrediction,
						    InformerModel,
						    InformerPreTrainedModel,
						)

else:
			import sys

			UpperCAmelCase_							:					Optional[int]		 =   _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





