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





  """simple docstring"""

  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	Tuple			=   self.config_class(**self.inputs_dict       )
     self.parent.assertTrue(hasattr(_a							,'embed_dim'       )       )
     self.parent.assertTrue(hasattr(_a							,'num_heads'       )       )







class UpperCAmelCase__	:





  """simple docstring"""

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


     '''simple docstring'''






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


  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     _a				:	Any			=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

     _a				:	Tuple			=   None
     if self.use_labels:
        _a				:	Optional[int]			=   ids_tensor([self.batch_size]							,self.num_labels       )

     _a				:	int			=   self.get_config()
     return config, pixel_values, labels


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


     '''simple docstring'''






     _a				:	Optional[int]			=   CvtModel(config=_a       )
     model.to(_a       )
     model.eval()
     _a				:	Optional[int]			=   model(_a       )
     _a				:	Optional[int]			=   (self.image_size, self.image_size)
     _a,  _a				:	Tuple			=   image_size[0], image_size[1]
     for i in range(len(self.depth       )       ):
        _a				:	int			=   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
        _a				:	List[str]			=   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      :     Optional[int]							,_a      :     Optional[int]							,_a      :     List[str]       ):


     '''simple docstring'''






     _a				:	str			=   self.num_labels
     _a				:	Tuple			=   CvtForImageClassification(_a       )
     model.to(_a       )
     model.eval()
     _a				:	int			=   model(_a							,labels=_a       )
     self.parent.assertEqual(result.logits.shape							,(self.batch_size, self.num_labels)       )


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a				:	List[Any]			=   self.prepare_config_and_inputs()
     _a,  _a,  _a				:	Optional[Any]			=   config_and_inputs
     _a				:	List[Any]			=   {'pixel_values': pixel_values}
     return config, inputs_dict







@require_torch
class UpperCAmelCase__	( lowercase__    ,				lowercase__    ,				unittest.TestCase	):





  """simple docstring"""

  __UpperCAmelCase				:				str   =					(CvtModel, CvtForImageClassification) if is_torch_available() else ()
  __UpperCAmelCase				:				Tuple   =					(
      {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification}
      if is_torch_available()
      else {}
  )

  __UpperCAmelCase				:				List[str]   =					False
  __UpperCAmelCase				:				Dict   =					False
  __UpperCAmelCase				:				Tuple   =					False
  __UpperCAmelCase				:				Union[str, Any]   =					False
  __UpperCAmelCase				:				List[str]   =					False


  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   CvtModelTester(self       )
     _a				:	Optional[Any]			=   ConfigTester(self							,config_class=_a							,has_text_modality=_a							,hidden_size=37       )


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


     '''simple docstring'''






     return


  @unittest.skip(reason='Cvt does not output attentions'       )
  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     pass


  @unittest.skip(reason='Cvt does not use inputs_embeds'       )
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     pass


  @unittest.skip(reason='Cvt does not support input and output embeddings'       )
  def   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     pass


  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a,  _a				:	Tuple			=   self.model_tester.prepare_config_and_inputs_for_common()

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

        _a				:	Optional[int]			=   ['pixel_values']
        self.assertListEqual(arg_names[:1]							,_a       )


  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_a       )


  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






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

        with torch.no_grad():
           _a				:	Optional[Any]			=   model(**self._prepare_for_class(_a							,_a       )       )

        _a				:	Tuple			=   outputs.hidden_states

        _a				:	str			=   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,
            ]							,)

     _a,  _a				:	Any			=   self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(_a							,_a							,_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[str]			=   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[int]       ):


     '''simple docstring'''






     pass


  @slow
  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _a				:	Any			=   CvtModel.from_pretrained(_a       )
        self.assertIsNotNone(_a       )





def 					UpperCAmelCase_		():






   """simple docstring"""

   _a				:	Dict			=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
   return image







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





  """simple docstring"""

  @cached_property
  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






     return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )


  @slow
  def   __lowercase		(		self      :     str       ):


     '''simple docstring'''






     _a				:	Optional[Any]			=   CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(_a       )

     _a				:	List[Any]			=   self.default_image_processor
     _a				:	Optional[Any]			=   prepare_img()
     _a				:	List[str]			=   image_processor(images=_a							,return_tensors='pt'       ).to(_a       )

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

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

     _a				:	List[str]			=   torch.tensor([0.9285, 0.9015, -0.3150]       ).to(_a       )

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





'''simple docstring'''







def 					UpperCAmelCase_		(__a      :    list ,	__a      :    list ,	__a      :    int ):






   """simple docstring"""

   _a				:	Optional[Any]			=   len(__a )
   _a				:	int			=   [[0] * n for i in range(__a )]
   for i in range(__a ):
      _a				:	Tuple			=   y_points[i]

   for i in range(2 ,	__a ):
      for j in range(__a ,	__a ):
         _a				:	Tuple			=   (
             (xa - x_points[j - i + 1]) * q[j][i - 1]
             - (xa - x_points[j]) * q[j - 1][i - 1]
         ) / (x_points[j] - x_points[j - i + 1])

   return [q[n - 1][n - 1], q]


if __name__ == "__main__":
  import doctest

  doctest.testmod()



