


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

			_snake_case  :	int			      =       True
except ImportError:
			_snake_case  :	Tuple			      =       False


try:
			from torch.hub import _get_torch_home

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

_snake_case  :	Tuple			      =       os.path.join(torch_cache_home, "transformers")

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







def        lowerCAmelCase_  (      __lowerCamelCase=OBJECTS							,			__lowerCamelCase=ATTRIBUTES			):
							__snake_case	:    Optional[int]											=     []
							with open(__lowerCamelCase			) as f:
														for object in f.readlines():
																					vg_classes.append(object.split(","			)[0].lower().strip()			)

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







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

class        a	:




							"""simple docstring"""


							__UpperCAmelCase					:							Dict  						=						{}

							def __init__(							self :						int					,			lowerCamelCase :						Optional[int]					,			lowerCamelCase :						str = "root"					,			lowerCamelCase :						Union[str, Any]=0       )			->					int:
														__snake_case	:    Union[str, Any]											=     name
														__snake_case	:    int											=     level
														__snake_case	:    Optional[Any]											=     {}
														for k, v in dictionary.items():
																					if v is None:
																												raise ValueError()
																					__snake_case	:    Union[str, Any]											=     copy.deepcopy(_A       )
																					__snake_case	:    int											=     copy.deepcopy(_A       )
																					if isinstance(_A					,			_A       ):
																												__snake_case	:    Optional[int]											=     Config(_A					,			name=_A					,			level=level + 1       )
																					__snake_case	:    List[str]											=     v
																					setattr(self					,			_A					,			_A       )

														__snake_case	:    Optional[Any]											=     d

							def __repr__(							self :						Optional[int]       )			->					List[str]:
														return str(list((self._pointer.keys())       )       )

							def __setattr__(							self :						List[Any]					,			lowerCamelCase :						Dict					,			lowerCamelCase :						List[Any]       )			->					Any:
														__snake_case	:    List[Any]											=     val
														__snake_case	:    Any											=     val
														__snake_case	:    Tuple											=     key.split("."       )
														__snake_case	:    List[Any]											=     len(_A       ) - 1
														__snake_case	:    Dict											=     self._pointer
														if len(_A       ) > 1:
																					for i, l in enumerate(_A       ):
																												if hasattr(self					,			_A       ) and isinstance(getattr(self					,			_A       )					,			_A       ):
																																			setattr(getattr(self					,			_A       )					,			".".join(levels[i:]       )					,			_A       )
																												if l == last_level:
																																			__snake_case	:    Tuple											=     val
																												else:
																																			__snake_case	:    List[Any]											=     pointer[l]

							def 					__snake_case      (							self :						List[Any]       )			->					Optional[Any]:
														return self._pointer

							def 					__snake_case      (							self :						List[Any]					,			lowerCamelCase :						Optional[Any]					,			lowerCamelCase :						Optional[Any]       )			->					Any:
														with open(F'{file_name}'					,			"w"       ) as stream:
																					dump(_A					,			_A       )

							def 					__snake_case      (							self :						Union[str, Any]					,			lowerCamelCase :						Optional[Any]					,			lowerCamelCase :						Union[str, Any]       )			->					Any:
														with open(F'{file_name}'					,			"w"       ) as stream:
																					json.dump(_A					,			_A       )

							@staticmethod
							def 					__snake_case      (							lowerCamelCase :						Dict       )			->					Any:
														with open(_A       ) as stream:
																					__snake_case	:    str											=     load(_A					,			Loader=_A       )
														return data

							def __str__(							self :						Optional[Any]       )			->					Tuple:
														__snake_case	:    int											=     '    '
														if self._name != "root":
																					__snake_case	:    Any											=     F'{t * (self._level-1)}{self._name}:\n'
														else:
																					__snake_case	:    Any											=     ''
														__snake_case	:    List[str]											=     self._level
														for i, (k, v) in enumerate(self._pointer.items()       ):
																					if isinstance(_A					,			_A       ):
																												r += F'{t * (self._level)}{v}\n'
																												self._level += 1
																					else:
																												r += F'{t * (self._level)}{k}: {v} ({type(_A       ).__name__})\n'
																					__snake_case	:    List[str]											=     level
														return r[:-1]

							@classmethod
							def 					__snake_case      (							cls :						List[str]					,			lowerCamelCase :						Optional[int]					,			**lowerCamelCase :						Any       )			->					Dict:
														__snake_case	:    Union[str, Any]											=     cls.get_config_dict(_A					,			**_A       )
														return cls(_A       )






							@classmethod
							def 					__snake_case      (							cls :						Optional[Any]					,			lowerCamelCase :						Optional[Any]					,			**lowerCamelCase :						Tuple       )			->					Optional[int]:
														__snake_case	:    Dict											=     kwargs.pop("cache_dir"					,			_A       )
														__snake_case	:    Tuple											=     kwargs.pop("force_download"					,			_A       )
														__snake_case	:    str											=     kwargs.pop("resume_download"					,			_A       )
														__snake_case	:    List[Any]											=     kwargs.pop("proxies"					,			_A       )
														__snake_case	:    Dict											=     kwargs.pop("local_files_only"					,			_A       )

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

														try:
																					# Load from URL or cache if already cached
																					__snake_case	:    Union[str, Any]											=     cached_path(
																					    _A					,			cache_dir=_A					,			force_download=_A					,			proxies=_A					,			resume_download=_A					,			local_files_only=_A					,			)
																					# Load config dict
																					if resolved_config_file is None:
																												raise EnvironmentError

																					__snake_case	:    List[str]											=     Config.load_yaml(_A       )

														except EnvironmentError:
																					__snake_case	:    int											=     'Can\'t load config for'
																					raise EnvironmentError(_A       )

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

														return Config.load_yaml(_A       ), kwargs







