
import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
    from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import DPTImageProcessor




class 				_lowerCamelCase :





     """simple docstring"""







     def __init__(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=2						,						__SCREAMING_SNAKE_CASE=3_2						,						__SCREAMING_SNAKE_CASE=1_6						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=3_2						,						__SCREAMING_SNAKE_CASE=4						,						__SCREAMING_SNAKE_CASE=[0, 1, 2, 3]						,						__SCREAMING_SNAKE_CASE=4						,						__SCREAMING_SNAKE_CASE=3_7						,						__SCREAMING_SNAKE_CASE="gelu"						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=0.02						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=[1, 3_8_4, 2_4, 2_4]						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=None						,						)  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				parent
           UpperCamelCase__    :   Any					=				batch_size
           UpperCamelCase__    :   Optional[int]					=				image_size
           UpperCamelCase__    :   int					=				patch_size
           UpperCamelCase__    :   str					=				num_channels
           UpperCamelCase__    :   List[str]					=				is_training
           UpperCamelCase__    :   Union[str, Any]					=				use_labels
           UpperCamelCase__    :   Tuple					=				hidden_size
           UpperCamelCase__    :   str					=				num_hidden_layers
           UpperCamelCase__    :   int					=				backbone_out_indices
           UpperCamelCase__    :   Optional[int]					=				num_attention_heads
           UpperCamelCase__    :   str					=				intermediate_size
           UpperCamelCase__    :   Dict					=				hidden_act
           UpperCamelCase__    :   int					=				hidden_dropout_prob
           UpperCamelCase__    :   Optional[Any]					=				attention_probs_dropout_prob
           UpperCamelCase__    :   List[str]					=				initializer_range
           UpperCamelCase__    :   Union[str, Any]					=				num_labels
           UpperCamelCase__    :   Union[str, Any]					=				backbone_featmap_shape
           UpperCamelCase__    :   Any					=				scope
           UpperCamelCase__    :   List[Any]					=				is_hybrid
           # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
           UpperCamelCase__    :   str					=				(image_size // patch_size) ** 2
           UpperCamelCase__    :   Union[str, Any]					=				num_patches + 1






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

           UpperCamelCase__    :   Any					=				self.get_config()

           return config, pixel_values, labels






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   int					=				{
               '''global_padding''': '''same''',
               '''layer_type''': '''bottleneck''',
               '''depths''': [3, 4, 9],
               '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
               '''embedding_dynamic_padding''': True,
               '''hidden_sizes''': [9_6, 1_9_2, 3_8_4, 7_6_8],
               '''num_groups''': 2,
           }

           return DPTConfig(
               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						,						backbone_out_indices=self.backbone_out_indices						,						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=__SCREAMING_SNAKE_CASE						,						initializer_range=self.initializer_range						,						is_hybrid=self.is_hybrid						,						backbone_config=__SCREAMING_SNAKE_CASE						,						backbone_featmap_shape=self.backbone_featmap_shape						,						)






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   Dict					=				DPTModel(config=__SCREAMING_SNAKE_CASE  )
           model.to(__SCREAMING_SNAKE_CASE  )
           model.eval()
           UpperCamelCase__    :   Any					=				model(__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(result.last_hidden_state.shape						,						(self.batch_size, self.seq_length, self.hidden_size)  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   List[Any]					=				self.num_labels
           UpperCamelCase__    :   Union[str, Any]					=				DPTForDepthEstimation(__SCREAMING_SNAKE_CASE  )
           model.to(__SCREAMING_SNAKE_CASE  )
           model.eval()
           UpperCamelCase__    :   Any					=				model(__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(result.predicted_depth.shape						,						(self.batch_size, self.image_size, self.image_size)  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Optional[int]					=				self.num_labels
           UpperCamelCase__    :   Optional[Any]					=				DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE  )
           model.to(__SCREAMING_SNAKE_CASE  )
           model.eval()
           UpperCamelCase__    :   List[Any]					=				model(__SCREAMING_SNAKE_CASE						,						labels=__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(
               result.logits.shape						,						(self.batch_size, self.num_labels, self.image_size, self.image_size)  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				self.prepare_config_and_inputs()
           UpperCamelCase__				,UpperCamelCase__				,UpperCamelCase__    :   List[Any]					=				config_and_inputs
           UpperCamelCase__    :   Optional[Any]					=				{'''pixel_values''': pixel_values}
           return config, inputs_dict




@require_torch
class 				_lowerCamelCase (      UpperCamelCase_	,							UpperCamelCase_	,							unittest.TestCase ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		   =  (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE_		   =  (
         {
             '''depth-estimation''': DPTForDepthEstimation,
             '''feature-extraction''': DPTModel,
             '''image-segmentation''': DPTForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   int					=				DPTModelTester(self  )
           UpperCamelCase__    :   List[str]					=				ConfigTester(self						,						config_class=__SCREAMING_SNAKE_CASE						,						has_text_modality=__SCREAMING_SNAKE_CASE						,						hidden_size=3_7  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           self.config_tester.run_common_tests()






     @unittest.skip(reason='''DPT does not use inputs_embeds'''  )
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Union[str, Any]:




           """simple docstring"""







           pass






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   Optional[int]					=				self.model_tester.prepare_config_and_inputs_for_common()

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






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   List[str]					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                 UpperCamelCase__    :   Dict					=				['''pixel_values''']
                 self.assertListEqual(arg_names[:1]						,						__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







           UpperCamelCase__    :   int					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Dict:




           """simple docstring"""







           UpperCamelCase__    :   int					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE  )






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




           """simple docstring"""







           UpperCamelCase__    :   int					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           for model_class in self.all_model_classes:
                 if model_class.__name__ == "DPTForDepthEstimation":
                       continue

                 UpperCamelCase__				,UpperCamelCase__    :   List[Any]					=				self.model_tester.prepare_config_and_inputs_for_common()
                 UpperCamelCase__    :   Union[str, Any]					=				True

                 if model_class in get_values(__SCREAMING_SNAKE_CASE  ):
                       continue

                 UpperCamelCase__    :   Union[str, Any]					=				model_class(__SCREAMING_SNAKE_CASE  )
                 model.to(__SCREAMING_SNAKE_CASE  )
                 model.train()
                 UpperCamelCase__    :   Optional[int]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   Any					=				model(**__SCREAMING_SNAKE_CASE  ).loss
                 loss.backward()






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           for model_class in self.all_model_classes:
                 if model_class.__name__ == "DPTForDepthEstimation":
                       continue

                 UpperCamelCase__				,UpperCamelCase__    :   Tuple					=				self.model_tester.prepare_config_and_inputs_for_common()
                 UpperCamelCase__    :   Optional[int]					=				False
                 UpperCamelCase__    :   List[str]					=				True

                 if model_class in get_values(__SCREAMING_SNAKE_CASE  ) or not model_class.supports_gradient_checkpointing:
                       continue
                 UpperCamelCase__    :   int					=				model_class(__SCREAMING_SNAKE_CASE  )
                 model.to(__SCREAMING_SNAKE_CASE  )
                 model.gradient_checkpointing_enable()
                 model.train()
                 UpperCamelCase__    :   Optional[Any]					=				self._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   Optional[Any]					=				model(**__SCREAMING_SNAKE_CASE  ).loss
                 loss.backward()






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




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   int					=				self.model_tester.prepare_config_and_inputs_for_common()

           UpperCamelCase__    :   Tuple					=				_config_zero_init(__SCREAMING_SNAKE_CASE  )
           for model_class in self.all_model_classes:
                 UpperCamelCase__    :   Dict					=				model_class(config=__SCREAMING_SNAKE_CASE  )
                 # Skip the check for the backbone
                 UpperCamelCase__    :   Any					=				[]
                 for name, module in model.named_modules():
                       if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                             UpperCamelCase__    :   str					=				[F'''{name}.{key}''' for key in module.state_dict().keys()]
                             break

                 for name, param in model.named_parameters():
                       if param.requires_grad:
                             if name in backbone_params:
                                   continue
                             self.assertIn(
                                 ((param.data.mean() * 1e9).round() / 1e9).item()						,						[0.0, 1.0]						,						msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''						,						)






     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''  )
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Union[str, Any]:




           """simple docstring"""







           pass






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
                 UpperCamelCase__    :   Dict					=				DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE  )
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   Union[str, Any]					=				self.model_tester.prepare_config_and_inputs_for_common()
           UpperCamelCase__    :   Any					=				'''add'''
           with self.assertRaises(__SCREAMING_SNAKE_CASE  ):
                 UpperCamelCase__    :   List[Any]					=				DPTForDepthEstimation(__SCREAMING_SNAKE_CASE  )


def 							SCREAMING_SNAKE_CASE_      (			):
      UpperCamelCase__    :   List[Any]					=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
      return image




@require_torch
@require_vision
@slow
class 				_lowerCamelCase (      unittest.TestCase ):





     """simple docstring"""







     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   str					=				DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas'''  )
           UpperCamelCase__    :   Optional[int]					=				DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas'''  ).to(__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   List[Any]					=				prepare_img()
           UpperCamelCase__    :   int					=				image_processor(images=__SCREAMING_SNAKE_CASE						,						return_tensors='''pt'''  ).to(__SCREAMING_SNAKE_CASE  )

           # forward pass
           with torch.no_grad():
                 UpperCamelCase__    :   Optional[Any]					=				model(**__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   List[Any]					=				outputs.predicted_depth

           # verify the predicted depth
           UpperCamelCase__    :   List[Any]					=				torch.Size((1, 3_8_4, 3_8_4)  )
           self.assertEqual(predicted_depth.shape						,						__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   Any					=				torch.tensor(
               [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]  ).to(__SCREAMING_SNAKE_CASE  )

           self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0						,						__SCREAMING_SNAKE_CASE						,						atol=1e-4  )  )




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						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=1_3						,						__SCREAMING_SNAKE_CASE=3_0						,						__SCREAMING_SNAKE_CASE=2						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=True						,						__SCREAMING_SNAKE_CASE=3_2						,						__SCREAMING_SNAKE_CASE=2						,						__SCREAMING_SNAKE_CASE=4						,						__SCREAMING_SNAKE_CASE=3_7						,						__SCREAMING_SNAKE_CASE="gelu"						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=1_0						,						__SCREAMING_SNAKE_CASE=0.02						,						__SCREAMING_SNAKE_CASE=3						,						__SCREAMING_SNAKE_CASE=None						,						__SCREAMING_SNAKE_CASE=2						,						)  ->   Union[str, Any]:




           """simple docstring"""







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

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






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

           UpperCamelCase__    :   List[Any]					=				self.get_config()

           return config, pixel_values, labels






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   str:




           """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=__SCREAMING_SNAKE_CASE						,						initializer_range=self.initializer_range						,						encoder_stride=self.encoder_stride						,						)






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				TFDeiTModel(config=__SCREAMING_SNAKE_CASE  )
           UpperCamelCase__    :   Optional[int]					=				model(__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(result.last_hidden_state.shape						,						(self.batch_size, self.seq_length, self.hidden_size)  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   str					=				TFDeiTForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE  )
           UpperCamelCase__    :   List[str]					=				model(__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(
               result.reconstruction.shape						,						(self.batch_size, self.num_channels, self.image_size, self.image_size)  )

           # test greyscale images
           UpperCamelCase__    :   Optional[int]					=				1
           UpperCamelCase__    :   Any					=				TFDeiTForMaskedImageModeling(__SCREAMING_SNAKE_CASE  )

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






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[int]:




           """simple docstring"""







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

           # test greyscale images
           UpperCamelCase__    :   int					=				1
           UpperCamelCase__    :   int					=				TFDeiTForImageClassification(__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   Dict					=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
           UpperCamelCase__    :   Optional[Any]					=				model(__SCREAMING_SNAKE_CASE						,						labels=__SCREAMING_SNAKE_CASE  )
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.type_sequence_label_size)  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Union[str, Any]					=				self.prepare_config_and_inputs()
           UpperCamelCase__				,UpperCamelCase__				,UpperCamelCase__    :   Any					=				config_and_inputs
           UpperCamelCase__    :   Optional[int]					=				{'''pixel_values''': pixel_values}
           return config, inputs_dict




@require_tf
class 				_lowerCamelCase (      UpperCamelCase_	,							UpperCamelCase_	,							unittest.TestCase ):





     """simple docstring"""







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

     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   List[Any]					=				TFDeiTModelTester(self  )
           UpperCamelCase__    :   str					=				ConfigTester(self						,						config_class=__SCREAMING_SNAKE_CASE						,						has_text_modality=__SCREAMING_SNAKE_CASE						,						hidden_size=3_7  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           self.config_tester.run_common_tests()






     @unittest.skip(reason='''DeiT does not use inputs_embeds'''  )
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   str:




           """simple docstring"""







           pass






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   Optional[Any]					=				self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 UpperCamelCase__    :   List[Any]					=				model_class(__SCREAMING_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(__SCREAMING_SNAKE_CASE						,						tf.keras.layers.Dense  )  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__				,UpperCamelCase__    :   List[str]					=				self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 UpperCamelCase__    :   Optional[Any]					=				model_class(__SCREAMING_SNAKE_CASE  )
                 UpperCamelCase__    :   str					=				inspect.signature(model.call  )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 UpperCamelCase__    :   str					=				[*signature.parameters.keys()]

                 UpperCamelCase__    :   int					=				['''pixel_values''']
                 self.assertListEqual(arg_names[:1]						,						__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   str					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Any:




           """simple docstring"""







           UpperCamelCase__    :   Any					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Any					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=False  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Optional[Any]					=				super()._prepare_for_class(__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						return_labels=__SCREAMING_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    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







           for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 UpperCamelCase__    :   Any					=				TFDeiTModel.from_pretrained(__SCREAMING_SNAKE_CASE  )
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE  )


def 							SCREAMING_SNAKE_CASE_      (			):
      UpperCamelCase__    :   Tuple					=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
      return image




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





     """simple docstring"""







     @cached_property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







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






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Dict:




           """simple docstring"""







           UpperCamelCase__    :   Union[str, Any]					=				TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''  )

           UpperCamelCase__    :   str					=				self.default_image_processor
           UpperCamelCase__    :   List[str]					=				prepare_img()
           UpperCamelCase__    :   int					=				image_processor(images=__SCREAMING_SNAKE_CASE						,						return_tensors='''tf'''  )

           # forward pass
           UpperCamelCase__    :   List[Any]					=				model(**__SCREAMING_SNAKE_CASE  )

           # verify the logits
           UpperCamelCase__    :   Union[str, Any]					=				tf.TensorShape((1, 1_0_0_0)  )
           self.assertEqual(outputs.logits.shape						,						__SCREAMING_SNAKE_CASE  )

           UpperCamelCase__    :   List[str]					=				tf.constant([-1.0266, 0.1912, -1.2861]  )

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


