
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

					UpperCamelCase_  =	True
except ImportError:
					UpperCamelCase_  =	False


try:
					from torch.hub import _get_torch_home

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

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

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





def 							_lowerCamelCase			(					lowerCamelCase_:  List[str]=OBJECTS				,	lowerCamelCase_:  Any=ATTRIBUTES		):



				'''simple docstring'''







				A     :  Tuple   =				[]
				with open(lowerCamelCase_		) as f:
								for object in f.readlines():
												vg_classes.append(object.split(''','''		)[0].lower().strip()		)

				A     :  str   =				[]
				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_:  Union[str, Any]		):



				'''simple docstring'''







				A     :  Dict   =				OrderedDict()
				with open(lowerCamelCase_				,	'''rb'''		) as f:
								A     :  int   =				pkl.load(lowerCamelCase_		)['''model''']
				for k in copy.deepcopy(list(ckp.keys()		)		):
								A     :  int   =				ckp.pop(lowerCamelCase_		)
								if isinstance(lowerCamelCase_				,	np.ndarray		):
												A     :  Any   =				torch.tensor(lowerCamelCase_		)
								else:
												assert isinstance(lowerCamelCase_				,	torch.tensor		), type(lowerCamelCase_		)
								A     :  Optional[int]   =				v
				return r

class     _SCREAMING_SNAKE_CASE							:
				lowerCamelCase_       =     {}





				def __init__(		self :		Optional[int]					,      snake_case_ :		dict					,      snake_case_ :		str = "root"					,      snake_case_ :		Tuple=0							):


								"""simple docstring"""

								A     :  List[str]   =				name
								A     :  Dict   =				level
								A     :  Dict   =				{}
								for k, v in dictionary.items():
												if v is None:
																raise ValueError()
												A     :  int   =				copy.deepcopy(snake_case_							)
												A     :  int   =				copy.deepcopy(snake_case_							)
												if isinstance(snake_case_					,      snake_case_							):
																A     :  List[str]   =				Config(snake_case_					,      name=snake_case_					,      level=level + 1							)
												A     :  Optional[int]   =				v
												setattr(self					,      snake_case_					,      snake_case_							)

								A     :  List[Any]   =				d





				def __repr__(		self :		Optional[int]							):


								"""simple docstring"""

								return str(list((self._pointer.keys())							)							)





				def __setattr__(		self :		str					,      snake_case_ :		Tuple					,      snake_case_ :		int							):


								"""simple docstring"""

								A     :  Tuple   =				val
								A     :  int   =				val
								A     :  List[str]   =				key.split('''.'''							)
								A     :  Dict   =				len(snake_case_							) - 1
								A     :  Dict   =				self._pointer
								if len(snake_case_							) > 1:
												for i, l in enumerate(snake_case_							):
																if hasattr(self					,      snake_case_							) and isinstance(getattr(self					,      snake_case_							)					,      snake_case_							):
																				setattr(getattr(self					,      snake_case_							)					,      '''.'''.join(levels[i:]							)					,      snake_case_							)
																if l == last_level:
																				A     :  int   =				val
																else:
																				A     :  int   =				pointer[l]





				def        _UpperCAmelCase						(		self :		Any							):


								"""simple docstring"""

								return self._pointer





				def        _UpperCAmelCase						(		self :		Optional[int]					,      snake_case_ :		Dict					,      snake_case_ :		Union[str, Any]							):


								"""simple docstring"""

								with open(f"""{file_name}"""					,      '''w'''							) as stream:
												dump(snake_case_					,      snake_case_							)





				def        _UpperCAmelCase						(		self :		List[Any]					,      snake_case_ :		int					,      snake_case_ :		Union[str, Any]							):


								"""simple docstring"""

								with open(f"""{file_name}"""					,      '''w'''							) as stream:
												json.dump(snake_case_					,      snake_case_							)





				@staticmethod
				def        _UpperCAmelCase						(		snake_case_ :		Union[str, Any]							):


								"""simple docstring"""

								with open(snake_case_							) as stream:
												A     :  Dict   =				load(snake_case_					,      Loader=snake_case_							)
								return data





				def __str__(		self :		Dict							):


								"""simple docstring"""

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





				@classmethod
				def        _UpperCAmelCase						(		cls :		List[Any]					,      snake_case_ :		str					,      **snake_case_ :		Union[str, Any]							):


								"""simple docstring"""

								A ,       A     :  Tuple   =				cls.get_config_dict(snake_case_					,      **snake_case_							)
								return cls(snake_case_							)






				@classmethod
				def        _UpperCAmelCase						(		cls :		Any					,      snake_case_ :		str					,      **snake_case_ :		str							):


								"""simple docstring"""

								A     :  Tuple   =				kwargs.pop('''cache_dir'''					,      snake_case_							)
								A     :  Union[str, Any]   =				kwargs.pop('''force_download'''					,      snake_case_							)
								A     :  List[Any]   =				kwargs.pop('''resume_download'''					,      snake_case_							)
								A     :  int   =				kwargs.pop('''proxies'''					,      snake_case_							)
								A     :  Union[str, Any]   =				kwargs.pop('''local_files_only'''					,      snake_case_							)

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

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

												A     :  List[Any]   =				Config.load_yaml(snake_case_							)

								except EnvironmentError:
												A     :  Dict   =				'''Can\'t load config for'''
												raise EnvironmentError(snake_case_							)

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

								return Config.load_yaml(snake_case_							), kwargs





