






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			:



				"""simple docstring"""



				def __init__(      self    :    Any			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    Union[str, Any]=3			,		UpperCamelCase__    :    List[str]=3_2			,		UpperCamelCase__    :    Optional[Any]=3			,		UpperCamelCase__    :    Tuple=1_0			,		UpperCamelCase__    :    Optional[int]=[1_0, 2_0, 3_0, 4_0]			,		UpperCamelCase__    :    Tuple=[1, 1, 2, 1]			,		UpperCamelCase__    :    int=True			,		UpperCamelCase__    :    Optional[Any]=True			,		UpperCamelCase__    :    Dict="relu"			,		UpperCamelCase__    :    Dict=3			,		UpperCamelCase__    :    Union[str, Any]=None			,		):






											'''simple docstring'''







											snake_case__	  =       parent
											snake_case__	  =       batch_size
											snake_case__	  =       image_size
											snake_case__	  =       num_channels
											snake_case__	  =       embeddings_size
											snake_case__	  =       hidden_sizes
											snake_case__	  =       depths
											snake_case__	  =       is_training
											snake_case__	  =       use_labels
											snake_case__	  =       hidden_act
											snake_case__	  =       num_labels
											snake_case__	  =       scope
											snake_case__	  =       len(_A)



				def 					__magic_name__							(      self    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

											snake_case__	  =       self.get_config()
											return config, pixel_values, labels



				def 					__magic_name__							(      self    :    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    :    Any			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       TFRegNetModel(config=_A)
											snake_case__	  =       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 // 3_2, self.image_size // 3_2)			,		)



				def 					__magic_name__							(      self    :    Union[str, Any]			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       self.num_labels
											snake_case__	  =       TFRegNetForImageClassification(_A)
											snake_case__	  =       model(_A			,		labels=_A			,		training=_A)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_labels))



				def 					__magic_name__							(      self    :    List[Any]):






											'''simple docstring'''







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


@require_tf
class    _lowerCAmelCase			(		a__     ,      a__     ,      unittest.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Any      =  (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
				_lowercase				:   Any      =  (
				    {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
				    if is_tf_available()
				    else {}
				)

				_lowercase				:   Optional[int]      =  False
				_lowercase				:   int      =  False
				_lowercase				:   Optional[Any]      =  False
				_lowercase				:   List[Any]      =  False
				_lowercase				:   Tuple      =  False



				def 					__magic_name__							(      self    :    str):






											'''simple docstring'''







											snake_case__	  =       TFRegNetModelTester(self)
											snake_case__	  =       ConfigTester(self			,		config_class=_A			,		has_text_modality=_A)



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											return



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






											'''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    :    int):






											'''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    :    Optional[Any]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs_for_common()

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

																		snake_case__	  =       ['pixel_values']
																		self.assertListEqual(arg_names[:1]			,		_A)



				def 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_A)



				def 					__magic_name__							(      self    :    str):






											'''simple docstring'''







											def check_hidden_states_output(UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    Optional[Any]):
																		snake_case__	  =       model_class(_A)
																		snake_case__	  =       model(**self._prepare_for_class(_A			,		_A)			,		training=_A)

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

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

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

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

																									check_hidden_states_output(_A			,		_A			,		_A)



				def 					__magic_name__							(      self    :    Optional[int]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs_for_common()

											def check_equivalence(UpperCamelCase__    :    int			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    Optional[int]={}):
																		snake_case__	  =       model(_A			,		return_dict=_A			,		**_A)
																		snake_case__	  =       model(_A			,		return_dict=_A			,		**_A).to_tuple()

																		def recursive_check(UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Tuple):
																									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:
																		snake_case__	  =       model_class(_A)

																		snake_case__	  =       self._prepare_for_class(_A			,		_A)
																		snake_case__	  =       self._prepare_for_class(_A			,		_A)
																		check_equivalence(_A			,		_A			,		_A)

																		snake_case__	  =       self._prepare_for_class(_A			,		_A			,		return_labels=_A)
																		snake_case__	  =       self._prepare_for_class(_A			,		_A			,		return_labels=_A)
																		check_equivalence(_A			,		_A			,		_A)

																		snake_case__	  =       self._prepare_for_class(_A			,		_A)
																		snake_case__	  =       self._prepare_for_class(_A			,		_A)
																		check_equivalence(_A			,		_A			,		_A			,		{"""output_hidden_states""": True})

																		snake_case__	  =       self._prepare_for_class(_A			,		_A			,		return_labels=_A)
																		snake_case__	  =       self._prepare_for_class(_A			,		_A			,		return_labels=_A)
																		check_equivalence(_A			,		_A			,		_A			,		{"""output_hidden_states""": True})



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_A)



				@slow
				def 					__magic_name__							(      self    :    Optional[int]):






											'''simple docstring'''







											for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		snake_case__	  =       TFRegNetModel.from_pretrained(_A)
																		self.assertIsNotNone(_A)


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



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



				"""simple docstring"""



				@cached_property
				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







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



				@slow
				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

											snake_case__	  =       self.default_image_processor
											snake_case__	  =       prepare_img()
											snake_case__	  =       image_processor(images=_A			,		return_tensors="""tf""")

											# forward pass
											snake_case__	  =       model(**_A			,		training=_A)

											# verify the logits
											snake_case__	  =       tf.TensorShape((1, 1_0_0_0))
											self.assertEqual(outputs.logits.shape			,		_A)

											snake_case__	  =       tf.constant([-0.41_80, -1.50_51, -3.48_36])

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








def _UpperCAmelCase   (	a						:	int  ,					a						:	Optional[Any] ):
							# "extended trapezoidal rule"
							# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
							snake_case__	  =       (boundary[1] - boundary[0]) / steps
							snake_case__	  =       boundary[0]
							snake_case__	  =       boundary[1]
							snake_case__	  =       make_points(a  ,					a  ,					a )
							snake_case__	  =       0.0
							y += (h / 2.0) * f(a )
							for i in x_i:
														# print(i)
														y += h * f(a )
							y += (h / 2.0) * f(a )
							return y

def _UpperCAmelCase   (	a						:	Dict  ,					a						:	Union[str, Any]  ,					a						:	Union[str, Any] ):
							snake_case__	  =       a + h
							while x < (b - h):
														yield x
														snake_case__	  =       x + h

def _UpperCAmelCase   (	a						:	Any ):  # enter your function here
							snake_case__	  =       (x - 0) * (x - 0)
							return y

def _UpperCAmelCase   (	):
							snake_case__	  =       0.0  # Lower bound of integration
							snake_case__	  =       1.0  # Upper bound of integration
							snake_case__	  =       10.0  # define number of steps or resolution
							snake_case__	  =       [a, b]  # define boundary of integration
							snake_case__	  =       method_a(a  ,					a )
							print(F'''y = {y}''' )


if __name__ == "__main__":
	main()
