

'''simple docstring'''
import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import CvtForImageClassification, CvtModel
     from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class 							A__   (	A__  ):





  def 						A  (		self				:     Dict			)     ->   List[str]:





       '''simple docstring'''






       _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__   :





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





       '''simple docstring'''






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





       '''simple docstring'''






       _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:
            _SCREAMING_SNAKE_CASE							   =ids_tensor([self.batch_size]							, self.num_labels			)

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





  def 						A  (		self				:     Dict			)     ->   Optional[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 						A  (		self				:     Tuple							, _a				:     List[Any]							, _a				:     Tuple							, _a				:     Any			)     ->   Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =CvtModel(config=_a			)
       model.to(_a			)
       model.eval()
       _SCREAMING_SNAKE_CASE							   =model(_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 						A  (		self				:     str							, _a				:     List[str]							, _a				:     Union[str, Any]							, _a				:     List[Any]			)     ->   Union[str, Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.num_labels
       _SCREAMING_SNAKE_CASE							   =CvtForImageClassification(_a			)
       model.to(_a			)
       model.eval()
       _SCREAMING_SNAKE_CASE							   =model(_a							, labels=_a			)
       self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.num_labels)			)





  def 						A  (		self				:     List[str]			)     ->   Tuple:





       '''simple docstring'''






       _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_torch
class 							A__   (	A__					,       A__					,       unittest.TestCase  ):
  A__					=    (CvtModel, CvtForImageClassification) if is_torch_available() else ()
  A__					=    (
      {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
      if is_torch_available()
      else {}
  )

  A__					=    False
  A__					=    False
  A__					=    False
  A__					=    False
  A__					=    False





  def 						A  (		self				:     Union[str, Any]			)     ->   List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =CvtModelTester(self			)
       _SCREAMING_SNAKE_CASE							   =ConfigTester(self							, config_class=_a							, has_text_modality=_a							, hidden_size=37			)





  def 						A  (		self				:     Any			)     ->   Any:





       '''simple docstring'''






       self.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()





  def 						A  (		self				:     Any			)     ->   Optional[Any]:





       '''simple docstring'''






       return





  @unittest.skip(reason='Cvt does not output attentions'			)
  def 						A  (		self				:     List[str]			)     ->   Optional[int]:





       '''simple docstring'''






       pass





  @unittest.skip(reason='Cvt does not use inputs_embeds'			)
  def 						A  (		self				:     str			)     ->   Optional[Any]:





       '''simple docstring'''






       pass





  @unittest.skip(reason='Cvt does not support input and output embeddings'			)
  def 						A  (		self				:     Tuple			)     ->   Any:





       '''simple docstring'''






       pass





  def 						A  (		self				:     str			)     ->   Union[str, Any]:





       '''simple docstring'''






       _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.forward			)
            # 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 						A  (		self				:     Union[str, Any]			)     ->   List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_a			)





  def 						A  (		self				:     Union[str, Any]			)     ->   Dict:





       '''simple docstring'''






       def check_hidden_states_output(_a				:     Optional[int]							, _a				:     Optional[Any]							, _a				:     str			):
            _SCREAMING_SNAKE_CASE							   =model_class(_a			)
            model.to(_a			)
            model.eval()

            with torch.no_grad():
                 _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 						A  (		self				:     Tuple			)     ->   List[str]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_a			)





  @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'			)
  def 						A  (		self				:     str			)     ->   List[Any]:





       '''simple docstring'''






       pass





  @slow
  def 						A  (		self				:     Optional[Any]			)     ->   Optional[Any]:





       '''simple docstring'''






       for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _SCREAMING_SNAKE_CASE							   =CvtModel.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_torch
@require_vision
class 							A__   (	unittest.TestCase  ):





  @cached_property
  def 						A  (		self				:     Tuple			)     ->   List[str]:





       '''simple docstring'''






       return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)





  @slow
  def 						A  (		self				:     List[str]			)     ->   Optional[int]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							   =CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(_a			)

       _SCREAMING_SNAKE_CASE							   =self.default_image_processor
       _SCREAMING_SNAKE_CASE							   =prepare_img()
       _SCREAMING_SNAKE_CASE							   =image_processor(images=_a							, return_tensors='pt'			).to(_a			)

       # forward pass
       with torch.no_grad():
            _SCREAMING_SNAKE_CASE							   =model(**_a			)

       # verify the logits
       _SCREAMING_SNAKE_CASE							   =torch.Size((1, 1000)			)
       self.assertEqual(outputs.logits.shape							, _a			)

       _SCREAMING_SNAKE_CASE							   =torch.tensor([0.92_85, 0.90_15, -0.31_50]			).to(_a			)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]							, _a							, atol=1e-4			)			)



'''simple docstring'''
def 	_lowerCAmelCase (						_UpperCamelCase						:					str    )				->      bool:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							   =0
     for ch in input_str:
          _SCREAMING_SNAKE_CASE							   =ord(_UpperCamelCase    )
          _SCREAMING_SNAKE_CASE							   =pow(2							,			_UpperCamelCase    )

          # If we already turned on bit for current character's unicode
          if bitmap >> ch_unicode & 1 == 1:
               return False
          bitmap |= ch_bit_index_on
     return True


if __name__ == "__main__":
     import doctest

     doctest.testmod()
