





import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
					import importlib_metadata
else:
					import importlib.metadata as importlib_metadata







def    __lowerCamelCase					(							__a   :List[str]    ,     __a   :Any=False    )		->				List[str]:






		"""simple docstring"""

		try:
				A__        =   os.environ[key]
		except KeyError:
				# KEY isn't set, default to `default`.
				A__        =   default
		else:
				# KEY is set, convert it to True or False.
				try:
						A__        =   strtobool(UpperCamelCase_    )
				except ValueError:
						# More values are supported, but let's keep the message simple.
						raise ValueError(F'If set, {key} must be yes or no.'    )
		return _value


A    :					List[str] =      parse_flag_from_env('''RUN_SLOW''', default=False)
A    :					List[str] =      parse_flag_from_env('''RUN_REMOTE''', default=False)
A    :					Union[str, Any] =      parse_flag_from_env('''RUN_LOCAL''', default=True)
A    :					Any =      parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
A    :					int =      pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
A    :					Union[str, Any] =      pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
A    :					Optional[Any] =      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
A    :					Tuple =      pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
A    :					Any =      pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
A    :					Optional[int] =      pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

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







def    __lowerCamelCase					(							__a   :str    )		->				Optional[Any]:






		"""simple docstring"""

		try:
				import faiss  # noqa
		except ImportError:
				A__        =   unittest.skip("""test requires faiss"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Dict    )		->				Optional[Any]:






		"""simple docstring"""

		try:
				import regex  # noqa
		except ImportError:
				A__        =   unittest.skip("""test requires regex"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Union[str, Any]    )		->				int:






		"""simple docstring"""

		try:
				import elasticsearch  # noqa
		except ImportError:
				A__        =   unittest.skip("""test requires elasticsearch"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :str    )		->				Tuple:






		"""simple docstring"""

		try:
				import sqlalchemy  # noqa
		except ImportError:
				A__        =   unittest.skip("""test requires sqlalchemy"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Tuple    )		->				Dict:






		"""simple docstring"""

		if not config.TORCH_AVAILABLE:
				A__        =   unittest.skip("""test requires PyTorch"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :List[Any]    )		->				Dict:






		"""simple docstring"""

		if not config.TF_AVAILABLE:
				A__        =   unittest.skip("""test requires TensorFlow"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :List[str]    )		->				Tuple:






		"""simple docstring"""

		if not config.JAX_AVAILABLE:
				A__        =   unittest.skip("""test requires JAX"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Union[str, Any]    )		->				str:






		"""simple docstring"""

		if not config.PIL_AVAILABLE:
				A__        =   unittest.skip("""test requires Pillow"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Optional[int]    )		->				Union[str, Any]:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :List[str]    )		->				Optional[int]:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :Any    )		->				Any:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :int    )		->				List[Any]:






		"""simple docstring"""

		def _require_spacy_model(__a   :Tuple    ):
				try:
						import spacy  # noqa F401

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

		return _require_spacy_model







def    __lowerCamelCase					(							__a   :Optional[Any]    )		->				int:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :Optional[Any]    )		->				List[Any]:






		"""simple docstring"""

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







def    __lowerCamelCase					(							__a   :str    )		->				List[str]:






		"""simple docstring"""

		if not _run_slow_tests or _run_slow_tests == 0:
				A__        =   unittest.skip("""test is slow"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Union[str, Any]    )		->				List[Any]:






		"""simple docstring"""

		if not _run_local_tests or _run_local_tests == 0:
				A__        =   unittest.skip("""test is local"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :int    )		->				str:






		"""simple docstring"""

		if not _run_packaged_tests or _run_packaged_tests == 0:
				A__        =   unittest.skip("""test is packaged"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							__a   :Dict    )		->				Tuple:






		"""simple docstring"""

		if not _run_remote_tests or _run_remote_tests == 0:
				A__        =   unittest.skip("""test requires remote"""    )(UpperCamelCase_    )
		return test_case







def    __lowerCamelCase					(							*__a   :Union[str, Any]    )		->				Dict:






		"""simple docstring"""

		def decorate(cls   :int    ):
				for name, fn in cls.__dict__.items():
						if callable(UpperCamelCase_    ) and name.startswith("""test"""    ):
								for decorator in decorators:
										A__        =   decorator(UpperCamelCase_    )
								setattr(cls    ,     UpperCamelCase_    ,     UpperCamelCase_    )
				return cls

		return decorate


class   A			(__a    ):
			'''simple docstring'''




			pass


class   A			(__a    ):
			'''simple docstring'''




			__lowerCamelCase	:       str							=    0
			__lowerCamelCase	:       Tuple							=    1
			__lowerCamelCase	:       Union[str, Any]							=    2







@contextmanager
def    __lowerCamelCase					(							__a   :List[Any]=OfflineSimulationMode.CONNECTION_FAILS    ,     __a   :List[str]=1E-16    )		->				Optional[int]:






		"""simple docstring"""

		A__        =   requests.Session().request

		def timeout_request(__a   :Any    ,     __a   :List[Any]    ,     __a   :List[str]    ,     **__a   :Tuple    ):
				# Change the url to an invalid url so that the connection hangs
				A__        =   """https://10.255.255.1"""
				if kwargs.get("""timeout"""    ) is None:
						raise RequestWouldHangIndefinitelyError(
						    F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'    )
				A__        =   timeout
				try:
						return online_request(UpperCamelCase_    ,     UpperCamelCase_    ,     **UpperCamelCase_    )
				except Exception as e:
						# The following changes in the error are just here to make the offline timeout error prettier
						A__        =   url
						A__        =   e.args[0]
						A__        =   (max_retry_error.args[0].replace("""10.255.255.1"""    ,     F'OfflineMock[{url}]'    ),)
						A__        =   (max_retry_error,)
						raise

		def raise_connection_error(__a   :List[str]    ,     __a   :List[str]    ,     **__a   :str    ):
				raise requests.ConnectionError("""Offline mode is enabled."""    ,     request=UpperCamelCase_    )

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







@contextmanager
def    __lowerCamelCase					(							*__a   :Optional[int]    ,     **__a   :Any    )		->				Optional[int]:






		"""simple docstring"""

		A__        =   str(Path().resolve()    )
		with tempfile.TemporaryDirectory(*UpperCamelCase_    ,     **UpperCamelCase_    ) as tmp_dir:
				try:
						os.chdir(UpperCamelCase_    )
						yield
				finally:
						os.chdir(UpperCamelCase_    )







@contextmanager
def    __lowerCamelCase					(							)		->				Any:






		"""simple docstring"""

		import gc

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







@contextmanager
def    __lowerCamelCase					(							)		->				Optional[Any]:






		"""simple docstring"""

		import gc

		gc.collect()
		A__        =   pa.total_allocated_bytes()
		yield
		assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."







def    __lowerCamelCase					(							__a   :Dict    ,     __a   :int    )		->				Optional[int]:






		"""simple docstring"""

		return deepcopy(UpperCamelCase_    ).integers(0    ,     1_0_0    ,     1_0    ).tolist() == deepcopy(UpperCamelCase_    ).integers(0    ,     1_0_0    ,     1_0    ).tolist()







def    __lowerCamelCase					(							__a   :Union[str, Any]    )		->				Optional[Any]:






		"""simple docstring"""

		import decorator
		from requests.exceptions import HTTPError

		def _wrapper(__a   :Optional[int]    ,     *__a   :Any    ,     **__a   :Any    ):
				try:
						return func(*UpperCamelCase_    ,     **UpperCamelCase_    )
				except HTTPError as err:
						if str(UpperCamelCase_    ).startswith("""500"""    ) or str(UpperCamelCase_    ).startswith("""502"""    ):
								pytest.xfail(str(UpperCamelCase_    )    )
						raise err

		return decorator.decorator(_wrapper    ,     UpperCamelCase_    )


class   A			:
			'''simple docstring'''




			def __init__(			self   :    Optional[int]							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int   )	->	Tuple:







					"""simple docstring"""






					A__        =   returncode
					A__        =   stdout
					A__        =   stderr







async def    __lowerCamelCase					(							__a   :Optional[Any]    ,     __a   :Dict    )		->				int:






		"""simple docstring"""

		while True:
				A__        =   await stream.readline()
				if line:
						callback(UpperCamelCase_    )
				else:
						break







async def    __lowerCamelCase					(							__a   :Any    ,     __a   :Optional[int]=None    ,     __a   :Dict=None    ,     __a   :Optional[Any]=None    ,     __a   :Any=False    ,     __a   :List[str]=False    )		->				List[str]:






		"""simple docstring"""

		if echo:
				print("""\nRunning: """    ,     """ """.join(UpperCamelCase_    )    )

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

		# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
		# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
		#
		# If it starts hanging, will need to switch to the following code. The problem is that no data
		# will be seen until it's done and if it hangs for example there will be no debug info.
		# out, err = await p.communicate()
		# return _RunOutput(p.returncode, out, err)

		A__        =   []
		A__        =   []

		def tee(__a   :List[Any]    ,     __a   :str    ,     __a   :Optional[Any]    ,     __a   :List[Any]=""    ):
				A__        =   line.decode("""utf-8"""    ).rstrip()
				sink.append(UpperCamelCase_    )
				if not quiet:
						print(UpperCamelCase_    ,     UpperCamelCase_    ,     file=UpperCamelCase_    )

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







def    __lowerCamelCase					(							__a   :Tuple    ,     __a   :Dict=None    ,     __a   :str=None    ,     __a   :int=1_8_0    ,     __a   :str=False    ,     __a   :Tuple=True    )		->				Optional[int]:






		"""simple docstring"""

		A__        =   asyncio.get_event_loop()
		A__        =   loop.run_until_complete(
		    _stream_subprocess(UpperCamelCase_    ,     env=UpperCamelCase_    ,     stdin=UpperCamelCase_    ,     timeout=UpperCamelCase_    ,     quiet=UpperCamelCase_    ,     echo=UpperCamelCase_    )    )

		A__        =   """ """.join(UpperCamelCase_    )
		if result.returncode > 0:
				A__        =   """\n""".join(result.stderr    )
				raise RuntimeError(
				    F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
				    F'The combined stderr from workers follows:\n{stderr}'    )

		# check that the subprocess actually did run and produced some output, should the test rely on
		# the remote side to do the testing
		if not result.stdout and not result.stderr:
				raise RuntimeError(F'\'{cmd_str}\' produced no output.'    )

		return result







def    __lowerCamelCase					(							)		->				int:






		"""simple docstring"""

		A__        =   os.environ.get("""PYTEST_XDIST_WORKER"""    ,     """gw0"""    )
		A__        =   re.sub(R"""^gw"""    ,     """"""    ,     UpperCamelCase_    ,     0    ,     re.M    )
		return int(UpperCamelCase_    )







def    __lowerCamelCase					(							)		->				List[Any]:






		"""simple docstring"""

		A__        =   2_9_5_0_0
		A__        =   pytest_xdist_worker_id()
		return port + uniq_delta





"""simple docstring"""





import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
							import torch

							from transformers import (
							    MODEL_FOR_PRETRAINING_MAPPING,
							    AlbertForMaskedLM,
							    AlbertForMultipleChoice,
							    AlbertForPreTraining,
							    AlbertForQuestionAnswering,
							    AlbertForSequenceClassification,
							    AlbertForTokenClassification,
							    AlbertModel,
							)
							from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class 						SCREAMING_SNAKE_CASE_ :




		"""simple docstring"""





		def __init__(     self							,  lowerCAmelCase__							,  lowerCAmelCase__=1_3							,  lowerCAmelCase__=7							,  lowerCAmelCase__=True							,  lowerCAmelCase__=True							,  lowerCAmelCase__=True							,  lowerCAmelCase__=True							,  lowerCAmelCase__=9_9							,  lowerCAmelCase__=1_6							,  lowerCAmelCase__=3_6							,  lowerCAmelCase__=6							,  lowerCAmelCase__=6							,  lowerCAmelCase__=6							,  lowerCAmelCase__=3_7							,  lowerCAmelCase__="gelu"							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=5_1_2							,  lowerCAmelCase__=1_6							,  lowerCAmelCase__=2							,  lowerCAmelCase__=0.02							,  lowerCAmelCase__=3							,  lowerCAmelCase__=4							,  lowerCAmelCase__=None							,  ):
				__SCREAMING_SNAKE_CASE            = parent
				__SCREAMING_SNAKE_CASE            = batch_size
				__SCREAMING_SNAKE_CASE            = seq_length
				__SCREAMING_SNAKE_CASE            = is_training
				__SCREAMING_SNAKE_CASE            = use_input_mask
				__SCREAMING_SNAKE_CASE            = use_token_type_ids
				__SCREAMING_SNAKE_CASE            = use_labels
				__SCREAMING_SNAKE_CASE            = vocab_size
				__SCREAMING_SNAKE_CASE            = embedding_size
				__SCREAMING_SNAKE_CASE            = hidden_size
				__SCREAMING_SNAKE_CASE            = num_hidden_layers
				__SCREAMING_SNAKE_CASE            = num_hidden_groups
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = intermediate_size
				__SCREAMING_SNAKE_CASE            = hidden_act
				__SCREAMING_SNAKE_CASE            = hidden_dropout_prob
				__SCREAMING_SNAKE_CASE            = attention_probs_dropout_prob
				__SCREAMING_SNAKE_CASE            = max_position_embeddings
				__SCREAMING_SNAKE_CASE            = type_vocab_size
				__SCREAMING_SNAKE_CASE            = type_sequence_label_size
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = num_labels
				__SCREAMING_SNAKE_CASE            = num_choices
				__SCREAMING_SNAKE_CASE            = scope




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = ids_tensor([self.batch_size, self.seq_length]							,  self.vocab_size)

				__SCREAMING_SNAKE_CASE            = None
				if self.use_input_mask:
						__SCREAMING_SNAKE_CASE            = random_attention_mask([self.batch_size, self.seq_length])

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

				__SCREAMING_SNAKE_CASE            = None
				__SCREAMING_SNAKE_CASE            = None
				__SCREAMING_SNAKE_CASE            = None
				if self.use_labels:
						__SCREAMING_SNAKE_CASE            = ids_tensor([self.batch_size]							,  self.type_sequence_label_size)
						__SCREAMING_SNAKE_CASE            = ids_tensor([self.batch_size, self.seq_length]							,  self.num_labels)
						__SCREAMING_SNAKE_CASE            = ids_tensor([self.batch_size]							,  self.num_choices)

				__SCREAMING_SNAKE_CASE            = self.get_config()

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




		def 	snake_case_     (     self):
				return AlbertConfig(
				    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							,  initializer_range=self.initializer_range							,  num_hidden_groups=self.num_hidden_groups							,  )




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = AlbertModel(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__)
				self.parent.assertEqual(result.last_hidden_state.shape							,  (self.batch_size, self.seq_length, self.hidden_size))
				self.parent.assertEqual(result.pooler_output.shape							,  (self.batch_size, self.hidden_size))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = AlbertForPreTraining(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(
				    lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  labels=lowerCAmelCase__							,  sentence_order_label=lowerCAmelCase__							,  )
				self.parent.assertEqual(result.prediction_logits.shape							,  (self.batch_size, self.seq_length, self.vocab_size))
				self.parent.assertEqual(result.sop_logits.shape							,  (self.batch_size, config.num_labels))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = AlbertForMaskedLM(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  labels=lowerCAmelCase__)
				self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.seq_length, self.vocab_size))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = AlbertForQuestionAnswering(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(
				    lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  start_positions=lowerCAmelCase__							,  end_positions=lowerCAmelCase__							,  )
				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 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.num_labels
				__SCREAMING_SNAKE_CASE            = AlbertForSequenceClassification(lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  labels=lowerCAmelCase__)
				self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.num_labels
				__SCREAMING_SNAKE_CASE            = AlbertForTokenClassification(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  labels=lowerCAmelCase__)
				self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.seq_length, self.num_labels))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.num_choices
				__SCREAMING_SNAKE_CASE            = AlbertForMultipleChoice(config=lowerCAmelCase__)
				model.to(lowerCAmelCase__)
				model.eval()
				__SCREAMING_SNAKE_CASE            = input_ids.unsqueeze(1).expand(-1							,  self.num_choices							,  -1).contiguous()
				__SCREAMING_SNAKE_CASE            = token_type_ids.unsqueeze(1).expand(-1							,  self.num_choices							,  -1).contiguous()
				__SCREAMING_SNAKE_CASE            = input_mask.unsqueeze(1).expand(-1							,  self.num_choices							,  -1).contiguous()
				__SCREAMING_SNAKE_CASE            = model(
				    lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  token_type_ids=lowerCAmelCase__							,  labels=lowerCAmelCase__							,  )
				self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_choices))




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.prepare_config_and_inputs()
				(
				    (
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,(
				    __SCREAMING_SNAKE_CASE
				)       ,
				)            = config_and_inputs
				__SCREAMING_SNAKE_CASE            = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
				return config, inputs_dict



@require_torch
class 						SCREAMING_SNAKE_CASE_ (						__a     ,				__a     ,				unittest.TestCase ):




		"""simple docstring"""





		__lowercase							:  Union[str, Any]						   =		(
		    (
		        AlbertModel,
		        AlbertForPreTraining,
		        AlbertForMaskedLM,
		        AlbertForMultipleChoice,
		        AlbertForSequenceClassification,
		        AlbertForTokenClassification,
		        AlbertForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		__lowercase							:  Optional[int]						   =		(
		    {
		        '''feature-extraction''': AlbertModel,
		        '''fill-mask''': AlbertForMaskedLM,
		        '''question-answering''': AlbertForQuestionAnswering,
		        '''text-classification''': AlbertForSequenceClassification,
		        '''token-classification''': AlbertForTokenClassification,
		        '''zero-shot''': AlbertForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		__lowercase							:  List[Any]						   =		True




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__=False):
				__SCREAMING_SNAKE_CASE            = super()._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__							,  return_labels=lowerCAmelCase__)

				if return_labels:
						if model_class in get_values(lowerCAmelCase__):
								__SCREAMING_SNAKE_CASE            = torch.zeros(
								    (self.model_tester.batch_size, self.model_tester.seq_length)							,  dtype=torch.long							,  device=lowerCAmelCase__)
								__SCREAMING_SNAKE_CASE            = torch.zeros(
								    self.model_tester.batch_size							,  dtype=torch.long							,  device=lowerCAmelCase__)
				return inputs_dict




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = AlbertModelTester(self)
				__SCREAMING_SNAKE_CASE            = ConfigTester(self							,  config_class=lowerCAmelCase__							,  hidden_size=3_7)




		def 	snake_case_     (     self):
				self.config_tester.run_common_tests()




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__)




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
						__SCREAMING_SNAKE_CASE            = type
						self.model_tester.create_and_check_model(*lowerCAmelCase__)




		@slow
		def 	snake_case_     (     self):
				for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__SCREAMING_SNAKE_CASE            = AlbertModel.from_pretrained(lowerCAmelCase__)
						self.assertIsNotNone(lowerCAmelCase__)



@require_torch
class 						SCREAMING_SNAKE_CASE_ (						unittest.TestCase ):




		"""simple docstring"""





		@slow
		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = AlbertModel.from_pretrained("""albert-base-v2""")
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]])
				__SCREAMING_SNAKE_CASE            = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
				with torch.no_grad():
						__SCREAMING_SNAKE_CASE            = model(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__)[0]
				__SCREAMING_SNAKE_CASE            = torch.Size((1, 1_1, 7_6_8))
				self.assertEqual(output.shape							,  lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = torch.tensor(
				    [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]])

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




