

'''simple docstring'''





import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 torch import nn

							from transformers import (
							    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
							    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
							    MODEL_MAPPING,
							    DeiTForImageClassification,
							    DeiTForImageClassificationWithTeacher,
							    DeiTForMaskedImageModeling,
							    DeiTModel,
							)
							from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import DeiTImageProcessor





class 		__SCREAMING_SNAKE_CASE							:







				def __init__(       self     :		Dict		,					UpperCAmelCase__     :		Optional[int]		,					UpperCAmelCase__     :		Tuple=13		,					UpperCAmelCase__     :		Optional[int]=30		,					UpperCAmelCase__     :		Tuple=2		,					UpperCAmelCase__     :		List[Any]=3		,					UpperCAmelCase__     :		Optional[int]=True		,					UpperCAmelCase__     :		int=True		,					UpperCAmelCase__     :		Any=32		,					UpperCAmelCase__     :		Union[str, Any]=5		,					UpperCAmelCase__     :		Union[str, Any]=4		,					UpperCAmelCase__     :		str=37		,					UpperCAmelCase__     :		Union[str, Any]="gelu"		,					UpperCAmelCase__     :		int=0.1		,					UpperCAmelCase__     :		List[str]=0.1		,					UpperCAmelCase__     :		int=10		,					UpperCAmelCase__     :		Tuple=0.02		,					UpperCAmelCase__     :		Tuple=3		,					UpperCAmelCase__     :		List[str]=None		,					UpperCAmelCase__     :		List[str]=2		,					):
										'''simple docstring'''
										lowercase :							Optional[Any]    		=parent
										lowercase :							List[str]    		=batch_size
										lowercase :							Tuple    		=image_size
										lowercase :							str    		=patch_size
										lowercase :							Optional[Any]    		=num_channels
										lowercase :							List[str]    		=is_training
										lowercase :							Any    		=use_labels
										lowercase :							str    		=hidden_size
										lowercase :							str    		=num_hidden_layers
										lowercase :							List[Any]    		=num_attention_heads
										lowercase :							List[Any]    		=intermediate_size
										lowercase :							Any    		=hidden_act
										lowercase :							Optional[Any]    		=hidden_dropout_prob
										lowercase :							Optional[int]    		=attention_probs_dropout_prob
										lowercase :							Optional[int]    		=type_sequence_label_size
										lowercase :							Optional[Any]    		=initializer_range
										lowercase :							Dict    		=scope
										lowercase :							Optional[int]    		=encoder_stride

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







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

										lowercase :							Any    		=self.get_config()

										return config, pixel_values, labels







				def  lowerCamelCase_	(       self     :		int   ):
										'''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=UpperCAmelCase__		,					initializer_range=self.initializer_range		,					encoder_stride=self.encoder_stride		,					)







				def  lowerCamelCase_	(       self     :		str		,					UpperCAmelCase__     :		Tuple		,					UpperCAmelCase__     :		Union[str, Any]		,					UpperCAmelCase__     :		List[Any]   ):
										'''simple docstring'''
										lowercase :							str    		=DeiTModel(config=UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()
										lowercase :							Optional[Any]    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)   )







				def  lowerCamelCase_	(       self     :		List[str]		,					UpperCAmelCase__     :		Dict		,					UpperCAmelCase__     :		Optional[int]		,					UpperCAmelCase__     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							Dict    		=DeiTForMaskedImageModeling(config=UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()
										lowercase :							Optional[int]    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(
										    result.reconstruction.shape		,					(self.batch_size, self.num_channels, self.image_size, self.image_size)   )

										# test greyscale images
										lowercase :							Dict    		=1
										lowercase :							Dict    		=DeiTForMaskedImageModeling(UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()

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







				def  lowerCamelCase_	(       self     :		str		,					UpperCAmelCase__     :		Optional[Any]		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		Dict   ):
										'''simple docstring'''
										lowercase :							Dict    		=self.type_sequence_label_size
										lowercase :							str    		=DeiTForImageClassification(UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()
										lowercase :							str    		=model(UpperCAmelCase__		,					labels=UpperCAmelCase__   )
										self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)   )

										# test greyscale images
										lowercase :							Union[str, Any]    		=1
										lowercase :							Optional[Any]    		=DeiTForImageClassification(UpperCAmelCase__   )
										model.to(UpperCAmelCase__   )
										model.eval()

										lowercase :							str    		=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
										lowercase :							List[str]    		=model(UpperCAmelCase__		,					labels=UpperCAmelCase__   )
										self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)   )







				def  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										lowercase :							Optional[Any]    		=self.prepare_config_and_inputs()
										(
										    (
										    lowercase
										)		,	(
										    lowercase
										)		,	(
										    lowercase
										)		,	
										) :							Optional[Any]    		=config_and_inputs
										lowercase :							Tuple    		={'''pixel_values''': pixel_values}
										return config, inputs_dict





@require_torch
class 		__SCREAMING_SNAKE_CASE							(			lowercase__						,							lowercase__						,							unittest.TestCase      ):
				lowerCamelCase_		       =    (
				    (
				        DeiTModel,
				        DeiTForImageClassification,
				        DeiTForImageClassificationWithTeacher,
				        DeiTForMaskedImageModeling,
				    )
				    if is_torch_available()
				    else ()
				)
				lowerCamelCase_		       =    (
				    {
				        'feature-extraction': DeiTModel,
				        'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
				    }
				    if is_torch_available()
				    else {}
				)

				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    False







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										lowercase :							str    		=DeiTModelTester(self   )
										lowercase :							Optional[int]    		=ConfigTester(self		,					config_class=UpperCAmelCase__		,					has_text_modality=UpperCAmelCase__		,					hidden_size=37   )







				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''simple docstring'''
										self.config_tester.run_common_tests()







				@unittest.skip(reason='''DeiT does not use inputs_embeds'''   )
				def  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										pass







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Union[str, Any]    		=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																lowercase :							Any    		=model_class(UpperCAmelCase__   )
																self.assertIsInstance(model.get_input_embeddings()		,					(nn.Module)   )
																lowercase :							List[Any]    		=model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(UpperCAmelCase__		,					nn.Linear   )   )







				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''simple docstring'''
										lowercase		,	lowercase :							str    		=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																lowercase :							Dict    		=model_class(UpperCAmelCase__   )
																lowercase :							List[Any]    		=inspect.signature(model.forward   )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																lowercase :							Optional[Any]    		=[*signature.parameters.keys()]

																lowercase :							Any    		=['''pixel_values''']
																self.assertListEqual(arg_names[:1]		,					UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Optional[Any]    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										lowercase :							Dict    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Any   ):
										'''simple docstring'''
										lowercase :							List[str]    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		int		,					UpperCAmelCase__     :		int		,					UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		Any=False   ):
										'''simple docstring'''
										lowercase :							Tuple    		=super()._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__		,					return_labels=UpperCAmelCase__   )

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

										return inputs_dict







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										if not self.model_tester.is_training:
																return

										lowercase		,	lowercase :							Optional[int]    		=self.model_tester.prepare_config_and_inputs_for_common()
										lowercase :							Dict    		=True

										for model_class in self.all_model_classes:
																# DeiTForImageClassificationWithTeacher supports inference-only
																if (
																    model_class in get_values(UpperCAmelCase__   )
																    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
																):
																						continue
																lowercase :							Any    		=model_class(UpperCAmelCase__   )
																model.to(UpperCAmelCase__   )
																model.train()
																lowercase :							Dict    		=self._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__		,					return_labels=UpperCAmelCase__   )
																lowercase :							List[Any]    		=model(**UpperCAmelCase__   ).loss
																loss.backward()







				def  lowerCamelCase_	(       self     :		List[str]   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Optional[Any]    		=self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
																return

										lowercase :							Optional[Any]    		=False
										lowercase :							Dict    		=True

										for model_class in self.all_model_classes:
																if model_class in get_values(UpperCAmelCase__   ) or not model_class.supports_gradient_checkpointing:
																						continue
																# DeiTForImageClassificationWithTeacher supports inference-only
																if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
																						continue
																lowercase :							Any    		=model_class(UpperCAmelCase__   )
																model.gradient_checkpointing_enable()
																model.to(UpperCAmelCase__   )
																model.train()
																lowercase :							str    		=self._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__		,					return_labels=UpperCAmelCase__   )
																lowercase :							Optional[Any]    		=model(**UpperCAmelCase__   ).loss
																loss.backward()







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										lowercase		,	lowercase :							str    		=self.model_tester.prepare_config_and_inputs_for_common()

										lowercase :							Optional[int]    		=[
										    {'''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(UpperCAmelCase__   ),
																        *get_values(UpperCAmelCase__   ),
																    ]
																    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
																):
																						continue

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

																												lowercase :							int    		=model_class(UpperCAmelCase__   )
																												model.to(UpperCAmelCase__   )
																												model.train()

																												lowercase :							str    		=self._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__		,					return_labels=UpperCAmelCase__   )

																												if problem_type["num_labels"] > 1:
																																		lowercase :							List[str]    		=inputs['''labels'''].unsqueeze(1   ).repeat(1		,					problem_type['''num_labels''']   )

																												lowercase :							int    		=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=UpperCAmelCase__   ) as warning_list:
																																		lowercase :							int    		=model(**UpperCAmelCase__   ).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     :		int   ):
										'''simple docstring'''
										for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																lowercase :							Any    		=DeiTModel.from_pretrained(UpperCAmelCase__   )
																self.assertIsNotNone(UpperCAmelCase__   )






