






import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
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 (
	    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
	    MODEL_MAPPING,
	    LevitForImageClassification,
	    LevitForImageClassificationWithTeacher,
	    LevitModel,
	)
	from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import LevitImageProcessor


class 					_snake_case						(			lowercase__ ):






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Tuple         =   self.config_class(**self.inputs_dict       )
					self.parent.assertTrue(hasattr(__lowercase					,"hidden_sizes"       )       )
					self.parent.assertTrue(hasattr(__lowercase					,"num_attention_heads"       )       )




class 					_snake_case						:






	def __init__(		self					,UpperCamelCase					,UpperCamelCase=13					,UpperCamelCase=64					,UpperCamelCase=3					,UpperCamelCase=3					,UpperCamelCase=2					,UpperCamelCase=1					,UpperCamelCase=16					,UpperCamelCase=[128, 256, 384]					,UpperCamelCase=[4, 6, 8]					,UpperCamelCase=[2, 3, 4]					,UpperCamelCase=[16, 16, 16]					,UpperCamelCase=0					,UpperCamelCase=[2, 2, 2]					,UpperCamelCase=[2, 2, 2]					,UpperCamelCase=0.02					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=2					,)						->    int:
					snake_case__      :List[str]         =   parent
					snake_case__      :Tuple         =   batch_size
					snake_case__      :Optional[int]         =   image_size
					snake_case__      :str         =   num_channels
					snake_case__      :int         =   kernel_size
					snake_case__      :Optional[int]         =   stride
					snake_case__      :List[Any]         =   padding
					snake_case__      :str         =   hidden_sizes
					snake_case__      :int         =   num_attention_heads
					snake_case__      :str         =   depths
					snake_case__      :Optional[int]         =   key_dim
					snake_case__      :Any         =   drop_path_rate
					snake_case__      :Optional[Any]         =   patch_size
					snake_case__      :List[str]         =   attention_ratio
					snake_case__      :Tuple         =   mlp_ratio
					snake_case__      :str         =   initializer_range
					snake_case__      :int         =   [
					    ["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
					    ["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
					]
					snake_case__      :List[str]         =   is_training
					snake_case__      :Optional[int]         =   use_labels
					snake_case__      :str         =   num_labels
					snake_case__      :Tuple         =   initializer_range






	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__      :Dict         =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

					snake_case__      :int         =   None
					if self.use_labels:
									snake_case__      :List[Any]         =   ids_tensor([self.batch_size]					,self.num_labels       )

					snake_case__      :Optional[int]         =   self.get_config()
					return config, pixel_values, labels






	def    lowerCAmelCase_							(		self       )						->    Dict:
					return LevitConfig(
					    image_size=self.image_size					,num_channels=self.num_channels					,kernel_size=self.kernel_size					,stride=self.stride					,padding=self.padding					,patch_size=self.patch_size					,hidden_sizes=self.hidden_sizes					,num_attention_heads=self.num_attention_heads					,depths=self.depths					,key_dim=self.key_dim					,drop_path_rate=self.drop_path_rate					,mlp_ratio=self.mlp_ratio					,attention_ratio=self.attention_ratio					,initializer_range=self.initializer_range					,down_ops=self.down_ops					,)






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Any:
					snake_case__      :List[str]         =   LevitModel(config=__lowercase       )
					model.to(__lowercase       )
					model.eval()
					snake_case__      :Dict         =   model(__lowercase       )
					snake_case__      :Union[str, Any]         =   (self.image_size, self.image_size)
					snake_case__    ,						snake_case__      :List[Any]         =   image_size[0], image_size[1]
					for _ in range(4       ):
									snake_case__      :Dict         =   floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1       )
									snake_case__      :Dict         =   floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1       )
					self.parent.assertEqual(
					    result.last_hidden_state.shape					,(self.batch_size, ceil(height / 4       ) * ceil(width / 4       ), self.hidden_sizes[-1])					,)






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Tuple:
					snake_case__      :Optional[int]         =   self.num_labels
					snake_case__      :List[str]         =   LevitForImageClassification(__lowercase       )
					model.to(__lowercase       )
					model.eval()
					snake_case__      :str         =   model(__lowercase					,labels=__lowercase       )
					self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.num_labels)       )






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




