
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__							(       __lowercase):




	'''simple docstring'''




	def      _lowerCamelCase       (      self	:str		)	->				List[str]:
								__UpperCamelCase			:     Optional[int]         =      self.config_class(**self.inputs_dict		)
								self.parent.assertTrue(hasattr(a  ,     "embed_dim"		)		)
								self.parent.assertTrue(hasattr(a  ,     "num_heads"		)		)




class 				lowerCamelCase__							:




	'''simple docstring'''




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







	def      _lowerCamelCase       (      self	:Optional[int]		)	->				int:
								__UpperCamelCase			:     Dict         =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

								__UpperCamelCase			:     List[str]         =      self.get_config()
								return config, pixel_values, labels







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







	def      _lowerCamelCase       (      self	:str		)	->				int:
								__UpperCamelCase			:     str         =      self.prepare_config_and_inputs()
								__UpperCamelCase			:     str         =      config_and_inputs
								__UpperCamelCase			:     Dict         =      {"pixel_values": pixel_values}
								return config, inputs_dict




@require_torch
class 				lowerCamelCase__							(       __lowercase  ,		__lowercase  ,		unittest.TestCase):




	'''simple docstring'''




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

	_A			=  False
	_A			=  False
	_A			=  False
	_A			=  False
	_A			=  False







	def      _lowerCamelCase       (      self	:Tuple		)	->				Dict:
								__UpperCamelCase			:     Optional[int]         =      CvtModelTester(self		)
								__UpperCamelCase			:     Optional[Any]         =      ConfigTester(self  ,     config_class=a  ,     has_text_modality=a  ,     hidden_size=3_7		)







	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Any:
								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	:int		)	->				Tuple:
								return







	@unittest.skip(reason="Cvt does not output attentions"		)
	def      _lowerCamelCase       (      self	:List[str]		)	->				Optional[Any]:
								pass







	@unittest.skip(reason="Cvt does not use inputs_embeds"		)
	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Dict:
								pass







	@unittest.skip(reason="Cvt does not support input and output embeddings"		)
	def      _lowerCamelCase       (      self	:int		)	->				int:
								pass







	def      _lowerCamelCase       (      self	:List[Any]		)	->				Union[str, Any]:
								__UpperCamelCase			:     Union[str, Any]         =      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															__UpperCamelCase			:     List[Any]         =      model_class(a		)
															__UpperCamelCase			:     Union[str, Any]         =      inspect.signature(model.forward		)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															__UpperCamelCase			:     Any         =      [*signature.parameters.keys()]

															__UpperCamelCase			:     List[str]         =      ["pixel_values"]
															self.assertListEqual(arg_names[:1]  ,     a		)







	def      _lowerCamelCase       (      self	:Dict		)	->				Optional[int]:
								__UpperCamelCase			:     Dict         =      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a		)







	def      _lowerCamelCase       (      self	:Tuple		)	->				Union[str, Any]:
								def check_hidden_states_output(a	:str  ,     a	:str  ,     a	:List[str]		):
															__UpperCamelCase			:     List[str]         =      model_class(a		)
															model.to(a		)
															model.eval()

															with torch.no_grad():
																						__UpperCamelCase			:     int         =      model(**self._prepare_for_class(a  ,     a		)		)

															__UpperCamelCase			:     Union[str, Any]         =      outputs.hidden_states

															__UpperCamelCase			:     Any         =      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,
															    ]  ,     )

								__UpperCamelCase			:     List[Any]         =      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															__UpperCamelCase			:     List[str]         =      True
															check_hidden_states_output(a  ,     a  ,     a		)

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

															check_hidden_states_output(a  ,     a  ,     a		)







	def      _lowerCamelCase       (      self	:Optional[int]		)	->				Dict:
								__UpperCamelCase			:     List[Any]         =      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      _lowerCamelCase       (      self	:Optional[Any]		)	->				Any:
								pass







	@slow
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				Optional[Any]:
								for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__UpperCamelCase			:     List[str]         =      CvtModel.from_pretrained(a		)
															self.assertIsNotNone(a		)




def 			_SCREAMING_SNAKE_CASE      (	)      ->					List[Any]:






							'''simple docstring'''





							__UpperCamelCase			:     str         =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
							return image




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




	'''simple docstring'''




	@cached_property
	def      _lowerCamelCase       (      self	:int		)	->				List[Any]:
								return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)







	@slow
	def      _lowerCamelCase       (      self	:Dict		)	->				int:
								__UpperCamelCase			:     int         =      CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(a		)

								__UpperCamelCase			:     int         =      self.default_image_processor
								__UpperCamelCase			:     int         =      prepare_img()
								__UpperCamelCase			:     int         =      image_processor(images=a  ,     return_tensors="pt"		).to(a		)

								# forward pass
								with torch.no_grad():
															__UpperCamelCase			:     Dict         =      model(**a		)

								# verify the logits
								__UpperCamelCase			:     List[Any]         =      torch.Size((1, 1_0_0_0)		)
								self.assertEqual(outputs.logits.shape  ,     a		)

								__UpperCamelCase			:     Any         =      torch.tensor([0.9285, 0.9015, -0.3150]		).to(a		)

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

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowercase						:      str									= {
    'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig']
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase						:      str									= ['VisionEncoderDecoderModel']

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase						:      List[Any]									= ['TFVisionEncoderDecoderModel']

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase						:      int									= ['FlaxVisionEncoderDecoderModel']

if TYPE_CHECKING:
		from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel

else:
		import sys

		lowercase						:      Dict									= _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)