
"""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 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						int									=      self.config_class(**self.inputs_dict )
			self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       ,		'embed_dim' ) )
			self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       ,		'num_heads' ) )




class  A__       :

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

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[int]									=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

			__lowerCAmelCase			:						List[Any]									=      None
			if self.use_labels:
				__lowerCAmelCase			:						Dict									=      ids_tensor([self.batch_size]       ,		self.num_labels )

			__lowerCAmelCase			:						Any									=      self.get_config()
			return config, pixel_values, labels

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







		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Tuple									=      self.prepare_config_and_inputs()
			__lowerCAmelCase			,   __lowerCAmelCase			,   __lowerCAmelCase			:						Tuple									=      config_and_inputs
			__lowerCAmelCase			:						Dict									=      {'pixel_values': pixel_values}
			return config, inputs_dict




@require_torch
class  A__       (	__a       ,     __a       ,     unittest.TestCase):
		A_						:       Dict				   =	(CvtModel, CvtForImageClassification) if is_torch_available() else ()
		A_						:       Optional[int]				   =	(
		    {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification}
		    if is_torch_available()
		    else {}
		)

		A_						:       List[str]				   =	False
		A_						:       Any				   =	False
		A_						:       Optional[int]				   =	False
		A_						:       Any				   =	False
		A_						:       str				   =	False

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Tuple									=      CvtModelTester(self )
			__lowerCAmelCase			:						int									=      ConfigTester(self       ,		config_class=_SCREAMING_SNAKE_CASE       ,		has_text_modality=_SCREAMING_SNAKE_CASE       ,		hidden_size=37 )

		def 							__lowerCamelCase							(      self ):
			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 ):
			return

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

		@unittest.skip(reason='Cvt does not use inputs_embeds' )
		def 							__lowerCamelCase							(      self ):
			pass

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

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			,   __lowerCAmelCase			:						Dict									=      self.model_tester.prepare_config_and_inputs_for_common()

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

				__lowerCAmelCase			:						str									=      ['pixel_values']
				self.assertListEqual(arg_names[:1]       ,		_SCREAMING_SNAKE_CASE )

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						List[Any]									=      self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE )

		def 							__lowerCamelCase							(      self ):

			def check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				__lowerCAmelCase			:						int									=      model_class(_SCREAMING_SNAKE_CASE )
				model.to(_SCREAMING_SNAKE_CASE )
				model.eval()

				with torch.no_grad():
					__lowerCAmelCase			:						Optional[int]									=      model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ) )

				__lowerCAmelCase			:						Dict									=      outputs.hidden_states

				__lowerCAmelCase			:						Optional[Any]									=      len(self.model_tester.depth )
				self.assertEqual(len(_SCREAMING_SNAKE_CASE )       ,		_SCREAMING_SNAKE_CASE )

				# 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,
				    ]       ,		)

			__lowerCAmelCase			,   __lowerCAmelCase			:						Optional[int]									=      self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase			:						Any									=      True
				check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE )

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

				check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE )

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Dict									=      self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE )

		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
		def 							__lowerCamelCase							(      self ):
			pass







		@slow
		def 							__lowerCamelCase							(      self ):

			for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__lowerCAmelCase			:						List[str]									=      CvtModel.from_pretrained(_SCREAMING_SNAKE_CASE )
				self.assertIsNotNone(_SCREAMING_SNAKE_CASE )



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




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

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







		@slow
		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[Any]									=      CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_SCREAMING_SNAKE_CASE )

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

			# forward pass
			with torch.no_grad():
				__lowerCAmelCase			:						Optional[int]									=      model(**_SCREAMING_SNAKE_CASE )

			# verify the logits
			__lowerCAmelCase			:						Union[str, Any]									=      torch.Size((1, 10_00) )
			self.assertEqual(outputs.logits.shape       ,		_SCREAMING_SNAKE_CASE )

			__lowerCAmelCase			:						Optional[Any]									=      torch.tensor([0.9285, 0.9015, -0.3150] ).to(_SCREAMING_SNAKE_CASE )

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





'''simple docstring'''







from __future__ import annotations





def 						snake_case_							(_a	:							Dict    ,   _a	:							str    ,   _a	:							Optional[Any]    ,   _a	:							List[str]     ):  # noqa: E741
    while r - l > 1:
        UpperCAmelCase			       =		(l + r) // 2
        if v[m] >= key:
            UpperCAmelCase			       =		m
        else:
            UpperCAmelCase			       =		m  # noqa: E741
    return r





def 						snake_case_							(_a	:							list[int]     ):
    if len(_a     ) == 0:
        return 0

    UpperCAmelCase			       =		[0] * len(_a     )
    UpperCAmelCase			       =		1

    UpperCAmelCase			       =		v[0]

    for i in range(1    ,   len(_a     )     ):
        if v[i] < tail[0]:
            UpperCAmelCase			       =		v[i]
        elif v[i] > tail[length - 1]:
            UpperCAmelCase			       =		v[i]
            length += 1
        else:
            UpperCAmelCase			       =		v[i]

    return length


if __name__ == "__main__":
   import doctest

   doctest.testmod()




