






"""simple docstring"""

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_							(      snake_case_  ):







				def     _snake_case					(							self							:						List[Any]	)				->					List[str]:
										__magic_name__            =     self.config_class(**self.inputs_dict	)
										self.parent.assertTrue(hasattr(__lowerCamelCase						,    "embed_dim"	)	)
										self.parent.assertTrue(hasattr(__lowerCamelCase						,    "num_heads"	)	)





class 						A_							:







				def __init__(							self							:						List[Any]						,    __lowerCamelCase							:						List[str]						,    __lowerCamelCase							:						int=1_3						,    __lowerCamelCase							:						Dict=6_4						,    __lowerCamelCase							:						Optional[int]=3						,    __lowerCamelCase							:						Optional[int]=[1_6, 4_8, 9_6]						,    __lowerCamelCase							:						Any=[1, 3, 6]						,    __lowerCamelCase							:						Optional[int]=[1, 2, 1_0]						,    __lowerCamelCase							:						List[Any]=[7, 3, 3]						,    __lowerCamelCase							:						Union[str, Any]=[4, 2, 2]						,    __lowerCamelCase							:						Optional[Any]=[2, 1, 1]						,    __lowerCamelCase							:						Optional[int]=[2, 2, 2]						,    __lowerCamelCase							:						List[str]=[False, False, True]						,    __lowerCamelCase							:						int=[0.0, 0.0, 0.0]						,    __lowerCamelCase							:						Union[str, Any]=0.02						,    __lowerCamelCase							:						Optional[int]=1e-12						,    __lowerCamelCase							:						str=True						,    __lowerCamelCase							:						Dict=True						,    __lowerCamelCase							:						int=2						,    )				->					int:
										__magic_name__            =     parent
										__magic_name__            =     batch_size
										__magic_name__            =     image_size
										__magic_name__            =     patch_sizes
										__magic_name__            =     patch_stride
										__magic_name__            =     patch_padding
										__magic_name__            =     is_training
										__magic_name__            =     use_labels
										__magic_name__            =     num_labels
										__magic_name__            =     num_channels
										__magic_name__            =     embed_dim
										__magic_name__            =     num_heads
										__magic_name__            =     stride_kv
										__magic_name__            =     depth
										__magic_name__            =     cls_token
										__magic_name__            =     attention_drop_rate
										__magic_name__            =     initializer_range
										__magic_name__            =     layer_norm_eps







				def     _snake_case					(							self							:						Union[str, Any]	)				->					Tuple:
										__magic_name__            =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

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







				def     _snake_case					(							self							:						Optional[int]	)				->					Dict:
										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     _snake_case					(							self							:						Dict						,    __lowerCamelCase							:						List[str]						,    __lowerCamelCase							:						Optional[Any]						,    __lowerCamelCase							:						Optional[int]	)				->					str:
										__magic_name__            =     TFCvtModel(config=__lowerCamelCase	)
										__magic_name__            =     model(__lowerCamelCase						,    training=__lowerCamelCase	)
										__magic_name__            =     (self.image_size, self.image_size)
										__magic_name__      ,    __magic_name__            =     image_size[0], image_size[1]
										for i in range(len(self.depth	)	):
																__magic_name__            =     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
																__magic_name__            =     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     _snake_case					(							self							:						List[Any]						,    __lowerCamelCase							:						Union[str, Any]						,    __lowerCamelCase							:						List[str]						,    __lowerCamelCase							:						Optional[Any]	)				->					int:
										__magic_name__            =     self.num_labels
										__magic_name__            =     TFCvtForImageClassification(__lowerCamelCase	)
										__magic_name__            =     model(__lowerCamelCase						,    labels=__lowerCamelCase						,    training=__lowerCamelCase	)
										self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.num_labels)	)







				def     _snake_case					(							self							:						Optional[int]	)				->					Tuple:
										__magic_name__            =     self.prepare_config_and_inputs()
										__magic_name__      ,    __magic_name__      ,    __magic_name__            =     config_and_inputs
										__magic_name__            =     {"pixel_values": pixel_values}
										return config, inputs_dict





