



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_		(  a__							):
       def 					snake_case_       (			self       )     ->		Any:
          UpperCamelCase    :  Optional[Any]							=	self.config_class(**self.inputs_dict       )
          self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'embed_dim'       )       )
          self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_,			'num_heads'       )       )






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

          UpperCamelCase    :  Union[str, Any]							=	None
          if self.use_labels:
             UpperCamelCase    :  int							=	ids_tensor([self.batch_size],			self.num_labels       )

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






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






@require_torch
class 				lowerCAmelCase_		(  a__       ,    a__       ,    unittest.TestCase							):
       UpperCAmelCase__				:					Any        =  (CvtModel, CvtForImageClassification) if is_torch_available() else ()
       UpperCAmelCase__				:					str        =  (
           {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
           if is_torch_available()
           else {}
       )

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

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

             UpperCamelCase    :  str							=	['pixel_values']
             self.assertListEqual(arg_names[:1],			SCREAMING_SNAKE_CASE_       )
       def 					snake_case_       (			self       )     ->		int:
          UpperCamelCase    :  str							=	self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_       )
       def 					snake_case_       (			self       )     ->		int:
          def check_hidden_states_output(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       ):
             UpperCamelCase    :  int							=	model_class(SCREAMING_SNAKE_CASE_       )
             model.to(SCREAMING_SNAKE_CASE_       )
             model.eval()

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

             UpperCamelCase    :  str							=	outputs.hidden_states

             UpperCamelCase    :  Dict							=	len(self.model_tester.depth       )
             self.assertEqual(len(SCREAMING_SNAKE_CASE_       ),			SCREAMING_SNAKE_CASE_       )

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

          for model_class in self.all_model_classes:
             UpperCamelCase    :  Optional[Any]							=	True
             check_hidden_states_output(SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_       )

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

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






       @slow
       def 					snake_case_       (			self       )     ->		Union[str, Any]:
          for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase    :  Optional[Any]							=	CvtModel.from_pretrained(SCREAMING_SNAKE_CASE_       )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_       )






def 		UpperCamelCase	(   )	->     Tuple:
   UpperCamelCase    :  int							=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
   return image



@require_torch
@require_vision
class 				lowerCAmelCase_		(  unittest.TestCase							):
       @cached_property
       def 					snake_case_       (			self       )     ->		int:
          return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )






       @slow
       def 					snake_case_       (			self       )     ->		Union[str, Any]:
          UpperCamelCase    :  Tuple							=	CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(SCREAMING_SNAKE_CASE_       )

          UpperCamelCase    :  List[str]							=	self.default_image_processor
          UpperCamelCase    :  int							=	prepare_img()
          UpperCamelCase    :  Optional[int]							=	image_processor(images=SCREAMING_SNAKE_CASE_,			return_tensors='pt'       ).to(SCREAMING_SNAKE_CASE_       )

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

          # verify the logits
          UpperCamelCase    :  List[str]							=	torch.Size((1, 1000)       )
          self.assertEqual(outputs.logits.shape,			SCREAMING_SNAKE_CASE_       )

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

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








def 		UpperCamelCase	(   snake_case__       :    int       ,     snake_case__       :    int	)	->     int:
   return int(input_a == input_a == 0	)
def 		UpperCamelCase	(   )	->     None:
   print('Truth Table of NOR Gate:'	)
   print('|   Input 1   |  Input 2  | Output |'	)
   print(F"""|      0      |    0      |  {nor_gate(0       ,     0	)}     |"""	)
   print(F"""|      0      |    1      |  {nor_gate(0       ,     1	)}     |"""	)
   print(F"""|      1      |    0      |  {nor_gate(1       ,     0	)}     |"""	)
   print(F"""|      1      |    1      |  {nor_gate(1       ,     1	)}     |"""	)


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    main()