def        lowerCAmelCase_  (      __lowerCamelCase			):
							__snake_case	:    List[Any]											=     torch.load("dump.pt"							,			map_location=in_tensor.device			)
							__snake_case	:    Any											=     in_tensor.numpy()
							__snake_case	:    Optional[Any]											=     out_tensor.numpy()[0]
							print(na.shape							,			na[0, 0, :5]			)
							print(na.shape							,			na[0, 0, :5]			)
							assert np.allclose(__lowerCamelCase							,			__lowerCamelCase							,			rtol=0.0_1							,			atol=0.1			), (
							    F'{sum([1 for x in np.isclose(__lowerCamelCase							,			__lowerCamelCase							,			rtol=0.0_1							,			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			):
							__snake_case	:    List[str]											=     urlparse(__lowerCamelCase			)
							return parsed.scheme in ("http", "https")







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase=True			):
							__snake_case	:    Dict											=     CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
							__snake_case	:    List[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							,			):
							__snake_case	:    int											=     'python/{}'.format(sys.version.split()[0]			)
							if _torch_available:
														ua += "; torch/{}".format(torch.__version__			)
							if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														ua += "; " + "; ".join("{}/{}".format(__lowerCamelCase							,			__lowerCamelCase			) for k, v in user_agent.items()			)
							elif isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														ua += "; " + user_agent
							__snake_case	:    Tuple											=     {'user-agent': ua}
							if resume_size > 0:
														__snake_case	:    str											=     'bytes=%d-' % (resume_size,)
							__snake_case	:    List[Any]											=     requests.get(__lowerCamelCase							,			stream=__lowerCamelCase							,			proxies=__lowerCamelCase							,			headers=__lowerCamelCase			)
							if response.status_code == 4_1_6:  # Range not satisfiable
														return
							__snake_case	:    List[str]											=     response.headers.get("Content-Length"			)
							__snake_case	:    Optional[int]											=     resume_size + int(__lowerCamelCase			) if content_length is not None else None
							__snake_case	:    int											=     tqdm(
							    unit="B"							,			unit_scale=__lowerCamelCase							,			total=__lowerCamelCase							,			initial=__lowerCamelCase							,			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(__lowerCamelCase			)			)
																					temp_file.write(__lowerCamelCase			)
							progress.close()







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=None							,			__lowerCamelCase=False							,			__lowerCamelCase=None							,			__lowerCamelCase=1_0							,			__lowerCamelCase=False							,			__lowerCamelCase=None							,			__lowerCamelCase=False							,			):
							if cache_dir is None:
														__snake_case	:    Tuple											=     TRANSFORMERS_CACHE
							if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														__snake_case	:    Dict											=     str(__lowerCamelCase			)

							os.makedirs(__lowerCamelCase							,			exist_ok=__lowerCamelCase			)

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

							__snake_case	:    Any											=     url_to_filename(__lowerCamelCase							,			__lowerCamelCase			)

							# get cache path to put the file
							__snake_case	:    List[str]											=     os.path.join(__lowerCamelCase							,			__lowerCamelCase			)

							# 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(__lowerCamelCase			):
																					return cache_path
														else:
																					__snake_case	:    str											=     [
																					    file
																					    for file in fnmatch.filter(os.listdir(__lowerCamelCase			)							,			filename + ".*"			)
																					    if not file.endswith(".json"			) and not file.endswith(".lock"			)
																					]
																					if len(__lowerCamelCase			) > 0:
																												return os.path.join(__lowerCamelCase							,			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(__lowerCamelCase			) and not force_download:
														return cache_path

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

														if resume_download:
																					__snake_case	:    Union[str, Any]											=     cache_path + '.incomplete'

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

																					__snake_case	:    str											=     _resumable_file_manager
																					if os.path.exists(__lowerCamelCase			):
																												__snake_case	:    List[str]											=     os.stat(__lowerCamelCase			).st_size
																					else:
																												__snake_case	:    str											=     0
														else:
																					__snake_case	:    List[Any]											=     partial(tempfile.NamedTemporaryFile							,			dir=__lowerCamelCase							,			delete=__lowerCamelCase			)
																					__snake_case	:    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"							,			__lowerCamelCase							,			temp_file.name							,			)

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

														os.replace(temp_file.name							,			__lowerCamelCase			)

														__snake_case	:    Dict											=     {'url': url, 'etag': etag}
														__snake_case	:    str											=     cache_path + '.json'
														with open(__lowerCamelCase							,			"w"			) as meta_file:
																					json.dump(__lowerCamelCase							,			__lowerCamelCase			)

							return cache_path







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=None			):
							__snake_case	:    str											=     url.encode("utf-8"			)
							__snake_case	:    Union[str, Any]											=     shaaaa(__lowerCamelCase			)
							__snake_case	:    Optional[int]											=     url_hash.hexdigest()

							if etag:
														__snake_case	:    Tuple											=     etag.encode("utf-8"			)
														__snake_case	:    List[Any]											=     shaaaa(__lowerCamelCase			)
														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							,			):
							if cache_dir is None:
														__snake_case	:    str											=     TRANSFORMERS_CACHE
							if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														__snake_case	:    List[str]											=     str(__lowerCamelCase			)
							if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														__snake_case	:    List[Any]											=     str(__lowerCamelCase			)

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

							if extract_compressed_file:
														if not is_zipfile(__lowerCamelCase			) and not tarfile.is_tarfile(__lowerCamelCase			):
																					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/"
														__snake_case	:    Optional[int]											=     os.path.split(__lowerCamelCase			)
														__snake_case	:    Union[str, Any]											=     output_file.replace("."							,			"-"			) + '-extracted'
														__snake_case	:    Dict											=     os.path.join(__lowerCamelCase							,			__lowerCamelCase			)

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

														# Prevent parallel extractions
														__snake_case	:    List[Any]											=     output_path + '.lock'
														with FileLock(__lowerCamelCase			):
																					shutil.rmtree(__lowerCamelCase							,			ignore_errors=__lowerCamelCase			)
																					os.makedirs(__lowerCamelCase			)
																					if is_zipfile(__lowerCamelCase			):
																												with ZipFile(__lowerCamelCase							,			"r"			) as zip_file:
																																			zip_file.extractall(__lowerCamelCase			)
																																			zip_file.close()
																					elif tarfile.is_tarfile(__lowerCamelCase			):
																												__snake_case	:    int											=     tarfile.open(__lowerCamelCase			)
																												tar_file.extractall(__lowerCamelCase			)
																												tar_file.close()
																					else:
																												raise EnvironmentError("Archive format of {} could not be identified".format(__lowerCamelCase			)			)

														return output_path_extracted

							return output_path







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







