

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       snake_case_  (						__A   ):







			'''simple docstring'''

			def 							snake_case__(	self					:							Any				) ->str:
									snake_case_  =      self.config_class(**self.inputs_dict				)
									self.parent.assertTrue(hasattr(_UpperCamelCase				,  '''embed_dim'''				)				)
									self.parent.assertTrue(hasattr(_UpperCamelCase				,  '''num_heads'''				)				)






class       snake_case_  :







			'''simple docstring'''

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







			def 							snake_case__(	self					:							Optional[int]				) ->Any:
									snake_case_  =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

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







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







			def 							snake_case__(	self					:							Optional[int]				) ->Union[str, Any]:
									snake_case_  =      self.prepare_config_and_inputs()
									snake_case_,       snake_case_,       snake_case_  =      config_and_inputs
									snake_case_  =      {'''pixel_values''': pixel_values}
									return config, inputs_dict






@require_torch
class       snake_case_  (						__A      ,			__A      ,			unittest.TestCase   ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE	:  Tuple		     =							(CvtModel, CvtForImageClassification) if is_torch_available() else ()
			SCREAMING_SNAKE_CASE	:  Dict		     =							(
			    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
			    if is_torch_available()
			    else {}
			)

			SCREAMING_SNAKE_CASE	:  Optional[Any]		     =							False
			SCREAMING_SNAKE_CASE	:  Optional[int]		     =							False
			SCREAMING_SNAKE_CASE	:  Dict		     =							False
			SCREAMING_SNAKE_CASE	:  Optional[Any]		     =							False
			SCREAMING_SNAKE_CASE	:  Tuple		     =							False







			def 							snake_case__(	self					:							Optional[Any]				) ->Optional[Any]:
									snake_case_  =      CvtModelTester(self				)
									snake_case_  =      ConfigTester(self				,  config_class=_UpperCamelCase				,  has_text_modality=_UpperCamelCase				,  hidden_size=3_7				)







			def 							snake_case__(	self					:							Dict				) ->Union[str, 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 							snake_case__(	self					:							str				) ->int:
									return







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







			@unittest.skip(reason='''Cvt does not use inputs_embeds'''				)
			def 							snake_case__(	self					:							Any				) ->Dict:
									pass







			@unittest.skip(reason='''Cvt does not support input and output embeddings'''				)
			def 							snake_case__(	self					:							List[Any]				) ->Union[str, Any]:
									pass







			def 							snake_case__(	self					:							Dict				) ->Dict:
									snake_case_,       snake_case_  =      self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case_  =      ['''pixel_values''']
															self.assertListEqual(arg_names[:1]				,  _UpperCamelCase				)







			def 							snake_case__(	self					:							int				) ->List[Any]:
									snake_case_  =      self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase				)







			def 							snake_case__(	self					:							List[Any]				) ->List[Any]:
									def check_hidden_states_output(_UpperCamelCase					:							List[Any]				,  _UpperCamelCase					:							Optional[Any]				,  _UpperCamelCase					:							Any				):
															snake_case_  =      model_class(_UpperCamelCase				)
															model.to(_UpperCamelCase				)
															model.eval()

															with torch.no_grad():
																					snake_case_  =      model(**self._prepare_for_class(_UpperCamelCase				,  _UpperCamelCase				)				)

															snake_case_  =      outputs.hidden_states

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

									snake_case_,       snake_case_  =      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															snake_case_  =      True
															check_hidden_states_output(_UpperCamelCase				,  _UpperCamelCase				,  _UpperCamelCase				)

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

															check_hidden_states_output(_UpperCamelCase				,  _UpperCamelCase				,  _UpperCamelCase				)







			def 							snake_case__(	self					:							Optional[Any]				) ->Any:
									snake_case_  =      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 							snake_case__(	self					:							Any				) ->Any:
									pass







			@slow
			def 							snake_case__(	self					:							Tuple				) ->Tuple:
									for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_  =      CvtModel.from_pretrained(_UpperCamelCase				)
															self.assertIsNotNone(_UpperCamelCase				)






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





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







			'''simple docstring'''

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







			@slow
			def 							snake_case__(	self					:							str				) ->str:
									snake_case_  =      CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_UpperCamelCase				)

									snake_case_  =      self.default_image_processor
									snake_case_  =      prepare_img()
									snake_case_  =      image_processor(images=_UpperCamelCase				,  return_tensors='''pt'''				).to(_UpperCamelCase				)

									# forward pass
									with torch.no_grad():
															snake_case_  =      model(**_UpperCamelCase				)

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

									snake_case_  =      torch.tensor([0.9285, 0.9015, -0.3150]				).to(_UpperCamelCase				)

									self.assertTrue(torch.allclose(outputs.logits[0, :3]				,  _UpperCamelCase				,  atol=1e-4				)				)
from __future__ import annotations






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				float		, _SCREAMING_SNAKE_CASE     :				float		, _SCREAMING_SNAKE_CASE     :				float		, ):
						if (electron_conc, hole_conc, intrinsic_conc).count(0			) != 1:
												raise ValueError("""You cannot supply more or less than 2 values"""			)
						elif electron_conc < 0:
												raise ValueError("""Electron concentration cannot be negative in a semiconductor"""			)
						elif hole_conc < 0:
												raise ValueError("""Hole concentration cannot be negative in a semiconductor"""			)
						elif intrinsic_conc < 0:
												raise ValueError(
												    """Intrinsic concentration cannot be negative in a semiconductor"""			)
						elif electron_conc == 0:
												return (
												    "electron_conc",
												    intrinsic_conc**2 / hole_conc,
												)
						elif hole_conc == 0:
												return (
												    "hole_conc",
												    intrinsic_conc**2 / electron_conc,
												)
						elif intrinsic_conc == 0:
												return (
												    "intrinsic_conc",
												    (electron_conc * hole_conc) ** 0.5,
												)
						else:
												return (-1, -1)


if __name__ == "__main__":
	import doctest

	doctest.testmod()






