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

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							self.config_class(**self.inputs_dict )
   self.parent.assertTrue(hasattr(snake_case__			,				"embed_dim" ) )
   self.parent.assertTrue(hasattr(snake_case__			,				"num_heads" ) )






class 							UpperCAmelCase_							:

 '''simple docstring'''







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



   '''simple docstring'''




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







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Union[str, Any]				       =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

   UpperCAmelCase__      :					List[str]				       =							self.get_config()
   return config, pixel_values, labels







 def 							UpperCamelCase  (					self		:  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 							UpperCamelCase  (					self		:  Any			,				snake_case__		:  List[str]			,				snake_case__		:  Tuple			,				snake_case__		:  Any ):



   '''simple docstring'''




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



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							self.num_labels
   UpperCAmelCase__      :					List[Any]				       =							TFCvtForImageClassification(snake_case__ )
   UpperCAmelCase__      :					int				       =							model(snake_case__			,				labels=snake_case__			,				training=snake_case__ )
   self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels) )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							self.prepare_config_and_inputs()
   UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__      :					int				       =							config_and_inputs
   UpperCAmelCase__      :					Tuple				       =							{"pixel_values": pixel_values}
   return config, inputs_dict






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

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







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							TFCvtModelTester(self )
   UpperCAmelCase__      :					List[Any]				       =							TFCvtConfigTester(self			,				config_class=snake_case__			,				has_text_modality=snake_case__			,				hidden_size=37 )







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



   '''simple docstring'''




   pass







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



   '''simple docstring'''




   pass







 @unittest.skip(reason="Cvt does not support input and output embeddings" )
 def 							UpperCamelCase  (					self		:  Any ):



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



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							tf.keras.mixed_precision.Policy("mixed_float16" )
   tf.keras.mixed_precision.set_global_policy(snake_case__ )
   super().test_keras_fit()
   tf.keras.mixed_precision.set_global_policy("float32" )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




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

   for model_class in self.all_model_classes:
     UpperCAmelCase__      :					Union[str, Any]				       =							model_class(snake_case__ )
     UpperCAmelCase__      :					List[Any]				       =							inspect.signature(model.call )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     UpperCAmelCase__      :					Any				       =							[*signature.parameters.keys()]

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







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   def check_hidden_states_output(snake_case__		:  Union[str, Any]			,				snake_case__		:  Union[str, Any]			,				snake_case__		:  Tuple ):
     UpperCAmelCase__      :					Dict				       =							model_class(snake_case__ )

     UpperCAmelCase__      :					Union[str, Any]				       =							model(**self._prepare_for_class(snake_case__			,				snake_case__ ) )
     UpperCAmelCase__      :					Optional[Any]				       =							outputs.hidden_states

     UpperCAmelCase__      :					Optional[int]				       =							len(self.model_tester.depth )
     self.assertEqual(len(snake_case__ )			,				snake_case__ )

     # 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,
         ]			,				)

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

   for model_class in self.all_model_classes:
     UpperCAmelCase__      :					int				       =							True
     check_hidden_states_output(snake_case__			,				snake_case__			,				snake_case__ )

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     UpperCAmelCase__      :					Tuple				       =							True

     check_hidden_states_output(snake_case__			,				snake_case__			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*snake_case__ )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*snake_case__ )







 @slow
 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase__      :					Optional[int]				       =							TFCvtModel.from_pretrained(snake_case__ )
     self.assertIsNotNone(snake_case__ )







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






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

 '''simple docstring'''







 @cached_property
 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )







 @slow
 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




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

   UpperCAmelCase__      :					List[str]				       =							self.default_image_processor
   UpperCAmelCase__      :					Union[str, Any]				       =							prepare_img()
   UpperCAmelCase__      :					Optional[int]				       =							image_processor(images=snake_case__			,				return_tensors="tf" )

   # forward pass
   UpperCAmelCase__      :					Tuple				       =							model(**snake_case__ )

   # verify the logits
   UpperCAmelCase__      :					Optional[Any]				       =							tf.TensorShape((1, 10_00) )
   self.assertEqual(outputs.logits.shape			,				snake_case__ )

   UpperCAmelCase__      :					str				       =							tf.constant([0.9285, 0.9015, -0.3150] )
   self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,				snake_case__			,				atol=1e-4 ) )





'''simple docstring'''





from math import factorial

SCREAMING_SNAKE_CASE     =       {str(digit): factorial(digit) for digit in range(1_0)}







def snake_case_     (					lowercase__		):
  if not isinstance(lowercase__   ,       lowercase__		):
    raise TypeError("Parameter number must be int"		)

  if number < 0:
    raise ValueError("Parameter number must be greater than or equal to 0"		)

  # Converts number in string to iterate on its digits and adds its factorial.
  return sum(DIGIT_FACTORIAL[digit] for digit in str(lowercase__		)		)







def snake_case_     (					lowercase__ = 6_0   ,       lowercase__ = 1_0_0_0_0_0_0		):

  if not isinstance(lowercase__   ,       lowercase__		) or not isinstance(lowercase__   ,       lowercase__		):
    raise TypeError("Parameters chain_length and number_limit must be int"		)

  if chain_length <= 0 or number_limit <= 0:
    raise ValueError(
        "Parameters chain_length and number_limit must be greater than 0"		)

  # the counter for the chains with the exact desired length
  UpperCAmelCase__      :					Union[str, Any]				       =							0
  # the cached sizes of the previous chains
  UpperCAmelCase__      :					dict[int, int]				       =							{}

  for start_chain_element in range(1   ,       lowercase__		):
    # The temporary set will contain the elements of the chain
    UpperCAmelCase__      :					Any				       =							set()
    UpperCAmelCase__      :					int				       =							0

    # Stop computing the chain when you find a cached size, a repeating item or the
    # length is greater then the desired one.
    UpperCAmelCase__      :					List[str]				       =							start_chain_element
    while (
        chain_element not in chain_sets_lengths
        and chain_element not in chain_set
        and chain_set_length <= chain_length
    ):
      chain_set.add(lowercase__		)
      chain_set_length += 1
      UpperCAmelCase__      :					List[str]				       =							digit_factorial_sum(lowercase__		)

    if chain_element in chain_sets_lengths:
      chain_set_length += chain_sets_lengths[chain_element]

    UpperCAmelCase__      :					List[str]				       =							chain_set_length

    # If chain contains the exact amount of elements increase the counter
    if chain_set_length == chain_length:
      chains_counter += 1

  return chains_counter


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      print(F'{solution()}')



