

'''simple docstring'''



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import (
						    TFDeiTForImageClassification,
						    TFDeiTForImageClassificationWithTeacher,
						    TFDeiTForMaskedImageModeling,
						    TFDeiTModel,
						)
						from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import DeiTImageProcessor



class lowerCamelCase			:



			'''simple docstring'''






			def __init__(				self	:						Dict		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Any=13		,      lowerCAmelCase_	:						str=30		,      lowerCAmelCase_	:						List[str]=2		,      lowerCAmelCase_	:						int=3		,      lowerCAmelCase_	:						List[str]=True		,      lowerCAmelCase_	:						Dict=True		,      lowerCAmelCase_	:						Optional[int]=32		,      lowerCAmelCase_	:						Optional[int]=2		,      lowerCAmelCase_	:						Dict=4		,      lowerCAmelCase_	:						Dict=37		,      lowerCAmelCase_	:						Optional[Any]="gelu"		,      lowerCAmelCase_	:						List[Any]=0.1		,      lowerCAmelCase_	:						Dict=0.1		,      lowerCAmelCase_	:						int=10		,      lowerCAmelCase_	:						Dict=0.02		,      lowerCAmelCase_	:						Any=3		,      lowerCAmelCase_	:						List[str]=None		,      lowerCAmelCase_	:						Optional[int]=2		,      )      ->		List[str]:





									'''simple docstring'''
									A__					:       Tuple     =parent
									A__					:       Any     =batch_size
									A__					:       Any     =image_size
									A__					:       int     =patch_size
									A__					:       Any     =num_channels
									A__					:       List[Any]     =is_training
									A__					:       List[Any]     =use_labels
									A__					:       Any     =hidden_size
									A__					:       str     =num_hidden_layers
									A__					:       Any     =num_attention_heads
									A__					:       Optional[int]     =intermediate_size
									A__					:       int     =hidden_act
									A__					:       str     =hidden_dropout_prob
									A__					:       Tuple     =attention_probs_dropout_prob
									A__					:       List[Any]     =type_sequence_label_size
									A__					:       int     =initializer_range
									A__					:       Union[str, Any]     =scope
									A__					:       Dict     =encoder_stride

									# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
									A__					:       Optional[Any]     =(image_size // patch_size) ** 2
									A__					:       Optional[Any]     =num_patches + 2


			def lowercase__						(				self	:						List[str]			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

									A__					:       Any     =None
									if self.use_labels:
															A__					:       Optional[Any]     =ids_tensor([self.batch_size]		,      self.type_sequence_label_size			)

									A__					:       int     =self.get_config()

									return config, pixel_values, labels


			def lowercase__						(				self	:						Optional[int]			)      ->		Optional[Any]:





									'''simple docstring'''
									return DeiTConfig(
									    image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      hidden_size=self.hidden_size		,      num_hidden_layers=self.num_hidden_layers		,      num_attention_heads=self.num_attention_heads		,      intermediate_size=self.intermediate_size		,      hidden_act=self.hidden_act		,      hidden_dropout_prob=self.hidden_dropout_prob		,      attention_probs_dropout_prob=self.attention_probs_dropout_prob		,      is_decoder=lowercase_		,      initializer_range=self.initializer_range		,      encoder_stride=self.encoder_stride		,      )


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						str			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       Any     =TFDeiTModel(config=lowercase_			)
									A__					:       List[str]     =model(lowercase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)


			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						List[Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       str     =TFDeiTForMaskedImageModeling(config=lowercase_			)
									A__					:       Dict     =model(lowercase_			)
									self.parent.assertEqual(
									    result.reconstruction.shape		,      (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

									# test greyscale images
									A__					:       Optional[Any]     =1
									A__					:       int     =TFDeiTForMaskedImageModeling(lowercase_			)

									A__					:       List[Any]     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
									A__					:       Optional[Any]     =model(lowercase_			)
									self.parent.assertEqual(result.reconstruction.shape		,      (self.batch_size, 1, self.image_size, self.image_size)			)


			def lowercase__						(				self	:						List[Any]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Any			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       Optional[int]     =self.type_sequence_label_size
									A__					:       Union[str, Any]     =TFDeiTForImageClassification(lowercase_			)
									A__					:       Dict     =model(lowercase_		,      labels=lowercase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.type_sequence_label_size)			)

									# test greyscale images
									A__					:       Dict     =1
									A__					:       List[str]     =TFDeiTForImageClassification(lowercase_			)

									A__					:       Any     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
									A__					:       Tuple     =model(lowercase_		,      labels=lowercase_			)
									self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.type_sequence_label_size)			)



			def lowercase__						(				self	:						str			)      ->		Tuple:





									'''simple docstring'''
									A__					:       List[str]     =self.prepare_config_and_inputs()
									A__					:       Dict     =config_and_inputs
									A__					:       Any     ={'''pixel_values''': pixel_values}
									return config, inputs_dict



@require_tf
class lowerCamelCase			(  a_	,						a_	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (
			        TFDeiTModel,
			        TFDeiTForImageClassification,
			        TFDeiTForImageClassificationWithTeacher,
			        TFDeiTForMaskedImageModeling,
			    )
			    if is_tf_available()
			    else ()
			)
			__snake_case        =	(
			    {
			        'feature-extraction': TFDeiTModel,
			        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
			    }
			    if is_tf_available()
			    else {}
			)

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


			def lowercase__						(				self	:						Union[str, Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       List[Any]     =TFDeiTModelTester(self			)
									A__					:       int     =ConfigTester(self		,      config_class=lowercase_		,      has_text_modality=lowercase_		,      hidden_size=37			)


			def lowercase__						(				self	:						Union[str, Any]			)      ->		Dict:





									'''simple docstring'''
									self.config_tester.run_common_tests()


			@unittest.skip(reason="""DeiT does not use inputs_embeds"""			)
			def lowercase__						(				self	:						List[Any]			)      ->		List[Any]:





									'''simple docstring'''
									pass


			def lowercase__						(				self	:						Dict			)      ->		str:





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       Optional[int]     =model_class(lowercase_			)
															self.assertIsInstance(model.get_input_embeddings()		,      (tf.keras.layers.Layer)			)
															A__					:       int     =model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowercase_		,      tf.keras.layers.Dense			)			)


			def lowercase__						(				self	:						str			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       Tuple     =model_class(lowercase_			)
															A__					:       Tuple     =inspect.signature(model.call			)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															A__					:       Tuple     =[*signature.parameters.keys()]

															A__					:       Tuple     =['''pixel_values''']
															self.assertListEqual(arg_names[:1]		,      lowercase_			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		List[str]:





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase_			)


			def lowercase__						(				self	:						int			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Optional[int]     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_			)


			def lowercase__						(				self	:						int			)      ->		Tuple:





									'''simple docstring'''
									A__					:       str     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowercase_			)


			def lowercase__						(				self	:						List[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Tuple=False			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Tuple     =super()._prepare_for_class(lowercase_		,      lowercase_		,      return_labels=lowercase_			)

									if return_labels:
															if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call			).parameters:
																					del inputs_dict["labels"]

									return inputs_dict



			@slow
			def lowercase__						(				self	:						List[Any]			)      ->		Any:





									'''simple docstring'''
									for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       Optional[Any]     =TFDeiTModel.from_pretrained(lowercase_			)
															self.assertIsNotNone(lowercase_			)


def 						__lowerCamelCase	(       )	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Optional[Any]     =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
						return image



@require_tf
@require_vision
class lowerCamelCase			(  unittest.TestCase						):



			'''simple docstring'''






			@cached_property
			def lowercase__						(				self	:						Dict			)      ->		List[str]:





									'''simple docstring'''
									return (
									    DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""			)
									    if is_vision_available()
									    else None
									)



			@slow
			def lowercase__						(				self	:						List[str]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       List[Any]     =TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""			)

									A__					:       int     =self.default_image_processor
									A__					:       Union[str, Any]     =prepare_img()
									A__					:       Dict     =image_processor(images=lowercase_		,      return_tensors="""tf"""			)

									# forward pass
									A__					:       Union[str, Any]     =model(**lowercase_			)

									# verify the logits
									A__					:       int     =tf.TensorShape((1, 10_00)			)
									self.assertEqual(outputs.logits.shape		,      lowercase_			)

									A__					:       Tuple     =tf.constant([-1.0266, 0.1912, -1.2861]			)

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




'''simple docstring'''



def 						__lowerCamelCase	(       __snake_case					:		int	)	->							bool:






						"""simple docstring"""





						if p < 2:
												raise ValueError("""p should not be less than 2!"""	)
						elif p == 2:
												return True

						A__					:       Any     =4
						A__					:       int     =(1 << p) - 1
						for _ in range(p - 2	):
												A__					:       Dict     =((s * s) - 2) % m
						return s == 0


if __name__ == "__main__":
		print(lucas_lehmer_test(7))
		print(lucas_lehmer_test(11))

