
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__ ,		UpperCamelCase__=False		)     ->   Union[str, Any]:
      try:
            UpperCamelCase__    :   Optional[Any]					=				os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            UpperCamelCase__    :   List[Any]					=				default
      else:
            # KEY is set, convert it to True or False.
            try:
                  UpperCamelCase__    :   List[str]					=				strtobool(UpperCamelCase__		)
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(f'''If set, {key} must be yes or no.'''		)
      return _value


lowerCamelCase      =parse_flag_from_env("RUN_SLOW", default=False)
lowerCamelCase      =parse_flag_from_env("RUN_REMOTE", default=False)
lowerCamelCase      =parse_flag_from_env("RUN_LOCAL", default=True)
lowerCamelCase      =parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
lowerCamelCase      =pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
lowerCamelCase      =pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
lowerCamelCase      =pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
lowerCamelCase      =pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
lowerCamelCase      =pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
lowerCamelCase      =pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
lowerCamelCase      =pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Optional[Any]:
      try:
            import faiss  # noqa
      except ImportError:
            UpperCamelCase__    :   Dict					=				unittest.skip('''test requires faiss'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Dict:
      try:
            import regex  # noqa
      except ImportError:
            UpperCamelCase__    :   List[str]					=				unittest.skip('''test requires regex'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Tuple:
      try:
            import elasticsearch  # noqa
      except ImportError:
            UpperCamelCase__    :   Dict					=				unittest.skip('''test requires elasticsearch'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Any:
      try:
            import sqlalchemy  # noqa
      except ImportError:
            UpperCamelCase__    :   Optional[Any]					=				unittest.skip('''test requires sqlalchemy'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Dict:
      if not config.TORCH_AVAILABLE:
            UpperCamelCase__    :   int					=				unittest.skip('''test requires PyTorch'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   int:
      if not config.TF_AVAILABLE:
            UpperCamelCase__    :   Optional[Any]					=				unittest.skip('''test requires TensorFlow'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   int:
      if not config.JAX_AVAILABLE:
            UpperCamelCase__    :   Optional[int]					=				unittest.skip('''test requires JAX'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Optional[int]:
      if not config.PIL_AVAILABLE:
            UpperCamelCase__    :   Dict					=				unittest.skip('''test requires Pillow'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   str:
      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip('''test requires transformers'''		)(UpperCamelCase__		)
      else:
            return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   List[Any]:
      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip('''test requires tiktoken'''		)(UpperCamelCase__		)
      else:
            return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Any:
      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip('''test requires spacy'''		)(UpperCamelCase__		)
      else:
            return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   str:

      def _require_spacy_model(UpperCamelCase__		):
            try:
                  import spacy  # noqa F401

                  spacy.load(UpperCamelCase__		)
            except ImportError:
                  return unittest.skip('''test requires spacy'''		)(UpperCamelCase__		)
            except OSError:
                  return unittest.skip('''test requires spacy model \'{}\''''.format(UpperCamelCase__		)		)(UpperCamelCase__		)
            else:
                  return test_case

      return _require_spacy_model


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   List[str]:
      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip('''test requires pyspark'''		)(UpperCamelCase__		)
      else:
            return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   int:
      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip('''test requires joblibspark'''		)(UpperCamelCase__		)
      else:
            return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   List[str]:
      if not _run_slow_tests or _run_slow_tests == 0:
            UpperCamelCase__    :   Optional[Any]					=				unittest.skip('''test is slow'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   List[Any]:
      if not _run_local_tests or _run_local_tests == 0:
            UpperCamelCase__    :   Optional[int]					=				unittest.skip('''test is local'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Tuple:
      if not _run_packaged_tests or _run_packaged_tests == 0:
            UpperCamelCase__    :   str					=				unittest.skip('''test is packaged'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   List[str]:
      if not _run_remote_tests or _run_remote_tests == 0:
            UpperCamelCase__    :   Union[str, Any]					=				unittest.skip('''test requires remote'''		)(UpperCamelCase__		)
      return test_case


def 							SCREAMING_SNAKE_CASE_      (			*UpperCamelCase__		)     ->   Optional[Any]:
      def decorate(cls		):
            for name, fn in cls.__dict__.items():
                  if callable(UpperCamelCase__		) and name.startswith('''test'''		):
                        for decorator in decorators:
                              UpperCamelCase__    :   Dict					=				decorator(UpperCamelCase__		)
                        setattr(cls ,		UpperCamelCase__ ,		UpperCamelCase__		)
            return cls

      return decorate




class 				_lowerCamelCase (      UpperCamelCase_ ):





     """simple docstring"""







     pass




class 				_lowerCamelCase (      UpperCamelCase_ ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		   =  0
     SCREAMING_SNAKE_CASE_		   =  1
     SCREAMING_SNAKE_CASE_		   =  2


@contextmanager
def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__=OfflineSimulationMode.CONNECTION_FAILS ,		UpperCamelCase__=1e-16		)     ->   Tuple:
      UpperCamelCase__    :   Tuple					=				requests.Session().request

      def timeout_request(UpperCamelCase__ ,		UpperCamelCase__ ,		UpperCamelCase__ ,		**UpperCamelCase__		):
            # Change the url to an invalid url so that the connection hangs
            UpperCamelCase__    :   List[Any]					=				'''https://10.255.255.1'''
            if kwargs.get('''timeout'''		) is None:
                  raise RequestWouldHangIndefinitelyError(
                      f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''		)
            UpperCamelCase__    :   Optional[Any]					=				timeout
            try:
                  return online_request(UpperCamelCase__ ,		UpperCamelCase__ ,		**UpperCamelCase__		)
            except Exception as e:
                  # The following changes in the error are just here to make the offline timeout error prettier
                  UpperCamelCase__    :   int					=				url
                  UpperCamelCase__    :   int					=				e.args[0]
                  UpperCamelCase__    :   List[str]					=				(max_retry_error.args[0].replace('''10.255.255.1''' ,		f'''OfflineMock[{url}]'''		),)
                  UpperCamelCase__    :   Union[str, Any]					=				(max_retry_error,)
                  raise

      def raise_connection_error(UpperCamelCase__ ,		UpperCamelCase__ ,		**UpperCamelCase__		):
            raise requests.ConnectionError('''Offline mode is enabled.''' ,		request=UpperCamelCase__		)

      if mode is OfflineSimulationMode.CONNECTION_FAILS:
            with patch('''requests.Session.send''' ,		UpperCamelCase__		):
                  yield
      elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
            # inspired from https://stackoverflow.com/a/904609
            with patch('''requests.Session.request''' ,		UpperCamelCase__		):
                  yield
      elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
            with patch('''datasets.config.HF_DATASETS_OFFLINE''' ,		UpperCamelCase__		):
                  yield
      else:
            raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''		)


@contextmanager
def 							SCREAMING_SNAKE_CASE_      (			*UpperCamelCase__ ,		**UpperCamelCase__		)     ->   Dict:
      UpperCamelCase__    :   List[str]					=				str(Path().resolve()		)
      with tempfile.TemporaryDirectory(*UpperCamelCase__ ,		**UpperCamelCase__		) as tmp_dir:
            try:
                  os.chdir(UpperCamelCase__		)
                  yield
            finally:
                  os.chdir(UpperCamelCase__		)


@contextmanager
def 							SCREAMING_SNAKE_CASE_      (			)     ->   str:
      import gc

      gc.collect()
      UpperCamelCase__    :   Optional[int]					=				pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."


@contextmanager
def 							SCREAMING_SNAKE_CASE_      (			)     ->   Dict:
      import gc

      gc.collect()
      UpperCamelCase__    :   Any					=				pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__ ,		UpperCamelCase__		)     ->   Optional[int]:
      return deepcopy(UpperCamelCase__		).integers(0 ,		1_0_0 ,		1_0		).tolist() == deepcopy(UpperCamelCase__		).integers(0 ,		1_0_0 ,		1_0		).tolist()


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__		)     ->   Optional[int]:
      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(UpperCamelCase__ ,		*UpperCamelCase__ ,		**UpperCamelCase__		):
            try:
                  return func(*UpperCamelCase__ ,		**UpperCamelCase__		)
            except HTTPError as err:
                  if str(UpperCamelCase__		).startswith('''500'''		) or str(UpperCamelCase__		).startswith('''502'''		):
                        pytest.xfail(str(UpperCamelCase__		)		)
                  raise err

      return decorator.decorator(_wrapper ,		UpperCamelCase__		)




class 				_lowerCamelCase :





     """simple docstring"""







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




           """simple docstring"""







           UpperCamelCase__    :   Any					=				returncode
           UpperCamelCase__    :   Dict					=				stdout
           UpperCamelCase__    :   Optional[int]					=				stderr


async def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__ ,		UpperCamelCase__		)     ->   str:
      while True:
            UpperCamelCase__    :   int					=				await stream.readline()
            if line:
                  callback(UpperCamelCase__		)
            else:
                  break


async def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__ ,		UpperCamelCase__=None ,		UpperCamelCase__=None ,		UpperCamelCase__=None ,		UpperCamelCase__=False ,		UpperCamelCase__=False		)     ->   Union[str, Any]:
      if echo:
            print('''\nRunning: ''' ,		''' '''.join(UpperCamelCase__		)		)

      UpperCamelCase__    :   Tuple					=				await asyncio.create_subprocess_exec(
          cmd[0] ,		*cmd[1:] ,		stdin=UpperCamelCase__ ,		stdout=asyncio.subprocess.PIPE ,		stderr=asyncio.subprocess.PIPE ,		env=UpperCamelCase__ ,		)

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      UpperCamelCase__    :   Optional[int]					=				[]
      UpperCamelCase__    :   List[str]					=				[]

      def tee(UpperCamelCase__ ,		UpperCamelCase__ ,		UpperCamelCase__ ,		UpperCamelCase__=""		):
            UpperCamelCase__    :   Optional[Any]					=				line.decode('''utf-8'''		).rstrip()
            sink.append(UpperCamelCase__		)
            if not quiet:
                  print(UpperCamelCase__ ,		UpperCamelCase__ ,		file=UpperCamelCase__		)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              _read_stream(p.stdout ,		lambda UpperCamelCase__		: tee(UpperCamelCase__ ,		UpperCamelCase__ ,		sys.stdout ,		label='''stdout:'''		)		),
              _read_stream(p.stderr ,		lambda UpperCamelCase__		: tee(UpperCamelCase__ ,		UpperCamelCase__ ,		sys.stderr ,		label='''stderr:'''		)		),
          ] ,		timeout=UpperCamelCase__ ,		)
      return _RunOutput(await p.wait() ,		UpperCamelCase__ ,		UpperCamelCase__		)


