





"""simple docstring"""




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        a_				(							_lowercase=OBJECTS       ,						_lowercase=ATTRIBUTES   ):
						_UpperCamelCase			:					Optional[int]     =    []
						with open(_lowercase   ) as f:
												for object in f.readlines():
																		vg_classes.append(object.split(''','''   )[0].lower().strip()   )

						_UpperCamelCase			:					str     =    []
						with open(_lowercase   ) as f:
												for object in f.readlines():
																		vg_attrs.append(object.split(''','''   )[0].lower().strip()   )
						return vg_classes, vg_attrs





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




class  _a						:
				UpperCamelCase								=    {}






				def __init__( self		:    List[Any], lowerCAmelCase__		:    dict, lowerCAmelCase__		:    str = "root", lowerCAmelCase__		:    Optional[int]=0							)	->      Tuple:




										'''simple docstring'''



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

										_UpperCamelCase			:					Optional[Any]     =    d






				def __repr__( self		:    List[str]							)	->      List[Any]:




										'''simple docstring'''



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






				def __setattr__( self		:    int, lowerCAmelCase__		:    List[str], lowerCAmelCase__		:    List[Any]							)	->      int:




										'''simple docstring'''



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






				def 				snake_case	( self		:    int							)	->      Union[str, Any]:




										'''simple docstring'''



										return self._pointer






				def 				snake_case	( self		:    int, lowerCAmelCase__		:    List[str], lowerCAmelCase__		:    Union[str, Any]							)	->      Tuple:




										'''simple docstring'''



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






				def 				snake_case	( self		:    Tuple, lowerCAmelCase__		:    Optional[Any], lowerCAmelCase__		:    Tuple							)	->      Optional[Any]:




										'''simple docstring'''



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






				@staticmethod
				def 				snake_case	( lowerCAmelCase__		:    List[Any]							)	->      List[str]:




										'''simple docstring'''



										with open(lowerCAmelCase__							) as stream:
																_UpperCamelCase			:					List[str]     =    load(lowerCAmelCase__, Loader=lowerCAmelCase__							)
										return data






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




										'''simple docstring'''



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






				@classmethod
				def 				snake_case	( cls		:    Optional[int], lowerCAmelCase__		:    str, **lowerCAmelCase__		:    Tuple							)	->      List[str]:




										'''simple docstring'''



										_UpperCamelCase   ,							_UpperCamelCase			:					int     =    cls.get_config_dict(lowerCAmelCase__, **lowerCAmelCase__							)
										return cls(lowerCAmelCase__							)






				@classmethod
				def 				snake_case	( cls		:    str, lowerCAmelCase__		:    str, **lowerCAmelCase__		:    Tuple							)	->      Tuple:




										'''simple docstring'''



										_UpperCamelCase			:					List[Any]     =    kwargs.pop('''cache_dir''', lowerCAmelCase__							)
										_UpperCamelCase			:					Optional[int]     =    kwargs.pop('''force_download''', lowerCAmelCase__							)
										_UpperCamelCase			:					List[str]     =    kwargs.pop('''resume_download''', lowerCAmelCase__							)
										_UpperCamelCase			:					str     =    kwargs.pop('''proxies''', lowerCAmelCase__							)
										_UpperCamelCase			:					Any     =    kwargs.pop('''local_files_only''', lowerCAmelCase__							)

										if os.path.isdir(lowerCAmelCase__							):
																_UpperCamelCase			:					Any     =    os.path.join(lowerCAmelCase__, lowerCAmelCase__							)
										elif os.path.isfile(lowerCAmelCase__							) or is_remote_url(lowerCAmelCase__							):
																_UpperCamelCase			:					Union[str, Any]     =    pretrained_model_name_or_path
										else:
																_UpperCamelCase			:					str     =    hf_bucket_url(lowerCAmelCase__, filename=lowerCAmelCase__, use_cdn=lowerCAmelCase__							)

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

																_UpperCamelCase			:					int     =    Config.load_yaml(lowerCAmelCase__							)

										except EnvironmentError:
																_UpperCamelCase			:					List[Any]     =    '''Can\'t load config for'''
																raise EnvironmentError(lowerCAmelCase__							)

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

										return Config.load_yaml(lowerCAmelCase__							), kwargs





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





