



"""simple docstring"""





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 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Dict    ,						SCREAMING_SNAKE_CASE       :							str=False   ):


							'''simple docstring'''







							try:
														__lowerCamelCase      :      Dict         =os.environ[key]
							except KeyError:
														# KEY isn't set, default to `default`.
														__lowerCamelCase      :      Optional[Any]         =default
							else:
														# KEY is set, convert it to True or False.
														try:
																					__lowerCamelCase      :      Dict         =strtobool(_SCREAMING_SNAKE_CASE   )
														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


_UpperCamelCase							=      parse_flag_from_env('RUN_SLOW', default=False)
_UpperCamelCase							=      parse_flag_from_env('RUN_REMOTE', default=False)
_UpperCamelCase							=      parse_flag_from_env('RUN_LOCAL', default=True)
_UpperCamelCase							=      parse_flag_from_env('RUN_PACKAGED', default=True)

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

# Audio
_UpperCamelCase							=      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
_UpperCamelCase							=      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
_UpperCamelCase							=      pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

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



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[str]   ):


							'''simple docstring'''







							try:
														import faiss  # noqa
							except ImportError:
														__lowerCamelCase      :      Optional[int]         =unittest.skip('''test requires faiss'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							try:
														import regex  # noqa
							except ImportError:
														__lowerCamelCase      :      str         =unittest.skip('''test requires regex'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str   ):


							'''simple docstring'''







							try:
														import elasticsearch  # noqa
							except ImportError:
														__lowerCamelCase      :      Optional[Any]         =unittest.skip('''test requires elasticsearch'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[str]   ):


							'''simple docstring'''







							try:
														import sqlalchemy  # noqa
							except ImportError:
														__lowerCamelCase      :      List[Any]         =unittest.skip('''test requires sqlalchemy'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							if not config.TORCH_AVAILABLE:
														__lowerCamelCase      :      List[Any]         =unittest.skip('''test requires PyTorch'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Any   ):


							'''simple docstring'''







							if not config.TF_AVAILABLE:
														__lowerCamelCase      :      Optional[int]         =unittest.skip('''test requires TensorFlow'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Optional[int]   ):


							'''simple docstring'''







							if not config.JAX_AVAILABLE:
														__lowerCamelCase      :      str         =unittest.skip('''test requires JAX'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[str]   ):


							'''simple docstring'''







							if not config.PIL_AVAILABLE:
														__lowerCamelCase      :      Union[str, Any]         =unittest.skip('''test requires Pillow'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Tuple   ):


							'''simple docstring'''







							try:
														import transformers  # noqa F401
							except ImportError:
														return unittest.skip('''test requires transformers'''   )(_SCREAMING_SNAKE_CASE   )
							else:
														return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							try:
														import tiktoken  # noqa F401
							except ImportError:
														return unittest.skip('''test requires tiktoken'''   )(_SCREAMING_SNAKE_CASE   )
							else:
														return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							try:
														import spacy  # noqa F401
							except ImportError:
														return unittest.skip('''test requires spacy'''   )(_SCREAMING_SNAKE_CASE   )
							else:
														return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[Any]   ):


							'''simple docstring'''







							def _require_spacy_model(SCREAMING_SNAKE_CASE       :							Optional[Any]   ):
														try:
																					import spacy  # noqa F401

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

							return _require_spacy_model



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Dict   ):


							'''simple docstring'''







							try:
														import pyspark  # noqa F401
							except ImportError:
														return unittest.skip('''test requires pyspark'''   )(_SCREAMING_SNAKE_CASE   )
							else:
														return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							try:
														import joblibspark  # noqa F401
							except ImportError:
														return unittest.skip('''test requires joblibspark'''   )(_SCREAMING_SNAKE_CASE   )
							else:
														return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Optional[Any]   ):


							'''simple docstring'''







							if not _run_slow_tests or _run_slow_tests == 0:
														__lowerCamelCase      :      Any         =unittest.skip('''test is slow'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Optional[Any]   ):


							'''simple docstring'''







							if not _run_local_tests or _run_local_tests == 0:
														__lowerCamelCase      :      Union[str, Any]         =unittest.skip('''test is local'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str   ):


							'''simple docstring'''







							if not _run_packaged_tests or _run_packaged_tests == 0:
														__lowerCamelCase      :      List[str]         =unittest.skip('''test is packaged'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[Any]   ):


							'''simple docstring'''







							if not _run_remote_tests or _run_remote_tests == 0:
														__lowerCamelCase      :      Optional[Any]         =unittest.skip('''test requires remote'''   )(_SCREAMING_SNAKE_CASE   )
							return test_case



def 				lowerCAmelCase_			(      *SCREAMING_SNAKE_CASE       :							List[str]   ):


							'''simple docstring'''







							def decorate(cls       :							Optional[int]   ):
														for name, fn in cls.__dict__.items():
																					if callable(_SCREAMING_SNAKE_CASE   ) and name.startswith('''test'''   ):
																												for decorator in decorators:
																																			__lowerCamelCase      :      List[Any]         =decorator(_SCREAMING_SNAKE_CASE   )
																												setattr(cls    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE   )
														return cls

							return decorate
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				pass

class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       List[Any]	 =		0
				__snake_case   :       Any	 =		1
				__snake_case   :       Optional[Any]	 =		2



@contextmanager
def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Tuple=OfflineSimulationMode.CONNECTION_FAILS    ,						SCREAMING_SNAKE_CASE       :							int=1E-16   ):


							'''simple docstring'''







							__lowerCamelCase      :      str         =requests.Session().request

							def timeout_request(SCREAMING_SNAKE_CASE       :							Dict    ,						SCREAMING_SNAKE_CASE       :							List[str]    ,						SCREAMING_SNAKE_CASE       :							int    ,						**SCREAMING_SNAKE_CASE       :							int   ):
														# Change the url to an invalid url so that the connection hangs
														__lowerCamelCase      :      Optional[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.'   )
														__lowerCamelCase      :      Dict         =timeout
														try:
																					return online_request(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						**_SCREAMING_SNAKE_CASE   )
														except Exception as e:
																					# The following changes in the error are just here to make the offline timeout error prettier
																					__lowerCamelCase      :      Optional[Any]         =url
																					__lowerCamelCase      :      str         =e.args[0]
																					__lowerCamelCase      :      List[Any]         =(max_retry_error.args[0].replace('''10.255.255.1'''    ,						F'OfflineMock[{url}]'   ),)
																					__lowerCamelCase      :      List[Any]         =(max_retry_error,)
																					raise

							def raise_connection_error(SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							Tuple    ,						**SCREAMING_SNAKE_CASE       :							List[Any]   ):
														raise requests.ConnectionError('''Offline mode is enabled.'''    ,						request=_SCREAMING_SNAKE_CASE   )

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



@contextmanager
def 				lowerCAmelCase_			(      *SCREAMING_SNAKE_CASE       :							Any    ,						**SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							__lowerCamelCase      :      Optional[Any]         =str(Path().resolve()   )
							with tempfile.TemporaryDirectory(*_SCREAMING_SNAKE_CASE    ,						**_SCREAMING_SNAKE_CASE   ) as tmp_dir:
														try:
																					os.chdir(_SCREAMING_SNAKE_CASE   )
																					yield
														finally:
																					os.chdir(_SCREAMING_SNAKE_CASE   )



@contextmanager
def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							import gc

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



@contextmanager
def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							import gc

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



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							str    ,						SCREAMING_SNAKE_CASE       :							Optional[int]   ):


							'''simple docstring'''







							return deepcopy(_SCREAMING_SNAKE_CASE   ).integers(0    ,						100    ,						10   ).tolist() == deepcopy(_SCREAMING_SNAKE_CASE   ).integers(0    ,						100    ,						10   ).tolist()



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Union[str, Any]   ):


							'''simple docstring'''







							import decorator
							from requests.exceptions import HTTPError

							def _wrapper(SCREAMING_SNAKE_CASE       :							Dict    ,						*SCREAMING_SNAKE_CASE       :							List[str]    ,						**SCREAMING_SNAKE_CASE       :							Optional[int]   ):
														try:
																					return func(*_SCREAMING_SNAKE_CASE    ,						**_SCREAMING_SNAKE_CASE   )
														except HTTPError as err:
																					if str(_SCREAMING_SNAKE_CASE   ).startswith('''500'''   ) or str(_SCREAMING_SNAKE_CASE   ).startswith('''502'''   ):
																												pytest.xfail(str(_SCREAMING_SNAKE_CASE   )   )
																					raise err

							return decorator.decorator(_wrapper    ,						_SCREAMING_SNAKE_CASE   )
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




				def __init__(     self  :List[str]						,    __lowercase  :List[Any]						,    __lowercase  :Any						,    __lowercase  :Optional[int]			):
											__lowerCamelCase      :      Optional[Any]         =returncode
											__lowerCamelCase      :      Dict         =stdout
											__lowerCamelCase      :      List[Any]         =stderr



async def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[str]    ,						SCREAMING_SNAKE_CASE       :							Dict   ):


							'''simple docstring'''







							while True:
														__lowerCamelCase      :      List[str]         =await stream.readline()
														if line:
																					callback(_SCREAMING_SNAKE_CASE   )
														else:
																					break



async def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							List[str]    ,						SCREAMING_SNAKE_CASE       :							Optional[Any]=None    ,						SCREAMING_SNAKE_CASE       :							List[Any]=None    ,						SCREAMING_SNAKE_CASE       :							List[str]=None    ,						SCREAMING_SNAKE_CASE       :							int=False    ,						SCREAMING_SNAKE_CASE       :							List[str]=False   ):


							'''simple docstring'''







							if echo:
														print('''\nRunning: '''    ,						''' '''.join(_SCREAMING_SNAKE_CASE   )   )

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

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

							__lowerCamelCase      :      List[str]         =[]
							__lowerCamelCase      :      Dict         =[]

							def tee(SCREAMING_SNAKE_CASE       :							Dict    ,						SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							List[Any]    ,						SCREAMING_SNAKE_CASE       :							Tuple=""   ):
														__lowerCamelCase      :      Tuple         =line.decode('''utf-8'''   ).rstrip()
														sink.append(_SCREAMING_SNAKE_CASE   )
														if not quiet:
																					print(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						file=_SCREAMING_SNAKE_CASE   )

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



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Any    ,						SCREAMING_SNAKE_CASE       :							Union[str, Any]=None    ,						SCREAMING_SNAKE_CASE       :							str=None    ,						SCREAMING_SNAKE_CASE       :							Optional[Any]=180    ,						SCREAMING_SNAKE_CASE       :							Optional[Any]=False    ,						SCREAMING_SNAKE_CASE       :							Union[str, Any]=True   ):


							'''simple docstring'''







							__lowerCamelCase      :      List[str]         =asyncio.get_event_loop()
							__lowerCamelCase      :      Union[str, Any]         =loop.run_until_complete(
							    _stream_subprocess(_SCREAMING_SNAKE_CASE    ,						env=_SCREAMING_SNAKE_CASE    ,						stdin=_SCREAMING_SNAKE_CASE    ,						timeout=_SCREAMING_SNAKE_CASE    ,						quiet=_SCREAMING_SNAKE_CASE    ,						echo=_SCREAMING_SNAKE_CASE   )   )

							__lowerCamelCase      :      Union[str, Any]         =''' '''.join(_SCREAMING_SNAKE_CASE   )
							if result.returncode > 0:
														__lowerCamelCase      :      Any         ='''\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 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Tuple         =os.environ.get('''PYTEST_XDIST_WORKER'''    ,						'''gw0'''   )
							__lowerCamelCase      :      Optional[int]         =re.sub(r'''^gw'''    ,						''''''    ,						_SCREAMING_SNAKE_CASE    ,						0    ,						re.M   )
							return int(_SCREAMING_SNAKE_CASE   )



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Dict         =29500
							__lowerCamelCase      :      str         =pytest_xdist_worker_id()
							return port + uniq_delta











"""simple docstring"""





import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch
							from torch import nn

							from transformers import (
							    MODEL_MAPPING,
							    BeitForImageClassification,
							    BeitForMaskedImageModeling,
							    BeitForSemanticSegmentation,
							    BeitModel,
							)
							from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							import PIL
							from PIL import Image

							from transformers import BeitImageProcessor
class 		SCREAMING_SNAKE_CASE_							:
				"""simple docstring"""




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

											# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
											__lowerCamelCase      :      Optional[int]         =(image_size // patch_size) ** 2
											__lowerCamelCase      :      Optional[Any]         =num_patches + 1




				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      Dict         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

											__lowerCamelCase      :      Any         =None
											__lowerCamelCase      :      str         =None
											if self.use_labels:
																		__lowerCamelCase      :      Dict         =ids_tensor([self.batch_size]						,    self.type_sequence_label_size			)
																		__lowerCamelCase      :      List[Any]         =ids_tensor([self.batch_size, self.image_size, self.image_size]						,    self.num_labels			)

											__lowerCamelCase      :      List[str]         =self.get_config()

											return config, pixel_values, labels, pixel_labels




				def 					__lowercase  (     self  :Tuple			):
											return BeitConfig(
											    vocab_size=self.vocab_size						,    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=__lowercase						,    initializer_range=self.initializer_range						,    out_indices=self.out_indices						,    )




				def 					__lowercase  (     self  :Any						,    __lowercase  :List[Any]						,    __lowercase  :str						,    __lowercase  :Union[str, Any]						,    __lowercase  :Dict			):
											__lowerCamelCase      :      Tuple         =BeitModel(config=__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      int         =model(__lowercase			)
											self.parent.assertEqual(result.last_hidden_state.shape						,    (self.batch_size, self.seq_length, self.hidden_size)			)




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :Dict						,    __lowercase  :Tuple						,    __lowercase  :Optional[Any]						,    __lowercase  :Any			):
											__lowerCamelCase      :      List[str]         =BeitForMaskedImageModeling(config=__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      int         =model(__lowercase			)
											self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.seq_length - 1, self.vocab_size)			)




				def 					__lowercase  (     self  :Dict						,    __lowercase  :str						,    __lowercase  :Tuple						,    __lowercase  :int						,    __lowercase  :str			):
											__lowerCamelCase      :      int         =self.type_sequence_label_size
											__lowerCamelCase      :      Optional[Any]         =BeitForImageClassification(__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      Optional[Any]         =model(__lowercase						,    labels=__lowercase			)
											self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.type_sequence_label_size)			)

											# test greyscale images
											__lowerCamelCase      :      int         =1
											__lowerCamelCase      :      str         =BeitForImageClassification(__lowercase			)
											model.to(__lowercase			)
											model.eval()

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




				def 					__lowercase  (     self  :List[Any]						,    __lowercase  :Dict						,    __lowercase  :List[str]						,    __lowercase  :int						,    __lowercase  :str			):
											__lowerCamelCase      :      Union[str, Any]         =self.num_labels
											__lowerCamelCase      :      Any         =BeitForSemanticSegmentation(__lowercase			)
											model.to(__lowercase			)
											model.eval()
											__lowerCamelCase      :      Any         =model(__lowercase			)
											self.parent.assertEqual(
											    result.logits.shape						,    (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)
											__lowerCamelCase      :      Optional[Any]         =model(__lowercase						,    labels=__lowercase			)
											self.parent.assertEqual(
											    result.logits.shape						,    (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)




				def 					__lowercase  (     self  :Optional[int]			):
											__lowerCamelCase      :      Optional[int]         =self.prepare_config_and_inputs()
											__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase      :      str         =config_and_inputs
											__lowerCamelCase      :      List[Any]         ={'''pixel_values''': pixel_values}
											return config, inputs_dict

@require_torch
class 		SCREAMING_SNAKE_CASE_							(    snake_case__       ,  snake_case__       ,  unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       List[Any]	 =		(
				    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				__snake_case   :       Any	 =		(
				    {
				        """feature-extraction""": BeitModel,
				        """image-classification""": BeitForImageClassification,
				        """image-segmentation""": BeitForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				__snake_case   :       Union[str, Any]	 =		False
				__snake_case   :       Optional[Any]	 =		False
				__snake_case   :       str	 =		False




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Optional[Any]         =BeitModelTester(self			)
											__lowerCamelCase      :      Optional[int]         =ConfigTester(self						,    config_class=__lowercase						,    has_text_modality=__lowercase						,    hidden_size=37			)




				def 					__lowercase  (     self  :Union[str, Any]			):
											self.config_tester.run_common_tests()




				@unittest.skip(reason='''BEiT does not use inputs_embeds'''			)
				def 					__lowercase  (     self  :List[str]			):
											pass




				@require_torch_multi_gpu
				@unittest.skip(reason='''BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''			)
				def 					__lowercase  (     self  :Union[str, Any]			):
											pass




				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase    ,						__lowerCamelCase      :      Tuple         =self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		__lowerCamelCase      :      Optional[int]         =model_class(__lowercase			)
																		self.assertIsInstance(model.get_input_embeddings()						,    (nn.Module)			)
																		__lowerCamelCase      :      Union[str, Any]         =model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(__lowercase						,    nn.Linear			)			)




				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase    ,						__lowerCamelCase      :      List[Any]         =self.model_tester.prepare_config_and_inputs_for_common()

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

																		__lowerCamelCase      :      List[Any]         =['''pixel_values''']
																		self.assertListEqual(arg_names[:1]						,    __lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      Optional[Any]         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__lowercase			)




				def 					__lowercase  (     self  :str			):
											__lowerCamelCase      :      int         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*__lowercase			)




				def 					__lowercase  (     self  :Dict			):
											__lowerCamelCase      :      str         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__lowercase			)




				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Any         =self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__lowercase			)




				def 					__lowercase  (     self  :str			):
											if not self.model_tester.is_training:
																		return

											__lowerCamelCase    ,						__lowerCamelCase      :      Any         =self.model_tester.prepare_config_and_inputs_for_common()
											__lowerCamelCase      :      Optional[Any]         =True

											for model_class in self.all_model_classes:
																		# we don't test BeitForMaskedImageModeling
																		if model_class in [*get_values(__lowercase			), BeitForMaskedImageModeling]:
																									continue

																		__lowerCamelCase      :      Any         =model_class(__lowercase			)
																		model.to(__lowercase			)
																		model.train()
																		__lowerCamelCase      :      Dict         =self._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)
																		__lowerCamelCase      :      List[Any]         =model(**__lowercase			).loss
																		loss.backward()




				def 					__lowercase  (     self  :List[Any]			):
											__lowerCamelCase    ,						__lowerCamelCase      :      Optional[int]         =self.model_tester.prepare_config_and_inputs_for_common()
											if not self.model_tester.is_training:
																		return

											__lowerCamelCase      :      str         =False
											__lowerCamelCase      :      int         =True

											for model_class in self.all_model_classes:
																		# we don't test BeitForMaskedImageModeling
																		if (
																		    model_class in [*get_values(__lowercase			), BeitForMaskedImageModeling]
																		    or not model_class.supports_gradient_checkpointing
																		):
																									continue

																		__lowerCamelCase      :      Any         =model_class(__lowercase			)
																		model.gradient_checkpointing_enable()
																		model.to(__lowercase			)
																		model.train()
																		__lowerCamelCase      :      Any         =self._prepare_for_class(__lowercase						,    __lowercase						,    return_labels=__lowercase			)
																		__lowerCamelCase      :      Union[str, Any]         =model(**__lowercase			).loss
																		loss.backward()




				def 					__lowercase  (     self  :Dict			):
											__lowerCamelCase    ,						__lowerCamelCase      :      str         =self.model_tester.prepare_config_and_inputs_for_common()

											__lowerCamelCase      :      Tuple         =_config_zero_init(__lowercase			)
											for model_class in self.all_model_classes:
																		__lowerCamelCase      :      List[Any]         =model_class(config=__lowercase			)
																		for name, param in model.named_parameters():
																									# we skip lambda parameters as these require special initial values
																									# determined by config.layer_scale_init_value
																									if "lambda" in name:
																																continue
																									if param.requires_grad:
																																self.assertIn(
																																    ((param.data.mean() * 1e9).round() / 1e9).item()						,    [0.0, 1.0]						,    msg=f'Parameter {name} of model {model_class} seems not properly initialized'						,    )




				@slow
				def 					__lowercase  (     self  :int			):
											for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		__lowerCamelCase      :      str         =BeitModel.from_pretrained(__lowercase			)
																		self.assertIsNotNone(__lowercase			)



def 				lowerCAmelCase_			(      ):


							'''simple docstring'''







							__lowerCamelCase      :      Tuple         =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
							return image
@require_torch
@require_vision
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				@cached_property
				def 					__lowercase  (     self  :Optional[Any]			):
											return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''			) if is_vision_available() else None




				@slow
				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase      :      Union[str, Any]         =BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''			).to(__lowercase			)

											__lowerCamelCase      :      Union[str, Any]         =self.default_image_processor
											__lowerCamelCase      :      List[str]         =prepare_img()
											__lowerCamelCase      :      Tuple         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).pixel_values.to(__lowercase			)

											# prepare bool_masked_pos
											__lowerCamelCase      :      Dict         =torch.ones((1, 196)						,    dtype=torch.bool			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      List[Any]         =model(pixel_values=__lowercase						,    bool_masked_pos=__lowercase			)
											__lowerCamelCase      :      List[Any]         =outputs.logits

											# verify the logits
											__lowerCamelCase      :      str         =torch.Size((1, 196, 8192)			)
											self.assertEqual(logits.shape						,    __lowercase			)

											__lowerCamelCase      :      Tuple         =torch.tensor(
											    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]			).to(__lowercase			)

											self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]						,    __lowercase						,    atol=1e-2			)			)




				@slow
				def 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Optional[int]         =BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''			).to(__lowercase			)

											__lowerCamelCase      :      str         =self.default_image_processor
											__lowerCamelCase      :      List[Any]         =prepare_img()
											__lowerCamelCase      :      List[Any]         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      int         =model(**__lowercase			)
											__lowerCamelCase      :      List[Any]         =outputs.logits

											# verify the logits
											__lowerCamelCase      :      Union[str, Any]         =torch.Size((1, 1000)			)
											self.assertEqual(logits.shape						,    __lowercase			)

											__lowerCamelCase      :      Optional[Any]         =torch.tensor([-1.2385, -1.0987, -1.0108]			).to(__lowercase			)

											self.assertTrue(torch.allclose(logits[0, :3]						,    __lowercase						,    atol=1e-4			)			)

											__lowerCamelCase      :      str         =281
											self.assertEqual(logits.argmax(-1			).item()						,    __lowercase			)




				@slow
				def 					__lowercase  (     self  :int			):
											__lowerCamelCase      :      Optional[int]         =BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''			).to(
											    __lowercase			)

											__lowerCamelCase      :      str         =self.default_image_processor
											__lowerCamelCase      :      str         =prepare_img()
											__lowerCamelCase      :      int         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      str         =model(**__lowercase			)
											__lowerCamelCase      :      int         =outputs.logits

											# verify the logits
											__lowerCamelCase      :      Dict         =torch.Size((1, 2_1841)			)
											self.assertEqual(logits.shape						,    __lowercase			)

											__lowerCamelCase      :      List[Any]         =torch.tensor([1.6881, -0.2787, 0.5901]			).to(__lowercase			)

											self.assertTrue(torch.allclose(logits[0, :3]						,    __lowercase						,    atol=1e-4			)			)

											__lowerCamelCase      :      List[Any]         =2396
											self.assertEqual(logits.argmax(-1			).item()						,    __lowercase			)




				@slow
				def 					__lowercase  (     self  :Optional[int]			):
											__lowerCamelCase      :      Tuple         =BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''			)
											__lowerCamelCase      :      int         =model.to(__lowercase			)

											__lowerCamelCase      :      Tuple         =BeitImageProcessor(do_resize=__lowercase						,    size=640						,    do_center_crop=__lowercase			)

											__lowerCamelCase      :      Optional[Any]         =load_dataset('''hf-internal-testing/fixtures_ade20k'''						,    split='''test'''			)
											__lowerCamelCase      :      Optional[int]         =Image.open(ds[0]['''file''']			)
											__lowerCamelCase      :      Union[str, Any]         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      List[Any]         =model(**__lowercase			)
											__lowerCamelCase      :      Tuple         =outputs.logits

											# verify the logits
											__lowerCamelCase      :      Optional[Any]         =torch.Size((1, 150, 160, 160)			)
											self.assertEqual(logits.shape						,    __lowercase			)

											__lowerCamelCase      :      List[Any]         =version.parse(PIL.__version__			) < version.parse('''9.0.0'''			)

											if is_pillow_less_than_a:
																		__lowerCamelCase      :      Any         =torch.tensor(
																		    [
																		        [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
																		        [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
																		        [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
																		    ]						,    device=__lowercase						,    )
											else:
																		__lowerCamelCase      :      int         =torch.tensor(
																		    [
																		        [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
																		        [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
																		        [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
																		    ]						,    device=__lowercase						,    )

											self.assertTrue(torch.allclose(logits[0, :3, :3, :3]						,    __lowercase						,    atol=1e-4			)			)




				@slow
				def 					__lowercase  (     self  :Any			):
											__lowerCamelCase      :      Any         =BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''			)
											__lowerCamelCase      :      Union[str, Any]         =model.to(__lowercase			)

											__lowerCamelCase      :      List[str]         =BeitImageProcessor(do_resize=__lowercase						,    size=640						,    do_center_crop=__lowercase			)

											__lowerCamelCase      :      List[str]         =load_dataset('''hf-internal-testing/fixtures_ade20k'''						,    split='''test'''			)
											__lowerCamelCase      :      Optional[Any]         =Image.open(ds[0]['''file''']			)
											__lowerCamelCase      :      List[Any]         =image_processor(images=__lowercase						,    return_tensors='''pt'''			).to(__lowercase			)

											# forward pass
											with torch.no_grad():
																		__lowerCamelCase      :      Tuple         =model(**__lowercase			)

											__lowerCamelCase      :      str         =outputs.logits.detach().cpu()

											__lowerCamelCase      :      Union[str, Any]         =image_processor.post_process_semantic_segmentation(outputs=__lowercase						,    target_sizes=[(500, 300)]			)
											__lowerCamelCase      :      Union[str, Any]         =torch.Size((500, 300)			)
											self.assertEqual(segmentation[0].shape						,    __lowercase			)

											__lowerCamelCase      :      Optional[Any]         =image_processor.post_process_semantic_segmentation(outputs=__lowercase			)
											__lowerCamelCase      :      List[str]         =torch.Size((160, 160)			)
											self.assertEqual(segmentation[0].shape						,    __lowercase			)




