





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
						import torch

						_lowerCAmelCase 				=     True
except ImportError:
						_lowerCAmelCase 				=     False


try:
						from torch.hub import _get_torch_home

						_lowerCAmelCase 				=     _get_torch_home()
except ImportError:
						_lowerCAmelCase 				=     os.path.expanduser(
						    os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
						)

_lowerCAmelCase 				=     os.path.join(torch_cache_home, """transformers""")

_lowerCAmelCase 				=     """https://cdn.huggingface.co"""
_lowerCAmelCase 				=     """https://s3.amazonaws.com/models.huggingface.co/bert"""
_lowerCAmelCase 				=     """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
_lowerCAmelCase 				=     os.path.join(PATH, """config.yaml""")
_lowerCAmelCase 				=     os.path.join(PATH, """attributes.txt""")
_lowerCAmelCase 				=     os.path.join(PATH, """objects.txt""")
_lowerCAmelCase 				=     os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
_lowerCAmelCase 				=     os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
_lowerCAmelCase 				=     os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
_lowerCAmelCase 				=     """pytorch_model.bin"""
_lowerCAmelCase 				=     """config.yaml"""



def     _lowerCAmelCase		(  _lowerCAmelCase=OBJECTS  ,_lowerCAmelCase=ATTRIBUTES     ):
			'''simple docstring'''


			A_     :				Union[str, Any]			      =	[]
			with open(UpperCAmelCase__     ) as f:
						for object in f.readlines():
									vg_classes.append(object.split(""","""     )[0].lower().strip()     )

			A_     :				Optional[int]			      =	[]
			with open(UpperCAmelCase__     ) as f:
						for object in f.readlines():
									vg_attrs.append(object.split(""","""     )[0].lower().strip()     )
			return vg_classes, vg_attrs



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
			'''simple docstring'''


			A_     :				str			      =	OrderedDict()
			with open(UpperCAmelCase__  ,"""rb"""     ) as f:
						A_     :				Union[str, Any]			      =	pkl.load(UpperCAmelCase__     )["""model"""]
			for k in copy.deepcopy(list(ckp.keys()     )     ):
						A_     :				Tuple			      =	ckp.pop(UpperCAmelCase__     )
						if isinstance(UpperCAmelCase__  ,np.ndarray     ):
									A_     :				List[Any]			      =	torch.tensor(UpperCAmelCase__     )
						else:
									assert isinstance(UpperCAmelCase__  ,torch.tensor     ), type(UpperCAmelCase__     )
						A_     :				str			      =	v
			return r

class    _UpperCAmelCase							:
						a						       =							{}
						def __init__(		self      ,       a__      ,       a__ = "root"      ,       a__=0       ):
									A_     :				List[Any]			      =	name
									A_     :				Optional[int]			      =	level
									A_     :				Optional[Any]			      =	{}
									for k, v in dictionary.items():
												if v is None:
															raise ValueError()
												A_     :				Union[str, Any]			      =	copy.deepcopy(__UpperCamelCase       )
												A_     :				Optional[int]			      =	copy.deepcopy(__UpperCamelCase       )
												if isinstance(__UpperCamelCase      ,       __UpperCamelCase       ):
															A_     :				List[Any]			      =	Config(__UpperCamelCase      ,       name=__UpperCamelCase      ,       level=level + 1       )
												A_     :				str			      =	v
												setattr(self      ,       __UpperCamelCase      ,       __UpperCamelCase       )

									A_     :				Union[str, Any]			      =	d
						def __repr__(		self       ):
									return str(list((self._pointer.keys())       )       )
						def __setattr__(		self      ,       a__      ,       a__       ):
									A_     :				List[str]			      =	val
									A_     :				int			      =	val
									A_     :				Dict			      =	key.split("""."""       )
									A_     :				str			      =	len(__UpperCamelCase       ) - 1
									A_     :				Optional[Any]			      =	self._pointer
									if len(__UpperCamelCase       ) > 1:
												for i, l in enumerate(__UpperCamelCase       ):
															if hasattr(self      ,       __UpperCamelCase       ) and isinstance(getattr(self      ,       __UpperCamelCase       )      ,       __UpperCamelCase       ):
																		setattr(getattr(self      ,       __UpperCamelCase       )      ,       """.""".join(levels[i:]       )      ,       __UpperCamelCase       )
															if l == last_level:
																		A_     :				int			      =	val
															else:
																		A_     :				List[Any]			      =	pointer[l]
						def 		_lowerCamelCase      (		self       ):
									return self._pointer
						def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
									with open(F"""{file_name}"""      ,       """w"""       ) as stream:
												dump(__UpperCamelCase      ,       __UpperCamelCase       )
						def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
									with open(F"""{file_name}"""      ,       """w"""       ) as stream:
												json.dump(__UpperCamelCase      ,       __UpperCamelCase       )
						@staticmethod
						def 		_lowerCamelCase      (		a__       ):
									with open(__UpperCamelCase       ) as stream:
												A_     :				Dict			      =	load(__UpperCamelCase      ,       Loader=__UpperCamelCase       )
									return data
						def __str__(		self       ):
									A_     :				Dict			      =	"""    """
									if self._name != "root":
												A_     :				Optional[Any]			      =	F"""{t * (self._level-1)}{self._name}:\n"""
									else:
												A_     :				Optional[Any]			      =	""""""
									A_     :				List[Any]			      =	self._level
									for i, (k, v) in enumerate(self._pointer.items()       ):
												if isinstance(__UpperCamelCase      ,       __UpperCamelCase       ):
															r += F"""{t * (self._level)}{v}\n"""
															self._level += 1
												else:
															r += F"""{t * (self._level)}{k}: {v} ({type(__UpperCamelCase       ).__name__})\n"""
												A_     :				Optional[int]			      =	level
									return r[:-1]
						@classmethod
						def 		_lowerCamelCase      (		cls      ,       a__      ,       **a__       ):
									A_      ,				A_     :				Any			      =	cls.get_config_dict(__UpperCamelCase      ,       **__UpperCamelCase       )
									return cls(__UpperCamelCase       )






						@classmethod
						def 		_lowerCamelCase      (		cls      ,       a__      ,       **a__       ):
									A_     :				Any			      =	kwargs.pop("""cache_dir"""      ,       __UpperCamelCase       )
									A_     :				Tuple			      =	kwargs.pop("""force_download"""      ,       __UpperCamelCase       )
									A_     :				int			      =	kwargs.pop("""resume_download"""      ,       __UpperCamelCase       )
									A_     :				Any			      =	kwargs.pop("""proxies"""      ,       __UpperCamelCase       )
									A_     :				Optional[Any]			      =	kwargs.pop("""local_files_only"""      ,       __UpperCamelCase       )

									if os.path.isdir(__UpperCamelCase       ):
												A_     :				Tuple			      =	os.path.join(__UpperCamelCase      ,       __UpperCamelCase       )
									elif os.path.isfile(__UpperCamelCase       ) or is_remote_url(__UpperCamelCase       ):
												A_     :				str			      =	pretrained_model_name_or_path
									else:
												A_     :				List[str]			      =	hf_bucket_url(__UpperCamelCase      ,       filename=__UpperCamelCase      ,       use_cdn=__UpperCamelCase       )

									try:
												# Load from URL or cache if already cached
												A_     :				Tuple			      =	cached_path(
												    __UpperCamelCase      ,       cache_dir=__UpperCamelCase      ,       force_download=__UpperCamelCase      ,       proxies=__UpperCamelCase      ,       resume_download=__UpperCamelCase      ,       local_files_only=__UpperCamelCase      ,       )
												# Load config dict
												if resolved_config_file is None:
															raise EnvironmentError

												A_     :				List[str]			      =	Config.load_yaml(__UpperCamelCase       )

									except EnvironmentError:
												A_     :				List[str]			      =	"""Can't load config for"""
												raise EnvironmentError(__UpperCamelCase       )

									if resolved_config_file == config_file:
												print("""loading configuration file from path"""       )
									else:
												print("""loading configuration file cache"""       )

									return Config.load_yaml(__UpperCamelCase       ), kwargs






