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



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



    def    _lowercase		(self       :       str					):
         UpperCAmelCase_			       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

         UpperCAmelCase_			       =  None
         if self.use_labels:
              UpperCAmelCase_			       =  ids_tensor([self.batch_size]  ,     self.num_labels					)

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



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






    def    _lowercase		(self       :       Any					):
         UpperCAmelCase_			       =  self.prepare_config_and_inputs()
         UpperCAmelCase_       ,					UpperCAmelCase_       ,					UpperCAmelCase_			       =  config_and_inputs
         UpperCAmelCase_			       =  {"pixel_values": pixel_values}
         return config, inputs_dict




@require_torch
class 			__A (					UpperCamelCase__						,      UpperCamelCase__						,      unittest.TestCase      ):
    a__			:		Dict			  =    (CvtModel, CvtForImageClassification) if is_torch_available() else ()
    a__			:		str			  =    (
        {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification}
        if is_torch_available()
        else {}
    )

    a__			:		Tuple			  =    False
    a__			:		Tuple			  =    False
    a__			:		Optional[Any]			  =    False
    a__			:		str			  =    False
    a__			:		List[str]			  =    False



    def    _lowercase		(self       :       Optional[int]					):
         UpperCAmelCase_			       =  CvtModelTester(self					)
         UpperCAmelCase_			       =  ConfigTester(self  ,     config_class=__a  ,     has_text_modality=__a  ,     hidden_size=37					)



    def    _lowercase		(self       :       Any					):
         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    _lowercase		(self       :       Union[str, Any]					):
         return



    @unittest.skip(reason="Cvt does not output attentions"					)
    def    _lowercase		(self       :       List[str]					):
         pass



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



    @unittest.skip(reason="Cvt does not support input and output embeddings"					)
    def    _lowercase		(self       :       List[Any]					):
         pass



    def    _lowercase		(self       :       List[Any]					):
         UpperCAmelCase_       ,					UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCAmelCase_			       =  ["pixel_values"]
              self.assertListEqual(arg_names[:1]  ,     __a					)



    def    _lowercase		(self       :       Dict					):
         UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__a					)



    def    _lowercase		(self       :       Optional[int]					):
         def check_hidden_states_output(__a       :       Any  ,     __a       :       Union[str, Any]  ,     __a       :       Tuple					):
              UpperCAmelCase_			       =  model_class(__a					)
              model.to(__a					)
              model.eval()

              with torch.no_grad():
                   UpperCAmelCase_			       =  model(**self._prepare_for_class(__a  ,     __a					)					)

              UpperCAmelCase_			       =  outputs.hidden_states

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

         UpperCAmelCase_       ,					UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_			       =  True
              check_hidden_states_output(__a  ,     __a  ,     __a					)

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

              check_hidden_states_output(__a  ,     __a  ,     __a					)



    def    _lowercase		(self       :       Optional[int]					):
         UpperCAmelCase_			       =  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    _lowercase		(self       :       Optional[Any]					):
         pass






    @slow
    def    _lowercase		(self       :       Optional[int]					):
         for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_			       =  CvtModel.from_pretrained(__a					)
              self.assertIsNotNone(__a					)





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


     '''simple docstring'''




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






@require_torch
@require_vision
class 			__A (					unittest.TestCase      ):



    @cached_property
    def    _lowercase		(self       :       Tuple					):
         return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)






    @slow
    def    _lowercase		(self       :       List[Any]					):
         UpperCAmelCase_			       =  CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(__a					)

         UpperCAmelCase_			       =  self.default_image_processor
         UpperCAmelCase_			       =  prepare_img()
         UpperCAmelCase_			       =  image_processor(images=__a  ,     return_tensors="pt"					).to(__a					)

         # forward pass
         with torch.no_grad():
              UpperCAmelCase_			       =  model(**__a					)

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

         UpperCAmelCase_			       =  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'''





from __future__ import annotations





def   a_   (		_UpperCAmelCase    :      list[int]				)    ->  bool:
      return len(set(_UpperCAmelCase				)				) == len(_UpperCAmelCase				)


if __name__ == "__main__":
    import doctest

    doctest.testmod()



