


import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
 __a     = """pt"""
elif is_tf_available():
 __a     = """tf"""
else:
 __a     = """jax"""






class   __lowercase				(  __snake_case ,					unittest.TestCase  ):
      UpperCamelCase								=       PerceiverTokenizer
      UpperCamelCase								=       False





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






         """simple docstring"""







         super().setUp()
         UpperCAmelCase							=     PerceiverTokenizer()
         tokenizer.save_pretrained(self.tmpdirname       )





      @cached_property
      def        _lowercase				(		self						:					Union[str, Any]       )    ->   int:






         """simple docstring"""







         return PerceiverTokenizer.from_pretrained("""deepmind/language-perceiver"""       )





      def        _lowercase				(		self						:					Any					,       **__lowerCamelCase						:					List[str]       )    ->   PerceiverTokenizer:






         """simple docstring"""







         return self.tokenizer_class.from_pretrained(self.tmpdirname					,       **__lowerCamelCase       )





      def        _lowercase				(		self						:					str					,       __lowerCamelCase						:					List[str]					,       __lowerCamelCase						:					Optional[int]=False					,       __lowerCamelCase						:					Dict=2_0					,       __lowerCamelCase						:					Tuple=5       )    ->   Tuple[str, list]:






         """simple docstring"""







         UpperCAmelCase							=     []
         for i in range(len(__lowerCamelCase       )       ):
            try:
               UpperCAmelCase							=     tokenizer.decode([i]					,       clean_up_tokenization_spaces=__lowerCamelCase       )
            except UnicodeDecodeError:
               pass
            toks.append((i, tok)       )

         UpperCAmelCase							=     list(filter(lambda __lowerCamelCase       : re.match(r"""^[ a-zA-Z]+$"""					,       t[1]       )					,       __lowerCamelCase       )       )
         UpperCAmelCase							=     list(filter(lambda __lowerCamelCase       : [t[0]] == tokenizer.encode(t[1]					,       add_special_tokens=__lowerCamelCase       )					,       __lowerCamelCase       )       )
         if max_length is not None and len(__lowerCamelCase       ) > max_length:
            UpperCAmelCase							=     toks[:max_length]
         if min_length is not None and len(__lowerCamelCase       ) < min_length and len(__lowerCamelCase       ) > 0:
            while len(__lowerCamelCase       ) < min_length:
               UpperCAmelCase							=     toks + toks
        # toks_str = [t[1] for t in toks]
         UpperCAmelCase							=     [t[0] for t in toks]

         # Ensure consistency
         UpperCAmelCase							=     tokenizer.decode(__lowerCamelCase					,       clean_up_tokenization_spaces=__lowerCamelCase       )
         if " " not in output_txt and len(__lowerCamelCase       ) > 1:
            UpperCAmelCase							=     (
                tokenizer.decode([toks_ids[0]]					,       clean_up_tokenization_spaces=__lowerCamelCase       )
                + """ """
                + tokenizer.decode(toks_ids[1:]					,       clean_up_tokenization_spaces=__lowerCamelCase       )
            )
         if with_prefix_space:
            UpperCAmelCase							=     """ """ + output_txt
         UpperCAmelCase							=     tokenizer.encode(__lowerCamelCase					,       add_special_tokens=__lowerCamelCase       )
         return output_txt, output_ids





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






         """simple docstring"""







         UpperCAmelCase							=     self.perceiver_tokenizer
         UpperCAmelCase							=     """Unicode €."""
         UpperCAmelCase							=     tokenizer(__lowerCamelCase       )
         UpperCAmelCase							=     [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5]
         self.assertEqual(encoded["""input_ids"""]					,       __lowerCamelCase       )

         # decoding
         UpperCAmelCase							=     tokenizer.decode(__lowerCamelCase       )
         self.assertEqual(__lowerCamelCase					,       """[CLS]Unicode €.[SEP]"""       )

         UpperCAmelCase							=     tokenizer("""e è é ê ë"""       )
         UpperCAmelCase							=     [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5]
         self.assertEqual(encoded["""input_ids"""]					,       __lowerCamelCase       )
         # decoding
         UpperCAmelCase							=     tokenizer.decode(__lowerCamelCase       )
         self.assertEqual(__lowerCamelCase					,       """[CLS]e è é ê ë[SEP]"""       )

         # encode/decode, but with `encode` instead of `__call__`
         self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë"""       )       )					,       """[CLS]e è é ê ë[SEP]"""       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.perceiver_tokenizer
         UpperCAmelCase							=     ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
         # fmt: off
         UpperCAmelCase							=     [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0]
         # fmt: on
         UpperCAmelCase							=     tokenizer(__lowerCamelCase					,       padding=__lowerCamelCase					,       return_tensors=__lowerCamelCase       )
         self.assertIsInstance(__lowerCamelCase					,       __lowerCamelCase       )

         if FRAMEWORK != "jax":
            UpperCAmelCase							=     list(batch.input_ids.numpy()[0]       )
         else:
            UpperCAmelCase							=     list(batch.input_ids.tolist()[0]       )

         self.assertListEqual(__lowerCamelCase					,       __lowerCamelCase       )

         self.assertEqual((2, 3_8)					,       batch.input_ids.shape       )
         self.assertEqual((2, 3_8)					,       batch.attention_mask.shape       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.perceiver_tokenizer
         UpperCAmelCase							=     ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
         UpperCAmelCase							=     tokenizer(__lowerCamelCase					,       padding=__lowerCamelCase					,       return_tensors=__lowerCamelCase       )
         # check if input_ids are returned and no decoder_input_ids
         self.assertIn("""input_ids"""					,       __lowerCamelCase       )
         self.assertIn("""attention_mask"""					,       __lowerCamelCase       )
         self.assertNotIn("""decoder_input_ids"""					,       __lowerCamelCase       )
         self.assertNotIn("""decoder_attention_mask"""					,       __lowerCamelCase       )





      def        _lowercase				(		self						:					Tuple       )    ->   Optional[Any]:






         """simple docstring"""







         UpperCAmelCase							=     self.perceiver_tokenizer
         UpperCAmelCase							=     [
             """Summary of the text.""",
             """Another summary.""",
         ]
         UpperCAmelCase							=     tokenizer(
             text_target=__lowerCamelCase					,       max_length=3_2					,       padding="""max_length"""					,       truncation=__lowerCamelCase					,       return_tensors=__lowerCamelCase       )
         self.assertEqual(3_2					,       targets["""input_ids"""].shape[1]       )





      def        _lowercase				(		self						:					Tuple       )    ->   Dict:






         """simple docstring"""







         UpperCAmelCase							=     self.get_tokenizers()
         for tokenizer in tokenizers:
            with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
               self.assertNotEqual(tokenizer.model_max_length					,       4_2       )

        # Now let's start the test
         UpperCAmelCase							=     self.get_tokenizers()
         for tokenizer in tokenizers:
            with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
               # Isolate this from the other tests because we save additional tokens/etc
               UpperCAmelCase							=     tempfile.mkdtemp()

               UpperCAmelCase							=     """ He is very happy, UNwant\u00E9d,running"""
               UpperCAmelCase							=     tokenizer.encode(__lowerCamelCase					,       add_special_tokens=__lowerCamelCase       )
               tokenizer.save_pretrained(__lowerCamelCase       )

               UpperCAmelCase							=     tokenizer.__class__.from_pretrained(__lowerCamelCase       )
               UpperCAmelCase							=     after_tokenizer.encode(__lowerCamelCase					,       add_special_tokens=__lowerCamelCase       )
               self.assertListEqual(__lowerCamelCase					,       __lowerCamelCase       )

               shutil.rmtree(__lowerCamelCase       )

         UpperCAmelCase							=     self.get_tokenizers(model_max_length=4_2       )
         for tokenizer in tokenizers:
            with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
               # Isolate this from the other tests because we save additional tokens/etc
               UpperCAmelCase							=     tempfile.mkdtemp()

               UpperCAmelCase							=     """ He is very happy, UNwant\u00E9d,running"""
               tokenizer.add_tokens(["""bim""", """bambam"""]       )
               UpperCAmelCase							=     tokenizer.additional_special_tokens
               additional_special_tokens.append("""new_additional_special_token"""       )
               tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens}       )
               UpperCAmelCase							=     tokenizer.encode(__lowerCamelCase					,       add_special_tokens=__lowerCamelCase       )
               tokenizer.save_pretrained(__lowerCamelCase       )

               UpperCAmelCase							=     tokenizer.__class__.from_pretrained(__lowerCamelCase       )
               UpperCAmelCase							=     after_tokenizer.encode(__lowerCamelCase					,       add_special_tokens=__lowerCamelCase       )
               self.assertListEqual(__lowerCamelCase					,       __lowerCamelCase       )
               self.assertIn("""new_additional_special_token"""					,       after_tokenizer.additional_special_tokens       )
               self.assertEqual(after_tokenizer.model_max_length					,       4_2       )

               UpperCAmelCase							=     tokenizer.__class__.from_pretrained(__lowerCamelCase					,       model_max_length=4_3       )
               self.assertEqual(tokenizer.model_max_length					,       4_3       )

               shutil.rmtree(__lowerCamelCase       )





      def        _lowercase				(		self						:					int       )    ->   Any:






         """simple docstring"""







         UpperCAmelCase							=     []
         if self.test_slow_tokenizer:
            tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())       )

         if self.test_rust_tokenizer:
            tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())       )

         for tokenizer_class, tokenizer_utils in tokenizer_list:
            with tempfile.TemporaryDirectory() as tmp_dir:
               tokenizer_utils.save_pretrained(__lowerCamelCase       )

               with open(os.path.join(__lowerCamelCase					,       """special_tokens_map.json"""       )					,       encoding="""utf-8"""       ) as json_file:
                  UpperCAmelCase							=     json.load(__lowerCamelCase       )

               with open(os.path.join(__lowerCamelCase					,       """tokenizer_config.json"""       )					,       encoding="""utf-8"""       ) as json_file:
                  UpperCAmelCase							=     json.load(__lowerCamelCase       )

               UpperCAmelCase							=     [F"""<extra_id_{i}>""" for i in range(1_2_5       )]

               UpperCAmelCase							=     added_tokens_extra_ids + [
                   """an_additional_special_token"""
               ]
               UpperCAmelCase							=     added_tokens_extra_ids + [
                   """an_additional_special_token"""
               ]

               with open(os.path.join(__lowerCamelCase					,       """special_tokens_map.json"""       )					,       """w"""					,       encoding="""utf-8"""       ) as outfile:
                  json.dump(__lowerCamelCase					,       __lowerCamelCase       )
               with open(os.path.join(__lowerCamelCase					,       """tokenizer_config.json"""       )					,       """w"""					,       encoding="""utf-8"""       ) as outfile:
                  json.dump(__lowerCamelCase					,       __lowerCamelCase       )

               # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
               # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
               # "special_tokens_map.json" files
               UpperCAmelCase							=     tokenizer_class.from_pretrained(
                   __lowerCamelCase					,       )
               self.assertIn(
                   """an_additional_special_token"""					,       tokenizer_without_change_in_init.additional_special_tokens       )
               self.assertEqual(
                   ["""an_additional_special_token"""]					,       tokenizer_without_change_in_init.convert_ids_to_tokens(
                       tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""]       )       )					,       )

               # Now we test that we can change the value of additional_special_tokens in the from_pretrained
               UpperCAmelCase							=     added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token"""					,       lstrip=__lowerCamelCase       )]
               UpperCAmelCase							=     tokenizer_class.from_pretrained(
                   __lowerCamelCase					,       additional_special_tokens=__lowerCamelCase					,       )

               self.assertIn("""a_new_additional_special_token"""					,       tokenizer.additional_special_tokens       )
               self.assertEqual(
                   ["""a_new_additional_special_token"""]					,       tokenizer.convert_ids_to_tokens(
                       tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""]       )       )					,       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.perceiver_tokenizer
         self.assertEqual(tokenizer.decode([1_7_8]       )					,       """�"""       )





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






         """simple docstring"""







         pass





      def        _lowercase				(		self						:					Tuple       )    ->   Any:






         """simple docstring"""







         pass





      def        _lowercase				(		self						:					Dict       )    ->   Tuple:






         """simple docstring"""







         pass





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






         """simple docstring"""







         pass





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






         """simple docstring"""







         UpperCAmelCase							=     self.get_tokenizers(fast=__lowerCamelCase					,       do_lower_case=__lowerCamelCase       )
         for tokenizer in tokenizers:
            with self.subTest(F"""{tokenizer.__class__.__name__}"""       ):
               UpperCAmelCase							=     ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""]
               UpperCAmelCase							=     tokenizer.convert_tokens_to_string(__lowerCamelCase       )

               self.assertIsInstance(__lowerCamelCase					,       __lowerCamelCase       )







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





      def __init__(		self						:					str					,       __lowerCamelCase						:					Optional[Any]					,       __lowerCamelCase						:					Optional[Any]=1_3					,       __lowerCamelCase						:					Optional[Any]=3_0					,       __lowerCamelCase						:					Any=2					,       __lowerCamelCase						:					List[str]=3					,       __lowerCamelCase						:					str=True					,       __lowerCamelCase						:					str=True					,       __lowerCamelCase						:					Union[str, Any]=3_2					,       __lowerCamelCase						:					Optional[int]=2					,       __lowerCamelCase						:					Optional[int]=4					,       __lowerCamelCase						:					Union[str, Any]=3_7					,       __lowerCamelCase						:					str="gelu"					,       __lowerCamelCase						:					str=0.1					,       __lowerCamelCase						:					List[str]=0.1					,       __lowerCamelCase						:					str=1_0					,       __lowerCamelCase						:					Union[str, Any]=0.02					,       __lowerCamelCase						:					List[str]=3					,       __lowerCamelCase						:					Optional[Any]=None					,       __lowerCamelCase						:					Any=2					,       )    ->   Tuple:






         """simple docstring"""







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

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





      def        _lowercase				(		self						:					Tuple       )    ->   int:






         """simple docstring"""







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

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

         UpperCAmelCase							=     self.get_config()

         return config, pixel_values, labels





      def        _lowercase				(		self						:					Tuple       )    ->   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=__lowerCamelCase					,       initializer_range=self.initializer_range					,       encoder_stride=self.encoder_stride					,       )





      def        _lowercase				(		self						:					Any					,       __lowerCamelCase						:					Optional[int]					,       __lowerCamelCase						:					Any					,       __lowerCamelCase						:					int       )    ->   Any:






         """simple docstring"""







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





      def        _lowercase				(		self						:					Optional[Any]					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					Any					,       __lowerCamelCase						:					Optional[Any]       )    ->   Union[str, Any]:






         """simple docstring"""







         UpperCAmelCase							=     TFDeiTForMaskedImageModeling(config=__lowerCamelCase       )
         UpperCAmelCase							=     model(__lowerCamelCase       )
         self.parent.assertEqual(
             result.reconstruction.shape					,       (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

         # test greyscale images
         UpperCAmelCase							=     1
         UpperCAmelCase							=     TFDeiTForMaskedImageModeling(__lowerCamelCase       )

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





      def        _lowercase				(		self						:					Union[str, Any]					,       __lowerCamelCase						:					List[Any]					,       __lowerCamelCase						:					Dict					,       __lowerCamelCase						:					int       )    ->   Any:






         """simple docstring"""







         UpperCAmelCase							=     self.type_sequence_label_size
         UpperCAmelCase							=     TFDeiTForImageClassification(__lowerCamelCase       )
         UpperCAmelCase							=     model(__lowerCamelCase					,       labels=__lowerCamelCase       )
         self.parent.assertEqual(result.logits.shape					,       (self.batch_size, self.type_sequence_label_size)       )

         # test greyscale images
         UpperCAmelCase							=     1
         UpperCAmelCase							=     TFDeiTForImageClassification(__lowerCamelCase       )

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





      def        _lowercase				(		self						:					Tuple       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase							=     self.prepare_config_and_inputs()
         UpperCAmelCase				,  UpperCAmelCase				,  UpperCAmelCase							=     config_and_inputs
         UpperCAmelCase							=     {"""pixel_values""": pixel_values}
         return config, inputs_dict






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

      UpperCamelCase								=       False
      UpperCamelCase								=       False
      UpperCamelCase								=       False
      UpperCamelCase								=       False





      def        _lowercase				(		self						:					str       )    ->   str:






         """simple docstring"""







         UpperCAmelCase							=     TFDeiTModelTester(self       )
         UpperCAmelCase							=     ConfigTester(self					,       config_class=__lowerCamelCase					,       has_text_modality=__lowerCamelCase					,       hidden_size=3_7       )





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






         """simple docstring"""







         self.config_tester.run_common_tests()





      @unittest.skip(reason="""DeiT does not use inputs_embeds"""       )
      def        _lowercase				(		self						:					List[Any]       )    ->   Dict:






         """simple docstring"""







         pass





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






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs_for_common()

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





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






         """simple docstring"""







         UpperCAmelCase				,  UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs_for_common()

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

            UpperCAmelCase							=     ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]					,       __lowerCamelCase       )





      def        _lowercase				(		self						:					Optional[int]       )    ->   Tuple:






         """simple docstring"""







         UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase       )





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






         """simple docstring"""







         UpperCAmelCase							=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase       )





      def        _lowercase				(		self						:					Optional[int]					,       __lowerCamelCase						:					List[Any]					,       __lowerCamelCase						:					List[Any]					,       __lowerCamelCase						:					Any=False       )    ->   int:






         """simple docstring"""







         UpperCAmelCase							=     super()._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase					,       return_labels=__lowerCamelCase       )

         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        _lowercase				(		self						:					Optional[int]       )    ->   str:






         """simple docstring"""







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

def   _UpperCamelCase				(						)						->Tuple:
   UpperCAmelCase							=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
   return image







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





      @cached_property
      def        _lowercase				(		self						:					List[str]       )    ->   Union[str, Any]:






         """simple docstring"""







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





      @slow
      def        _lowercase				(		self						:					Optional[int]       )    ->   List[str]:






         """simple docstring"""







         UpperCAmelCase							=     TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""       )

         UpperCAmelCase							=     self.default_image_processor
         UpperCAmelCase							=     prepare_img()
         UpperCAmelCase							=     image_processor(images=__lowerCamelCase					,       return_tensors="""tf"""       )

         # forward pass
         UpperCAmelCase							=     model(**__lowerCamelCase       )

         # verify the logits
         UpperCAmelCase							=     tf.TensorShape((1, 1_0_0_0)       )
         self.assertEqual(outputs.logits.shape					,       __lowerCamelCase       )

         UpperCAmelCase							=     tf.constant([-1.0_266, 0.1_912, -1.2_861]       )

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



