





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






       """simple docstring"""





       def snake_case__		(				self  :						Optional[Any]	)       ->	Tuple:

            '''simple docstring'''




            _UpperCamelCase							       =			self.config_class(**self.inputs_dict	)
            self.parent.assertTrue(hasattr(lowerCAmelCase__			,					'''embed_dim'''	)	)
            self.parent.assertTrue(hasattr(lowerCAmelCase__			,					'''num_heads'''	)	)

class 							__lowerCAmelCase	:






       """simple docstring"""





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

            '''simple docstring'''




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

            '''simple docstring'''




            _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 snake_case__		(				self  :						Optional[int]	)       ->	Union[str, 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 snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						str	)       ->	Tuple:

            '''simple docstring'''




            _UpperCamelCase							       =			CvtModel(config=lowerCAmelCase__	)
            model.to(lowerCAmelCase__	)
            model.eval()
            _UpperCamelCase							       =			model(lowerCAmelCase__	)
            _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 snake_case__		(				self  :						Optional[int]			,					lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						Tuple			,					lowerCAmelCase__  :						Dict	)       ->	Optional[Any]:

            '''simple docstring'''




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







       def snake_case__		(				self  :						Tuple	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.prepare_config_and_inputs()
            _UpperCamelCase       ,							_UpperCamelCase       ,							_UpperCamelCase							       =			config_and_inputs
            _UpperCamelCase							       =			{'''pixel_values''': pixel_values}
            return config, inputs_dict

@require_torch
class 							__lowerCAmelCase	(       __magic_name__		,		__magic_name__		,		unittest.TestCase					):






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

       _snake_case      :	Optional[Any]									=       False
       _snake_case      :	int									=       False
       _snake_case      :	Union[str, Any]									=       False
       _snake_case      :	Tuple									=       False
       _snake_case      :	List[Any]									=       False





       def snake_case__		(				self  :						str	)       ->	List[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			CvtModelTester(self	)
            _UpperCamelCase							       =			ConfigTester(self			,					config_class=lowerCAmelCase__			,					has_text_modality=lowerCAmelCase__			,					hidden_size=37	)





       def snake_case__		(				self  :						str	)       ->	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 snake_case__		(				self  :						Optional[int]	)       ->	List[str]:

            '''simple docstring'''




            return





       @unittest.skip(reason='''Cvt does not output attentions'''	)
       def snake_case__		(				self  :						int	)       ->	Tuple:

            '''simple docstring'''




            pass





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

            '''simple docstring'''




            pass





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

            '''simple docstring'''




            pass





       def snake_case__		(				self  :						Dict	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase       ,							_UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 _UpperCamelCase							       =			model_class(lowerCAmelCase__	)
                 _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]			,					lowerCAmelCase__	)





       def snake_case__		(				self  :						List[str]	)       ->	List[str]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCAmelCase__	)





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

            '''simple docstring'''




            def check_hidden_states_output(lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						str	):
                 _UpperCamelCase							       =			model_class(lowerCAmelCase__	)
                 model.to(lowerCAmelCase__	)
                 model.eval()

                 with torch.no_grad():
                      _UpperCamelCase							       =			model(**self._prepare_for_class(lowerCAmelCase__			,					lowerCAmelCase__	)	)

                 _UpperCamelCase							       =			outputs.hidden_states

                 _UpperCamelCase							       =			len(self.model_tester.depth	)
                 self.assertEqual(len(lowerCAmelCase__	)			,					lowerCAmelCase__	)

                 # 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(lowerCAmelCase__			,					lowerCAmelCase__			,					lowerCAmelCase__	)

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

                 check_hidden_states_output(lowerCAmelCase__			,					lowerCAmelCase__			,					lowerCAmelCase__	)





       def snake_case__		(				self  :						int	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__	)





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

            '''simple docstring'''




            pass







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

            '''simple docstring'''




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







