


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 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






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




							"""simple docstring"""


							lowercase__					      =		self.config_class(**self.inputs_dict		)
							self.parent.assertTrue(hasattr(_UpperCAmelCase				, """embed_dim"""		)		)
							self.parent.assertTrue(hasattr(_UpperCAmelCase				, """num_heads"""		)		)






class 							A   :
					'''simple docstring'''






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




							"""simple docstring"""


							lowercase__					      =		parent
							lowercase__					      =		batch_size
							lowercase__					      =		image_size
							lowercase__					      =		patch_sizes
							lowercase__					      =		patch_stride
							lowercase__					      =		patch_padding
							lowercase__					      =		is_training
							lowercase__					      =		use_labels
							lowercase__					      =		num_labels
							lowercase__					      =		num_channels
							lowercase__					      =		embed_dim
							lowercase__					      =		num_heads
							lowercase__					      =		stride_kv
							lowercase__					      =		depth
							lowercase__					      =		cls_token
							lowercase__					      =		attention_drop_rate
							lowercase__					      =		initializer_range
							lowercase__					      =		layer_norm_eps

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




							"""simple docstring"""


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

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

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

					def   lowerCamelCase__					(self   :						List[str]		)						->       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   lowerCamelCase__					(self   :						Dict				, _UpperCAmelCase   :						Tuple				, _UpperCAmelCase   :						Union[str, Any]				, _UpperCAmelCase   :						Dict		)						->       List[Any]:




							"""simple docstring"""


							lowercase__					      =		TFCvtModel(config=_UpperCAmelCase		)
							lowercase__					      =		model(_UpperCAmelCase				, training=_UpperCAmelCase		)
							lowercase__					      =		(self.image_size, self.image_size)
							lowercase__      ,     lowercase__					      =		image_size[0], image_size[1]
							for i in range(len(self.depth		)		):
									lowercase__					      =		floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1		)
									lowercase__					      =		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   lowerCamelCase__					(self   :						Union[str, Any]				, _UpperCAmelCase   :						int				, _UpperCAmelCase   :						Tuple				, _UpperCAmelCase   :						int		)						->       Dict:




							"""simple docstring"""


							lowercase__					      =		self.num_labels
							lowercase__					      =		TFCvtForImageClassification(_UpperCAmelCase		)
							lowercase__					      =		model(_UpperCAmelCase				, labels=_UpperCAmelCase				, training=_UpperCAmelCase		)
							self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_labels)		)


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




							"""simple docstring"""


							lowercase__					      =		self.prepare_config_and_inputs()
							lowercase__      ,     lowercase__      ,     lowercase__					      =		config_and_inputs
							lowercase__					      =		{"""pixel_values""": pixel_values}
							return config, inputs_dict






