
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 a__    (       A_,     A_=False					):






  '''simple docstring'''





  try:
    __magic_name__				     =       os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    __magic_name__				     =       default
  else:
    # KEY is set, convert it to True or False.
    try:
      __magic_name__				     =       strtobool(A_					)
    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


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

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

# Audio
__lowerCAmelCase			:     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
__lowerCAmelCase			:     Union[str, 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
__lowerCAmelCase			:     Dict           =   pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
__lowerCAmelCase			:     Optional[Any]           =   pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





  def _require_spacy_model(A_					):
    try:
      import spacy  # noqa F401

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

  return _require_spacy_model

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       A_					):






  '''simple docstring'''





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

def a__    (       *A_					):






  '''simple docstring'''





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

  return decorate




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  pass







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		0
  a__           =		1
  a__           =		2







@contextmanager
def a__    (       A_=OfflineSimulationMode.CONNECTION_FAILS,     A_=1e-16					):






  '''simple docstring'''





  __magic_name__				     =       requests.Session().request

  def timeout_request(A_,     A_,     A_,     **A_					):
    # Change the url to an invalid url so that the connection hangs
    __magic_name__				     =       """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.'''					)
    __magic_name__				     =       timeout
    try:
      return online_request(A_,     A_,     **A_					)
    except Exception as e:
      # The following changes in the error are just here to make the offline timeout error prettier
      __magic_name__				     =       url
      __magic_name__				     =       e.args[0]
      __magic_name__				     =       (max_retry_error.args[0].replace("""10.255.255.1""",     f'''OfflineMock[{url}]'''					),)
      __magic_name__				     =       (max_retry_error,)
      raise

  def raise_connection_error(A_,     A_,     **A_					):
    raise requests.ConnectionError("""Offline mode is enabled.""",     request=A_					)

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

@contextmanager
def a__    (       *A_,     **A_					):






  '''simple docstring'''





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

@contextmanager
def a__    (       ):






  '''simple docstring'''





  import gc

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

@contextmanager
def a__    (       ):






  '''simple docstring'''





  import gc

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

def a__    (       A_,     A_					):






  '''simple docstring'''





  return deepcopy(A_					).integers(0,     100,     10					).tolist() == deepcopy(A_					).integers(0,     100,     10					).tolist()

def a__    (       A_					):






  '''simple docstring'''





  import decorator
  from requests.exceptions import HTTPError

  def _wrapper(A_,     *A_,     **A_					):
    try:
      return func(*A_,     **A_					)
    except HTTPError as err:
      if str(A_					).startswith("""500"""					) or str(A_					).startswith("""502"""					):
        pytest.xfail(str(A_					)					)
      raise err

  return decorator.decorator(_wrapper,     A_					)




class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Optional[Any]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Optional[Any]    )			->	int:







    """simple docstring"""






    __magic_name__				     =       returncode
    __magic_name__				     =       stdout
    __magic_name__				     =       stderr







async def a__    (       A_,     A_					):






  '''simple docstring'''





  while True:
    __magic_name__				     =       await stream.readline()
    if line:
      callback(A_					)
    else:
      break

async def a__    (       A_,     A_=None,     A_=None,     A_=None,     A_=False,     A_=False					):






  '''simple docstring'''





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

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

  # 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)

  __magic_name__				     =       []
  __magic_name__				     =       []

  def tee(A_,     A_,     A_,     A_=""					):
    __magic_name__				     =       line.decode("""utf-8"""					).rstrip()
    sink.append(A_					)
    if not quiet:
      print(A_,     A_,     file=A_					)

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

def a__    (       A_,     A_=None,     A_=None,     A_=180,     A_=False,     A_=True					):






  '''simple docstring'''





  __magic_name__				     =       asyncio.get_event_loop()
  __magic_name__				     =       loop.run_until_complete(
      _stream_subprocess(A_,     env=A_,     stdin=A_,     timeout=A_,     quiet=A_,     echo=A_					)					)

  __magic_name__				     =       """ """.join(A_					)
  if result.returncode > 0:
    __magic_name__				     =       """\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 a__    (       ):






  '''simple docstring'''





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





