



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







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   parent
            __SCREAMING_SNAKE_CASE       		=   batch_size
            __SCREAMING_SNAKE_CASE       		=   image_size
            __SCREAMING_SNAKE_CASE       		=   patch_size
            __SCREAMING_SNAKE_CASE       		=   num_channels
            __SCREAMING_SNAKE_CASE       		=   is_training
            __SCREAMING_SNAKE_CASE       		=   use_labels
            __SCREAMING_SNAKE_CASE       		=   hidden_size
            __SCREAMING_SNAKE_CASE       		=   num_hidden_layers
            __SCREAMING_SNAKE_CASE       		=   num_attention_heads
            __SCREAMING_SNAKE_CASE       		=   intermediate_size
            __SCREAMING_SNAKE_CASE       		=   hidden_act
            __SCREAMING_SNAKE_CASE       		=   hidden_dropout_prob
            __SCREAMING_SNAKE_CASE       		=   attention_probs_dropout_prob
            __SCREAMING_SNAKE_CASE       		=   type_sequence_label_size
            __SCREAMING_SNAKE_CASE       		=   initializer_range
            __SCREAMING_SNAKE_CASE       		=   scope
            __SCREAMING_SNAKE_CASE       		=   encoder_stride

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







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

            __SCREAMING_SNAKE_CASE       		=   self.get_config()

            return config, pixel_values, labels







      def  _a   (					self		:     Dict			)							->		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=__SCREAMING_SNAKE_CASE				,				initializer_range=self.initializer_range				,				encoder_stride=self.encoder_stride				,				)







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   TFDeiTModel(config=__SCREAMING_SNAKE_CASE			)
            __SCREAMING_SNAKE_CASE       		=   model(__SCREAMING_SNAKE_CASE			)
            self.parent.assertEqual(result.last_hidden_state.shape				,				(self.batch_size, self.seq_length, self.hidden_size)			)







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   TFDeiTForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE			)
            __SCREAMING_SNAKE_CASE       		=   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
            __SCREAMING_SNAKE_CASE       		=   1
            __SCREAMING_SNAKE_CASE       		=   TFDeiTForMaskedImageModeling(__SCREAMING_SNAKE_CASE			)

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







      def  _a   (					self		:     List[str]				,				__SCREAMING_SNAKE_CASE		:     Any				,				__SCREAMING_SNAKE_CASE		:     Optional[int]				,				__SCREAMING_SNAKE_CASE		:     Optional[int]			)							->		int:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   self.type_sequence_label_size
            __SCREAMING_SNAKE_CASE       		=   TFDeiTForImageClassification(__SCREAMING_SNAKE_CASE			)
            __SCREAMING_SNAKE_CASE       		=   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
            __SCREAMING_SNAKE_CASE       		=   1
            __SCREAMING_SNAKE_CASE       		=   TFDeiTForImageClassification(__SCREAMING_SNAKE_CASE			)

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







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   self.prepare_config_and_inputs()
            __SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE       		=   config_and_inputs
            __SCREAMING_SNAKE_CASE       		=   {'''pixel_values''': pixel_values}
            return config, inputs_dict






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

      lowerCAmelCase										=				False
      lowerCAmelCase										=				False
      lowerCAmelCase										=				False
      lowerCAmelCase										=				False







      def  _a   (					self		:     int			)							->		List[str]:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   TFDeiTModelTester(self			)
            __SCREAMING_SNAKE_CASE       		=   ConfigTester(self				,				config_class=__SCREAMING_SNAKE_CASE				,				has_text_modality=__SCREAMING_SNAKE_CASE				,				hidden_size=37			)







      def  _a   (					self		:     Dict			)							->		int:






            """simple docstring"""

            self.config_tester.run_common_tests()







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






            """simple docstring"""

            pass







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE       		=   self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  __SCREAMING_SNAKE_CASE       		=   model_class(__SCREAMING_SNAKE_CASE			)
                  self.assertIsInstance(model.get_input_embeddings()				,				(tf.keras.layers.Layer)			)
                  __SCREAMING_SNAKE_CASE       		=   model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE				,				tf.keras.layers.Dense			)			)







      def  _a   (					self		:     Optional[int]			)							->		Dict:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE       		=   self.model_tester.prepare_config_and_inputs_for_common()

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

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







      def  _a   (					self		:     List[Any]			)							->		int:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE			)







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






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE			)







      def  _a   (					self		:     List[str]				,				__SCREAMING_SNAKE_CASE		:     List[str]				,				__SCREAMING_SNAKE_CASE		:     Tuple				,				__SCREAMING_SNAKE_CASE		:     Tuple=False			)							->		Any:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   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  _a   (					self		:     List[Any]			)							->		Tuple:






            """simple docstring"""

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






