






'''simple docstring'''


import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


lowerCamelCase_				: List[str]    	=							get_logger(__name__)
class    _SCREAMING_SNAKE_CASE							:


   '''simple docstring'''





   def __init__(   self							:						Union[str, Any] ,      lowercase							:						Optional[str] = None			)							->    Tuple:

         '''simple docstring'''







         UpperCamelCase__         = (
             os.path.join(lowercase ,      config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
         )
         UpperCamelCase__         = Extractor






   def 				A      (   self							:						List[Any] ,      lowercase							:						str			)							->    str:

         '''simple docstring'''







         from .file_utils import hash_url_to_filename

         # Path where we extract compressed archives
         # We extract in the cache dir, and get the extracted path name by hashing the original path"
         UpperCamelCase__         = os.path.abspath(lowercase			)
         return os.path.join(self.extract_dir ,      hash_url_to_filename(lowercase			)			)






   def 				A      (   self							:						str ,      lowercase							:						str ,      lowercase							:						bool			)							->    bool:

         '''simple docstring'''







         return force_extract or (
             not os.path.isfile(lowercase			) and not (os.path.isdir(lowercase			) and os.listdir(lowercase			))
         )







   def 				A      (   self							:						Optional[Any] ,      lowercase							:						str ,      lowercase							:						bool = False			)							->    str:

         '''simple docstring'''







         UpperCamelCase__         = self.extractor.infer_extractor_format(lowercase			)
         if not extractor_format:
               return input_path
         UpperCamelCase__         = self._get_output_path(lowercase			)
         if self._do_extract(lowercase ,      lowercase			):
               self.extractor.extract(lowercase ,      lowercase ,      lowercase			)
         return output_path
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   @classmethod
   @abstractmethod
   def 				A      (   cls							:						List[Any] ,      lowercase							:						Union[Path, str] ,      **lowercase							:						Dict			)							->    bool:

         '''simple docstring'''







         ...







   @staticmethod
   @abstractmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         ...
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							List[bytes]					     =					[]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						int			)							->    Dict:

         '''simple docstring'''







         with open(lowercase ,      """rb"""			) as f:
               return f.read(lowercase			)







   @classmethod
   def 				A      (   cls							:						Any ,      lowercase							:						Union[Path, str] ,      lowercase							:						bytes = b""			)							->    bool:

         '''simple docstring'''







         if not magic_number:
               UpperCamelCase__         = max(len(lowercase			) for cls_magic_number in cls.magic_numbers			)
               try:
                     UpperCamelCase__         = cls.read_magic_number(lowercase ,      lowercase			)
               except OSError:
                     return False
         return any(magic_number.startswith(lowercase			) for cls_magic_number in cls.magic_numbers			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   @classmethod
   def 				A      (   cls							:						List[Any] ,      lowercase							:						Union[Path, str] ,      **lowercase							:						str			)							->    bool:

         '''simple docstring'''







         return tarfile.is_tarfile(lowercase			)






   @staticmethod
   def 				A      (   lowercase							:						Tuple ,      lowercase							:						List[str]			)							->    int:

         '''simple docstring'''







         def resolved(lowercase							:						str			) -> str:
               return os.path.realpath(os.path.abspath(lowercase			)			)

         def badpath(lowercase							:						str ,      lowercase							:						str			) -> bool:
               # joinpath will ignore base if path is absolute
               return not resolved(os.path.join(lowercase ,      lowercase			)			).startswith(lowercase			)

         def badlink(lowercase							:						Optional[Any] ,      lowercase							:						str			) -> bool:
               # Links are interpreted relative to the directory containing the link
               UpperCamelCase__         = resolved(os.path.join(lowercase ,      os.path.dirname(info.name			)			)			)
               return badpath(info.linkname ,      base=lowercase			)

         UpperCamelCase__         = resolved(lowercase			)

         for finfo in members:
               if badpath(finfo.name ,      lowercase			):
                     logger.error(f"Extraction of {finfo.name} is blocked (illegal path)"			)
               elif finfo.issym() and badlink(lowercase ,      lowercase			):
                     logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}"			)
               elif finfo.islnk() and badlink(lowercase ,      lowercase			):
                     logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}"			)
               else:
                     yield finfo







   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         os.makedirs(lowercase ,      exist_ok=lowercase			)
         UpperCamelCase__         = tarfile.open(lowercase			)
         tar_file.extractall(lowercase ,      members=TarExtractor.safemembers(lowercase ,      lowercase			)			)
         tar_file.close()
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							Optional[int]					     =					[B"\x1F\x8B"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         with gzip.open(lowercase ,      """rb"""			) as gzip_file:
               with open(lowercase ,      """wb"""			) as extracted_file:
                     shutil.copyfileobj(lowercase ,      lowercase			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							str					     =					[
       B"PK\x03\x04",
       B"PK\x05\x06",  # empty archive
       B"PK\x07\x08",  # spanned archive
   ]






   @classmethod
   def 				A      (   cls							:						List[Any] ,      lowercase							:						Union[Path, str] ,      lowercase							:						bytes = b""			)							->    bool:

         '''simple docstring'''







         if super().is_extractable(lowercase ,      magic_number=lowercase			):
               return True
         try:
               # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
               # From: https://github.com/python/cpython/pull/5053
               from zipfile import (
                   _CD_SIGNATURE,
                   _ECD_DISK_NUMBER,
                   _ECD_DISK_START,
                   _ECD_ENTRIES_TOTAL,
                   _ECD_OFFSET,
                   _ECD_SIZE,
                   _EndRecData,
                   sizeCentralDir,
                   stringCentralDir,
                   structCentralDir,
               )

               with open(lowercase ,      """rb"""			) as fp:
                     UpperCamelCase__         = _EndRecData(lowercase			)
                     if endrec:
                           if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
                                 return True  # Empty zipfiles are still zipfiles
                           elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
                                 fp.seek(endrec[_ECD_OFFSET]			)  # Central directory is on the same disk
                                 if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
                                       UpperCamelCase__         = fp.read(lowercase			)  # CD is where we expect it to be
                                       if len(lowercase			) == sizeCentralDir:
                                             UpperCamelCase__         = struct.unpack(lowercase ,      lowercase			)  # CD is the right size
                                             if centdir[_CD_SIGNATURE] == stringCentralDir:
                                                   return True  # First central directory entry  has correct magic number
               return False
         except Exception:  # catch all errors in case future python versions change the zipfile internals
               return False







   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         os.makedirs(lowercase ,      exist_ok=lowercase			)
         with zipfile.ZipFile(lowercase ,      """r"""			) as zip_file:
               zip_file.extractall(lowercase			)
               zip_file.close()
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							Optional[Any]					     =					[B"\xFD\x37\x7A\x58\x5A\x00"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         with lzma.open(lowercase			) as compressed_file:
               with open(lowercase ,      """wb"""			) as extracted_file:
                     shutil.copyfileobj(lowercase ,      lowercase			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							Optional[Any]					     =					[B"Rar!\x1a\x07\x00", B"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         if not config.RARFILE_AVAILABLE:
               raise ImportError("""Please pip install rarfile"""			)
         import rarfile

         os.makedirs(lowercase ,      exist_ok=lowercase			)
         UpperCamelCase__         = rarfile.RarFile(lowercase			)
         rf.extractall(lowercase			)
         rf.close()
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							int					     =					[B"\x28\xb5\x2F\xFD"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         if not config.ZSTANDARD_AVAILABLE:
               raise ImportError("""Please pip install zstandard"""			)
         import zstandard as zstd

         UpperCamelCase__         = zstd.ZstdDecompressor()
         with open(lowercase ,      """rb"""			) as ifh, open(lowercase ,      """wb"""			) as ofh:
               dctx.copy_stream(lowercase ,      lowercase			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							int					     =					[B"\x42\x5A\x68"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         with bza.open(lowercase ,      """rb"""			) as compressed_file:
               with open(lowercase ,      """wb"""			) as extracted_file:
                     shutil.copyfileobj(lowercase ,      lowercase			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							Tuple					     =					[B"\x37\x7A\xBC\xAF\x27\x1C"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         if not config.PY7ZR_AVAILABLE:
               raise ImportError("""Please pip install py7zr"""			)
         import pyazr

         os.makedirs(lowercase ,      exist_ok=lowercase			)
         with pyazr.SevenZipFile(lowercase ,      """r"""			) as archive:
               archive.extractall(lowercase			)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


   '''simple docstring'''





   __a							:							Any					     =					[B"\x04\x22\x4D\x18"]






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str]			)							->    None:

         '''simple docstring'''







         if not config.LZ4_AVAILABLE:
               raise ImportError("""Please pip install lz4"""			)
         import lza.frame

         with lza.frame.open(lowercase ,      """rb"""			) as compressed_file:
               with open(lowercase ,      """wb"""			) as extracted_file:
                     shutil.copyfileobj(lowercase ,      lowercase			)
class    _SCREAMING_SNAKE_CASE							:


   '''simple docstring'''





   __a							:							Dict[str, Type[BaseExtractor]]					     =					{
       "tar": TarExtractor,
       "gzip": GzipExtractor,
       "zip": ZipExtractor,
       "xz": XzExtractor,
       "rar": RarExtractor,
       "zstd": ZstdExtractor,
       "bz2": BzipaExtractor,
       "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
       "lz4": LzaExtractor,  # <Added version="2.4.0"/>
   }






   @classmethod
   def 				A      (   cls							:						Any			)							->    Optional[int]:

         '''simple docstring'''







         return max(
             len(lowercase			)
             for extractor in cls.extractors.values()
             if issubclass(lowercase ,      lowercase			)
             for extractor_magic_number in extractor.magic_numbers			)






   @staticmethod
   def 				A      (   lowercase							:						Union[Path, str] ,      lowercase							:						int			)							->    Dict:

         '''simple docstring'''







         try:
               return MagicNumberBaseExtractor.read_magic_number(lowercase ,      magic_number_length=lowercase			)
         except OSError:
               return b""






   @classmethod
   def 				A      (   cls							:						Union[str, Any] ,      lowercase							:						Union[Path, str] ,      lowercase							:						bool = False			)							->    bool:

         '''simple docstring'''







         warnings.warn(
             """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
             """Use 'infer_extractor_format' instead.""" ,      category=lowercase ,      )
         UpperCamelCase__         = cls.infer_extractor_format(lowercase			)
         if extractor_format:
               return True if not return_extractor else (True, cls.extractors[extractor_format])
         return False if not return_extractor else (False, None)






   @classmethod
   def 				A      (   cls							:						Optional[Any] ,      lowercase							:						Union[Path, str]			)							->    str:  # <Added version="2.4.0"/>

         '''simple docstring'''







         UpperCamelCase__         = cls._get_magic_number_max_length()
         UpperCamelCase__         = cls._read_magic_number(lowercase ,      lowercase			)
         for extractor_format, extractor in cls.extractors.items():
               if extractor.is_extractable(lowercase ,      magic_number=lowercase			):
                     return extractor_format







   @classmethod
   def 				A      (   cls							:						List[Any] ,      lowercase							:						Union[Path, str] ,      lowercase							:						Union[Path, str] ,      lowercase							:						Optional[str] = None ,      lowercase							:						Optional[BaseExtractor] = "deprecated" ,      )							->    None:

         '''simple docstring'''







         os.makedirs(os.path.dirname(lowercase			) ,      exist_ok=lowercase			)
         # Prevent parallel extractions
         UpperCamelCase__         = str(Path(lowercase			).with_suffix(""".lock"""			)			)
         with FileLock(lowercase			):
               shutil.rmtree(lowercase ,      ignore_errors=lowercase			)
               if extractor_format or extractor != "deprecated":
                     if extractor != "deprecated" or not isinstance(lowercase ,      lowercase			):  # passed as positional arg
                           warnings.warn(
                               """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
                               """Use 'extractor_format' instead.""" ,      category=lowercase ,      )
                           UpperCamelCase__         = extractor if extractor != """deprecated""" else extractor_format
                     else:
                           UpperCamelCase__         = cls.extractors[extractor_format]
                     return extractor.extract(lowercase ,      lowercase			)
               else:
                     warnings.warn(
                         """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """
                         """exception in 3.0.0.""" ,      category=lowercase ,      )
                     for extractor in cls.extractors.values():
                           if extractor.is_extractable(lowercase			):
                                 return extractor.extract(lowercase ,      lowercase			)








'''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							:						Optional[int] ,      lowercase							:						List[str] ,      lowercase							:						List[Any]=1_3 ,      lowercase							:						Union[str, Any]=7 ,      lowercase							:						Dict=True ,      lowercase							:						Optional[int]=True ,      lowercase							:						List[Any]=True ,      lowercase							:						Dict=True ,      lowercase							:						List[str]=9_9 ,      lowercase							:						Dict=1_6 ,      lowercase							:						Dict=3_6 ,      lowercase							:						str=6 ,      lowercase							:						List[Any]=6 ,      lowercase							:						int=6 ,      lowercase							:						Union[str, Any]=3_7 ,      lowercase							:						Union[str, Any]="gelu" ,      lowercase							:						List[Any]=0.1 ,      lowercase							:						List[str]=0.1 ,      lowercase							:						str=5_1_2 ,      lowercase							:						Any=1_6 ,      lowercase							:						str=2 ,      lowercase							:						List[Any]=0.0_2 ,      lowercase							:						Tuple=3 ,      lowercase							:						Dict=4 ,      lowercase							:						Dict=None ,      )							->    List[Any]:

									'''simple docstring'''







									UpperCamelCase__         = parent
									UpperCamelCase__         = batch_size
									UpperCamelCase__         = seq_length
									UpperCamelCase__         = is_training
									UpperCamelCase__         = use_input_mask
									UpperCamelCase__         = use_token_type_ids
									UpperCamelCase__         = use_labels
									UpperCamelCase__         = vocab_size
									UpperCamelCase__         = embedding_size
									UpperCamelCase__         = hidden_size
									UpperCamelCase__         = num_hidden_layers
									UpperCamelCase__         = num_hidden_groups
									UpperCamelCase__         = num_attention_heads
									UpperCamelCase__         = intermediate_size
									UpperCamelCase__         = hidden_act
									UpperCamelCase__         = hidden_dropout_prob
									UpperCamelCase__         = attention_probs_dropout_prob
									UpperCamelCase__         = max_position_embeddings
									UpperCamelCase__         = type_vocab_size
									UpperCamelCase__         = type_sequence_label_size
									UpperCamelCase__         = initializer_range
									UpperCamelCase__         = num_labels
									UpperCamelCase__         = num_choices
									UpperCamelCase__         = scope






			def 				A      (   self							:						List[str]			)							->    str:

									'''simple docstring'''







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

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

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

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

									UpperCamelCase__         = self.get_config()

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






			def 				A      (   self							:						Optional[int]			)							->    str:

									'''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 				A      (   self							:						List[str] ,      lowercase							:						Union[str, Any] ,      lowercase							:						Optional[Any] ,      lowercase							:						Dict ,      lowercase							:						str ,      lowercase							:						int ,      lowercase							:						List[str] ,      lowercase							:						Optional[Any]			)							->    Optional[int]:

									'''simple docstring'''







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

									'''simple docstring'''







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

									'''simple docstring'''







									UpperCamelCase__         = AlbertForMaskedLM(config=lowercase			)
									model.to(lowercase			)
									model.eval()
									UpperCamelCase__         = model(lowercase ,      attention_mask=lowercase ,      token_type_ids=lowercase ,      labels=lowercase			)
									self.parent.assertEqual(result.logits.shape ,      (self.batch_size, self.seq_length, self.vocab_size)			)






			def 				A      (   self							:						Optional[Any] ,      lowercase							:						Any ,      lowercase							:						Union[str, Any] ,      lowercase							:						List[Any] ,      lowercase							:						List[Any] ,      lowercase							:						List[str] ,      lowercase							:						Optional[Any] ,      lowercase							:						Optional[Any]			)							->    List[Any]:

									'''simple docstring'''







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

									'''simple docstring'''







									UpperCamelCase__         = self.num_labels
									UpperCamelCase__         = AlbertForSequenceClassification(lowercase			)
									model.to(lowercase			)
									model.eval()
									UpperCamelCase__         = model(lowercase ,      attention_mask=lowercase ,      token_type_ids=lowercase ,      labels=lowercase			)
									self.parent.assertEqual(result.logits.shape ,      (self.batch_size, self.num_labels)			)






			def 				A      (   self							:						List[str] ,      lowercase							:						int ,      lowercase							:						Any ,      lowercase							:						Tuple ,      lowercase							:						List[str] ,      lowercase							:						Optional[int] ,      lowercase							:						List[Any] ,      lowercase							:						Dict			)							->    Optional[int]:

									'''simple docstring'''







									UpperCamelCase__         = self.num_labels
									UpperCamelCase__         = AlbertForTokenClassification(config=lowercase			)
									model.to(lowercase			)
									model.eval()
									UpperCamelCase__         = model(lowercase ,      attention_mask=lowercase ,      token_type_ids=lowercase ,      labels=lowercase			)
									self.parent.assertEqual(result.logits.shape ,      (self.batch_size, self.seq_length, self.num_labels)			)






			def 				A      (   self							:						List[Any] ,      lowercase							:						Union[str, Any] ,      lowercase							:						List[Any] ,      lowercase							:						Any ,      lowercase							:						List[str] ,      lowercase							:						Optional[Any] ,      lowercase							:						List[str] ,      lowercase							:						List[Any]			)							->    str:

									'''simple docstring'''







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







			def 				A      (   self							:						Optional[int]			)							->    List[str]:

									'''simple docstring'''







									UpperCamelCase__         = self.prepare_config_and_inputs()
									(
									    (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   (
									    UpperCamelCase__
									)    ,   
									)         = config_and_inputs
									UpperCamelCase__         = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
									return config, inputs_dict
@require_torch
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       ,unittest.TestCase	):


			'''simple docstring'''





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






			def 				A      (   self							:						Any ,      lowercase							:						int ,      lowercase							:						Dict ,      lowercase							:						Optional[Any]=False			)							->    Tuple:

									'''simple docstring'''







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

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






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

									'''simple docstring'''







									UpperCamelCase__         = AlbertModelTester(self			)
									UpperCamelCase__         = ConfigTester(self ,      config_class=lowercase ,      hidden_size=3_7			)






			def 				A      (   self							:						int			)							->    List[str]:

									'''simple docstring'''







									self.config_tester.run_common_tests()






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

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase			)






			def 				A      (   self							:						int			)							->    Dict:

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*lowercase			)






			def 				A      (   self							:						Tuple			)							->    int:

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*lowercase			)






			def 				A      (   self							:						Any			)							->    int:

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_multiple_choice(*lowercase			)






			def 				A      (   self							:						List[str]			)							->    int:

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_question_answering(*lowercase			)






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

									'''simple docstring'''







									UpperCamelCase__         = self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_sequence_classification(*lowercase			)






			def 				A      (   self							:						Tuple			)							->    List[str]:

									'''simple docstring'''







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







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

									'''simple docstring'''







									for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCamelCase__         = AlbertModel.from_pretrained(lowercase			)
															self.assertIsNotNone(lowercase			)
@require_torch
class    _SCREAMING_SNAKE_CASE							(		unittest.TestCase	):


			'''simple docstring'''





			@slow
			def 				A      (   self							:						List[Any]			)							->    Optional[int]:

									'''simple docstring'''







									UpperCamelCase__         = AlbertModel.from_pretrained("""albert-base-v2"""			)
									UpperCamelCase__         = 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]]			)
									UpperCamelCase__         = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
									with torch.no_grad():
															UpperCamelCase__         = model(lowercase ,      attention_mask=lowercase			)[0]
									UpperCamelCase__         = torch.Size((1, 1_1, 7_6_8)			)
									self.assertEqual(output.shape ,      lowercase			)
									UpperCamelCase__         = torch.tensor(
									    [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]			)

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