def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       29500
  __magic_name__				     =       pytest_xdist_worker_id()
  return port + uniq_delta



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        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Optional[Any]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: int=13			,							UpperCamelCase__			: Optional[int]=7			,							UpperCamelCase__			: Any=True			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: int=True			,							UpperCamelCase__			: Optional[Any]=True			,							UpperCamelCase__			: int=99			,							UpperCamelCase__			: Any=16			,							UpperCamelCase__			: str=36			,							UpperCamelCase__			: List[str]=6			,							UpperCamelCase__			: List[str]=6			,							UpperCamelCase__			: Union[str, Any]=6			,							UpperCamelCase__			: int=37			,							UpperCamelCase__			: Optional[int]="gelu"			,							UpperCamelCase__			: List[Any]=0.1			,							UpperCamelCase__			: Optional[int]=0.1			,							UpperCamelCase__			: int=512			,							UpperCamelCase__			: str=16			,							UpperCamelCase__			: int=2			,							UpperCamelCase__			: List[Any]=0.02			,							UpperCamelCase__			: Optional[int]=3			,							UpperCamelCase__			: Optional[Any]=4			,							UpperCamelCase__			: Dict=None			,							)			->	Any:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       seq_length
    __magic_name__				     =       is_training
    __magic_name__				     =       use_input_mask
    __magic_name__				     =       use_token_type_ids
    __magic_name__				     =       use_labels
    __magic_name__				     =       vocab_size
    __magic_name__				     =       embedding_size
    __magic_name__				     =       hidden_size
    __magic_name__				     =       num_hidden_layers
    __magic_name__				     =       num_hidden_groups
    __magic_name__				     =       num_attention_heads
    __magic_name__				     =       intermediate_size
    __magic_name__				     =       hidden_act
    __magic_name__				     =       hidden_dropout_prob
    __magic_name__				     =       attention_probs_dropout_prob
    __magic_name__				     =       max_position_embeddings
    __magic_name__				     =       type_vocab_size
    __magic_name__				     =       type_sequence_label_size
    __magic_name__				     =       initializer_range
    __magic_name__				     =       num_labels
    __magic_name__				     =       num_choices
    __magic_name__				     =       scope
  def 							_lowercase							( self			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

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

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

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

    __magic_name__				     =       self.get_config()

    return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
  def 							_lowercase							( self			: Any    )			->	List[Any]:







    """simple docstring"""






    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 							_lowercase							( self			: int			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Optional[Any]    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       AlbertModel(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__    )
    __magic_name__				     =       model(UpperCamelCase__			,							token_type_ids=UpperCamelCase__    )
    __magic_name__				     =       model(UpperCamelCase__    )
    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 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Union[str, Any]    )			->	str:







    """simple docstring"""






    __magic_name__				     =       AlbertForPreTraining(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(
        UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__			,							sentence_order_label=UpperCamelCase__			,							)
    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 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       AlbertForMaskedLM(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__    )
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )
  def 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: str			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Optional[int]			,							UpperCamelCase__			: Tuple    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       AlbertForQuestionAnswering(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(
        UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							start_positions=UpperCamelCase__			,							end_positions=UpperCamelCase__			,							)
    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 							_lowercase							( self			: Union[str, Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: int    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       self.num_labels
    __magic_name__				     =       AlbertForSequenceClassification(UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__    )
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )
  def 							_lowercase							( self			: int			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Optional[int]    )			->	int:







    """simple docstring"""






    __magic_name__				     =       self.num_labels
    __magic_name__				     =       AlbertForTokenClassification(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__			,							labels=UpperCamelCase__    )
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.num_labels)    )
  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: int			,							UpperCamelCase__			: str    )			->	List[Any]:







    """simple docstring"""






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





  def 							_lowercase							( self			: int    )			->	Optional[int]:







    """simple docstring"""






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







@require_torch
class        UpperCAmelCase_			( _A  ,       _A  ,       unittest.TestCase     ):


  '''simple docstring'''







  a__           =		(
      (
          AlbertModel,
          AlbertForPreTraining,
          AlbertForMaskedLM,
          AlbertForMultipleChoice,
          AlbertForSequenceClassification,
          AlbertForTokenClassification,
          AlbertForQuestionAnswering,
      )
      if is_torch_available()
      else ()
  )
  a__           =		(
      {
          """feature-extraction""": AlbertModel,
          """fill-mask""": AlbertForMaskedLM,
          """question-answering""": AlbertForQuestionAnswering,
          """text-classification""": AlbertForSequenceClassification,
          """token-classification""": AlbertForTokenClassification,
          """zero-shot""": AlbertForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  a__           =		True
  def 							_lowercase							( self			: str			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Union[str, Any]=False    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       super()._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__			,							return_labels=UpperCamelCase__    )

    if return_labels:
      if model_class in get_values(UpperCamelCase__    ):
        __magic_name__				     =       torch.zeros(
            (self.model_tester.batch_size, self.model_tester.seq_length)			,							dtype=torch.long			,							device=UpperCamelCase__    )
        __magic_name__				     =       torch.zeros(
            self.model_tester.batch_size			,							dtype=torch.long			,							device=UpperCamelCase__    )
    return inputs_dict
  def 							_lowercase							( self			: int    )			->	int:







    """simple docstring"""






    __magic_name__				     =       AlbertModelTester(self    )
    __magic_name__				     =       ConfigTester(self			,							config_class=UpperCamelCase__			,							hidden_size=37    )
  def 							_lowercase							( self			: Optional[int]    )			->	Optional[Any]:







    """simple docstring"""






    self.config_tester.run_common_tests()
  def 							_lowercase							( self			: Dict    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: int    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__    )
  def 							_lowercase							( self			: List[Any]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__    )
  def 							_lowercase							( self			: Dict    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__    )
  def 							_lowercase							( self			: Dict    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__    )
  def 							_lowercase							( self			: Union[str, Any]    )			->	Any:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__    )
  def 							_lowercase							( self			: Tuple    )			->	Optional[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
      __magic_name__				     =       type
      self.model_tester.create_and_check_model(*UpperCamelCase__    )





  @slow
  def 							_lowercase							( self			: Optional[int]    )			->	Optional[int]:







    """simple docstring"""






    for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __magic_name__				     =       AlbertModel.from_pretrained(UpperCamelCase__    )
      self.assertIsNotNone(UpperCamelCase__    )







@require_torch
class        UpperCAmelCase_			( unittest.TestCase     ):


  '''simple docstring'''







  @slow
  def 							_lowercase							( self			: Dict    )			->	Union[str, Any]:







    """simple docstring"""






    __magic_name__				     =       AlbertModel.from_pretrained("""albert-base-v2"""    )
    __magic_name__				     =       torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]    )
    __magic_name__				     =       torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]    )
    with torch.no_grad():
      __magic_name__				     =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__    )[0]
    __magic_name__				     =       torch.Size((1, 11, 768)    )
    self.assertEqual(output.shape			,							UpperCamelCase__    )
    __magic_name__				     =       torch.tensor(
        [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]    )

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