def     _a (	)						->    List[Any]:
      __SCREAMING_SNAKE_CASE       		=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
      return image




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







      @cached_property
      def  _a   (					self		:     str			)							->		Tuple:






            """simple docstring"""

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







      @slow
      def  _a   (					self		:     Optional[int]			)							->		Tuple:






            """simple docstring"""

            __SCREAMING_SNAKE_CASE       		=   TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''			)

            __SCREAMING_SNAKE_CASE       		=   self.default_image_processor
            __SCREAMING_SNAKE_CASE       		=   prepare_img()
            __SCREAMING_SNAKE_CASE       		=   image_processor(images=__SCREAMING_SNAKE_CASE				,				return_tensors='''tf'''			)

            # forward pass
            __SCREAMING_SNAKE_CASE       		=   model(**__SCREAMING_SNAKE_CASE			)

            # verify the logits
            __SCREAMING_SNAKE_CASE       		=   tf.TensorShape((1, 10_00)			)
            self.assertEqual(outputs.logits.shape				,				__SCREAMING_SNAKE_CASE			)

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

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






import inspect
import warnings
from typing import Any, Dict, Optional, Union

from packaging import version





def 						__A						(      *__lowerCamelCase				,     __lowerCamelCase = None				,     __lowerCamelCase=True				,     __lowerCamelCase=2       ) ->			Dict:
	from .. import __version__

	a									=				take_from
	a									=				()
	if not isinstance(args[0]				,     __lowerCamelCase       ):
		a									=				(args,)

	for attribute, version_name, message in args:
		if version.parse(version.parse(__lowerCamelCase       ).base_version       ) >= version.parse(__lowerCamelCase       ):
			raise ValueError(
			    f'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\''
			    f' version {__version__} is >= {version_name}'       )

		a									=				None
		if isinstance(__lowerCamelCase				,     __lowerCamelCase       ) and attribute in deprecated_kwargs:
			values += (deprecated_kwargs.pop(__lowerCamelCase       ),)
			a									=				f'The `{attribute}` argument is deprecated and will be removed in version {version_name}.'
		elif hasattr(__lowerCamelCase				,     __lowerCamelCase       ):
			values += (getattr(__lowerCamelCase				,     __lowerCamelCase       ),)
			a									=				f'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.'
		elif deprecated_kwargs is None:
			a									=				f'`{attribute}` is deprecated and will be removed in version {version_name}.'

		if warning is not None:
			a									=				warning + """ """ if standard_warn else """"""
			warnings.warn(warning + message				,     __lowerCamelCase				,     stacklevel=__lowerCamelCase       )

	if isinstance(__lowerCamelCase				,     __lowerCamelCase       ) and len(__lowerCamelCase       ) > 0:
		a									=				inspect.getouterframes(inspect.currentframe()       )[1]
		a									=				call_frame.filename
		a									=				call_frame.lineno
		a									=				call_frame.function
		a							,					a									=				next(iter(deprecated_kwargs.items()       )       )
		raise TypeError(f'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`'       )

	if len(__lowerCamelCase       ) == 0:
		return
	elif len(__lowerCamelCase       ) == 1:
		return values[0]
	return values