@require_tf
class 						A_							(      snake_case_					,							snake_case_					,							unittest.TestCase  ):
				UpperCAmelCase__        =				(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
				UpperCAmelCase__        =				(
				    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
				    if is_tf_available()
				    else {}
				)
				UpperCAmelCase__        =				False
				UpperCAmelCase__        =				False
				UpperCAmelCase__        =				False
				UpperCAmelCase__        =				False
				UpperCAmelCase__        =				False







				def     _snake_case					(							self							:						List[str]	)				->					Union[str, Any]:
										__magic_name__            =     TFCvtModelTester(self	)
										__magic_name__            =     TFCvtConfigTester(self						,    config_class=__lowerCamelCase						,    has_text_modality=__lowerCamelCase						,    hidden_size=3_7	)







				def     _snake_case					(							self							:						Any	)				->					Optional[Any]:
										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     _snake_case					(							self							:						Union[str, Any]	)				->					Any:
										pass







				@unittest.skip(reason="Cvt does not use inputs_embeds"	)
				def     _snake_case					(							self							:						Tuple	)				->					List[Any]:
										pass







				@unittest.skip(reason="Cvt does not support input and output embeddings"	)
				def     _snake_case					(							self							:						str	)				->					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."						,    )
				def     _snake_case					(							self							:						int	)				->					str:
										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     _snake_case					(							self							:						Union[str, Any]	)				->					str:
										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     _snake_case					(							self							:						str	)				->					int:
										__magic_name__            =     tf.keras.mixed_precision.Policy("mixed_float16"	)
										tf.keras.mixed_precision.set_global_policy(__lowerCamelCase	)
										super().test_keras_fit()
										tf.keras.mixed_precision.set_global_policy("float32"	)







				def     _snake_case					(							self							:						Union[str, Any]	)				->					Dict:
										__magic_name__      ,    __magic_name__            =     self.model_tester.prepare_config_and_inputs_for_common()

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

																__magic_name__            =     ["pixel_values"]
																self.assertListEqual(arg_names[:1]						,    __lowerCamelCase	)







				def     _snake_case					(							self							:						List[Any]	)				->					Optional[int]:
										def check_hidden_states_output(__lowerCamelCase							:						Tuple						,    __lowerCamelCase							:						List[str]						,    __lowerCamelCase							:						Optional[Any]	):
																__magic_name__            =     model_class(__lowerCamelCase	)

																__magic_name__            =     model(**self._prepare_for_class(__lowerCamelCase						,    __lowerCamelCase	)	)
																__magic_name__            =     outputs.hidden_states

																__magic_name__            =     len(self.model_tester.depth	)
																self.assertEqual(len(__lowerCamelCase	)						,    __lowerCamelCase	)

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

										__magic_name__      ,    __magic_name__            =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																__magic_name__            =     True
																check_hidden_states_output(__lowerCamelCase						,    __lowerCamelCase						,    __lowerCamelCase	)

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

																check_hidden_states_output(__lowerCamelCase						,    __lowerCamelCase						,    __lowerCamelCase	)







				def     _snake_case					(							self							:						int	)				->					int:
										__magic_name__            =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__lowerCamelCase	)







				def     _snake_case					(							self							:						List[str]	)				->					List[str]:
										__magic_name__            =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase	)







				@slow
				def     _snake_case					(							self							:						Optional[Any]	)				->					Tuple:
										for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__magic_name__            =     TFCvtModel.from_pretrained(__lowerCamelCase	)
																self.assertIsNotNone(__lowerCamelCase	)






def _lowerCAmelCase	(  ):

						'''simple docstring'''






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


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







				@cached_property
				def     _snake_case					(							self							:						Tuple	)				->					List[str]:
										return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)







				@slow
				def     _snake_case					(							self							:						Optional[int]	)				->					List[str]:
										__magic_name__            =     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

										__magic_name__            =     self.default_image_processor
										__magic_name__            =     prepare_img()
										__magic_name__            =     image_processor(images=__lowerCamelCase						,    return_tensors="tf"	)

										# forward pass
										__magic_name__            =     model(**__lowerCamelCase	)

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

										__magic_name__            =     tf.constant([0.9285, 0.9015, -0.3150]	)
										self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						,    __lowerCamelCase						,    atol=1e-4	)	)











"""simple docstring"""

def _lowerCAmelCase	(  __lowerCamelCase:str   ):

						'''simple docstring'''






						return "".join(chr(ord(__lowerCamelCase   ) - 3_2   ) if "a" <= char <= "z" else char for char in word   )


if __name__ == "__main__":
			from doctest import testmod

			testmod()