def        lowerCAmelCase_  (      __lowerCamelCase			):
							__snake_case	:    List[str]											=     requests.get(__lowerCamelCase			)
							__snake_case	:    Any											=     np.array(Image.open(BytesIO(response.content			)			)			)
							return img







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







def        lowerCAmelCase_  (      ):
							print(F'{os.path.abspath(os.path.join(__lowerCamelCase							,			os.pardir			)			)}/demo.ipynb'			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase="RGB"			):
							assert isinstance(__lowerCamelCase							,			__lowerCamelCase			)
							if os.path.isfile(__lowerCamelCase			):
														__snake_case	:    Any											=     cva.imread(__lowerCamelCase			)
							else:
														__snake_case	:    List[str]											=     get_image_from_url(__lowerCamelCase			)
														assert img is not None, F'could not connect to: {im}'
							__snake_case	:    Any											=     cva.cvtColor(__lowerCamelCase							,			cva.COLOR_BGR2RGB			)
							if input_format == "RGB":
														__snake_case	:    Union[str, Any]											=     img[:, :, ::-1]
							return img







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase=1			):
							return (images[i : i + batch] for i in range(0							,			len(__lowerCamelCase			)							,			__lowerCamelCase			))










import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 transformers import CvtForImageClassification, CvtModel
			from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor

class        a	(_lowerCAmelCase   ):




							"""simple docstring"""


							def 					__snake_case      (							self :						str       )			->					Dict:
														__snake_case	:    Any											=     self.config_class(**self.inputs_dict       )
														self.parent.assertTrue(hasattr(lowerCamelCase					,			"embed_dim"       )       )
														self.parent.assertTrue(hasattr(lowerCamelCase					,			"num_heads"       )       )

class        a	:




							"""simple docstring"""


							def __init__(							self :						str					,			lowerCamelCase :						Union[str, Any]					,			lowerCamelCase :						Any=13					,			lowerCamelCase :						Any=64					,			lowerCamelCase :						int=3					,			lowerCamelCase :						Tuple=[16, 48, 96]					,			lowerCamelCase :						Optional[int]=[1, 3, 6]					,			lowerCamelCase :						List[str]=[1, 2, 10]					,			lowerCamelCase :						Any=[7, 3, 3]					,			lowerCamelCase :						Any=[4, 2, 2]					,			lowerCamelCase :						Optional[Any]=[2, 1, 1]					,			lowerCamelCase :						str=[2, 2, 2]					,			lowerCamelCase :						Dict=[False, False, True]					,			lowerCamelCase :						Dict=[0.0, 0.0, 0.0]					,			lowerCamelCase :						Optional[Any]=0.02					,			lowerCamelCase :						Tuple=1E-12					,			lowerCamelCase :						Union[str, Any]=True					,			lowerCamelCase :						Union[str, Any]=True					,			lowerCamelCase :						List[str]=2					,			)			->					Optional[int]:
														__snake_case	:    Tuple											=     parent
														__snake_case	:    List[str]											=     batch_size
														__snake_case	:    Optional[int]											=     image_size
														__snake_case	:    Optional[int]											=     patch_sizes
														__snake_case	:    Union[str, Any]											=     patch_stride
														__snake_case	:    int											=     patch_padding
														__snake_case	:    Optional[Any]											=     is_training
														__snake_case	:    Optional[Any]											=     use_labels
														__snake_case	:    Tuple											=     num_labels
														__snake_case	:    Union[str, Any]											=     num_channels
														__snake_case	:    Tuple											=     embed_dim
														__snake_case	:    List[str]											=     num_heads
														__snake_case	:    Dict											=     stride_kv
														__snake_case	:    Optional[int]											=     depth
														__snake_case	:    List[Any]											=     cls_token
														__snake_case	:    List[Any]											=     attention_drop_rate
														__snake_case	:    Any											=     initializer_range
														__snake_case	:    str											=     layer_norm_eps

							def 					__snake_case      (							self :						List[str]       )			->					str:
														__snake_case	:    str											=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

														__snake_case	:    Tuple											=     None
														if self.use_labels:
																					__snake_case	:    Tuple											=     ids_tensor([self.batch_size]					,			self.num_labels       )

														__snake_case	:    Optional[Any]											=     self.get_config()
														return config, pixel_values, labels

							def 					__snake_case      (							self :						Tuple       )			->					Optional[Any]:
														return CvtConfig(
														    image_size=self.image_size					,			num_labels=self.num_labels					,			num_channels=self.num_channels					,			embed_dim=self.embed_dim					,			num_heads=self.num_heads					,			patch_sizes=self.patch_sizes					,			patch_padding=self.patch_padding					,			patch_stride=self.patch_stride					,			stride_kv=self.stride_kv					,			depth=self.depth					,			cls_token=self.cls_token					,			attention_drop_rate=self.attention_drop_rate					,			initializer_range=self.initializer_range					,			)

							def 					__snake_case      (							self :						Optional[int]					,			lowerCamelCase :						Union[str, Any]					,			lowerCamelCase :						str					,			lowerCamelCase :						str       )			->					Tuple:
														__snake_case	:    int											=     CvtModel(config=lowerCamelCase       )
														model.to(lowerCamelCase       )
														model.eval()
														__snake_case	:    List[str]											=     model(lowerCamelCase       )
														__snake_case	:    List[Any]											=     (self.image_size, self.image_size)
														__snake_case				,    __snake_case	:    List[str]											=     image_size[0], image_size[1]
														for i in range(len(self.depth       )       ):
																					__snake_case	:    int											=     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
																					__snake_case	:    Union[str, Any]											=     floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
														self.parent.assertEqual(result.last_hidden_state.shape					,			(self.batch_size, self.embed_dim[-1], height, width)       )

							def 					__snake_case      (							self :						List[str]					,			lowerCamelCase :						Optional[int]					,			lowerCamelCase :						Dict					,			lowerCamelCase :						int       )			->					Optional[Any]:
														__snake_case	:    str											=     self.num_labels
														__snake_case	:    Any											=     CvtForImageClassification(lowerCamelCase       )
														model.to(lowerCamelCase       )
														model.eval()
														__snake_case	:    List[Any]											=     model(lowerCamelCase					,			labels=lowerCamelCase       )
														self.parent.assertEqual(result.logits.shape					,			(self.batch_size, self.num_labels)       )






							def 					__snake_case      (							self :						Union[str, Any]       )			->					List[Any]:
														__snake_case	:    List[Any]											=     self.prepare_config_and_inputs()
														__snake_case				,    __snake_case				,    __snake_case	:    str											=     config_and_inputs
														__snake_case	:    List[str]											=     {"pixel_values": pixel_values}
														return config, inputs_dict