def     _lowerCAmelCase		(  _lowerCAmelCase     ):
			'''simple docstring'''


			A_     :				List[str]			      =	torch.load("""dump.pt"""  ,map_location=in_tensor.device     )
			A_     :				Optional[int]			      =	in_tensor.numpy()
			A_     :				Any			      =	out_tensor.numpy()[0]
			print(na.shape  ,na[0, 0, :5]     )
			print(na.shape  ,na[0, 0, :5]     )
			assert np.allclose(UpperCAmelCase__  ,UpperCAmelCase__  ,rtol=0.01  ,atol=0.1     ), (
			    f"""{sum([1 for x in np.isclose(UpperCAmelCase__  ,UpperCAmelCase__  ,rtol=0.01  ,atol=0.1     ).flatten() if x is False]     )/len(na.flatten()     )*1_0_0:.4f} %"""
			    " element-wise mismatch"
			)
			raise Exception("""tensors are all good"""     )

			# Hugging face functions below



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
			'''simple docstring'''


			A_     :				str			      =	urlparse(UpperCAmelCase__     )
			return parsed.scheme in ("http", "https")



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase=True     ):
			'''simple docstring'''


			A_     :				Optional[int]			      =	CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
			A_     :				Any			      =	"""/""" not in model_id
			if legacy_format:
						return f"""{endpoint}/{model_id}-{filename}"""
			else:
						return f"""{endpoint}/{model_id}/{filename}"""



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase  ,_lowerCAmelCase=None  ,_lowerCAmelCase=0  ,_lowerCAmelCase=None  ,):
			'''simple docstring'''


			A_     :				List[str]			      =	"""python/{}""".format(sys.version.split()[0]     )
			if _torch_available:
						ua += "; torch/{}".format(torch.__version__     )
			if isinstance(UpperCAmelCase__  ,UpperCAmelCase__     ):
						ua += "; " + "; ".join("""{}/{}""".format(UpperCAmelCase__  ,UpperCAmelCase__     ) for k, v in user_agent.items()     )
			elif isinstance(UpperCAmelCase__  ,UpperCAmelCase__     ):
						ua += "; " + user_agent
			A_     :				Union[str, Any]			      =	{"""user-agent""": ua}
			if resume_size > 0:
						A_     :				List[str]			      =	"""bytes=%d-""" % (resume_size,)
			A_     :				Tuple			      =	requests.get(UpperCAmelCase__  ,stream=UpperCAmelCase__  ,proxies=UpperCAmelCase__  ,headers=UpperCAmelCase__     )
			if response.status_code == 4_1_6:  # Range not satisfiable
						return
			A_     :				Union[str, Any]			      =	response.headers.get("""Content-Length"""     )
			A_     :				Any			      =	resume_size + int(UpperCAmelCase__     ) if content_length is not None else None
			A_     :				Optional[Any]			      =	tqdm(
			    unit="""B"""  ,unit_scale=UpperCAmelCase__  ,total=UpperCAmelCase__  ,initial=UpperCAmelCase__  ,desc="""Downloading"""  ,)
			for chunk in response.iter_content(chunk_size=1_0_2_4     ):
						if chunk:  # filter out keep-alive new chunks
									progress.update(len(UpperCAmelCase__     )     )
									temp_file.write(UpperCAmelCase__     )
			progress.close()



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,_lowerCAmelCase=None  ,_lowerCAmelCase=1_0  ,_lowerCAmelCase=False  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,):
			'''simple docstring'''


			if cache_dir is None:
						A_     :				Optional[Any]			      =	TRANSFORMERS_CACHE
			if isinstance(UpperCAmelCase__  ,UpperCAmelCase__     ):
						A_     :				Dict			      =	str(UpperCAmelCase__     )

			os.makedirs(UpperCAmelCase__  ,exist_ok=UpperCAmelCase__     )

			A_     :				Tuple			      =	None
			if not local_files_only:
						try:
									A_     :				Union[str, Any]			      =	requests.head(UpperCAmelCase__  ,allow_redirects=UpperCAmelCase__  ,proxies=UpperCAmelCase__  ,timeout=UpperCAmelCase__     )
									if response.status_code == 2_0_0:
												A_     :				List[str]			      =	response.headers.get("""ETag"""     )
						except (EnvironmentError, requests.exceptions.Timeout):
									# etag is already None
									pass

			A_     :				Any			      =	url_to_filename(UpperCAmelCase__  ,UpperCAmelCase__     )

			# get cache path to put the file
			A_     :				Dict			      =	os.path.join(UpperCAmelCase__  ,UpperCAmelCase__     )

			# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
			# try to get the last downloaded one
			if etag is None:
						if os.path.exists(UpperCAmelCase__     ):
									return cache_path
						else:
									A_     :				int			      =	[
									    file
									    for file in fnmatch.filter(os.listdir(UpperCAmelCase__     )  ,filename + """.*"""     )
									    if not file.endswith(""".json"""     ) and not file.endswith(""".lock"""     )
									]
									if len(UpperCAmelCase__     ) > 0:
												return os.path.join(UpperCAmelCase__  ,matching_files[-1]     )
									else:
												# If files cannot be found and local_files_only=True,
												# the models might've been found if local_files_only=False
												# Notify the user about that
												if local_files_only:
															raise ValueError(
															    """Cannot find the requested files in the cached path and outgoing traffic has been"""
															    """ disabled. To enable model look-ups and downloads online, set 'local_files_only'"""
															    """ to False."""     )
												return None

    # From now on, etag is not None.
			if os.path.exists(UpperCAmelCase__     ) and not force_download:
						return cache_path

			# Prevent parallel downloads of the same file with a lock.
			A_     :				List[Any]			      =	cache_path + """.lock"""
			with FileLock(UpperCAmelCase__     ):
						# If the download just completed while the lock was activated.
						if os.path.exists(UpperCAmelCase__     ) and not force_download:
									# Even if returning early like here, the lock will be released.
									return cache_path

						if resume_download:
									A_     :				int			      =	cache_path + """.incomplete"""

									@contextmanager
									def _resumable_file_manager():
												with open(UpperCAmelCase__  ,"""a+b"""     ) as f:
															yield f

									A_     :				List[Any]			      =	_resumable_file_manager
									if os.path.exists(UpperCAmelCase__     ):
												A_     :				int			      =	os.stat(UpperCAmelCase__     ).st_size
									else:
												A_     :				Tuple			      =	0
						else:
									A_     :				List[str]			      =	partial(tempfile.NamedTemporaryFile  ,dir=UpperCAmelCase__  ,delete=UpperCAmelCase__     )
									A_     :				Union[str, Any]			      =	0

						# Download to temporary file, then copy to cache dir once finished.
						# Otherwise you get corrupt cache entries if the download gets interrupted.
						with temp_file_manager() as temp_file:
									print(
									    """%s not found in cache or force_download set to True, downloading to %s"""  ,UpperCAmelCase__  ,temp_file.name  ,)

									http_get(
									    UpperCAmelCase__  ,UpperCAmelCase__  ,proxies=UpperCAmelCase__  ,resume_size=UpperCAmelCase__  ,user_agent=UpperCAmelCase__  ,)

						os.replace(temp_file.name  ,UpperCAmelCase__     )

						A_     :				Optional[int]			      =	{"""url""": url, """etag""": etag}
						A_     :				Any			      =	cache_path + """.json"""
						with open(UpperCAmelCase__  ,"""w"""     ) as meta_file:
									json.dump(UpperCAmelCase__  ,UpperCAmelCase__     )

			return cache_path



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase=None     ):
			'''simple docstring'''


			A_     :				Any			      =	url.encode("""utf-8"""     )
			A_     :				str			      =	shaaaa(UpperCAmelCase__     )
			A_     :				Dict			      =	url_hash.hexdigest()

			if etag:
						A_     :				Optional[int]			      =	etag.encode("""utf-8"""     )
						A_     :				List[str]			      =	shaaaa(UpperCAmelCase__     )
						filename += "." + etag_hash.hexdigest()

			if url.endswith(""".h5"""     ):
						filename += ".h5"

			return filename



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,_lowerCAmelCase=None  ,_lowerCAmelCase=False  ,_lowerCAmelCase=False  ,_lowerCAmelCase=False  ,):
			'''simple docstring'''


			if cache_dir is None:
						A_     :				Any			      =	TRANSFORMERS_CACHE
			if isinstance(UpperCAmelCase__  ,UpperCAmelCase__     ):
						A_     :				Any			      =	str(UpperCAmelCase__     )
			if isinstance(UpperCAmelCase__  ,UpperCAmelCase__     ):
						A_     :				List[str]			      =	str(UpperCAmelCase__     )

			if is_remote_url(UpperCAmelCase__     ):
						# URL, so get it from the cache (downloading if necessary)
						A_     :				Union[str, Any]			      =	get_from_cache(
						    UpperCAmelCase__  ,cache_dir=UpperCAmelCase__  ,force_download=UpperCAmelCase__  ,proxies=UpperCAmelCase__  ,resume_download=UpperCAmelCase__  ,user_agent=UpperCAmelCase__  ,local_files_only=UpperCAmelCase__  ,)
			elif os.path.exists(UpperCAmelCase__     ):
						# File, and it exists.
						A_     :				Union[str, Any]			      =	url_or_filename
			elif urlparse(UpperCAmelCase__     ).scheme == "":
						# File, but it doesn't exist.
						raise EnvironmentError("""file {} not found""".format(UpperCAmelCase__     )     )
			else:
						# Something unknown
						raise ValueError("""unable to parse {} as a URL or as a local path""".format(UpperCAmelCase__     )     )

			if extract_compressed_file:
						if not is_zipfile(UpperCAmelCase__     ) and not tarfile.is_tarfile(UpperCAmelCase__     ):
									return output_path

						# Path where we extract compressed archives
						# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
						A_      ,				A_     :				Tuple			      =	os.path.split(UpperCAmelCase__     )
						A_     :				str			      =	output_file.replace("""."""  ,"""-"""     ) + """-extracted"""
						A_     :				Optional[Any]			      =	os.path.join(UpperCAmelCase__  ,UpperCAmelCase__     )

						if os.path.isdir(UpperCAmelCase__     ) and os.listdir(UpperCAmelCase__     ) and not force_extract:
									return output_path_extracted

						# Prevent parallel extractions
						A_     :				Tuple			      =	output_path + """.lock"""
						with FileLock(UpperCAmelCase__     ):
									shutil.rmtree(UpperCAmelCase__  ,ignore_errors=UpperCAmelCase__     )
									os.makedirs(UpperCAmelCase__     )
									if is_zipfile(UpperCAmelCase__     ):
												with ZipFile(UpperCAmelCase__  ,"""r"""     ) as zip_file:
															zip_file.extractall(UpperCAmelCase__     )
															zip_file.close()
									elif tarfile.is_tarfile(UpperCAmelCase__     ):
												A_     :				str			      =	tarfile.open(UpperCAmelCase__     )
												tar_file.extractall(UpperCAmelCase__     )
												tar_file.close()
									else:
												raise EnvironmentError("""Archive format of {} could not be identified""".format(UpperCAmelCase__     )     )

						return output_path_extracted

			return output_path



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase=","     ):
			'''simple docstring'''


			assert isinstance(UpperCAmelCase__  ,UpperCAmelCase__     )
			if os.path.isfile(UpperCAmelCase__     ):
						with open(UpperCAmelCase__     ) as f:
									A_     :				Tuple			      =	eval(f.read()     )
			else:
						A_     :				Dict			      =	requests.get(UpperCAmelCase__     )
						try:
									A_     :				Optional[Any]			      =	requests.json()
						except Exception:
									A_     :				Union[str, Any]			      =	req.content.decode()
									assert data is not None, "could not connect"
									try:
												A_     :				int			      =	eval(UpperCAmelCase__     )
									except Exception:
												A_     :				int			      =	data.split("""\n"""     )
						req.close()
			return data



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
			'''simple docstring'''


			A_     :				Tuple			      =	requests.get(UpperCAmelCase__     )
			A_     :				Optional[int]			      =	np.array(Image.open(BytesIO(response.content     )     )     )
			return img



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
			'''simple docstring'''


			A_     :				Optional[int]			      =	url.split("""/"""     )[-1]
			if fn not in os.listdir(os.getcwd()     ):
						wget.download(UpperCAmelCase__     )
			with open(UpperCAmelCase__  ,"""rb"""     ) as stream:
						A_     :				List[str]			      =	pkl.load(UpperCAmelCase__     )
			A_     :				Tuple			      =	weights.pop("""model"""     )
			A_     :				Optional[Any]			      =	{}
			for k, v in model.items():
						A_     :				Dict			      =	torch.from_numpy(UpperCAmelCase__     )
						if "running_var" in k:
									A_     :				Union[str, Any]			      =	torch.tensor([0]     )
									A_     :				Optional[int]			      =	k.replace("""running_var"""  ,"""num_batches_tracked"""     )
									A_     :				int			      =	zero
			return new