def 							SCREAMING_SNAKE_CASE_      (			UpperCamelCase__ ,		UpperCamelCase__=None ,		UpperCamelCase__=None ,		UpperCamelCase__=1_8_0 ,		UpperCamelCase__=False ,		UpperCamelCase__=True		)     ->   str:
      UpperCamelCase__    :   Union[str, Any]					=				asyncio.get_event_loop()
      UpperCamelCase__    :   Any					=				loop.run_until_complete(
          _stream_subprocess(UpperCamelCase__ ,		env=UpperCamelCase__ ,		stdin=UpperCamelCase__ ,		timeout=UpperCamelCase__ ,		quiet=UpperCamelCase__ ,		echo=UpperCamelCase__		)		)

      UpperCamelCase__    :   Any					=				''' '''.join(UpperCamelCase__		)
      if result.returncode > 0:
            UpperCamelCase__    :   str					=				'''\n'''.join(result.stderr		)
            raise RuntimeError(
                f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
                f'''The combined stderr from workers follows:\n{stderr}'''		)

      # check that the subprocess actually did run and produced some output, should the test rely on
      # the remote side to do the testing
      if not result.stdout and not result.stderr:
            raise RuntimeError(f'''\'{cmd_str}\' produced no output.'''		)

      return result


def 							SCREAMING_SNAKE_CASE_      (			)     ->   Optional[int]:
      UpperCamelCase__    :   int					=				os.environ.get('''PYTEST_XDIST_WORKER''' ,		'''gw0'''		)
      UpperCamelCase__    :   List[Any]					=				re.sub(R'''^gw''' ,		'''''' ,		UpperCamelCase__ ,		0 ,		re.M		)
      return int(UpperCamelCase__		)


def 							SCREAMING_SNAKE_CASE_      (			)     ->   Optional[int]:
      UpperCamelCase__    :   Optional[Any]					=				2_9_5_0_0
      UpperCamelCase__    :   int					=				pytest_xdist_worker_id()
      return port + uniq_delta




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


