
'''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				(__SCREAMING_SNAKE_CASE):





       """simple docstring"""




       def        UpperCamelCase				(							self      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.config_class(**self.inputs_dict      )
          self.parent.assertTrue(hasattr(_a       ,							"""embed_dim"""      )      )
          self.parent.assertTrue(hasattr(_a       ,							"""num_heads"""      )      )






class    _a				:





       """simple docstring"""




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






       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

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






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






       def        UpperCamelCase				(							self      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				self.prepare_config_and_inputs()
          _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				config_and_inputs
          _SCREAMING_SNAKE_CASE      =				{"""pixel_values""": pixel_values}
          return config, inputs_dict






@require_tf
class    _a				(__SCREAMING_SNAKE_CASE  ,					__SCREAMING_SNAKE_CASE  ,					unittest.TestCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
       SCREAMING_SNAKE_CASE      =  (
           {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
           if is_tf_available()
           else {}
       )
       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False






       def        UpperCamelCase				(							self      )    ->			str:
          _SCREAMING_SNAKE_CASE      =				TFCvtModelTester(self      )
          _SCREAMING_SNAKE_CASE      =				TFCvtConfigTester(self       ,							config_class=_a       ,							has_text_modality=_a       ,							hidden_size=37      )






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






       @unittest.skip(reason="""Cvt does not use inputs_embeds"""      )
       def        UpperCamelCase				(							self      )    ->			Union[str, Any]:
          pass






       @unittest.skip(reason="""Cvt does not support input and output embeddings"""      )
       def        UpperCamelCase				(							self      )    ->			List[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        UpperCamelCase				(							self      )    ->			List[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        UpperCamelCase				(							self      )    ->			List[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        UpperCamelCase				(							self      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				tf.keras.mixed_precision.Policy("""mixed_float16"""      )
          tf.keras.mixed_precision.set_global_policy(_a      )
          super().test_keras_fit()
          tf.keras.mixed_precision.set_global_policy("""float32"""      )






       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs_for_common()

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

             _SCREAMING_SNAKE_CASE      =				["""pixel_values"""]
             self.assertListEqual(arg_names[:1]       ,							_a      )






       def        UpperCamelCase				(							self      )    ->			Any:
          def check_hidden_states_output(A__       ,							A__       ,							A__      ):
             _SCREAMING_SNAKE_CASE      =				model_class(_a      )

             _SCREAMING_SNAKE_CASE      =				model(**self._prepare_for_class(_a       ,							_a      )      )
             _SCREAMING_SNAKE_CASE      =				outputs.hidden_states

             _SCREAMING_SNAKE_CASE      =				len(self.model_tester.depth      )
             self.assertEqual(len(_a      )       ,							_a      )

             # 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      =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             _SCREAMING_SNAKE_CASE      =				True
             check_hidden_states_output(_a       ,							_a       ,							_a      )

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

             check_hidden_states_output(_a       ,							_a       ,							_a      )






       def        UpperCamelCase				(							self      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_a      )






       def        UpperCamelCase				(							self      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_a      )






       @slow
       def        UpperCamelCase				(							self      )    ->			List[str]:
          for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _SCREAMING_SNAKE_CASE      =				TFCvtModel.from_pretrained(_a      )
             self.assertIsNotNone(_a      )






def    lowerCAmelCase_	(				)     ->     Dict:




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







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





       """simple docstring"""




       @cached_property
       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )






       @slow
       def        UpperCamelCase				(							self      )    ->			Optional[int]:
          _SCREAMING_SNAKE_CASE      =				TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

          _SCREAMING_SNAKE_CASE      =				self.default_image_processor
          _SCREAMING_SNAKE_CASE      =				prepare_img()
          _SCREAMING_SNAKE_CASE      =				image_processor(images=_a       ,							return_tensors="""tf"""      )

          # forward pass
          _SCREAMING_SNAKE_CASE      =				model(**_a      )

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

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

'''simple docstring'''



def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""

   if not isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      raise ValueError("""multiplicative_persistence() only accepts integral values"""						)
   if num < 0:
      raise ValueError("""multiplicative_persistence() does not accept negative values"""						)

   _SCREAMING_SNAKE_CASE      =				0
   _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

   while len(SCREAMING_SNAKE_CASE_						) != 1:
      _SCREAMING_SNAKE_CASE      =				[int(SCREAMING_SNAKE_CASE_						) for i in num_string]

      _SCREAMING_SNAKE_CASE      =				1
      for i in range(0    ,      len(SCREAMING_SNAKE_CASE_						)						):
         total *= numbers[i]

      _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

      steps += 1
   return steps
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""

   if not isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      raise ValueError("""additive_persistence() only accepts integral values"""						)
   if num < 0:
      raise ValueError("""additive_persistence() does not accept negative values"""						)

   _SCREAMING_SNAKE_CASE      =				0
   _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

   while len(SCREAMING_SNAKE_CASE_						) != 1:
      _SCREAMING_SNAKE_CASE      =				[int(SCREAMING_SNAKE_CASE_						) for i in num_string]

      _SCREAMING_SNAKE_CASE      =				0
      for i in range(0    ,      len(SCREAMING_SNAKE_CASE_						)						):
         total += numbers[i]

      _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

      steps += 1
   return steps


if __name__ == "__main__":
     import doctest

     doctest.testmod()






