
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 		_lowercase    (			self    :     Optional[Any]			)			->	Tuple:
					lowercase_	    =   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 					lowercase__:



	"""simple docstring"""




	def __init__(			self    :     Dict			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]=1_3			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]=6_4			,				SCREAMING_SNAKE_CASE_    :     Any=3			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=[1_6, 4_8, 9_6]			,				SCREAMING_SNAKE_CASE_    :     List[str]=[1, 3, 6]			,				SCREAMING_SNAKE_CASE_    :     List[Any]=[1, 2, 1_0]			,				SCREAMING_SNAKE_CASE_    :     Tuple=[7, 3, 3]			,				SCREAMING_SNAKE_CASE_    :     int=[4, 2, 2]			,				SCREAMING_SNAKE_CASE_    :     List[Any]=[2, 1, 1]			,				SCREAMING_SNAKE_CASE_    :     Any=[2, 2, 2]			,				SCREAMING_SNAKE_CASE_    :     Any=[False, False, True]			,				SCREAMING_SNAKE_CASE_    :     int=[0.0, 0.0, 0.0]			,				SCREAMING_SNAKE_CASE_    :     Dict=0.02			,				SCREAMING_SNAKE_CASE_    :     str=1e-12			,				SCREAMING_SNAKE_CASE_    :     Optional[int]=True			,				SCREAMING_SNAKE_CASE_    :     int=True			,				SCREAMING_SNAKE_CASE_    :     int=2			,				)			->	Optional[Any]:
					lowercase_	    =   parent
					lowercase_	    =   batch_size
					lowercase_	    =   image_size
					lowercase_	    =   patch_sizes
					lowercase_	    =   patch_stride
					lowercase_	    =   patch_padding
					lowercase_	    =   is_training
					lowercase_	    =   use_labels
					lowercase_	    =   num_labels
					lowercase_	    =   num_channels
					lowercase_	    =   embed_dim
					lowercase_	    =   num_heads
					lowercase_	    =   stride_kv
					lowercase_	    =   depth
					lowercase_	    =   cls_token
					lowercase_	    =   attention_drop_rate
					lowercase_	    =   initializer_range
					lowercase_	    =   layer_norm_eps
	def 		_lowercase    (			self    :     Union[str, Any]			)			->	int:
					lowercase_	    =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

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




	def 		_lowercase    (			self    :     List[str]			)			->	str:
					lowercase_	    =   self.prepare_config_and_inputs()
					lowercase_    ,      lowercase_    ,      lowercase_	    =   config_and_inputs
					lowercase_	    =   {'''pixel_values''': pixel_values}
					return config, inputs_dict

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



	"""simple docstring"""




	a     :int       	=      (CvtModel, CvtForImageClassification) if is_torch_available() else ()
	a     :Union[str, Any]       	=      (
	    {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification}
	    if is_torch_available()
	    else {}
	)

	a     :Union[str, Any]       	=      False
	a     :Optional[int]       	=      False
	a     :Union[str, Any]       	=      False
	a     :Optional[int]       	=      False
	a     :str       	=      False
	def 		_lowercase    (			self    :     str			)			->	str:
					lowercase_	    =   CvtModelTester(self			)
					lowercase_	    =   ConfigTester(self			,				config_class=__SCREAMING_SNAKE_CASE			,				has_text_modality=__SCREAMING_SNAKE_CASE			,				hidden_size=3_7			)
	def 		_lowercase    (			self    :     Tuple			)			->	Dict:
					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    :     str			)			->	Tuple:
					return
	@unittest.skip(reason='''Cvt does not output attentions'''			)
	def 		_lowercase    (			self    :     List[str]			)			->	Optional[int]:
					pass
	@unittest.skip(reason='''Cvt does not use inputs_embeds'''			)
	def 		_lowercase    (			self    :     int			)			->	List[str]:
					pass
	@unittest.skip(reason='''Cvt does not support input and output embeddings'''			)
	def 		_lowercase    (			self    :     int			)			->	List[Any]:
					pass
	def 		_lowercase    (			self    :     Any			)			->	Optional[int]:
					lowercase_    ,      lowercase_	    =   self.model_tester.prepare_config_and_inputs_for_common()

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

									lowercase_	    =   ['''pixel_values''']
									self.assertListEqual(arg_names[:1]			,				__SCREAMING_SNAKE_CASE			)
	def 		_lowercase    (			self    :     Union[str, Any]			)			->	Dict:
					lowercase_	    =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)
	def 		_lowercase    (			self    :     Tuple			)			->	List[Any]:




					def check_hidden_states_output(SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     List[str]			,				SCREAMING_SNAKE_CASE_    :     str			):
									lowercase_	    =   model_class(__SCREAMING_SNAKE_CASE			)
									model.to(__SCREAMING_SNAKE_CASE			)
									model.eval()

									with torch.no_grad():
													lowercase_	    =   model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			)			)

									lowercase_	    =   outputs.hidden_states

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

					lowercase_    ,      lowercase_	    =   self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									lowercase_	    =   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"]
									lowercase_	    =   True

									check_hidden_states_output(__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			,				__SCREAMING_SNAKE_CASE			)
	def 		_lowercase    (			self    :     List[Any]			)			->	List[str]:
					lowercase_	    =   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 		_lowercase    (			self    :     str			)			->	int:
					pass




	@slow
	def 		_lowercase    (			self    :     List[str]			)			->	Dict:




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




