



"""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  _UpperCAmelCase (    a__):

	def 		_snake_case      (  self	: Any       ):
					snake_case_				:  Tuple       =			self.config_class(**self.inputs_dict       )
					self.parent.assertTrue(hasattr(lowerCAmelCase__						,  '''embed_dim'''       )       )
					self.parent.assertTrue(hasattr(lowerCAmelCase__						,  '''num_heads'''       )       )





class  _UpperCAmelCase :

	def __init__(  self	: Optional[Any]						,  lowercase_	: Tuple						,  lowercase_	: List[Any]=13						,  lowercase_	: str=64						,  lowercase_	: Tuple=3						,  lowercase_	: Optional[int]=[16, 48, 96]						,  lowercase_	: Optional[int]=[1, 3, 6]						,  lowercase_	: List[Any]=[1, 2, 10]						,  lowercase_	: str=[7, 3, 3]						,  lowercase_	: str=[4, 2, 2]						,  lowercase_	: Optional[int]=[2, 1, 1]						,  lowercase_	: str=[2, 2, 2]						,  lowercase_	: Optional[Any]=[False, False, True]						,  lowercase_	: Optional[Any]=[0.0, 0.0, 0.0]						,  lowercase_	: str=0.02						,  lowercase_	: Any=1E-12						,  lowercase_	: Any=True						,  lowercase_	: Dict=True						,  lowercase_	: Optional[Any]=2						,  ):
					snake_case_				:  List[str]       =			parent
					snake_case_				:  Tuple       =			batch_size
					snake_case_				:  str       =			image_size
					snake_case_				:  List[Any]       =			patch_sizes
					snake_case_				:  List[Any]       =			patch_stride
					snake_case_				:  int       =			patch_padding
					snake_case_				:  int       =			is_training
					snake_case_				:  str       =			use_labels
					snake_case_				:  List[str]       =			num_labels
					snake_case_				:  str       =			num_channels
					snake_case_				:  Optional[int]       =			embed_dim
					snake_case_				:  Optional[Any]       =			num_heads
					snake_case_				:  Tuple       =			stride_kv
					snake_case_				:  Union[str, Any]       =			depth
					snake_case_				:  Optional[Any]       =			cls_token
					snake_case_				:  List[Any]       =			attention_drop_rate
					snake_case_				:  List[str]       =			initializer_range
					snake_case_				:  str       =			layer_norm_eps

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

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

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

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






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





@require_tf
class  _UpperCAmelCase (    a__					,  a__					,  unittest.TestCase):
	_lowerCAmelCase     :    List[str]	      =	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	_lowerCAmelCase     :    List[Any]	      =	(
	    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	_lowerCAmelCase     :    Optional[Any]	      =	False
	_lowerCAmelCase     :    List[str]	      =	False
	_lowerCAmelCase     :    Optional[Any]	      =	False
	_lowerCAmelCase     :    int	      =	False
	_lowerCAmelCase     :    Dict	      =	False

	def 		_snake_case      (  self	: Union[str, Any]       ):
					snake_case_				:  Dict       =			TFCvtModelTester(self       )
					snake_case_				:  List[Any]       =			TFCvtConfigTester(self						,  config_class=lowerCAmelCase__						,  has_text_modality=lowerCAmelCase__						,  hidden_size=37       )

	def 		_snake_case      (  self	: 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	: Tuple       ):
					pass

	@unittest.skip(reason='''Cvt does not use inputs_embeds'''       )
	def 		_snake_case      (  self	: Any       ):
					pass

	@unittest.skip(reason='''Cvt does not support input and output embeddings'''       )
	def 		_snake_case      (  self	: Dict       ):
					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	: Tuple       ):
					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	: 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	: Tuple       ):
					snake_case_				:  Optional[int]       =			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	: Dict       ):
					snake_case_				:  Dict       =			self.model_tester.prepare_config_and_inputs_for_common()

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

									snake_case_				:  Union[str, Any]       =			["pixel_values"]
									self.assertListEqual(arg_names[:1]						,  lowerCAmelCase__       )

	def 		_snake_case      (  self	: Any       ):
					def check_hidden_states_output(lowercase_	: List[Any]						,  lowercase_	: Union[str, Any]						,  lowercase_	: Optional[int]       ):
									snake_case_				:  Union[str, Any]       =			model_class(lowerCAmelCase__       )

									snake_case_				:  Union[str, Any]       =			model(**self._prepare_for_class(lowerCAmelCase__						,  lowerCAmelCase__       )       )
									snake_case_				:  Dict       =			outputs.hidden_states

									snake_case_				:  Any       =			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,
									    ]						,  )

					snake_case_				:  Optional[int]       =			self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									snake_case_				:  Dict       =			True
									check_hidden_states_output(lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__       )

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									snake_case_				:  Optional[int]       =			True

									check_hidden_states_output(lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__       )

	def 		_snake_case      (  self	: List[str]       ):
					snake_case_				:  Tuple       =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCAmelCase__       )

	def 		_snake_case      (  self	: Tuple       ):
					snake_case_				:  Dict       =			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__       )






	@slow
	def 		_snake_case      (  self	: str       ):
					for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case_				:  Tuple       =			TFCvtModel.from_pretrained(lowerCAmelCase__       )
									self.assertIsNotNone(lowerCAmelCase__       )





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






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

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






	@slow
	def 		_snake_case      (  self	: List[Any]       ):
					snake_case_				:  Union[str, Any]       =			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

					snake_case_				:  Any       =			self.default_image_processor
					snake_case_				:  Any       =			prepare_img()
					snake_case_				:  str       =			image_processor(images=lowerCAmelCase__						,  return_tensors='''tf'''       )

					# forward pass
					snake_case_				:  List[str]       =			model(**lowerCAmelCase__       )

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

					snake_case_				:  str       =			tf.constant([0.92_85, 0.90_15, -0.31_50]       )
					self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						,  lowerCAmelCase__						,  atol=1E-4       )       )










"""simple docstring"""

def __lowercase    (							_a					):
    snake_case_				:  Optional[Any]       =			int(_a					)
    if decimal in (0, 1):  # Exit cases for the recursion
        return str(_a					)
    snake_case_,			snake_case_				:  Optional[int]       =			divmod(_a	,    2					)
    return binary_recursive(_a					) + str(_a					)




def __lowercase    (							_a					):
    snake_case_				:  Dict       =			str(_a					).strip()
    if not number:
        raise ValueError('''No input value was provided'''					)
    snake_case_				:  List[str]       =			'''-''' if number.startswith('''-'''					) else ''''''
    snake_case_				:  Optional[Any]       =			number.lstrip('''-'''					)
    if not number.isnumeric():
        raise ValueError('''Input value is not an integer'''					)
    return f"{negative}0b{binary_recursive(int(_a					)					)}"


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

     testmod()





