






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


     def 				_A       (				self       :	str      ):
       SCREAMING_SNAKE_CASE       :      Optional[Any]							=    self.config_class(**self.inputs_dict      )
       self.parent.assertTrue(hasattr(UpperCAmelCase_					, "embed_dim"      )      )
       self.parent.assertTrue(hasattr(UpperCAmelCase_					, "num_heads"      )      )





class  SCREAMING_SNAKE_CASE			:
     '''simple docstring'''


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


     def 				_A       (				self       :	Dict      ):
       SCREAMING_SNAKE_CASE       :      str							=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

       SCREAMING_SNAKE_CASE       :      Tuple							=    self.get_config()
       return config, pixel_values, labels


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






     def 				_A       (				self       :	Any      ):
       SCREAMING_SNAKE_CASE       :      str							=    self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE       :      Any							=    config_and_inputs
       SCREAMING_SNAKE_CASE       :      Tuple							=    {"pixel_values": pixel_values}
       return config, inputs_dict





@require_tf
class  SCREAMING_SNAKE_CASE			(			lowerCAmelCase      ,		lowerCAmelCase      ,		unittest.TestCase					):
     '''simple docstring'''


     UpperCamelCase_							:		Union[str, Any]			=	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
     UpperCamelCase_							:		List[str]			=	(
         {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
         if is_tf_available()
         else {}
     )
     UpperCamelCase_							:		Dict			=	False
     UpperCamelCase_							:		Any			=	False
     UpperCamelCase_							:		List[str]			=	False
     UpperCamelCase_							:		Union[str, Any]			=	False
     UpperCamelCase_							:		Any			=	False


     def 				_A       (				self       :	List[Any]      ):
       SCREAMING_SNAKE_CASE       :      Dict							=    TFCvtModelTester(self      )
       SCREAMING_SNAKE_CASE       :      int							=    TFCvtConfigTester(self					, config_class=UpperCAmelCase_					, has_text_modality=UpperCAmelCase_					, hidden_size=37      )


     def 				_A       (				self       :	List[str]      ):
       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 				_A       (				self       :	Any      ):
       pass


     @unittest.skip(reason="Cvt does not use inputs_embeds"      )
     def 				_A       (				self       :	int      ):
       pass


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

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

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


     def 				_A       (				self       :	Optional[int]      ):
       def check_hidden_states_output(UpperCAmelCase_       :	Tuple					, UpperCAmelCase_       :	int					, UpperCAmelCase_       :	List[str]      ):
         SCREAMING_SNAKE_CASE       :      Any							=    model_class(UpperCAmelCase_      )

         SCREAMING_SNAKE_CASE       :      str							=    model(**self._prepare_for_class(UpperCAmelCase_					, UpperCAmelCase_      )      )
         SCREAMING_SNAKE_CASE       :      int							=    outputs.hidden_states

         SCREAMING_SNAKE_CASE       :      Union[str, Any]							=    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,
             ]					, )

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

       for model_class in self.all_model_classes:
         SCREAMING_SNAKE_CASE       :      Optional[Any]							=    True
         check_hidden_states_output(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_      )

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

         check_hidden_states_output(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_      )


     def 				_A       (				self       :	Any      ):
       SCREAMING_SNAKE_CASE       :      List[Any]							=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase_      )


     def 				_A       (				self       :	Optional[Any]      ):
       SCREAMING_SNAKE_CASE       :      int							=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_      )






     @slow
     def 				_A       (				self       :	Union[str, Any]      ):
       for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         SCREAMING_SNAKE_CASE       :      str							=    TFCvtModel.from_pretrained(UpperCAmelCase_      )
         self.assertIsNotNone(UpperCAmelCase_      )





def   lowerCamelCase__			(     ):

  """simple docstring"""






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


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


     @cached_property
     def 				_A       (				self       :	Union[str, Any]      ):
       return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )






     @slow
     def 				_A       (				self       :	Tuple      ):
       SCREAMING_SNAKE_CASE       :      Tuple							=    TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

       SCREAMING_SNAKE_CASE       :      Tuple							=    self.default_image_processor
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    prepare_img()
       SCREAMING_SNAKE_CASE       :      List[str]							=    image_processor(images=UpperCAmelCase_					, return_tensors="tf"      )

       # forward pass
       SCREAMING_SNAKE_CASE       :      Optional[int]							=    model(**UpperCAmelCase_      )

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

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














from ..utils import DummyObject, requires_backends


class  SCREAMING_SNAKE_CASE			(			metaclass=lowerCAmelCase					):
     '''simple docstring'''


     UpperCamelCase_							:		Union[str, Any]			=	['''keras_nlp''']


     def __init__(				self       :	Dict					, *UpperCAmelCase_       :	Optional[Any]					, **UpperCAmelCase_       :	Dict      ):
       requires_backends(self					, ["keras_nlp"]      )