def        a_				(							_lowercase       ,						_lowercase       ,						_lowercase=True   ):
						_UpperCamelCase			:					List[str]     =    CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
						_UpperCamelCase			:					Optional[int]     =    '''/''' not in model_id
						if legacy_format:
												return F"""{endpoint}/{model_id}-{filename}"""
						else:
												return F"""{endpoint}/{model_id}/{filename}"""





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





def        a_				(							_lowercase       ,						_lowercase=None       ,						_lowercase=False       ,						_lowercase=None       ,						_lowercase=10       ,						_lowercase=False       ,						_lowercase=None       ,						_lowercase=False       ,						):
						if cache_dir is None:
												_UpperCamelCase			:					Any     =    TRANSFORMERS_CACHE
						if isinstance(_lowercase       ,						_lowercase   ):
												_UpperCamelCase			:					int     =    str(_lowercase   )

						os.makedirs(_lowercase       ,						exist_ok=_lowercase   )

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

						_UpperCamelCase			:					Optional[Any]     =    url_to_filename(_lowercase       ,						_lowercase   )

						# get cache path to put the file
						_UpperCamelCase			:					Any     =    os.path.join(_lowercase       ,						_lowercase   )

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

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

												if resume_download:
																		_UpperCamelCase			:					Any     =    cache_path + '''.incomplete'''

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

																		_UpperCamelCase			:					List[str]     =    _resumable_file_manager
																		if os.path.exists(_lowercase   ):
																								_UpperCamelCase			:					str     =    os.stat(_lowercase   ).st_size
																		else:
																								_UpperCamelCase			:					Tuple     =    0
												else:
																		_UpperCamelCase			:					Tuple     =    partial(tempfile.NamedTemporaryFile       ,						dir=_lowercase       ,						delete=_lowercase   )
																		_UpperCamelCase			:					Optional[int]     =    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'''       ,						_lowercase       ,						temp_file.name       ,						)

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

												os.replace(temp_file.name       ,						_lowercase   )

												_UpperCamelCase			:					List[str]     =    {'''url''': url, '''etag''': etag}
												_UpperCamelCase			:					List[Any]     =    cache_path + '''.json'''
												with open(_lowercase       ,						'''w'''   ) as meta_file:
																		json.dump(_lowercase       ,						_lowercase   )

						return cache_path





def        a_				(							_lowercase       ,						_lowercase=None   ):
						_UpperCamelCase			:					str     =    url.encode('''utf-8'''   )
						_UpperCamelCase			:					Any     =    shaaaa(_lowercase   )
						_UpperCamelCase			:					Union[str, Any]     =    url_hash.hexdigest()

						if etag:
												_UpperCamelCase			:					List[Any]     =    etag.encode('''utf-8'''   )
												_UpperCamelCase			:					Union[str, Any]     =    shaaaa(_lowercase   )
												filename += "." + etag_hash.hexdigest()

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

						return filename





def        a_				(							_lowercase       ,						_lowercase=None       ,						_lowercase=False       ,						_lowercase=None       ,						_lowercase=False       ,						_lowercase=None       ,						_lowercase=False       ,						_lowercase=False       ,						_lowercase=False       ,						):
						if cache_dir is None:
												_UpperCamelCase			:					Union[str, Any]     =    TRANSFORMERS_CACHE
						if isinstance(_lowercase       ,						_lowercase   ):
												_UpperCamelCase			:					Tuple     =    str(_lowercase   )
						if isinstance(_lowercase       ,						_lowercase   ):
												_UpperCamelCase			:					str     =    str(_lowercase   )

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

						if extract_compressed_file:
												if not is_zipfile(_lowercase   ) and not tarfile.is_tarfile(_lowercase   ):
																		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/"
												_UpperCamelCase   ,							_UpperCamelCase			:					str     =    os.path.split(_lowercase   )
												_UpperCamelCase			:					str     =    output_file.replace('''.'''       ,						'''-'''   ) + '''-extracted'''
												_UpperCamelCase			:					Tuple     =    os.path.join(_lowercase       ,						_lowercase   )

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

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

												return output_path_extracted

						return output_path





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





def        a_				(							_lowercase   ):
						_UpperCamelCase			:					Union[str, Any]     =    requests.get(_lowercase   )
						_UpperCamelCase			:					List[Any]     =    np.array(Image.open(BytesIO(response.content   )   )   )
						return img





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





def        a_				(							):
						print(F"""{os.path.abspath(os.path.join(_lowercase       ,						os.pardir   )   )}/demo.ipynb"""   )





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






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










"""simple docstring"""




import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						from transformers.models.electra.modeling_flax_electra import (
						    FlaxElectraForCausalLM,
						    FlaxElectraForMaskedLM,
						    FlaxElectraForMultipleChoice,
						    FlaxElectraForPreTraining,
						    FlaxElectraForQuestionAnswering,
						    FlaxElectraForSequenceClassification,
						    FlaxElectraForTokenClassification,
						    FlaxElectraModel,
						)




class  _a						(      unittest.TestCase				):






				def __init__( self		:    str, lowerCAmelCase__		:    Tuple, lowerCAmelCase__		:    List[str]=1_3, lowerCAmelCase__		:    Optional[int]=7, lowerCAmelCase__		:    Optional[Any]=True, lowerCAmelCase__		:    Optional[int]=True, lowerCAmelCase__		:    Any=True, lowerCAmelCase__		:    str=True, lowerCAmelCase__		:    Any=9_9, lowerCAmelCase__		:    Union[str, Any]=2_4, lowerCAmelCase__		:    Optional[Any]=3_2, lowerCAmelCase__		:    Tuple=5, lowerCAmelCase__		:    int=4, lowerCAmelCase__		:    List[Any]=3_7, lowerCAmelCase__		:    Dict="gelu", lowerCAmelCase__		:    Any=0.1, lowerCAmelCase__		:    Any=0.1, lowerCAmelCase__		:    str=5_1_2, lowerCAmelCase__		:    Tuple=1_6, lowerCAmelCase__		:    int=2, lowerCAmelCase__		:    int=0.02, lowerCAmelCase__		:    Optional[int]=4, )	->      Union[str, Any]:




										'''simple docstring'''



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






				def 				snake_case	( self		:    Optional[Any]							)	->      Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[Any]     =    ids_tensor([self.batch_size, self.seq_length], self.vocab_size							)

										_UpperCamelCase			:					Dict     =    None
										if self.use_attention_mask:
																_UpperCamelCase			:					Union[str, Any]     =    random_attention_mask([self.batch_size, self.seq_length]							)

										_UpperCamelCase			:					Optional[Any]     =    None
										if self.use_token_type_ids:
																_UpperCamelCase			:					Union[str, Any]     =    ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size							)

										_UpperCamelCase			:					Optional[Any]     =    ElectraConfig(
										    vocab_size=self.vocab_size, hidden_size=self.hidden_size, embedding_size=self.embedding_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, initializer_range=self.initializer_range, )

										return config, input_ids, token_type_ids, attention_mask






				def 				snake_case	( self		:    Any							)	->      Optional[int]:




										'''simple docstring'''



										_UpperCamelCase			:					Dict     =    self.prepare_config_and_inputs()
										_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase   ,							_UpperCamelCase			:					Tuple     =    config_and_inputs
										_UpperCamelCase			:					List[Any]     =    {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
										return config, inputs_dict




@require_flax
class  _a						(      _lowerCAmelCase	,				unittest.TestCase				):
				UpperCamelCase								=    True

				UpperCamelCase								=    (
				    (
				        FlaxElectraModel,
				        FlaxElectraForCausalLM,
				        FlaxElectraForMaskedLM,
				        FlaxElectraForPreTraining,
				        FlaxElectraForTokenClassification,
				        FlaxElectraForQuestionAnswering,
				        FlaxElectraForMultipleChoice,
				        FlaxElectraForSequenceClassification,
				    )
				    if is_flax_available()
				    else ()
				)






				def 				snake_case	( self		:    Union[str, Any]							)	->      Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase			:					List[Any]     =    FlaxElectraModelTester(self							)






				@slow
				def 				snake_case	( self		:    Optional[Any]							)	->      str:




										'''simple docstring'''



										for model_class_name in self.all_model_classes:
																if model_class_name == FlaxElectraForMaskedLM:
																						_UpperCamelCase			:					int     =    model_class_name.from_pretrained('''google/electra-small-generator'''							)
																else:
																						_UpperCamelCase			:					Any     =    model_class_name.from_pretrained('''google/electra-small-discriminator'''							)
																_UpperCamelCase			:					List[str]     =    model(np.ones((1, 1)							)							)
																self.assertIsNotNone(lowerCAmelCase__							)