def 							_lowerCamelCase			(					lowerCamelCase_:  Any		):



				'''simple docstring'''







				A     :  str   =				torch.load('''dump.pt'''				,	map_location=in_tensor.device		)
				A     :  List[str]   =				in_tensor.numpy()
				A     :  List[str]   =				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()		)*100:.4f} %"""
				    " element-wise mismatch"
				)
				raise Exception('''tensors are all good'''		)

				# Hugging face functions below





def 							_lowerCamelCase			(					lowerCamelCase_:  Dict		):



				'''simple docstring'''







				A     :  Any   =				urlparse(lowerCamelCase_		)
				return parsed.scheme in ("http", "https")





def 							_lowerCamelCase			(					lowerCamelCase_:  str				,	lowerCamelCase_:  str				,	lowerCamelCase_:  Optional[Any]=True		):



				'''simple docstring'''







				A     :  Any   =				CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
				A     :  List[str]   =				'''/''' not in model_id
				if legacy_format:
								return f"""{endpoint}/{model_id}-{filename}"""
				else:
								return f"""{endpoint}/{model_id}/{filename}"""





def 							_lowerCamelCase			(					lowerCamelCase_:  Any				,	lowerCamelCase_:  Any				,	lowerCamelCase_:  int=None				,	lowerCamelCase_:  Optional[Any]=0				,	lowerCamelCase_:  Optional[int]=None				,	):



				'''simple docstring'''







				A     :  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
				A     :  int   =				{'''user-agent''': ua}
				if resume_size > 0:
								A     :  List[Any]   =				'''bytes=%d-''' % (resume_size,)
				A     :  List[Any]   =				requests.get(lowerCamelCase_				,	stream=lowerCamelCase_				,	proxies=lowerCamelCase_				,	headers=lowerCamelCase_		)
				if response.status_code == 416:  # Range not satisfiable
								return
				A     :  Union[str, Any]   =				response.headers.get('''Content-Length'''		)
				A     :  Tuple   =				resume_size + int(lowerCamelCase_		) if content_length is not None else None
				A     :  Any   =				tqdm(
				    unit='''B'''				,	unit_scale=lowerCamelCase_				,	total=lowerCamelCase_				,	initial=lowerCamelCase_				,	desc='''Downloading'''				,	)
				for chunk in response.iter_content(chunk_size=1024		):
								if chunk:  # filter out keep-alive new chunks
												progress.update(len(lowerCamelCase_		)		)
												temp_file.write(lowerCamelCase_		)
				progress.close()





def 							_lowerCamelCase			(					lowerCamelCase_:  int				,	lowerCamelCase_:  List[str]=None				,	lowerCamelCase_:  Dict=False				,	lowerCamelCase_:  Optional[Any]=None				,	lowerCamelCase_:  str=10				,	lowerCamelCase_:  List[Any]=False				,	lowerCamelCase_:  Dict=None				,	lowerCamelCase_:  Any=False				,	):



				'''simple docstring'''







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

				os.makedirs(lowerCamelCase_				,	exist_ok=lowerCamelCase_		)

				A     :  Optional[Any]   =				None
				if not local_files_only:
								try:
												A     :  Union[str, Any]   =				requests.head(lowerCamelCase_				,	allow_redirects=lowerCamelCase_				,	proxies=lowerCamelCase_				,	timeout=lowerCamelCase_		)
												if response.status_code == 200:
																A     :  Optional[int]   =				response.headers.get('''ETag'''		)
								except (EnvironmentError, requests.exceptions.Timeout):
												# etag is already None
												pass

				A     :  Union[str, Any]   =				url_to_filename(lowerCamelCase_				,	lowerCamelCase_		)

				# get cache path to put the file
				A     :  Optional[int]   =				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:
												A     :  Optional[int]   =				[
												    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.
				A     :  int   =				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:
												A     :  Any   =				cache_path + '''.incomplete'''

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

												A     :  Optional[Any]   =				_resumable_file_manager
												if os.path.exists(lowerCamelCase_		):
																A     :  List[str]   =				os.stat(lowerCamelCase_		).st_size
												else:
																A     :  Dict   =				0
								else:
												A     :  Optional[int]   =				partial(tempfile.NamedTemporaryFile				,	dir=lowerCamelCase_				,	delete=lowerCamelCase_		)
												A     :  Dict   =				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_		)

								A     :  int   =				{'''url''': url, '''etag''': etag}
								A     :  int   =				cache_path + '''.json'''
								with open(lowerCamelCase_				,	'''w'''		) as meta_file:
												json.dump(lowerCamelCase_				,	lowerCamelCase_		)

				return cache_path





def 							_lowerCamelCase			(					lowerCamelCase_:  List[Any]				,	lowerCamelCase_:  Dict=None		):



				'''simple docstring'''







				A     :  Optional[int]   =				url.encode('''utf-8'''		)
				A     :  Optional[int]   =				shaaaa(lowerCamelCase_		)
				A     :  Optional[Any]   =				url_hash.hexdigest()

				if etag:
								A     :  List[Any]   =				etag.encode('''utf-8'''		)
								A     :  List[Any]   =				shaaaa(lowerCamelCase_		)
								filename += "." + etag_hash.hexdigest()

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

				return filename





def 							_lowerCamelCase			(					lowerCamelCase_:  Any				,	lowerCamelCase_:  int=None				,	lowerCamelCase_:  str=False				,	lowerCamelCase_:  str=None				,	lowerCamelCase_:  Union[str, Any]=False				,	lowerCamelCase_:  Optional[Any]=None				,	lowerCamelCase_:  List[Any]=False				,	lowerCamelCase_:  Dict=False				,	lowerCamelCase_:  List[str]=False				,	):



				'''simple docstring'''







				if cache_dir is None:
								A     :  Dict   =				TRANSFORMERS_CACHE
				if isinstance(lowerCamelCase_				,	lowerCamelCase_		):
								A     :  int   =				str(lowerCamelCase_		)
				if isinstance(lowerCamelCase_				,	lowerCamelCase_		):
								A     :  str   =				str(lowerCamelCase_		)

				if is_remote_url(lowerCamelCase_		):
								# URL, so get it from the cache (downloading if necessary)
								A     :  List[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.
								A     :  Any   =				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/"
								A ,       A     :  int   =				os.path.split(lowerCamelCase_		)
								A     :  Tuple   =				output_file.replace('''.'''				,	'''-'''		) + '''-extracted'''
								A     :  str   =				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
								A     :  List[str]   =				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_		):
																A     :  Union[str, Any]   =				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_:  List[str]				,	lowerCamelCase_:  Optional[int]=","		):



				'''simple docstring'''







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





def 							_lowerCamelCase			(					lowerCamelCase_:  str		):



				'''simple docstring'''







				A     :  List[str]   =				requests.get(lowerCamelCase_		)
				A     :  Optional[Any]   =				np.array(Image.open(BytesIO(response.content		)		)		)
				return img





def 							_lowerCamelCase			(					lowerCamelCase_:  Union[str, Any]		):



				'''simple docstring'''







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





def 							_lowerCamelCase			(					):



				'''simple docstring'''







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





def 							_lowerCamelCase			(					lowerCamelCase_:  int				,	lowerCamelCase_:  List[Any]="RGB"		):



				'''simple docstring'''







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






def 							_lowerCamelCase			(					lowerCamelCase_:  int				,	lowerCamelCase_:  List[Any]=1		):



				'''simple docstring'''







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

import unittest

from transformers import YosoConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
					import torch

					from transformers import (
					    YosoForMaskedLM,
					    YosoForMultipleChoice,
					    YosoForQuestionAnswering,
					    YosoForSequenceClassification,
					    YosoForTokenClassification,
					    YosoModel,
					)
					from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST

class     _SCREAMING_SNAKE_CASE							:





				def __init__(		self :		Dict					,      snake_case_ :		Tuple					,      snake_case_ :		Union[str, Any]=13					,      snake_case_ :		int=7					,      snake_case_ :		int=True					,      snake_case_ :		int=True					,      snake_case_ :		Optional[Any]=True					,      snake_case_ :		Optional[int]=True					,      snake_case_ :		Tuple=99					,      snake_case_ :		List[str]=32					,      snake_case_ :		Any=5					,      snake_case_ :		Union[str, Any]=4					,      snake_case_ :		List[Any]=37					,      snake_case_ :		str="gelu"					,      snake_case_ :		int=0.1					,      snake_case_ :		Optional[Any]=0.1					,      snake_case_ :		Union[str, Any]=512					,      snake_case_ :		Optional[int]=16					,      snake_case_ :		Any=2					,      snake_case_ :		Union[str, Any]=0.02					,      snake_case_ :		List[str]=3					,      snake_case_ :		List[str]=4					,      snake_case_ :		Optional[int]=None					,      ):


								"""simple docstring"""

								A     :  List[Any]   =				parent
								A     :  Dict   =				batch_size
								A     :  Optional[Any]   =				seq_length
								A     :  str   =				is_training
								A     :  int   =				use_input_mask
								A     :  Any   =				use_token_type_ids
								A     :  Tuple   =				use_labels
								A     :  Optional[int]   =				vocab_size
								A     :  Union[str, Any]   =				hidden_size
								A     :  Optional[int]   =				num_hidden_layers
								A     :  Tuple   =				num_attention_heads
								A     :  Dict   =				intermediate_size
								A     :  Any   =				hidden_act
								A     :  Tuple   =				hidden_dropout_prob
								A     :  Tuple   =				attention_probs_dropout_prob
								A     :  int   =				max_position_embeddings
								A     :  Any   =				type_vocab_size
								A     :  Dict   =				type_sequence_label_size
								A     :  Optional[Any]   =				initializer_range
								A     :  Union[str, Any]   =				num_labels
								A     :  Tuple   =				num_choices
								A     :  Union[str, Any]   =				scope





				def        _UpperCAmelCase						(		self :		Any							):


								"""simple docstring"""

								A     :  str   =				ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size							)

								A     :  Any   =				None
								if self.use_input_mask:
												A     :  List[str]   =				random_attention_mask([self.batch_size, self.seq_length]							)

								A     :  int   =				None
								if self.use_token_type_ids:
												A     :  str   =				ids_tensor([self.batch_size, self.seq_length]					,      self.type_vocab_size							)

								A     :  Dict   =				None
								A     :  Any   =				None
								A     :  Union[str, Any]   =				None
								if self.use_labels:
												A     :  Optional[int]   =				ids_tensor([self.batch_size]					,      self.type_sequence_label_size							)
												A     :  Union[str, Any]   =				ids_tensor([self.batch_size, self.seq_length]					,      self.num_labels							)
												A     :  Optional[Any]   =				ids_tensor([self.batch_size]					,      self.num_choices							)

								A     :  Dict   =				self.get_config()

								return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





				def        _UpperCAmelCase						(		self :		Dict							):


								"""simple docstring"""

								return YosoConfig(
								    vocab_size=self.vocab_size					,      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					,      max_position_embeddings=self.max_position_embeddings					,      type_vocab_size=self.type_vocab_size					,      is_decoder=snake_case_					,      initializer_range=self.initializer_range					,      )





				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

								A     :  List[Any]   =				self.get_config()
								A     :  Tuple   =				300
								return config





				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								(
								    (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       
								)     :  List[Any]   =				self.prepare_config_and_inputs()

								A     :  Tuple   =				True
								A     :  Tuple   =				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]							)
								A     :  Union[str, Any]   =				ids_tensor([self.batch_size, self.seq_length]					,      vocab_size=2							)

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    input_mask,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								    encoder_hidden_states,
								    encoder_attention_mask,
								)





				def        _UpperCAmelCase						(		self :		Dict					,      snake_case_ :		int					,      snake_case_ :		Optional[Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		List[str]					,      snake_case_ :		Tuple					,      snake_case_ :		List[str]							):


								"""simple docstring"""

								A     :  Optional[Any]   =				YosoModel(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  List[str]   =				model(snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_							)
								A     :  int   =				model(snake_case_					,      token_type_ids=snake_case_							)
								A     :  int   =				model(snake_case_							)
								self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)							)





				def        _UpperCAmelCase						(		self :		List[str]					,      snake_case_ :		int					,      snake_case_ :		Tuple					,      snake_case_ :		List[str]					,      snake_case_ :		str					,      snake_case_ :		int					,      snake_case_ :		List[str]					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Optional[int]					,      snake_case_ :		int					,      ):


								"""simple docstring"""

								A     :  List[str]   =				True
								A     :  Tuple   =				YosoModel(snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  str   =				model(
								    snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      encoder_hidden_states=snake_case_					,      encoder_attention_mask=snake_case_					,      )
								A     :  Any   =				model(
								    snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      encoder_hidden_states=snake_case_					,      )
								A     :  List[Any]   =				model(snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_							)
								self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)							)





				def        _UpperCAmelCase						(		self :		Tuple					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		List[str]					,      snake_case_ :		Any					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		int					,      snake_case_ :		Tuple					,      snake_case_ :		str							):


								"""simple docstring"""

								A     :  List[Any]   =				YosoForMaskedLM(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  List[Any]   =				model(snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.vocab_size)							)





				def        _UpperCAmelCase						(		self :		Union[str, Any]					,      snake_case_ :		Tuple					,      snake_case_ :		str					,      snake_case_ :		Dict					,      snake_case_ :		Any					,      snake_case_ :		Optional[int]					,      snake_case_ :		int					,      snake_case_ :		Tuple							):


								"""simple docstring"""

								A     :  Optional[int]   =				YosoForQuestionAnswering(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  int   =				model(
								    snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      start_positions=snake_case_					,      end_positions=snake_case_					,      )
								self.parent.assertEqual(result.start_logits.shape					,      (self.batch_size, self.seq_length)							)
								self.parent.assertEqual(result.end_logits.shape					,      (self.batch_size, self.seq_length)							)





				def        _UpperCAmelCase						(		self :		Tuple					,      snake_case_ :		Any					,      snake_case_ :		List[Any]					,      snake_case_ :		List[Any]					,      snake_case_ :		Optional[Any]					,      snake_case_ :		List[Any]					,      snake_case_ :		Optional[Any]					,      snake_case_ :		str							):


								"""simple docstring"""

								A     :  List[str]   =				self.num_labels
								A     :  int   =				YosoForSequenceClassification(snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Optional[int]   =				model(snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)							)





				def        _UpperCAmelCase						(		self :		Any					,      snake_case_ :		Any					,      snake_case_ :		Any					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Tuple					,      snake_case_ :		Union[str, Any]					,      snake_case_ :		Tuple					,      snake_case_ :		int							):


								"""simple docstring"""

								A     :  List[str]   =				self.num_labels
								A     :  Optional[Any]   =				YosoForTokenClassification(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  Dict   =				model(snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_							)
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.num_labels)							)





				def        _UpperCAmelCase						(		self :		int					,      snake_case_ :		List[str]					,      snake_case_ :		List[Any]					,      snake_case_ :		str					,      snake_case_ :		Tuple					,      snake_case_ :		Any					,      snake_case_ :		Optional[int]					,      snake_case_ :		str							):


								"""simple docstring"""

								A     :  Optional[Any]   =				self.num_choices
								A     :  Optional[int]   =				YosoForMultipleChoice(config=snake_case_							)
								model.to(snake_case_							)
								model.eval()
								A     :  str   =				input_ids.unsqueeze(1							).expand(-1					,      self.num_choices					,      -1							).contiguous()
								A     :  int   =				token_type_ids.unsqueeze(1							).expand(-1					,      self.num_choices					,      -1							).contiguous()
								A     :  Tuple   =				input_mask.unsqueeze(1							).expand(-1					,      self.num_choices					,      -1							).contiguous()
								A     :  str   =				model(
								    snake_case_					,      attention_mask=snake_case_					,      token_type_ids=snake_case_					,      labels=snake_case_					,      )
								self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_choices)							)






				def        _UpperCAmelCase						(		self :		Tuple							):


								"""simple docstring"""

								A     :  Tuple   =				self.prepare_config_and_inputs()
								(
								    (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       (
								    A
								) ,       
								)     :  Dict   =				config_and_inputs
								A     :  Any   =				{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict



@require_torch
class     _SCREAMING_SNAKE_CASE							(		snake_case,    snake_case,    unittest.TestCase							):
				lowerCamelCase_       =     (
				    (
				        YosoModel,
				        YosoForMaskedLM,
				        YosoForMultipleChoice,
				        YosoForQuestionAnswering,
				        YosoForSequenceClassification,
				        YosoForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				lowerCamelCase_       =     False
				lowerCamelCase_       =     False
				lowerCamelCase_       =     False

				lowerCamelCase_       =     ()
				lowerCamelCase_       =     (
				    {
				        'feature-extraction': YosoModel,
				        'fill-mask': YosoForMaskedLM,
				        'question-answering': YosoForQuestionAnswering,
				        'text-classification': YosoForSequenceClassification,
				        'token-classification': YosoForTokenClassification,
				        'zero-shot': YosoForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)





				def        _UpperCAmelCase						(		self :		Optional[int]							):


								"""simple docstring"""

								A     :  Optional[Any]   =				YosoModelTester(self							)
								A     :  Dict   =				ConfigTester(self					,      config_class=snake_case_					,      hidden_size=37							)





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								self.config_tester.run_common_tests()





				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								A     :  Union[str, Any]   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case_							)





				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								A     :  Optional[Any]   =				self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
												A     :  Dict   =				type
												self.model_tester.create_and_check_model(*snake_case_							)





				def        _UpperCAmelCase						(		self :		str							):


								"""simple docstring"""

								A     :  Tuple   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Union[str, Any]							):


								"""simple docstring"""

								A     :  Any   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Optional[Any]							):


								"""simple docstring"""

								A     :  List[str]   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*snake_case_							)





				def        _UpperCAmelCase						(		self :		Dict							):


								"""simple docstring"""

								A     :  Dict   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*snake_case_							)





				def        _UpperCAmelCase						(		self :		List[str]							):


								"""simple docstring"""

								A     :  Dict   =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_token_classification(*snake_case_							)





				@slow
				def        _UpperCAmelCase						(		self :		Tuple							):


								"""simple docstring"""

								for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A     :  Dict   =				YosoModel.from_pretrained(snake_case_							)
												self.assertIsNotNone(snake_case_							)






				def        _UpperCAmelCase						(		self :		Union[str, Any]							):


								"""simple docstring"""

								return



@require_torch
class     _SCREAMING_SNAKE_CASE							(		unittest.TestCase							):





				@slow
				def        _UpperCAmelCase						(		self :		List[Any]							):


								"""simple docstring"""

								A     :  Optional[int]   =				YosoModel.from_pretrained('''uw-madison/yoso-4096'''							)
								A     :  Any   =				torch.tensor([[0, 1, 2, 3, 4, 5]]							)

								with torch.no_grad():
												A     :  str   =				model(snake_case_							)[0]

								A     :  Union[str, Any]   =				torch.Size((1, 6, 768)							)
								self.assertEqual(output.shape					,      snake_case_							)

								A     :  int   =				torch.tensor(
								    [[[-0.06_11, 0.12_42, 0.08_40], [0.02_80, -0.00_48, 0.11_25], [0.01_06, 0.02_26, 0.07_51]]]							)

								self.assertTrue(torch.allclose(output[:, :3, :3]					,      snake_case_					,      atol=1E-4							)							)





				@slow
				def        _UpperCAmelCase						(		self :		int							):


								"""simple docstring"""

								A     :  Tuple   =				YosoForMaskedLM.from_pretrained('''uw-madison/yoso-4096'''							)
								A     :  Dict   =				torch.tensor([[0, 1, 2, 3, 4, 5]]							)

								with torch.no_grad():
												A     :  str   =				model(snake_case_							)[0]

								A     :  Optional[Any]   =				5_0265

								A     :  Union[str, Any]   =				torch.Size((1, 6, vocab_size)							)
								self.assertEqual(output.shape					,      snake_case_							)

								A     :  str   =				torch.tensor(
								    [[[-2.13_13, -3.72_85, -2.24_07], [-2.70_47, -3.33_14, -2.64_08], [0.06_29, -2.51_66, -0.33_56]]]							)

								self.assertTrue(torch.allclose(output[:, :3, :3]					,      snake_case_					,      atol=1E-4							)							)






				@slow
				def        _UpperCAmelCase						(		self :		Dict							):


								"""simple docstring"""

								A     :  str   =				YosoForMaskedLM.from_pretrained('''uw-madison/yoso-4096'''							)
								A     :  Tuple   =				torch.arange(4096							).unsqueeze(0							)

								with torch.no_grad():
												A     :  Optional[Any]   =				model(snake_case_							)[0]

								A     :  Optional[int]   =				5_0265

								A     :  Tuple   =				torch.Size((1, 4096, vocab_size)							)
								self.assertEqual(output.shape					,      snake_case_							)

								A     :  Optional[Any]   =				torch.tensor(
								    [[[-2.39_14, -4.37_42, -5.09_56], [-4.09_88, -4.23_84, -7.04_06], [-3.14_27, -3.71_92, -6.68_00]]]							)

								self.assertTrue(torch.allclose(output[:, :3, :3]					,      snake_case_					,      atol=1E-4							)							)