
"""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   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     def  lowerCAmelCase__       (      self  )->					List[str]:
          UpperCAmelCase__							: List[str] 							=						self.config_class(**self.inputs_dict  )
          self.parent.assertTrue(hasattr(__UpperCamelCase ,			"embed_dim"  )  )
          self.parent.assertTrue(hasattr(__UpperCamelCase ,			"num_heads"  )  )







class   _lowercase						:


     '''simple docstring'''





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



     def  lowerCAmelCase__       (      self  )->					int:
          UpperCAmelCase__							: str 							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

          UpperCAmelCase__							: int 							=						None
          if self.use_labels:
               UpperCAmelCase__							: str 							=						ids_tensor([self.batch_size] ,			self.num_labels  )

          UpperCAmelCase__							: Optional[int] 							=						self.get_config()
          return config, pixel_values, labels



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



     def  lowerCAmelCase__       (      self  )->					int:
          UpperCAmelCase__							: int 							=						self.prepare_config_and_inputs()
          UpperCAmelCase__							: Tuple 							=						config_and_inputs
          UpperCAmelCase__							: Optional[Any] 							=						{"pixel_values": pixel_values}
          return config, inputs_dict







@require_torch
class   _lowercase						(       lowerCAmelCase_	,   lowerCAmelCase_	,   unittest.TestCase				):


     '''simple docstring'''





     _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  lowerCAmelCase__       (      self  )->					List[Any]:
          UpperCAmelCase__							: Dict 							=						CvtModelTester(self  )
          UpperCAmelCase__							: str 							=						ConfigTester(self ,			config_class=__UpperCamelCase ,			has_text_modality=__UpperCamelCase ,			hidden_size=37  )



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



     @unittest.skip(reason="Cvt does not output attentions"  )
     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          pass



     @unittest.skip(reason="Cvt does not use inputs_embeds"  )
     def  lowerCAmelCase__       (      self  )->					Optional[Any]:
          pass



     @unittest.skip(reason="Cvt does not support input and output embeddings"  )
     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          pass



     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          UpperCAmelCase__							: Optional[Any] 							=						self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase__							: List[str] 							=						["pixel_values"]
               self.assertListEqual(arg_names[:1] ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					Tuple:
          UpperCAmelCase__							: List[Any] 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					str:
          def check_hidden_states_output(__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  ):
               UpperCAmelCase__							: Tuple 							=						model_class(__UpperCamelCase  )
               model.to(__UpperCamelCase  )
               model.eval()

               with torch.no_grad():
                    UpperCAmelCase__							: str 							=						model(**self._prepare_for_class(__UpperCamelCase ,			__UpperCamelCase  )  )

               UpperCAmelCase__							: int 							=						outputs.hidden_states

               UpperCAmelCase__							: Any 							=						len(self.model_tester.depth  )
               self.assertEqual(len(__UpperCamelCase  ) ,			__UpperCamelCase  )

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

          for model_class in self.all_model_classes:
               UpperCAmelCase__							: Dict 							=						True
               check_hidden_states_output(__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )

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

               check_hidden_states_output(__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )



     def  lowerCAmelCase__       (      self  )->					str:
          UpperCAmelCase__							: int 							=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase  )



     @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."  )
     def  lowerCAmelCase__       (      self  )->					int:
          pass



     @slow
     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__							: str 							=						CvtModel.from_pretrained(__UpperCamelCase  )
               self.assertIsNotNone(__UpperCamelCase  )





def 							a__ (				):






     '''simple docstring'''
     UpperCAmelCase__							: Tuple 							=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
     return image







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


     '''simple docstring'''





     @cached_property
     def  lowerCAmelCase__       (      self  )->					List[Any]:
          return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )



     @slow
     def  lowerCAmelCase__       (      self  )->					List[Any]:
          UpperCAmelCase__							: Tuple 							=						CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  ).to(__UpperCamelCase  )

          UpperCAmelCase__							: Dict 							=						self.default_image_processor
          UpperCAmelCase__							: Any 							=						prepare_img()
          UpperCAmelCase__							: Optional[int] 							=						image_processor(images=__UpperCamelCase ,			return_tensors="pt"  ).to(__UpperCamelCase  )

          # forward pass
          with torch.no_grad():
               UpperCAmelCase__							: Tuple 							=						model(**__UpperCamelCase  )

          # verify the logits
          UpperCAmelCase__							: Optional[Any] 							=						torch.Size((1, 10_00)  )
          self.assertEqual(outputs.logits.shape ,			__UpperCamelCase  )

          UpperCAmelCase__							: Dict 							=						torch.tensor([0.9285, 0.9015, -0.3150]  ).to(__UpperCamelCase  )

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





"""simple docstring"""




from typing import TYPE_CHECKING

from ....utils import _LazyModule


A__      :	List[str]          =    {"""tokenization_tapex""": ["""TapexTokenizer"""]}


if TYPE_CHECKING:
    from .tokenization_tapex import TapexTokenizer


else:
    import sys

    A__      :	Any          =    _LazyModule(__name__, globals()["""__file__"""], _import_structure)



