






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







	"""simple docstring"""



	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   Any        =			self.config_class(**self.inputs_dict       )
							self.parent.assertTrue(hasattr(_lowercase  ,      'embed_dim'       )       )
							self.parent.assertTrue(hasattr(_lowercase  ,      'num_heads'       )       )






class 							__magic_name__     :







	"""simple docstring"""



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

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

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







	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   Optional[int]        =			self.prepare_config_and_inputs()
							lowercase_  ,      lowercase_  ,      lowercase_      :   Dict        =			config_and_inputs
							lowercase_      :   Optional[Any]        =			{'pixel_values': pixel_values}
							return config, inputs_dict






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







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Optional[int]        =  (CvtModel, CvtForImageClassification) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE_					:      List[str]        =  (
	    {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
	    if is_torch_available()
	    else {}
	)

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

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

													lowercase_      :   List[str]        =			['pixel_values']
													self.assertListEqual(arg_names[:1]  ,      _lowercase       )
	def        lowerCamelCase__		(							self       )						->  List[str]:
							lowercase_      :   Optional[int]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							def check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       ):
													lowercase_      :   int        =			model_class(_lowercase       )
													model.to(_lowercase       )
													model.eval()

													with torch.no_grad():
																			lowercase_      :   List[str]        =			model(**self._prepare_for_class(_lowercase  ,      _lowercase       )       )

													lowercase_      :   Any        =			outputs.hidden_states

													lowercase_      :   str        =			len(self.model_tester.depth       )
													self.assertEqual(len(_lowercase       )  ,      _lowercase       )

													# 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_      :   Optional[Any]        =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase_      :   Any        =			True
													check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													lowercase_      :   Union[str, Any]        =			True

													check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       )
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   Any        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_lowercase       )
	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							pass







	@slow
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_      :   Optional[int]        =			CvtModel.from_pretrained(_lowercase       )
													self.assertIsNotNone(_lowercase       )






def 	_UpperCAmelCase    (  )			->			Union[str, Any]:





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






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







	"""simple docstring"""



	@cached_property
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )







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

							lowercase_      :   Tuple        =			self.default_image_processor
							lowercase_      :   Any        =			prepare_img()
							lowercase_      :   Union[str, Any]        =			image_processor(images=_lowercase  ,      return_tensors='pt'       ).to(_lowercase       )

							# forward pass
							with torch.no_grad():
													lowercase_      :   Optional[Any]        =			model(**_lowercase       )

							# verify the logits
							lowercase_      :   str        =			torch.Size((1, 1000)       )
							self.assertEqual(outputs.logits.shape  ,      _lowercase       )

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

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








'''simple docstring'''

from ..utils import DummyObject, requires_backends






class 							__magic_name__     (	metaclass=UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      str        =  ['transformers', 'torch', 'note_seq']
	def __init__(							self  ,      *_lowercase  ,      **_lowercase       )						->  Dict:
							requires_backends(self  ,      ['transformers', 'torch', 'note_seq']       )
	@classmethod
	def        lowerCamelCase__		(							cls  ,      *_lowercase  ,      **_lowercase       )						->  List[str]:
							requires_backends(cls  ,      ['transformers', 'torch', 'note_seq']       )







	@classmethod
	def        lowerCamelCase__		(							cls  ,      *_lowercase  ,      **_lowercase       )						->  Dict:
							requires_backends(cls  ,      ['transformers', 'torch', 'note_seq']       )
