


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

   '''simple docstring'''







   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						self.config_class(**self.inputs_dict							)
         self.parent.assertTrue(hasattr(_lowerCamelCase       ,  """embed_dim"""							)							)
         self.parent.assertTrue(hasattr(_lowerCamelCase       ,  """num_heads"""							)							)



class 							_UpperCamelCase :

   '''simple docstring'''







   def __init__(  self  : str       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : Union[str, Any]=1_3       ,  _lowerCamelCase  : Union[str, Any]=6_4       ,  _lowerCamelCase  : Union[str, Any]=3       ,  _lowerCamelCase  : Optional[int]=[1_6, 4_8, 9_6]       ,  _lowerCamelCase  : Union[str, Any]=[1, 3, 6]       ,  _lowerCamelCase  : int=[1, 2, 1_0]       ,  _lowerCamelCase  : List[Any]=[7, 3, 3]       ,  _lowerCamelCase  : str=[4, 2, 2]       ,  _lowerCamelCase  : Any=[2, 1, 1]       ,  _lowerCamelCase  : List[Any]=[2, 2, 2]       ,  _lowerCamelCase  : Union[str, Any]=[False, False, True]       ,  _lowerCamelCase  : Union[str, Any]=[0.0, 0.0, 0.0]       ,  _lowerCamelCase  : Any=0.02       ,  _lowerCamelCase  : Any=1E-12       ,  _lowerCamelCase  : Tuple=True       ,  _lowerCamelCase  : int=True       ,  _lowerCamelCase  : Optional[Any]=2       ,  ):






         '''simple docstring'''



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

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



         __lowerCamelCase     :      List[Any]       						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

         __lowerCamelCase     :      str       						=						self.get_config()
         return config, pixel_values, labels

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






         '''simple docstring'''



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






         '''simple docstring'''



         __lowerCamelCase     :      Dict       						=						self.num_labels
         __lowerCamelCase     :      Tuple       						=						TFCvtForImageClassification(_lowerCamelCase							)
         __lowerCamelCase     :      Any       						=						model(_lowerCamelCase       ,  labels=_lowerCamelCase       ,  training=_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)							)


   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.prepare_config_and_inputs()
         __lowerCamelCase						, __lowerCamelCase						, __lowerCamelCase     :      Dict       						=						config_and_inputs
         __lowerCamelCase     :      Optional[Any]       						=						{"""pixel_values""": pixel_values}
         return config, inputs_dict



@require_tf
class 							_UpperCamelCase (						A,A,unittest.TestCase						):

   '''simple docstring'''







   a_				:							List[str]    = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
   a_				:							Optional[Any]    = (
       {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
       if is_tf_available()
       else {}
   )
   a_				:							Optional[int]    = False
   a_				:							List[str]    = False
   a_				:							Optional[int]    = False
   a_				:							Tuple    = False
   a_				:							Union[str, Any]    = False

   def   _snake_case    (  self  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						TFCvtModelTester(self							)
         __lowerCamelCase     :      Dict       						=						TFCvtConfigTester(self       ,  config_class=_lowerCamelCase       ,  has_text_modality=_lowerCamelCase       ,  hidden_size=3_7							)

   def   _snake_case    (  self  : Dict							):






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






         '''simple docstring'''



         pass

   @unittest.skip(reason="""Cvt does not use inputs_embeds"""							)
   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         pass

   @unittest.skip(reason="""Cvt does not support input and output embeddings"""							)
   def   _snake_case    (  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."""       ,  )
   def   _snake_case    (  self  : Union[str, Any]							):






         '''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   _snake_case    (  self  : 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   _snake_case    (  self  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      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  : Any							):






         '''simple docstring'''



         __lowerCamelCase						, __lowerCamelCase     :      Any       						=						self.model_tester.prepare_config_and_inputs_for_common()

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

               __lowerCamelCase     :      List[str]       						=						["""pixel_values"""]
               self.assertListEqual(arg_names[:1]       ,  _lowerCamelCase							)

   def   _snake_case    (  self  : Dict							):






         '''simple docstring'''



         def check_hidden_states_output(_lowerCamelCase  : Dict       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : List[str]							):
               __lowerCamelCase     :      Optional[Any]       						=						model_class(_lowerCamelCase							)

               __lowerCamelCase     :      Optional[int]       						=						model(**self._prepare_for_class(_lowerCamelCase       ,  _lowerCamelCase							)							)
               __lowerCamelCase     :      Union[str, Any]       						=						outputs.hidden_states

               __lowerCamelCase     :      List[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,
                   ]       ,  )

         __lowerCamelCase						, __lowerCamelCase     :      Tuple       						=						self.model_tester.prepare_config_and_inputs_for_common()

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

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __lowerCamelCase     :      List[Any]       						=						True

               check_hidden_states_output(_lowerCamelCase       ,  _lowerCamelCase       ,  _lowerCamelCase							)

   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[int]       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCamelCase							)

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






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase							)


   @slow
   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __lowerCamelCase     :      List[Any]       						=						TFCvtModel.from_pretrained(_lowerCamelCase							)
               self.assertIsNotNone(_lowerCamelCase							)





def   _UpperCAmelCase       (     ):
      """simple docstring"""




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




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

   '''simple docstring'''







   @cached_property
   def   _snake_case    (  self  : Any							):






         '''simple docstring'''



         return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)


   @slow
   def   _snake_case    (  self  : Any							):






         '''simple docstring'''



         __lowerCamelCase     :      List[Any]       						=						TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

         __lowerCamelCase     :      List[str]       						=						self.default_image_processor
         __lowerCamelCase     :      List[str]       						=						prepare_img()
         __lowerCamelCase     :      Tuple       						=						image_processor(images=_lowerCamelCase       ,  return_tensors="""tf"""							)

         # forward pass
         __lowerCamelCase     :      Any       						=						model(**_lowerCamelCase							)

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

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







def   _UpperCAmelCase       (     UpperCAmelCase      :			str      ):
      """simple docstring"""




      __lowerCamelCase     :      List[Any]       						=						hex_num.strip()
      if not hex_num:
            raise ValueError("""No value was passed to the function"""      )

      __lowerCamelCase     :      Dict       						=						hex_num[0] == """-"""
      if is_negative:
            __lowerCamelCase     :      Optional[Any]       						=						hex_num[1:]

      try:
            __lowerCamelCase     :      Any       						=						int(UpperCAmelCase						,	16      )
      except ValueError:
            raise ValueError("""Invalid value was passed to the function"""      )

      __lowerCamelCase     :      List[str]       						=						""""""
      while int_num > 0:
            __lowerCamelCase     :      Dict       						=						str(int_num % 2      ) + bin_str
            int_num >>= 1

      return int(("""-""" + bin_str) if is_negative else bin_str      )


if __name__ == "__main__":
    import doctest

    doctest.testmod()



