






"""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 					snake_case		(							_lowerCAmelCase						):


   '''simple docstring'''

   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= self.config_class(**self.inputs_dict  )
     self.parent.assertTrue(hasattr(_lowerCamelCase,       '''embed_dim'''  )  )
     self.parent.assertTrue(hasattr(_lowerCamelCase,       '''num_heads'''  )  )





class 					snake_case		:


   '''simple docstring'''

   def __init__(	self :     Dict,       _lowerCamelCase :     Dict,       _lowerCamelCase :     int=13,       _lowerCamelCase :     str=64,       _lowerCamelCase :     Tuple=3,       _lowerCamelCase :     Optional[int]=[16, 48, 96],       _lowerCamelCase :     Dict=[1, 3, 6],       _lowerCamelCase :     Optional[Any]=[1, 2, 10],       _lowerCamelCase :     Optional[int]=[7, 3, 3],       _lowerCamelCase :     str=[4, 2, 2],       _lowerCamelCase :     str=[2, 1, 1],       _lowerCamelCase :     List[str]=[2, 2, 2],       _lowerCamelCase :     List[str]=[False, False, True],       _lowerCamelCase :     str=[0.0, 0.0, 0.0],       _lowerCamelCase :     int=0.02,       _lowerCamelCase :     int=1e-12,       _lowerCamelCase :     Optional[int]=True,       _lowerCamelCase :     Any=True,       _lowerCamelCase :     int=2,       ):

     '''simple docstring'''
     __A									= parent
     __A									= batch_size
     __A									= image_size
     __A									= patch_sizes
     __A									= patch_stride
     __A									= patch_padding
     __A									= is_training
     __A									= use_labels
     __A									= num_labels
     __A									= num_channels
     __A									= embed_dim
     __A									= num_heads
     __A									= stride_kv
     __A									= depth
     __A									= cls_token
     __A									= attention_drop_rate
     __A									= initializer_range
     __A									= layer_norm_eps


   def 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A									= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

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


   def 				_SCREAMING_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 				_SCREAMING_SNAKE_CASE				(	self :     List[str],       _lowerCamelCase :     Optional[int],       _lowerCamelCase :     Dict,       _lowerCamelCase :     Optional[int]  ):

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

     '''simple docstring'''
     __A									= self.num_labels
     __A									= TFCvtForImageClassification(_lowerCamelCase  )
     __A									= model(_lowerCamelCase,       labels=_lowerCamelCase,       training=_lowerCamelCase  )
     self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.num_labels)  )






   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     __A									= self.prepare_config_and_inputs()
     __A			,    __A			,    __A									= config_and_inputs
     __A									= {'''pixel_values''': pixel_values}
     return config, inputs_dict





@require_tf
class 					snake_case		(							_lowerCAmelCase   ,	_lowerCAmelCase   ,	unittest.TestCase						):


   '''simple docstring'''

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


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     __A									= TFCvtModelTester(self  )
     __A									= TFCvtConfigTester(self,       config_class=_lowerCamelCase,       has_text_modality=_lowerCamelCase,       hidden_size=37  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     int  ):

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

     '''simple docstring'''
     pass


   @unittest.skip(reason='''Cvt does not use inputs_embeds'''  )
   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     pass


   @unittest.skip(reason='''Cvt does not support input and output embeddings'''  )
   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str]  ):

     '''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 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''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 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''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 				_SCREAMING_SNAKE_CASE				(	self :     int  ):

     '''simple docstring'''
     __A									= 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 				_SCREAMING_SNAKE_CASE				(	self :     str  ):

     '''simple docstring'''
     __A			,    __A									= self.model_tester.prepare_config_and_inputs_for_common()

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

       __A									= ['''pixel_values''']
       self.assertListEqual(arg_names[:1],       _lowerCamelCase  )


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

     '''simple docstring'''
     def check_hidden_states_output(_lowerCamelCase :     List[Any],       _lowerCamelCase :     Optional[Any],       _lowerCamelCase :     Any  ):
       __A									= model_class(_lowerCamelCase  )

       __A									= model(**self._prepare_for_class(_lowerCamelCase,       _lowerCamelCase  )  )
       __A									= outputs.hidden_states

       __A									= 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,
           ],       )

     __A			,    __A									= self.model_tester.prepare_config_and_inputs_for_common()

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

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

       check_hidden_states_output(_lowerCamelCase,       _lowerCamelCase,       _lowerCamelCase  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     __A									= self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowerCamelCase  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Any  ):

     '''simple docstring'''
     __A									= self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase  )






   @slow
   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __A									= TFCvtModel.from_pretrained(_lowerCamelCase  )
       self.assertIsNotNone(_lowerCamelCase  )





def 					lowerCAmelCase				(    ):




  """simple docstring"""







  __A									= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
  return image





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


   '''simple docstring'''

   @cached_property
   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )






   @slow
   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int]  ):

     '''simple docstring'''
     __A									= TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

     __A									= self.default_image_processor
     __A									= prepare_img()
     __A									= image_processor(images=_lowerCamelCase,       return_tensors='''tf'''  )

     # forward pass
     __A									= model(**_lowerCamelCase  )

     # verify the logits
     __A									= tf.TensorShape((1, 10_00)  )
     self.assertEqual(outputs.logits.shape,       _lowerCamelCase  )

     __A									= 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"""


class 					snake_case		:


   '''simple docstring'''

   def __init__(	self :     List[str],       _lowerCamelCase :     list[int]  ):

     '''simple docstring'''
     __A									= len(_lowerCamelCase  )
     __A									= [0] * len_array

     if len_array > 0:
       __A									= array[0]

     for i in range(1,       _lowerCamelCase  ):
       __A									= self.prefix_sum[i - 1] + array[i]


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[Any],       _lowerCamelCase :     int,       _lowerCamelCase :     int  ):

     '''simple docstring'''
     if start == 0:
       return self.prefix_sum[end]

     return self.prefix_sum[end] - self.prefix_sum[start - 1]






   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str],       _lowerCamelCase :     int  ):

     '''simple docstring'''
     __A									= {0}
     for sum_item in self.prefix_sum:
       if sum_item - target_sum in sums:
         return True

       sums.add(_lowerCamelCase  )

     return False


if __name__ == "__main__":
       import doctest

       doctest.testmod()




