





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  A__       :





      def __init__(			self	,							A_	,							A_=13	,							A_=30	,							A_=2	,							A_=3	,							A_=True	,							A_=True	,							A_=32	,							A_=2	,							A_=4	,							A_=37	,							A_="gelu"	,							A_=0.1	,							A_=0.1	,							A_=10	,							A_=0.02	,							A_=3	,							A_=None	,							A_=2	,							):
       '''simple docstring'''




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

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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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

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

       UpperCamelCase     : Union[str, Any]	     =       self.get_config()

       return config, pixel_values, labels





      def 	__UpperCamelCase(			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=A_	,							initializer_range=self.initializer_range	,							encoder_stride=self.encoder_stride	,							)





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




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





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       TFDeiTForMaskedImageModeling(config=A_       )
       UpperCamelCase     : Optional[Any]	     =       model(A_       )
       self.parent.assertEqual(
           result.reconstruction.shape	,							(self.batch_size, self.num_channels, self.image_size, self.image_size)       )

       # test greyscale images
       UpperCamelCase     : Dict	     =       1
       UpperCamelCase     : Optional[Any]	     =       TFDeiTForMaskedImageModeling(A_       )

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





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.type_sequence_label_size
       UpperCamelCase     : List[Any]	     =       TFDeiTForImageClassification(A_       )
       UpperCamelCase     : Optional[int]	     =       model(A_	,							labels=A_       )
       self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.type_sequence_label_size)       )

       # test greyscale images
       UpperCamelCase     : List[Any]	     =       1
       UpperCamelCase     : Optional[Any]	     =       TFDeiTForImageClassification(A_       )

       UpperCamelCase     : Optional[int]	     =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
       UpperCamelCase     : List[Any]	     =       model(A_	,							labels=A_       )
       self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.type_sequence_label_size)       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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



@require_tf
class  A__       (	__snake_case	,       __snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :str						   =       (
          (
              TFDeiTModel,
              TFDeiTForImageClassification,
              TFDeiTForImageClassificationWithTeacher,
              TFDeiTForMaskedImageModeling,
          )
          if is_tf_available()
          else ()
      )
      _UpperCAmelCase     :Tuple						   =       (
          {
              'feature-extraction': TFDeiTModel,
              'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
          }
          if is_tf_available()
          else {}
      )

      _UpperCAmelCase     :Dict						   =       False
      _UpperCAmelCase     :List[str]						   =       False
      _UpperCAmelCase     :Optional[Any]						   =       False
      _UpperCAmelCase     :Optional[int]						   =       False





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       TFDeiTModelTester(self       )
       UpperCamelCase     : Optional[Any]	     =       ConfigTester(self	,							config_class=A_	,							has_text_modality=A_	,							hidden_size=37       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      @unittest.skip(reason="DeiT does not use inputs_embeds"       )
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.model_tester.prepare_config_and_inputs_for_common()

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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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

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

        UpperCamelCase     : Any	     =       ["pixel_values"]
        self.assertListEqual(arg_names[:1]	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*A_       )





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : List[str]	     =       super()._prepare_for_class(A_	,							A_	,							return_labels=A_       )

       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 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCamelCase     : str	     =       TFDeiTModel.from_pretrained(A_       )
        self.assertIsNotNone(A_       )



def 		A_    (					)						->			str:
 UpperCamelCase     : Union[str, Any]	     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image



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





      @cached_property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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





      @slow
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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

       UpperCamelCase     : List[Any]	     =       self.default_image_processor
       UpperCamelCase     : Union[str, Any]	     =       prepare_img()
       UpperCamelCase     : Union[str, Any]	     =       image_processor(images=A_	,							return_tensors="tf"       )

       # forward pass
       UpperCamelCase     : str	     =       model(**A_       )

       # verify the logits
       UpperCamelCase     : Dict	     =       tf.TensorShape((1, 1000)       )
       self.assertEqual(outputs.logits.shape	,							A_       )

       UpperCamelCase     : Tuple	     =       tf.constant([-1.02_66, 0.19_12, -1.28_61]       )

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









import sys

from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

__lowerCamelCase	:					Optional[int]			  =					"""python tqdm regex requests packaging filelock numpy tokenizers""".split()
if sys.version_info < (3, 7):
    pkgs_to_check_at_runtime.append("""dataclasses""")
if sys.version_info < (3, 8):
    pkgs_to_check_at_runtime.append("""importlib_metadata""")

for pkg in pkgs_to_check_at_runtime:
    if pkg in deps:
        if pkg == "tokenizers":
            # must be loaded here, or else tqdm check may fail
            from .utils import is_tokenizers_available

            if not is_tokenizers_available():
                continue  # not required, check version only if installed

        require_version_core(deps[pkg])
    else:
        raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""")



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase=None					)						->			Optional[Any]:
 require_version(deps[pkg]							,       _lowerCAmelCase					)