def    a__							(							)						->						Tuple:





     """simple docstring"""

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




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






       """simple docstring"""





       @cached_property
       def snake_case__		(				self  :						Dict	)       ->	Tuple:

            '''simple docstring'''




            return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)







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

            '''simple docstring'''




            _UpperCamelCase							       =			CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(lowerCAmelCase__	)

            _UpperCamelCase							       =			self.default_image_processor
            _UpperCamelCase							       =			prepare_img()
            _UpperCamelCase							       =			image_processor(images=lowerCAmelCase__			,					return_tensors='''pt'''	).to(lowerCAmelCase__	)

            # forward pass
            with torch.no_grad():
                 _UpperCamelCase							       =			model(**lowerCAmelCase__	)

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

            _UpperCamelCase							       =			torch.tensor([0.9285, 0.9015, -0.3150]	).to(lowerCAmelCase__	)

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










'''simple docstring'''

def    a__							(							lowercase   :	Dict,   lowercase   :	Optional[Any] )						->						int:





     """simple docstring"""

     _UpperCamelCase							       =			0
     _UpperCamelCase							       =			len(lowercase ) - 1

     while left <= right:
          # avoid divided by 0 during interpolation
          if sorted_collection[left] == sorted_collection[right]:
               if sorted_collection[left] == item:
                    return left
               else:
                    return None

          _UpperCamelCase							       =			left + ((item - sorted_collection[left]) * (right - left)) // (
              sorted_collection[right] - sorted_collection[left]
          )

          # out of range check
          if point < 0 or point >= len(lowercase ):
               return None

          _UpperCamelCase							       =			sorted_collection[point]
          if current_item == item:
               return point
          else:
               if point < left:
                    _UpperCamelCase							       =			left
                    _UpperCamelCase							       =			point
               elif point > right:
                    _UpperCamelCase							       =			right
                    _UpperCamelCase							       =			point
               else:
                    if item < current_item:
                         _UpperCamelCase							       =			point - 1
                    else:
                         _UpperCamelCase							       =			point + 1
     return None







def    a__							(							lowercase   :	int,   lowercase   :	Optional[int],   lowercase   :	List[Any],   lowercase   :	List[Any] )						->						Dict:





     """simple docstring"""

     if sorted_collection[left] == sorted_collection[right]:
          if sorted_collection[left] == item:
               return left
          else:
               return None

     _UpperCamelCase							       =			left + ((item - sorted_collection[left]) * (right - left)) // (
         sorted_collection[right] - sorted_collection[left]
     )

     # out of range check
     if point < 0 or point >= len(lowercase ):
          return None

     if sorted_collection[point] == item:
          return point
     elif point < left:
          return interpolation_search_by_recursion(lowercase,   lowercase,   lowercase,   lowercase )
     elif point > right:
          return interpolation_search_by_recursion(lowercase,   lowercase,   lowercase,   lowercase )
     else:
          if sorted_collection[point] > item:
               return interpolation_search_by_recursion(
                   lowercase,   lowercase,   lowercase,   point - 1 )
          else:
               return interpolation_search_by_recursion(
                   lowercase,   lowercase,   point + 1,   lowercase )







def    a__							(							lowercase   :	Any )						->						List[Any]:





     """simple docstring"""

     if collection != sorted(lowercase ):
          raise ValueError('''Collection must be ascending sorted''' )
     return True


if __name__ == "__main__":
   import sys
   lowercase__		:     int			=							0
   if debug == 1:
      lowercase__		:     Optional[Any]			=							[10, 30, 40, 45, 50, 66, 77, 93]
      try:
         __assert_sorted(collection)
      except ValueError:
         sys.exit('Sequence must be ascending sorted to apply interpolation search')
      lowercase__		:     List[str]			=							67

   lowercase__		:     Optional[int]			=							interpolation_search(collection, target)
   if result is not None:
      print(F"""{target} found at positions: {result}""")
   else:
      print('Not found')



