



'''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 					UpperCAmelCase__	(		UpperCamelCase__ ):



					def        UpperCAmelCase_ (    self     )     ->			List[str]:
						__lowerCAmelCase												=  self.config_class(**self.inputs_dict     )
						self.parent.assertTrue(hasattr(UpperCamelCase			,				"embed_dim"     )     )
						self.parent.assertTrue(hasattr(UpperCamelCase			,				"num_heads"     )     )






class 					UpperCAmelCase__	:



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



					def        UpperCAmelCase_ (    self     )     ->			Optional[Any]:
						__lowerCAmelCase												=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

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



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



					def        UpperCAmelCase_ (    self     )     ->			Dict:
						__lowerCAmelCase												=  self.prepare_config_and_inputs()
						__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase												=  config_and_inputs
						__lowerCAmelCase												=  {"pixel_values": pixel_values}
						return config, inputs_dict






@require_torch
class 					UpperCAmelCase__	(		UpperCamelCase__							,       UpperCamelCase__							,       unittest.TestCase ):
					a      :     Tuple        =							(CvtModel, CvtForImageClassification) if is_torch_available() else ()
					a      :     Dict        =							(
					    {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification}
					    if is_torch_available()
					    else {}
					)

					a      :     Tuple        =							False
					a      :     Optional[Any]        =							False
					a      :     List[Any]        =							False
					a      :     Optional[Any]        =							False
					a      :     List[Any]        =							False



					def        UpperCAmelCase_ (    self     )     ->			int:
						__lowerCAmelCase												=  CvtModelTester(self     )
						__lowerCAmelCase												=  ConfigTester(self			,				config_class=UpperCamelCase			,				has_text_modality=UpperCamelCase			,				hidden_size=37     )



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



					@unittest.skip(reason="Cvt does not output attentions"     )
					def        UpperCAmelCase_ (    self     )     ->			Optional[int]:
						pass



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



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



					def        UpperCAmelCase_ (    self     )     ->			Dict:
						__lowerCAmelCase							,       __lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs_for_common()

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

							__lowerCAmelCase												=  ["pixel_values"]
							self.assertListEqual(arg_names[:1]			,				UpperCamelCase     )



					def        UpperCAmelCase_ (    self     )     ->			Union[str, Any]:
						__lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase     )



					def        UpperCAmelCase_ (    self     )     ->			Tuple:
						def check_hidden_states_output(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     ):
							__lowerCAmelCase												=  model_class(UpperCamelCase     )
							model.to(UpperCamelCase     )
							model.eval()

							with torch.no_grad():
								__lowerCAmelCase												=  model(**self._prepare_for_class(UpperCamelCase			,				UpperCamelCase     )     )

							__lowerCAmelCase												=  outputs.hidden_states

							__lowerCAmelCase												=  len(self.model_tester.depth     )
							self.assertEqual(len(UpperCamelCase     )			,				UpperCamelCase     )

							# 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												=  self.model_tester.prepare_config_and_inputs_for_common()

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

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

							check_hidden_states_output(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )



					def        UpperCAmelCase_ (    self     )     ->			List[str]:
						__lowerCAmelCase												=  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCamelCase     )



					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."     )
					def        UpperCAmelCase_ (    self     )     ->			Optional[Any]:
						pass



					@slow
					def        UpperCAmelCase_ (    self     )     ->			Optional[int]:
						for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__lowerCAmelCase												=  CvtModel.from_pretrained(UpperCamelCase     )
							self.assertIsNotNone(UpperCamelCase     )



def   __lowerCAmelCase					(							):






	'''simple docstring'''




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






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



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



					@slow
					def        UpperCAmelCase_ (    self     )     ->			List[Any]:
						__lowerCAmelCase												=  CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(UpperCamelCase     )

						__lowerCAmelCase												=  self.default_image_processor
						__lowerCAmelCase												=  prepare_img()
						__lowerCAmelCase												=  image_processor(images=UpperCamelCase			,				return_tensors="pt"     ).to(UpperCamelCase     )

						# forward pass
						with torch.no_grad():
							__lowerCAmelCase												=  model(**UpperCamelCase     )

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

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

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




'''simple docstring'''



from __future__ import annotations



def   __lowerCAmelCase					(							lowerCamelCase   :						list					):






	'''simple docstring'''




	if not nums:
		raise ValueError("List is empty"					)
	return sum(lowerCamelCase					) / len(lowerCamelCase					)


if __name__ == "__main__":
	import doctest

	doctest.testmod()