def     _lowerCAmelCase		(  ):
			'''simple docstring'''


			print(f"""{os.path.abspath(os.path.join(UpperCAmelCase__  ,os.pardir     )     )}/demo.ipynb"""     )



def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase="RGB"     ):
			'''simple docstring'''


			assert isinstance(UpperCAmelCase__  ,UpperCAmelCase__     )
			if os.path.isfile(UpperCAmelCase__     ):
						A_     :				Tuple			      =	cva.imread(UpperCAmelCase__     )
			else:
						A_     :				Union[str, Any]			      =	get_image_from_url(UpperCAmelCase__     )
						assert img is not None, f"""could not connect to: {im}"""
			A_     :				str			      =	cva.cvtColor(UpperCAmelCase__  ,cva.COLOR_BGR2RGB     )
			if input_format == "RGB":
						A_     :				Any			      =	img[:, :, ::-1]
			return img







def     _lowerCAmelCase		(  _lowerCAmelCase  ,_lowerCAmelCase=1     ):
			'''simple docstring'''


			return (images[i : i + batch] for i in range(0  ,len(UpperCAmelCase__     )  ,UpperCAmelCase__     ))













import inspect
import math
import tempfile
import unittest

import numpy as np

from transformers import ViTMAEConfig
from transformers.testing_utils import require_torch, 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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import ViTMAEForPreTraining, ViTMAEModel
      from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor

class    _UpperCAmelCase							:
      def __init__(		self      ,       a__      ,       a__=13      ,       a__=30      ,       a__=2      ,       a__=3      ,       a__=True      ,       a__=True      ,       a__=32      ,       a__=5      ,       a__=4      ,       a__=37      ,       a__="gelu"      ,       a__=0.1      ,       a__=0.1      ,       a__=10      ,       a__=0.02      ,       a__=3      ,       a__=0.6      ,       a__=None      ,       ):
         A_     :				int			      =	parent
         A_     :				Optional[int]			      =	batch_size
         A_     :				Any			      =	image_size
         A_     :				Optional[int]			      =	patch_size
         A_     :				int			      =	num_channels
         A_     :				str			      =	is_training
         A_     :				str			      =	use_labels
         A_     :				str			      =	hidden_size
         A_     :				Union[str, Any]			      =	num_hidden_layers
         A_     :				Tuple			      =	num_attention_heads
         A_     :				Any			      =	intermediate_size
         A_     :				List[Any]			      =	hidden_act
         A_     :				List[Any]			      =	hidden_dropout_prob
         A_     :				Optional[int]			      =	attention_probs_dropout_prob
         A_     :				str			      =	type_sequence_label_size
         A_     :				int			      =	initializer_range
         A_     :				List[Any]			      =	mask_ratio
         A_     :				str			      =	scope

         # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
         # (we add 1 for the [CLS] token)
         A_     :				Optional[Any]			      =	(image_size // patch_size) ** 2
         A_     :				List[Any]			      =	int(math.ceil((1 - mask_ratio) * (num_patches + 1)       )       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				List[str]			      =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         A_     :				int			      =	None
         if self.use_labels:
            A_     :				List[Any]			      =	ids_tensor([self.batch_size]      ,       self.type_sequence_label_size       )

         A_     :				Any			      =	self.get_config()

         return config, pixel_values, labels
      def 		_lowerCamelCase      (		self       ):
         return ViTMAEConfig(
             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=a__      ,       initializer_range=self.initializer_range      ,       mask_ratio=self.mask_ratio      ,       )
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__      ,       a__       ):
         A_     :				Optional[int]			      =	ViTMAEModel(config=a__       )
         model.to(a__       )
         model.eval()
         A_     :				int			      =	model(a__       )
         self.parent.assertEqual(result.last_hidden_state.shape      ,       (self.batch_size, self.seq_length, self.hidden_size)       )
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__      ,       a__       ):
         A_     :				int			      =	ViTMAEForPreTraining(a__       )
         model.to(a__       )
         model.eval()
         A_     :				Optional[Any]			      =	model(a__       )
         A_     :				Dict			      =	(self.image_size // self.patch_size) ** 2
         A_     :				Optional[int]			      =	self.patch_size**2 * self.num_channels
         self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, num_patches, expected_num_channels)       )

         # test greyscale images
         A_     :				Optional[int]			      =	1
         A_     :				Any			      =	ViTMAEForPreTraining(a__       )
         model.to(a__       )
         model.eval()
         A_     :				Dict			      =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
         A_     :				List[Any]			      =	model(a__       )
         A_     :				Optional[int]			      =	self.patch_size**2
         self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, num_patches, expected_num_channels)       )






      def 		_lowerCamelCase      (		self       ):
         A_     :				Optional[Any]			      =	self.prepare_config_and_inputs()
         A_      ,				A_      ,				A_     :				Any			      =	config_and_inputs
         A_     :				Dict			      =	{"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_torch
class    _UpperCAmelCase							(		_lowerCamelCase			,       _lowerCamelCase			,       unittest.TestCase     ):
      a						       =							(ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
      a						       =							{'''feature-extraction''': ViTMAEModel} if is_torch_available() else {}

      a						       =							False
      a						       =							False
      a						       =							False
      a						       =							False
      def 		_lowerCamelCase      (		self       ):
         A_     :				int			      =	ViTMAEModelTester(self       )
         A_     :				List[Any]			      =	ConfigTester(self      ,       config_class=a__      ,       has_text_modality=a__      ,       hidden_size=37       )
      def 		_lowerCamelCase      (		self       ):
         self.config_tester.run_common_tests()
      @unittest.skip(reason="""ViTMAE does not use inputs_embeds"""       )
      def 		_lowerCamelCase      (		self       ):
         pass
      def 		_lowerCamelCase      (		self       ):
         A_      ,				A_     :				Union[str, Any]			      =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            A_     :				Dict			      =	model_class(a__       )
            self.assertIsInstance(model.get_input_embeddings()      ,       (nn.Module)       )
            A_     :				int			      =	model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(a__      ,       nn.Linear       )       )
      def 		_lowerCamelCase      (		self       ):
         A_      ,				A_     :				int			      =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            A_     :				Any			      =	model_class(a__       )
            A_     :				Union[str, Any]			      =	inspect.signature(model.forward       )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            A_     :				Dict			      =	[*signature.parameters.keys()]

            A_     :				List[str]			      =	["""pixel_values"""]
            self.assertListEqual(arg_names[:1]      ,       a__       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				Dict			      =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a__       )
      def 		_lowerCamelCase      (		self       ):
         A_     :				Any			      =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_pretraining(*a__       )
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__      ,       a__       ):
         # make masks reproducible
         np.random.seed(2       )

         A_     :				Optional[Any]			      =	int((pt_model.config.image_size // pt_model.config.patch_size) ** 2       )
         A_     :				List[str]			      =	np.random.uniform(size=(self.model_tester.batch_size, num_patches)       )
         A_     :				Optional[Any]			      =	torch.from_numpy(a__       )

         # Add `noise` argument.
         # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
         A_     :				Any			      =	pt_noise

         super().check_pt_tf_models(a__      ,       a__      ,       a__       )
      def 		_lowerCamelCase      (		self       ):
         A_      ,				A_     :				int			      =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            A_     :				List[Any]			      =	model_class(a__       )
            model.to(a__       )
            model.eval()
            # make random mask reproducible
            torch.manual_seed(2       )
            with torch.no_grad():
               A_     :				Union[str, Any]			      =	model(**self._prepare_for_class(a__      ,       a__       )       )

            A_     :				int			      =	outputs[0].cpu().numpy()
            A_     :				Union[str, Any]			      =	0

            with tempfile.TemporaryDirectory() as tmpdirname:
               model.save_pretrained(a__       )
               A_     :				Union[str, Any]			      =	model_class.from_pretrained(a__       )
               model.to(a__       )
               # make random mask reproducible
               torch.manual_seed(2       )
               with torch.no_grad():
                  A_     :				Optional[int]			      =	model(**self._prepare_for_class(a__      ,       a__       )       )

               # Make sure we don't have nans
               A_     :				Optional[int]			      =	after_outputs[0].cpu().numpy()
               A_     :				str			      =	0
               A_     :				Optional[int]			      =	np.amax(np.abs(out_a - out_a       )       )
               self.assertLessEqual(a__      ,       1E-5       )
      @unittest.skip(
          reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""       )
      def 		_lowerCamelCase      (		self       ):
         pass
      @unittest.skip(
          reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""       )
      def 		_lowerCamelCase      (		self       ):
         pass
      @unittest.skip(
          reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results."""       )
      def 		_lowerCamelCase      (		self       ):
         pass
      @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load"""       )
      def 		_lowerCamelCase      (		self       ):
         pass
      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""       )
      def 		_lowerCamelCase      (		self       ):
         pass






      @slow
      def 		_lowerCamelCase      (		self       ):
         for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            A_     :				Union[str, Any]			      =	ViTMAEModel.from_pretrained(a__       )
            self.assertIsNotNone(a__       )






def     _lowerCAmelCase		(  ):
   '''simple docstring'''


   A_     :				List[Any]			      =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
   return image







@require_torch
@require_vision
class    _UpperCAmelCase							(		unittest.TestCase     ):
      @cached_property
      def 		_lowerCamelCase      (		self       ):
         return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base"""       ) if is_vision_available() else None






      @slow
      def 		_lowerCamelCase      (		self       ):
         # make random mask reproducible across the PT and TF model
         np.random.seed(2       )

         A_     :				Union[str, Any]			      =	ViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base"""       ).to(a__       )

         A_     :				Optional[Any]			      =	self.default_image_processor
         A_     :				Union[str, Any]			      =	prepare_img()
         A_     :				Union[str, Any]			      =	image_processor(images=a__      ,       return_tensors="""pt"""       ).to(a__       )

         # prepare a noise vector that will be also used for testing the TF model
         # (this way we can ensure that the PT and TF models operate on the same inputs)
         A_     :				Optional[int]			      =	ViTMAEConfig()
         A_     :				Tuple			      =	int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2       )
         A_     :				Tuple			      =	np.random.uniform(size=(1, num_patches)       )

         # forward pass
         with torch.no_grad():
            A_     :				Dict			      =	model(**a__      ,       noise=torch.from_numpy(a__       ).to(device=a__       )       )

         # verify the logits
         A_     :				Tuple			      =	torch.Size((1, 196, 768)       )
         self.assertEqual(outputs.logits.shape      ,       a__       )

         A_     :				List[str]			      =	torch.tensor(
             [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]]       )

         self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]      ,       expected_slice.to(a__       )      ,       atol=1E-4       )       )