@require_tf
class 							A   (	UpperCAmelCase__			,  UpperCAmelCase__			,  unittest.TestCase							):
					'''simple docstring'''






					A__      =			(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
					A__      =			(
					    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
					    if is_tf_available()
					    else {}
					)
					A__      =			False
					A__      =			False
					A__      =			False
					A__      =			False
					A__      =			False

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




							"""simple docstring"""


							lowercase__					      =		TFCvtModelTester(self		)
							lowercase__					      =		TFCvtConfigTester(self				, config_class=_UpperCAmelCase				, has_text_modality=_UpperCAmelCase				, hidden_size=37		)

					def   lowerCamelCase__					(self   :						Union[str, Any]		)						->       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   lowerCamelCase__					(self   :						Any		)						->       List[str]:




							"""simple docstring"""


							pass

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




							"""simple docstring"""


							pass

					@unittest.skip(reason="""Cvt does not support input and output embeddings"""		)
					def   lowerCamelCase__					(self   :						Optional[Any]		)						->       Optional[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   lowerCamelCase__					(self   :						List[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   lowerCamelCase__					(self   :						int		)						->       Tuple:




							"""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   lowerCamelCase__					(self   :						Union[str, Any]		)						->       List[Any]:




							"""simple docstring"""


							lowercase__					      =		tf.keras.mixed_precision.Policy("""mixed_float16"""		)
							tf.keras.mixed_precision.set_global_policy(_UpperCAmelCase		)
							super().test_keras_fit()
							tf.keras.mixed_precision.set_global_policy("""float32"""		)

					def   lowerCamelCase__					(self   :						Any		)						->       Optional[Any]:




							"""simple docstring"""


							lowercase__      ,     lowercase__					      =		self.model_tester.prepare_config_and_inputs_for_common()

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

									lowercase__					      =		["""pixel_values"""]
									self.assertListEqual(arg_names[:1]				, _UpperCAmelCase		)

					def   lowerCamelCase__					(self   :						Any		)						->       Optional[int]:




							"""simple docstring"""


							def check_hidden_states_output(_UpperCAmelCase   :						int				, _UpperCAmelCase   :						Dict				, _UpperCAmelCase   :						Any		):
									lowercase__					      =		model_class(_UpperCAmelCase		)

									lowercase__					      =		model(**self._prepare_for_class(_UpperCAmelCase				, _UpperCAmelCase		)		)
									lowercase__					      =		outputs.hidden_states

									lowercase__					      =		len(self.model_tester.depth		)
									self.assertEqual(len(_UpperCAmelCase		)				, _UpperCAmelCase		)

									# 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,
									    ]				, )

							lowercase__      ,     lowercase__					      =		self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowercase__					      =		True
									check_hidden_states_output(_UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase		)

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

									check_hidden_states_output(_UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase		)

					def   lowerCamelCase__					(self   :						Optional[Any]		)						->       int:




							"""simple docstring"""


							lowercase__					      =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCAmelCase		)

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




							"""simple docstring"""


							lowercase__					      =		self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)


					@slow
					def   lowerCamelCase__					(self   :						Dict		)						->       List[str]:




							"""simple docstring"""


							for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowercase__					      =		TFCvtModel.from_pretrained(_UpperCAmelCase		)
									self.assertIsNotNone(_UpperCAmelCase		)






def 			UpperCamelCase (     )       ->  Dict:
		"""simple docstring"""




		lowercase__					      =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
		return image







@require_tf
@require_vision
class 							A   (	unittest.TestCase							):
					'''simple docstring'''






					@cached_property
					def   lowerCamelCase__					(self   :						List[Any]		)						->       int:




							"""simple docstring"""


							return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)


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




							"""simple docstring"""


							lowercase__					      =		TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

							lowercase__					      =		self.default_image_processor
							lowercase__					      =		prepare_img()
							lowercase__					      =		image_processor(images=_UpperCAmelCase				, return_tensors="""tf"""		)

							# forward pass
							lowercase__					      =		model(**_UpperCAmelCase		)

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

							lowercase__					      =		tf.constant([0.9_285, 0.9_015, -0.3_150]		)
							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()				, _UpperCAmelCase				, atol=1E-4		)		)





class 							A   :
					'''simple docstring'''






					def __init__(self   :						int				, _UpperCAmelCase   :						list		)						->       None:




							"""simple docstring"""


							lowercase__					      =		set_counts
							lowercase__					      =		max(_UpperCAmelCase		)
							lowercase__					      =		len(_UpperCAmelCase		)
							lowercase__					      =		[1] * num_sets
							lowercase__					      =		list(range(_UpperCAmelCase		)		)

					def   lowerCamelCase__					(self   :						List[Any]				, _UpperCAmelCase   :						int				, _UpperCAmelCase   :						int		)						->       bool:




							"""simple docstring"""


							lowercase__					      =		self.get_parent(_UpperCAmelCase		)
							lowercase__					      =		self.get_parent(_UpperCAmelCase		)

							if src_parent == dst_parent:
									return False

							if self.ranks[dst_parent] >= self.ranks[src_parent]:
									self.set_counts[dst_parent] += self.set_counts[src_parent]
									lowercase__					      =		0
									lowercase__					      =		dst_parent
									if self.ranks[dst_parent] == self.ranks[src_parent]:
											self.ranks[dst_parent] += 1
									lowercase__					      =		self.set_counts[dst_parent]
							else:
									self.set_counts[src_parent] += self.set_counts[dst_parent]
									lowercase__					      =		0
									lowercase__					      =		src_parent
									lowercase__					      =		self.set_counts[src_parent]

							lowercase__					      =		max(self.max_set				, _UpperCAmelCase		)
							return True


					def   lowerCamelCase__					(self   :						List[Any]				, _UpperCAmelCase   :						int		)						->       int:




							"""simple docstring"""


							if self.parents[disj_set] == disj_set:
									return disj_set
							lowercase__					      =		self.get_parent(self.parents[disj_set]		)
							return self.parents[disj_set]