def 							a		(				):


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


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



	"""simple docstring"""




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




	@slow
	def 		_lowercase    (			self    :     List[str]			)			->	List[Any]:
					lowercase_	    =   CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(__SCREAMING_SNAKE_CASE			)

					lowercase_	    =   self.default_image_processor
					lowercase_	    =   prepare_img()
					lowercase_	    =   image_processor(images=__SCREAMING_SNAKE_CASE			,				return_tensors='''pt'''			).to(__SCREAMING_SNAKE_CASE			)

					# forward pass
					with torch.no_grad():
									lowercase_	    =   model(**__SCREAMING_SNAKE_CASE			)

					# verify the logits
					lowercase_	    =   torch.Size((1, 1_0_0_0)			)
					self.assertEqual(outputs.logits.shape			,				__SCREAMING_SNAKE_CASE			)

					lowercase_	    =   torch.tensor([0.92_85, 0.90_15, -0.31_50]			).to(__SCREAMING_SNAKE_CASE			)

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










'''simple docstring'''



import inspect
import warnings
from typing import Any, Dict, Optional, Union

from packaging import version







def       _UpperCamelCase			(*_lowerCamelCase				:  str ,						_lowerCamelCase				:  Optional[Union[Dict, Any]] = None ,						_lowerCamelCase				:  List[Any]=True ,						_lowerCamelCase				:  str=2						)-> str:




     '''simple docstring'''





     from .. import __version__

     __snake_case            =	take_from
     __snake_case            =	()
     if not isinstance(args[0] ,						_lowerCamelCase						):
          __snake_case            =	(args,)

     for attribute, version_name, message in args:
          if version.parse(version.parse(_lowerCamelCase						).base_version						) >= version.parse(_lowerCamelCase						):
               raise ValueError(
                   f'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\''''
                   f''' version {__version__} is >= {version_name}'''						)

          __snake_case            =	None
          if isinstance(_lowerCamelCase ,						_lowerCamelCase						) and attribute in deprecated_kwargs:
               values += (deprecated_kwargs.pop(_lowerCamelCase						),)
               __snake_case            =	f'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.'''
          elif hasattr(_lowerCamelCase ,						_lowerCamelCase						):
               values += (getattr(_lowerCamelCase ,						_lowerCamelCase						),)
               __snake_case            =	f'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.'''
          elif deprecated_kwargs is None:
               __snake_case            =	f'''`{attribute}` is deprecated and will be removed in version {version_name}.'''

          if warning is not None:
               __snake_case            =	warning + ''' ''' if standard_warn else ''''''
               warnings.warn(warning + message ,						_lowerCamelCase ,						stacklevel=_lowerCamelCase						)

     if isinstance(_lowerCamelCase ,						_lowerCamelCase						) and len(_lowerCamelCase						) > 0:
          __snake_case            =	inspect.getouterframes(inspect.currentframe()						)[1]
          __snake_case            =	call_frame.filename
          __snake_case            =	call_frame.lineno
          __snake_case            =	call_frame.function
          __snake_case       ,     __snake_case            =	next(iter(deprecated_kwargs.items()						)						)
          raise TypeError(f'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`'''						)

     if len(_lowerCamelCase						) == 0:
          return
     elif len(_lowerCamelCase						) == 1:
          return values[0]
     return values