def 				_lowerCAmelCase			(   )				->  List[str]:
						lowercase :							Optional[int]    		=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
						return image







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







				@cached_property
				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										return (
										    DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   )
										    if is_vision_available()
										    else None
										)







				@slow
				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							Any    		=DeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   ).to(
										    UpperCAmelCase__   )

										lowercase :							Tuple    		=self.default_image_processor
										lowercase :							Tuple    		=prepare_img()
										lowercase :							Any    		=image_processor(images=UpperCAmelCase__		,					return_tensors='''pt'''   ).to(UpperCAmelCase__   )

										# forward pass
										with torch.no_grad():
																lowercase :							str    		=model(**UpperCAmelCase__   )

										# verify the logits
										lowercase :							List[Any]    		=torch.Size((1, 1000)   )
										self.assertEqual(outputs.logits.shape		,					UpperCAmelCase__   )

										lowercase :							Any    		=torch.tensor([-1.02_66, 0.19_12, -1.28_61]   ).to(UpperCAmelCase__   )

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







				@slow
				@require_accelerate
				@require_torch_gpu
				def  lowerCamelCase_	(       self     :		Optional[Any]   ):
										'''simple docstring'''
										lowercase :							Union[str, Any]    		=DeiTModel.from_pretrained(
										    '''facebook/deit-base-distilled-patch16-224'''		,					torch_dtype=torch.floataa		,					device_map='''auto'''   )
										lowercase :							Optional[Any]    		=self.default_image_processor

										lowercase :							List[Any]    		=prepare_img()
										lowercase :							Union[str, Any]    		=image_processor(images=UpperCAmelCase__		,					return_tensors='''pt'''   )
										lowercase :							Optional[Any]    		=inputs.pixel_values.to(UpperCAmelCase__   )

										# forward pass to make sure inference works in fp16
										with torch.no_grad():
																lowercase :							Optional[int]    		=model(UpperCAmelCase__   )







