


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




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

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




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:List[Any]										=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

       a						:int										=	self.get_config()

       return config, pixel_values, labels




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       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 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase   ):
       a						:Union[str, Any]										=	TFDeiTModel(config=UpperCamelCase__   )
       a						:Tuple										=	model(UpperCamelCase__   )
       self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, self.seq_length, self.hidden_size)   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase   ):
       a						:List[Any]										=	TFDeiTForMaskedImageModeling(config=UpperCamelCase__   )
       a						:Dict										=	model(UpperCamelCase__   )
       self.parent.assertEqual(
           result.reconstruction.shape ,  (self.batch_size, self.num_channels, self.image_size, self.image_size)   )

       # test greyscale images
       a						:int										=	1
       a						:Dict										=	TFDeiTForMaskedImageModeling(UpperCamelCase__   )

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




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase   ):
       a						:int										=	self.type_sequence_label_size
       a						:Tuple										=	TFDeiTForImageClassification(UpperCamelCase__   )
       a						:Union[str, Any]										=	model(UpperCamelCase__ ,  labels=UpperCamelCase__   )
       self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.type_sequence_label_size)   )

       # test greyscale images
       a						:Optional[int]										=	1
       a						:Optional[int]										=	TFDeiTForImageClassification(UpperCamelCase__   )

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




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:int										=	self.prepare_config_and_inputs()
       a							,    a							,    a						:Optional[int]										=	config_and_inputs
       a						:Optional[int]										=	{'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_tf
class 		_snake_case  (				__a						,   __a						,   unittest.TestCase							):
 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   ):
       a						:int										=	TFDeiTModelTester(self   )
       a						:Union[str, Any]										=	ConfigTester(self ,  config_class=UpperCamelCase__ ,  has_text_modality=UpperCamelCase__ ,  hidden_size=37   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       self.config_tester.run_common_tests()




 @unittest.skip(reason='''DeiT does not use inputs_embeds'''   )
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       pass




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a							,    a						:List[Any]										=	self.model_tester.prepare_config_and_inputs_for_common()

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




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a							,    a						:Tuple										=	self.model_tester.prepare_config_and_inputs_for_common()

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

             a						:Any										=	['''pixel_values''']
             self.assertListEqual(arg_names[:1] ,  UpperCamelCase__   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Union[str, Any]										=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[int]										=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Union[str, Any]										=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase=False   ):
       a						:List[str]										=	super()._prepare_for_class(UpperCamelCase__ ,  UpperCamelCase__ ,  return_labels=UpperCamelCase__   )

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



       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             a						:Optional[int]										=	TFDeiTModel.from_pretrained(UpperCamelCase__   )
             self.assertIsNotNone(UpperCamelCase__   )







def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:Optional[Any]										=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
      return image







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




 @cached_property
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return (
           DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   )
           if is_vision_available()
           else None
       )




 @slow
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[int]										=	TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   )

       a						:Dict										=	self.default_image_processor
       a						:Tuple										=	prepare_img()
       a						:Tuple										=	image_processor(images=UpperCamelCase__ ,  return_tensors='''tf'''   )

       # forward pass
       a						:int										=	model(**UpperCamelCase__   )

       # verify the logits
       a						:List[str]										=	tf.TensorShape((1, 1000)   )
       self.assertEqual(outputs.logits.shape ,  UpperCamelCase__   )

       a						:Union[str, Any]										=	tf.constant([-1.0266, 0.1912, -1.2861]   )

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









from . import __version__

# Backward compatibility imports, to make sure all those objects can be found in file_utils
from .utils import (
    CLOUDFRONT_DISTRIB_PREFIX,
    CONFIG_NAME,
    DISABLE_TELEMETRY,
    DUMMY_INPUTS,
    DUMMY_MASK,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    FEATURE_EXTRACTOR_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    MODEL_CARD_NAME,
    MULTIPLE_CHOICE_DUMMY_INPUTS,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    SENTENCEPIECE_UNDERLINE,
    SPIECE_UNDERLINE,
    TF2_WEIGHTS_NAME,
    TF_WEIGHTS_NAME,
    TORCH_FX_REQUIRED_VERSION,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
    ContextManagers,
    DummyObject,
    EntryNotFoundError,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    TensorType,
    _LazyModule,
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    cached_property,
    copy_func,
    default_cache_path,
    define_sagemaker_information,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    get_torch_version,
    has_file,
    http_user_agent,
    is_apex_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_datasets_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_librosa_available,
    is_offline_mode,
    is_onnx_available,
    is_pandas_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_tensor,
    is_tensorflow_probability_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    replace_return_docstrings,
    requires_backends,
    to_numpy,
    to_py_obj,
    torch_only_method,
)