@require_torch
class 					_snake_case						(			lowercase__       ,    lowercase__       ,    unittest.TestCase ):
	_A          =   (
	    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
	    if is_torch_available()
	    else ()
	)
	_A          =   (
	    {
	        """feature-extraction""": LevitModel,
	        """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher),
	    }
	    if is_torch_available()
	    else {}
	)

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






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :Union[str, Any]         =   LevitModelTester(self       )
					snake_case__      :str         =   ConfigTester(self					,config_class=__lowercase					,has_text_modality=__lowercase					,hidden_size=37       )






	def    lowerCAmelCase_							(		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    lowerCAmelCase_							(		self       )						->    Tuple:
					return






	@unittest.skip(reason="Levit does not use inputs_embeds"       )
	def    lowerCAmelCase_							(		self       )						->    Any:
					pass






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






	@unittest.skip(reason="Levit does not output attentions"       )
	def    lowerCAmelCase_							(		self       )						->    Any:
					pass






	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__    ,						snake_case__      :List[str]         =   self.model_tester.prepare_config_and_inputs_for_common()

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

									snake_case__      :Any         =   ["pixel_values"]
									self.assertListEqual(arg_names[:1]					,__lowercase       )






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					def check_hidden_states_output(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       ):
									snake_case__      :List[str]         =   model_class(__lowercase       )
									model.to(__lowercase       )
									model.eval()

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

									snake_case__      :str         =   outputs.hidden_states

									snake_case__      :int         =   len(self.model_tester.depths       ) + 1
									self.assertEqual(len(__lowercase       )					,__lowercase       )

									snake_case__      :Optional[Any]         =   (self.model_tester.image_size, self.model_tester.image_size)
									snake_case__    ,						snake_case__      :Union[str, Any]         =   image_size[0], image_size[1]
									for _ in range(4       ):
													snake_case__      :int         =   floor(
													    (
													        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
													        / self.model_tester.stride
													    )
													    + 1       )
													snake_case__      :Optional[Any]         =   floor(
													    (
													        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
													        / self.model_tester.stride
													    )
													    + 1       )
									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]       )					,[
									        height * width,
									        self.model_tester.hidden_sizes[0],
									    ]					,)

					snake_case__    ,						snake_case__      :Dict         =   self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									snake_case__      :List[Any]         =   True
									check_hidden_states_output(__lowercase					,__lowercase					,__lowercase       )

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

									check_hidden_states_output(__lowercase					,__lowercase					,__lowercase       )






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






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=False       )						->    Dict:
					snake_case__      :Any         =   super()._prepare_for_class(__lowercase					,__lowercase					,return_labels=__lowercase       )

					if return_labels:
									if model_class.__name__ == "LevitForImageClassificationWithTeacher":
													del inputs_dict["labels"]

					return inputs_dict






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					snake_case__      :Tuple         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__lowercase       )






	def    lowerCAmelCase_							(		self       )						->    Dict:
					snake_case__      :Optional[Any]         =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__lowercase       )






	def    lowerCAmelCase_							(		self       )						->    Dict:
					if not self.model_tester.is_training:
									return

					snake_case__    ,						snake_case__      :Any         =   self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__      :Optional[int]         =   True

					for model_class in self.all_model_classes:
									# LevitForImageClassificationWithTeacher supports inference-only
									if (
									    model_class in get_values(__lowercase       )
									    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
									):
													continue
									snake_case__      :Tuple         =   model_class(__lowercase       )
									model.to(__lowercase       )
									model.train()
									snake_case__      :Dict         =   self._prepare_for_class(__lowercase					,__lowercase					,return_labels=__lowercase       )
									snake_case__      :int         =   model(**__lowercase       ).loss
									loss.backward()






	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__    ,						snake_case__      :List[str]         =   self.model_tester.prepare_config_and_inputs_for_common()
					if not self.model_tester.is_training:
									return

					snake_case__      :List[Any]         =   False
					snake_case__      :int         =   True

					for model_class in self.all_model_classes:
									if model_class in get_values(__lowercase       ) or not model_class.supports_gradient_checkpointing:
													continue
									# LevitForImageClassificationWithTeacher supports inference-only
									if model_class.__name__ == "LevitForImageClassificationWithTeacher":
													continue
									snake_case__      :Tuple         =   model_class(__lowercase       )
									model.gradient_checkpointing_enable()
									model.to(__lowercase       )
									model.train()
									snake_case__      :Union[str, Any]         =   self._prepare_for_class(__lowercase					,__lowercase					,return_labels=__lowercase       )
									snake_case__      :Dict         =   model(**__lowercase       ).loss
									loss.backward()






	def    lowerCAmelCase_							(		self       )						->    Optional[Any]:
					snake_case__    ,						snake_case__      :int         =   self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__      :Optional[Any]         =   [
					    {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
					    {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
					    {"title": "regression", "num_labels": 1, "dtype": torch.float},
					]

					for model_class in self.all_model_classes:
									if (
									    model_class
									    not in [
									        *get_values(__lowercase       ),
									    ]
									    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
									):
													continue

									for problem_type in problem_types:
													with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}'       ):
																	snake_case__      :Optional[int]         =   problem_type["title"]
																	snake_case__      :Tuple         =   problem_type["num_labels"]

																	snake_case__      :List[Any]         =   model_class(__lowercase       )
																	model.to(__lowercase       )
																	model.train()

																	snake_case__      :Dict         =   self._prepare_for_class(__lowercase					,__lowercase					,return_labels=__lowercase       )

																	if problem_type["num_labels"] > 1:
																					snake_case__      :Optional[Any]         =   inputs["labels"].unsqueeze(1       ).repeat(1					,problem_type["num_labels"]       )

																	snake_case__      :List[str]         =   inputs["labels"].to(problem_type["dtype"]       )

																	# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																	# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																	# they have the same size." which is a symptom something in wrong for the regression problem.
																	# See https://github.com/huggingface/transformers/issues/11780
																	with warnings.catch_warnings(record=__lowercase       ) as warning_list:
																					snake_case__      :Dict         =   model(**__lowercase       ).loss
																	for w in warning_list:
																					if "Using a target size that is different to the input size" in str(w.message       ):
																									raise ValueError(
																									    f'Something is going wrong in the regression problem: intercepted {w.message}'       )

																	loss.backward()






	@slow
	def    lowerCAmelCase_							(		self       )						->    str:
					for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__      :Optional[Any]         =   LevitModel.from_pretrained(__lowercase       )
									self.assertIsNotNone(__lowercase       )





def 					lowercase_ (    )     -> str:





				'''simple docstring'''


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


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






	@cached_property
	def    lowerCAmelCase_							(		self       )						->    Dict:
					return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )






	@slow
	def    lowerCAmelCase_							(		self       )						->    Dict:
					snake_case__      :Union[str, Any]         =   LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(
					    __lowercase       )

					snake_case__      :str         =   self.default_image_processor
					snake_case__      :Tuple         =   prepare_img()
					snake_case__      :Union[str, Any]         =   image_processor(images=__lowercase					,return_tensors="pt"       ).to(__lowercase       )

					# forward pass
					with torch.no_grad():
									snake_case__      :str         =   model(**__lowercase       )

					# verify the logits
					snake_case__      :int         =   torch.Size((1, 1_000)       )
					self.assertEqual(outputs.logits.shape					,__lowercase       )

					snake_case__      :int         =   torch.tensor([1.0448, -0.3745, -1.8317]       ).to(__lowercase       )

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







def 					lowercase_ (    __snake_case     :							Tuple	,	__snake_case     :							Optional[int]      )     -> List[Any]:





				'''simple docstring'''


				snake_case__      :Dict         =   ""
				for i in table:
								res += inp[i - 1]
				return res





def 					lowercase_ (    __snake_case     :							List[str]      )     -> int:





				'''simple docstring'''


				return data[1:] + data[0]





def 					lowercase_ (    __snake_case     :							int	,	__snake_case     :							Union[str, Any]      )     -> Union[str, Any]:





				'''simple docstring'''


				snake_case__      :Union[str, Any]         =   ""
				for i in range(len(__snake_case      )      ):
								if a[i] == b[i]:
												res += "0"
								else:
												res += "1"
				return res





def 					lowercase_ (    __snake_case     :							Optional[int]	,	__snake_case     :							Dict      )     -> Union[str, Any]:





				'''simple docstring'''


				snake_case__      :int         =   int("0b" + data[0] + data[-1]	,	2      )
				snake_case__      :Union[str, Any]         =   int("0b" + data[1:3]	,	2      )
				return bin(s[row][col]      )[2:]





def 					lowercase_ (    __snake_case     :							Dict	,	__snake_case     :							Optional[Any]	,	__snake_case     :							Dict	,	__snake_case     :							List[Any]	,	__snake_case     :							Optional[int]      )     -> List[str]:





				'''simple docstring'''


				snake_case__      :Tuple         =   message[:4]
				snake_case__      :int         =   message[4:]
				snake_case__      :int         =   apply_table(__snake_case	,	__snake_case      )
				snake_case__      :Union[str, Any]         =   xor(__snake_case	,	__snake_case      )
				snake_case__      :Tuple         =   apply_sbox(__snake_case	,	temp[:4]      )  # noqa: E741
				snake_case__      :List[str]         =   apply_sbox(__snake_case	,	temp[4:]      )
				snake_case__      :int         =   "0" * (2 - len(__snake_case      )) + l  # noqa: E741
				snake_case__      :int         =   "0" * (2 - len(__snake_case      )) + r
				snake_case__      :Optional[Any]         =   apply_table(l + r	,	__snake_case      )
				snake_case__      :Tuple         =   xor(__snake_case	,	__snake_case      )
				return temp + right


if __name__ == "__main__":
	__UpperCAmelCase							:   Dict							=  input("Enter 10 bit key: ")
	__UpperCAmelCase							:   Tuple							=  input("Enter 8 bit message: ")

	__UpperCAmelCase							:   Any							=  [6, 3, 7, 4, 8, 5, 1_0, 9]
	__UpperCAmelCase							:   List[str]							=  [3, 5, 2, 7, 4, 1_0, 1, 9, 8, 6]
	__UpperCAmelCase							:   Tuple							=  [2, 4, 3, 1]
	__UpperCAmelCase							:   List[Any]							=  [2, 6, 3, 1, 4, 8, 5, 7]
	__UpperCAmelCase							:   Optional[Any]							=  [4, 1, 3, 5, 7, 2, 8, 6]
	__UpperCAmelCase							:   Optional[int]							=  [4, 1, 2, 3, 2, 3, 4, 1]
	__UpperCAmelCase							:   List[Any]							=  [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
	__UpperCAmelCase							:   Union[str, Any]							=  [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]

	# key generation
	__UpperCAmelCase							:   int							=  apply_table(key, paa_table)
	__UpperCAmelCase							:   Dict							=  temp[:5]
	__UpperCAmelCase							:   Optional[int]							=  temp[5:]
	__UpperCAmelCase							:   Optional[int]							=  left_shift(left)
	__UpperCAmelCase							:   Union[str, Any]							=  left_shift(right)
	__UpperCAmelCase							:   int							=  apply_table(left + right, pa_table)
	__UpperCAmelCase							:   Tuple							=  left_shift(left)
	__UpperCAmelCase							:   Union[str, Any]							=  left_shift(right)
	__UpperCAmelCase							:   Dict							=  left_shift(left)
	__UpperCAmelCase							:   Optional[Any]							=  left_shift(right)
	__UpperCAmelCase							:   Optional[int]							=  apply_table(left + right, pa_table)

	# encryption
	__UpperCAmelCase							:   Tuple							=  apply_table(message, IP)
	__UpperCAmelCase							:   Tuple							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   List[Any]							=  temp[4:] + temp[:4]
	__UpperCAmelCase							:   int							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   Union[str, Any]							=  apply_table(temp, IP_inv)
	print("Cipher text is:", CT)

	# decryption
	__UpperCAmelCase							:   List[Any]							=  apply_table(CT, IP)
	__UpperCAmelCase							:   List[Any]							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   int							=  temp[4:] + temp[:4]
	__UpperCAmelCase							:   Union[str, Any]							=  function(expansion, sa, sa, keya, temp)
	__UpperCAmelCase							:   Union[str, Any]							=  apply_table(temp, IP_inv)
	print("Plain text after decypting is:", PT)