'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE     =       {"""configuration_deit""": ["""DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DeiTConfig""", """DeiTOnnxConfig"""]}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE     =       ["""DeiTFeatureExtractor"""]
      SCREAMING_SNAKE_CASE     =       ["""DeiTImageProcessor"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE     =       [
          """DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """DeiTForImageClassification""",
          """DeiTForImageClassificationWithTeacher""",
          """DeiTForMaskedImageModeling""",
          """DeiTModel""",
          """DeiTPreTrainedModel""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE     =       [
          """TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """TFDeiTForImageClassification""",
          """TFDeiTForImageClassificationWithTeacher""",
          """TFDeiTForMaskedImageModeling""",
          """TFDeiTModel""",
          """TFDeiTPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .feature_extraction_deit import DeiTFeatureExtractor
            from .image_processing_deit import DeiTImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_deit import (
                DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                DeiTForImageClassification,
                DeiTForImageClassificationWithTeacher,
                DeiTForMaskedImageModeling,
                DeiTModel,
                DeiTPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_deit import (
                TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFDeiTForImageClassification,
                TFDeiTForImageClassificationWithTeacher,
                TFDeiTForMaskedImageModeling,
                TFDeiTModel,
                TFDeiTPreTrainedModel,
            )


else:
      import sys

      SCREAMING_SNAKE_CASE     =       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



