





from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
						from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						def UpperCAmelCase_				(      self      :      List[str]	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Dict											=	self.config_class(**self.inputs_dict	)
							self.parent.assertTrue(hasattr(_A		,   'embed_dim'	)	)
							self.parent.assertTrue(hasattr(_A		,   'num_heads'	)	)
class SCREAMING_SNAKE_CASE_						:






						def __init__(      self      :      Dict		,   _A      :      Tuple		,   _A      :      Union[str, Any]=13		,   _A      :      str=64		,   _A      :      int=3		,   _A      :      Any=[16, 48, 96]		,   _A      :      str=[1, 3, 6]		,   _A      :      Optional[int]=[1, 2, 10]		,   _A      :      Any=[7, 3, 3]		,   _A      :      Dict=[4, 2, 2]		,   _A      :      Any=[2, 1, 1]		,   _A      :      str=[2, 2, 2]		,   _A      :      Any=[False, False, True]		,   _A      :      str=[0.0, 0.0, 0.0]		,   _A      :      Optional[int]=0.0_2		,   _A      :      Optional[Any]=1E-12		,   _A      :      List[str]=True		,   _A      :      Optional[int]=True		,   _A      :      List[Any]=2		,   )							->    List[str]:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	parent
							snake_case_		:			Optional[Any]											=	batch_size
							snake_case_		:			Optional[Any]											=	image_size
							snake_case_		:			Tuple											=	patch_sizes
							snake_case_		:			int											=	patch_stride
							snake_case_		:			List[Any]											=	patch_padding
							snake_case_		:			Optional[Any]											=	is_training
							snake_case_		:			int											=	use_labels
							snake_case_		:			List[str]											=	num_labels
							snake_case_		:			List[Any]											=	num_channels
							snake_case_		:			Union[str, Any]											=	embed_dim
							snake_case_		:			Union[str, Any]											=	num_heads
							snake_case_		:			Optional[int]											=	stride_kv
							snake_case_		:			int											=	depth
							snake_case_		:			str											=	cls_token
							snake_case_		:			List[str]											=	attention_drop_rate
							snake_case_		:			List[str]											=	initializer_range
							snake_case_		:			int											=	layer_norm_eps






						def UpperCAmelCase_				(      self      :      str	)							->    str:







							"""simple docstring"""


							snake_case_		:			Dict											=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

							snake_case_		:			Union[str, Any]											=	None
							if self.use_labels:
								# create a random int32 tensor of given shape
								snake_case_		:			int											=	ids_tensor([self.batch_size]		,   self.num_labels	)

							snake_case_		:			Optional[int]											=	self.get_config()
							return config, pixel_values, labels






						def UpperCAmelCase_				(      self      :      Tuple	)							->    Optional[Any]:







							"""simple docstring"""


							return CvtConfig(
							    image_size=self.image_size		,   num_labels=self.num_labels		,   num_channels=self.num_channels		,   embed_dim=self.embed_dim		,   num_heads=self.num_heads		,   patch_sizes=self.patch_sizes		,   patch_padding=self.patch_padding		,   patch_stride=self.patch_stride		,   stride_kv=self.stride_kv		,   depth=self.depth		,   cls_token=self.cls_token		,   attention_drop_rate=self.attention_drop_rate		,   initializer_range=self.initializer_range		,   )






						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      Optional[int]		,   _A      :      List[str]		,   _A      :      Dict	)							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			int											=	TFCvtModel(config=_A	)
							snake_case_		:			Union[str, Any]											=	model(_A		,   training=_A	)
							snake_case_		:			Union[str, Any]											=	(self.image_size, self.image_size)
							snake_case_						,snake_case_		:			Any											=	image_size[0], image_size[1]
							for i in range(len(self.depth	)	):
								snake_case_		:			Any											=	floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
								snake_case_		:			Any											=	floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
							self.parent.assertEqual(result.last_hidden_state.shape		,   (self.batch_size, self.embed_dim[-1], height, width)	)






						def UpperCAmelCase_				(      self      :      Dict		,   _A      :      Union[str, Any]		,   _A      :      Any		,   _A      :      Union[str, Any]	)							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			List[str]											=	self.num_labels
							snake_case_		:			Optional[int]											=	TFCvtForImageClassification(_A	)
							snake_case_		:			Optional[int]											=	model(_A		,   labels=_A		,   training=_A	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.num_labels)	)






						def UpperCAmelCase_				(      self      :      int	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			str											=	self.prepare_config_and_inputs()
							snake_case_						,snake_case_						,snake_case_		:			int											=	config_and_inputs
							snake_case_		:			str											=	{'pixel_values': pixel_values}
							return config, inputs_dict
@require_tf
class SCREAMING_SNAKE_CASE_						(					snake_case_       ,				snake_case_       ,				unittest.TestCase					):
						__magic_name__:			Any       =       (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
						__magic_name__:			Optional[Any]       =       (
						    {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
						    if is_tf_available()
						    else {}
						)
						__magic_name__:			List[str]       =       False
						__magic_name__:			List[str]       =       False
						__magic_name__:			str       =       False
						__magic_name__:			Optional[Any]       =       False
						__magic_name__:			str       =       False






						def UpperCAmelCase_				(      self      :      str	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Dict											=	TFCvtModelTester(self	)
							snake_case_		:			Dict											=	TFCvtConfigTester(self		,   config_class=_A		,   has_text_modality=_A		,   hidden_size=37	)






						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    List[str]:







							"""simple docstring"""


							self.config_tester.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()






						@unittest.skip(reason='Cvt does not output attentions'	)
						def UpperCAmelCase_				(      self      :      List[Any]	)							->    Optional[Any]:







							"""simple docstring"""


							pass






						@unittest.skip(reason='Cvt does not use inputs_embeds'	)
						def UpperCAmelCase_				(      self      :      int	)							->    Optional[int]:







							"""simple docstring"""


							pass






						@unittest.skip(reason='Cvt does not support input and output embeddings'	)
						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    Union[str, Any]:







							"""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.'		,   )
						def UpperCAmelCase_				(      self      :      Any	)							->    Tuple:







							"""simple docstring"""


							super().test_dataset_conversion()






						@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 UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Any:







							"""simple docstring"""


							super().test_keras_fit()






						@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'	)
						def UpperCAmelCase_				(      self      :      Tuple	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			Any											=	tf.keras.mixed_precision.Policy('mixed_float16'	)
							tf.keras.mixed_precision.set_global_policy(_A	)
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy('float32'	)






						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Dict:







							"""simple docstring"""


							snake_case_						,snake_case_		:			List[Any]											=	self.model_tester.prepare_config_and_inputs_for_common()

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

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






						def UpperCAmelCase_				(      self      :      Dict	)							->    Optional[Any]:







							"""simple docstring"""


							def check_hidden_states_output(_A      :      Optional[int]		,   _A      :      Union[str, Any]		,   _A      :      Optional[int]	):
								snake_case_		:			Optional[Any]											=	model_class(_A	)

								snake_case_		:			Tuple											=	model(**self._prepare_for_class(_A		,   _A	)	)
								snake_case_		:			Dict											=	outputs.hidden_states

								snake_case_		:			int											=	len(self.model_tester.depth	)
								self.assertEqual(len(_A	)		,   _A	)

								# verify the first hidden states (first block)
								self.assertListEqual(
								    list(hidden_states[0].shape[-3:]	)		,   [
								        self.model_tester.embed_dim[0],
								        self.model_tester.image_size // 4,
								        self.model_tester.image_size // 4,
								    ]		,   )

							snake_case_						,snake_case_		:			Dict											=	self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		:			List[str]											=	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_		:			str											=	True

								check_hidden_states_output(_A		,   _A		,   _A	)






						def UpperCAmelCase_				(      self      :      Dict	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A	)






						def UpperCAmelCase_				(      self      :      Dict	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A	)






						@slow
						def UpperCAmelCase_				(      self      :      Dict	)							->    Tuple:







							"""simple docstring"""


							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		:			Tuple											=	TFCvtModel.from_pretrained(_A	)
								self.assertIsNotNone(_A	)


def 							SCREAMING_SNAKE_CASE__						(    ):
	snake_case_		:			Optional[Any]											=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
	return image


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






						@cached_property
						def UpperCAmelCase_				(      self      :      Optional[Any]	)							->    Dict:







							"""simple docstring"""


							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)






						@slow
						def UpperCAmelCase_				(      self      :      Tuple	)							->    str:







							"""simple docstring"""


							snake_case_		:			Dict											=	TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

							snake_case_		:			Union[str, Any]											=	self.default_image_processor
							snake_case_		:			Optional[Any]											=	prepare_img()
							snake_case_		:			Tuple											=	image_processor(images=_A		,   return_tensors='tf'	)

							# forward pass
							snake_case_		:			List[Any]											=	model(**_A	)

							# verify the logits
							snake_case_		:			Tuple											=	tf.TensorShape((1, 1000)	)
							self.assertEqual(outputs.logits.shape		,   _A	)

							snake_case_		:			List[str]											=	tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]	)
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()		,   _A		,   atol=1E-4	)	)








def 							SCREAMING_SNAKE_CASE__						(    __a   ):
	if not isinstance(__a   , __a   ):
		raise ValueError('Input must be an integer'   )
	if input_num <= 0:
		raise ValueError('Input must be positive'   )
	return sum(
	    divisor for divisor in range(1   , input_num // 2 + 1   ) if input_num % divisor == 0   )


if __name__ == "__main__":
						import doctest

						doctest.testmod()