@require_torch
class        a	(_lowerCAmelCase  ,       _lowerCAmelCase  ,       unittest.TestCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							List[str]  						=						(CvtModel, CvtForImageClassification) if is_torch_available() else ()
							__UpperCAmelCase					:							List[str]  						=						(
							    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
							    if is_torch_available()
							    else {}
							)

							__UpperCAmelCase					:							List[str]  						=						False
							__UpperCAmelCase					:							Tuple  						=						False
							__UpperCAmelCase					:							List[Any]  						=						False
							__UpperCAmelCase					:							Optional[int]  						=						False
							__UpperCAmelCase					:							List[Any]  						=						False

							def 					__snake_case      (							self :						str       )			->					List[str]:
														__snake_case	:    Tuple											=     CvtModelTester(self       )
														__snake_case	:    Tuple											=     ConfigTester(self					,			config_class=lowerCamelCase					,			has_text_modality=lowerCamelCase					,			hidden_size=37       )

							def 					__snake_case      (							self :						Union[str, Any]       )			->					Union[str, Any]:
														self.create_and_test_config_common_properties()
														self.config_tester.create_and_test_config_to_json_string()
														self.config_tester.create_and_test_config_to_json_file()
														self.config_tester.create_and_test_config_from_and_save_pretrained()
														self.config_tester.create_and_test_config_with_num_labels()
														self.config_tester.check_config_can_be_init_without_params()
														self.config_tester.check_config_arguments_init()

							def 					__snake_case      (							self :						Tuple       )			->					Union[str, Any]:
														return

							@unittest.skip(reason="Cvt does not output attentions"       )
							def 					__snake_case      (							self :						Optional[int]       )			->					List[str]:
														pass

							@unittest.skip(reason="Cvt does not use inputs_embeds"       )
							def 					__snake_case      (							self :						List[str]       )			->					Any:
														pass

							@unittest.skip(reason="Cvt does not support input and output embeddings"       )
							def 					__snake_case      (							self :						int       )			->					List[Any]:
														pass

							def 					__snake_case      (							self :						int       )			->					int:
														__snake_case				,    __snake_case	:    Optional[int]											=     self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					__snake_case	:    str											=     model_class(lowerCamelCase       )
																					__snake_case	:    List[Any]											=     inspect.signature(model.forward       )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					__snake_case	:    List[str]											=     [*signature.parameters.keys()]

																					__snake_case	:    Dict											=     ["pixel_values"]
																					self.assertListEqual(arg_names[:1]					,			lowerCamelCase       )

							def 					__snake_case      (							self :						str       )			->					Dict:
														__snake_case	:    List[str]											=     self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowerCamelCase       )

							def 					__snake_case      (							self :						int       )			->					Optional[Any]:
														def check_hidden_states_output(lowerCamelCase :						Dict					,			lowerCamelCase :						Dict					,			lowerCamelCase :						Optional[Any]       ):
																					__snake_case	:    Any											=     model_class(lowerCamelCase       )
																					model.to(lowerCamelCase       )
																					model.eval()

																					with torch.no_grad():
																												__snake_case	:    List[str]											=     model(**self._prepare_for_class(lowerCamelCase					,			lowerCamelCase       )       )

																					__snake_case	:    List[Any]											=     outputs.hidden_states

																					__snake_case	:    Optional[int]											=     len(self.model_tester.depth       )
																					self.assertEqual(len(lowerCamelCase       )					,			lowerCamelCase       )

																					# verify the first hidden states (first block)
																					self.assertListEqual(
																					    list(hidden_states[0].shape[-3:]       )					,			[
																					        self.model_tester.embed_dim[0],
																					        self.model_tester.image_size // 4,
																					        self.model_tester.image_size // 4,
																					    ]					,			)

														__snake_case				,    __snake_case	:    List[str]											=     self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					__snake_case	:    Union[str, Any]											=     True
																					check_hidden_states_output(lowerCamelCase					,			lowerCamelCase					,			lowerCamelCase       )

																					# check that output_hidden_states also work using config
																					del inputs_dict["output_hidden_states"]
																					__snake_case	:    List[str]											=     True

																					check_hidden_states_output(lowerCamelCase					,			lowerCamelCase					,			lowerCamelCase       )

							def 					__snake_case      (							self :						Optional[int]       )			->					Optional[Any]:
														__snake_case	:    Any											=     self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*lowerCamelCase       )

							@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."       )
							def 					__snake_case      (							self :						List[str]       )			->					Optional[int]:
														pass






							@slow
							def 					__snake_case      (							self :						Tuple       )			->					List[str]:
														for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					__snake_case	:    int											=     CvtModel.from_pretrained(lowerCamelCase       )
																					self.assertIsNotNone(lowerCamelCase       )







def        lowerCAmelCase_  (      ):
							__snake_case	:    Any											=     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
							return image

@require_torch
@require_vision
class        a	(unittest.TestCase   ):




							"""simple docstring"""


							@cached_property
							def 					__snake_case      (							self :						Optional[Any]       )			->					Union[str, Any]:
														return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )






							@slow
							def 					__snake_case      (							self :						int       )			->					Tuple:
														__snake_case	:    Optional[Any]											=     CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(lowerCamelCase       )

														__snake_case	:    Optional[int]											=     self.default_image_processor
														__snake_case	:    Union[str, Any]											=     prepare_img()
														__snake_case	:    Dict											=     image_processor(images=lowerCamelCase					,			return_tensors="pt"       ).to(lowerCamelCase       )

														# forward pass
														with torch.no_grad():
																					__snake_case	:    Any											=     model(**lowerCamelCase       )

														# verify the logits
														__snake_case	:    Any											=     torch.Size((1, 1000)       )
														self.assertEqual(outputs.logits.shape					,			lowerCamelCase       )

														__snake_case	:    Optional[Any]											=     torch.tensor([0.92_85, 0.90_15, -0.31_50]       ).to(lowerCamelCase       )

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

