

'''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   UpperCamelCase__    :


		"""simple docstring"""

		def __init__( self    ,			snake_case    ,			snake_case=1_3    ,			snake_case=3_0    ,			snake_case=2    ,			snake_case=3    ,			snake_case=True    ,			snake_case=True    ,			snake_case=3_2    ,			snake_case=2    ,			snake_case=4    ,			snake_case=3_7    ,			snake_case="gelu"    ,			snake_case=0.1    ,			snake_case=0.1    ,			snake_case=1_0    ,			snake_case=0.02    ,			snake_case=3    ,			snake_case=None    ,			snake_case=2    ,			):


							'''simple docstring'''

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

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







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							UpperCAmelCase		:							Dict   					=   None
							if self.use_labels:
												UpperCAmelCase		:							Tuple   					=   ids_tensor([self.batch_size]    ,			self.type_sequence_label_size			)

							UpperCAmelCase		:							int   					=   self.get_config()

							return config, pixel_values, labels







		def       A_       ( self			):


							'''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=__snake_case    ,			initializer_range=self.initializer_range    ,			encoder_stride=self.encoder_stride    ,			)







		def       A_       ( self    ,			snake_case    ,			snake_case    ,			snake_case			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]   					=   TFDeiTModel(config=__snake_case			)
							UpperCAmelCase		:							Optional[Any]   					=   model(__snake_case			)
							self.parent.assertEqual(result.last_hidden_state.shape    ,			(self.batch_size, self.seq_length, self.hidden_size)			)







		def       A_       ( self    ,			snake_case    ,			snake_case    ,			snake_case			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[int]   					=   TFDeiTForMaskedImageModeling(config=__snake_case			)
							UpperCAmelCase		:							Optional[int]   					=   model(__snake_case			)
							self.parent.assertEqual(
							    result.reconstruction.shape    ,			(self.batch_size, self.num_channels, self.image_size, self.image_size)			)

							# test greyscale images
							UpperCAmelCase		:							List[Any]   					=   1
							UpperCAmelCase		:							Optional[Any]   					=   TFDeiTForMaskedImageModeling(__snake_case			)

							UpperCAmelCase		:							Dict   					=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							UpperCAmelCase		:							Any   					=   model(__snake_case			)
							self.parent.assertEqual(result.reconstruction.shape    ,			(self.batch_size, 1, self.image_size, self.image_size)			)







		def       A_       ( self    ,			snake_case    ,			snake_case    ,			snake_case			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   self.type_sequence_label_size
							UpperCAmelCase		:							Union[str, Any]   					=   TFDeiTForImageClassification(__snake_case			)
							UpperCAmelCase		:							Union[str, Any]   					=   model(__snake_case    ,			labels=__snake_case			)
							self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.type_sequence_label_size)			)

							# test greyscale images
							UpperCAmelCase		:							Union[str, Any]   					=   1
							UpperCAmelCase		:							Union[str, Any]   					=   TFDeiTForImageClassification(__snake_case			)

							UpperCAmelCase		:							Dict   					=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							UpperCAmelCase		:							Optional[int]   					=   model(__snake_case    ,			labels=__snake_case			)
							self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.type_sequence_label_size)			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]   					=   self.prepare_config_and_inputs()
							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							str   					=   config_and_inputs
							UpperCAmelCase		:							List[str]   					=   {"pixel_values": pixel_values}
							return config, inputs_dict







@require_tf
class   UpperCamelCase__    (   lowerCAmelCase_							,							lowerCAmelCase_							,							unittest.TestCase   ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :	int   =							(
		    (
		        TFDeiTModel,
		        TFDeiTForImageClassification,
		        TFDeiTForImageClassificationWithTeacher,
		        TFDeiTForMaskedImageModeling,
		    )
		    if is_tf_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE__  :	Union[str, Any]   =							(
		    {
		        "feature-extraction": TFDeiTModel,
		        "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
		    }
		    if is_tf_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE__  :	Tuple   =							False
		SCREAMING_SNAKE_CASE__  :	List[str]   =							False
		SCREAMING_SNAKE_CASE__  :	Dict   =							False
		SCREAMING_SNAKE_CASE__  :	int   =							False







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]   					=   TFDeiTModelTester(self			)
							UpperCAmelCase		:							str   					=   ConfigTester(self    ,			config_class=__snake_case    ,			has_text_modality=__snake_case    ,			hidden_size=3_7			)







		def       A_       ( self			):


							'''simple docstring'''

							self.config_tester.run_common_tests()







		@unittest.skip(reason="DeiT does not use inputs_embeds"			)
		def       A_       ( self			):


							'''simple docstring'''

							pass







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase		:							str   					=   self.model_tester.prepare_config_and_inputs_for_common()

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







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase		:							Any   					=   self.model_tester.prepare_config_and_inputs_for_common()

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

												UpperCAmelCase		:							int   					=   ["pixel_values"]
												self.assertListEqual(arg_names[:1]    ,			__snake_case			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]   					=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__snake_case			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]   					=   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__snake_case			)







		def       A_       ( self    ,			snake_case    ,			snake_case    ,			snake_case=False			):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]   					=   super()._prepare_for_class(__snake_case    ,			__snake_case    ,			return_labels=__snake_case			)

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


							'''simple docstring'''

							for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase		:							Optional[Any]   					=   TFDeiTModel.from_pretrained(__snake_case			)
												self.assertIsNotNone(__snake_case			)





def       lowercase					(     ):



					'''simple docstring'''







					UpperCAmelCase		:							Union[str, Any]   					=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
					return image







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


		"""simple docstring"""

		@cached_property
		def       A_       ( self			):


							'''simple docstring'''

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







		@slow
		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							str   					=   TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"			)

							UpperCAmelCase		:							Tuple   					=   self.default_image_processor
							UpperCAmelCase		:							Optional[int]   					=   prepare_img()
							UpperCAmelCase		:							Any   					=   image_processor(images=__snake_case    ,			return_tensors="tf"			)

							# forward pass
							UpperCAmelCase		:							Any   					=   model(**__snake_case			)

							# verify the logits
							UpperCAmelCase		:							Tuple   					=   tf.TensorShape((1, 1_0_0_0)			)
							self.assertEqual(outputs.logits.shape    ,			__snake_case			)

							UpperCAmelCase		:							int   					=   tf.constant([-1.0266, 0.1912, -1.2861]			)

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



from __future__ import annotations






def        UpperCamelCase_(							_snake_case   :  int	):




			"""simple docstring"""






			__a        =str(_snake_case	)
			return len(_snake_case	) == 9 and set(_snake_case	) == set('123456789'	)






def        UpperCamelCase_(							):




			"""simple docstring"""






			for base_num in range(9999       ,     4999       ,     -1	):
						__a        =100002 * base_num
						if is_9_pandigital(_snake_case	):
									return candidate

			for base_num in range(333       ,     99       ,     -1	):
						__a        =1002003 * base_num
						if is_9_pandigital(_snake_case	):
									return candidate

			return None


if __name__ == "__main__":
						print(f'''{solution() = }''')






