




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		(  __UpperCAmelCase     ):



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.config_class(**self.inputs_dict   )
								self.parent.assertTrue(hasattr(UpperCamelCase__,	'''embed_dim'''   )   )
								self.parent.assertTrue(hasattr(UpperCamelCase__,	'''num_heads'''   )   )







class  A		:



		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,	):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.prepare_config_and_inputs()
								lowerCAmelCase_			,					lowerCAmelCase_			,					lowerCAmelCase_      			=  config_and_inputs
								lowerCAmelCase_      			=  {'''pixel_values''': pixel_values}
								return config, inputs_dict







@require_torch
class  A		(  __UpperCAmelCase      ,				__UpperCAmelCase      ,				unittest.TestCase     ):
		__snake_case									=   (CvtModel, CvtForImageClassification) if is_torch_available() else ()
		__snake_case									=   (
		    {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
		    if is_torch_available()
		    else {}
		)

		__snake_case									=   False
		__snake_case									=   False
		__snake_case									=   False
		__snake_case									=   False
		__snake_case									=   False



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  CvtModelTester(self   )
								lowerCAmelCase_      			=  ConfigTester(self,	config_class=UpperCamelCase__,	has_text_modality=UpperCamelCase__,	hidden_size=37   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								return



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







								"""simple docstring"""



								pass



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







								"""simple docstring"""



								pass



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







								"""simple docstring"""



								pass



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*UpperCamelCase__   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								pass







		@slow
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







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






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



		@cached_property
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )







		@slow
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								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.9_285, 0.9_015, -0.3_150]   ).to(UpperCamelCase__   )

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










def __UpperCamelCase			(       _A  ):
						if not numbers:
												return 0

						if not isinstance(_A ,  (list, tuple)  ) or not all(
						    isinstance(_A ,  _A  ) for number in numbers  ):
												raise ValueError('''numbers must be an iterable of integers'''  )

						lowerCAmelCase_      			=  lowerCAmelCase_      			=  lowerCAmelCase_      			=  numbers[0]

						for i in range(1 ,  len(_A  )  ):
												# update the maximum and minimum subarray products
												lowerCAmelCase_      			=  numbers[i]
												if number < 0:
																		lowerCAmelCase_			,					lowerCAmelCase_      			=  min_till_now, max_till_now
												lowerCAmelCase_      			=  max(_A ,  max_till_now * number  )
												lowerCAmelCase_      			=  min(_A ,  min_till_now * number  )

												# update the maximum product found till now
												lowerCAmelCase_      			=  max(_A ,  _A  )

						return max_prod




