






"""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:     List[Any]				,		__A:     int				,		__A:     List[str]=13				,		__A:     Any=7				,		__A:     Dict=True				,		__A:     Dict=True				,		__A:     int=True				,		__A:     Optional[Any]=True				,		__A:     Dict=99				,		__A:     List[str]=16				,		__A:     Dict=36				,		__A:     List[Any]=6				,		__A:     Optional[int]=6				,		__A:     str=6				,		__A:     Any=37				,		__A:     List[str]="gelu"				,		__A:     Union[str, Any]=0.1				,		__A:     Union[str, Any]=0.1				,		__A:     Optional[Any]=512				,		__A:     int=16				,		__A:     List[str]=2				,		__A:     List[Any]=0.0_2				,		__A:     Optional[int]=3				,		__A:     str=4				,		__A:     Dict=None				,		):

												'''simple docstring'''

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




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

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

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

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

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

												a__          =  self.get_config()

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




							def  lowercase		(   self:     Optional[int]    ):

												'''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:     Any				,		__A:     Tuple				,		__A:     List[str]				,		__A:     Union[str, Any]				,		__A:     int				,		__A:     Union[str, Any]				,		__A:     Tuple				,		__A:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  AlbertModel(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A				,		token_type_ids=__A    )
												a__          =  model(__A				,		token_type_ids=__A    )
												a__          =  model(__A    )
												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:     str				,		__A:     str				,		__A:     str				,		__A:     int				,		__A:     Tuple				,		__A:     Any				,		__A:     Optional[int]				,		__A:     Tuple    ):

												'''simple docstring'''

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

												'''simple docstring'''

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




							def  lowercase		(   self:     Any				,		__A:     Any				,		__A:     Tuple				,		__A:     Optional[Any]				,		__A:     Any				,		__A:     Optional[Any]				,		__A:     Tuple				,		__A:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  AlbertForQuestionAnswering(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(
												    __A				,		attention_mask=__A				,		token_type_ids=__A				,		start_positions=__A				,		end_positions=__A				,		)
												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:     List[str]				,		__A:     Union[str, Any]				,		__A:     int				,		__A:     Dict				,		__A:     Tuple				,		__A:     Union[str, Any]				,		__A:     List[Any]				,		__A:     str    ):

												'''simple docstring'''

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




							def  lowercase		(   self:     str				,		__A:     str				,		__A:     Union[str, Any]				,		__A:     Optional[int]				,		__A:     Tuple				,		__A:     Tuple				,		__A:     List[str]				,		__A:     Optional[int]    ):

												'''simple docstring'''

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




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

												'''simple docstring'''

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





							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

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







@require_torch
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE	    =(
							    (
							        AlbertModel,
							        AlbertForPreTraining,
							        AlbertForMaskedLM,
							        AlbertForMultipleChoice,
							        AlbertForSequenceClassification,
							        AlbertForTokenClassification,
							        AlbertForQuestionAnswering,
							    )
							    if is_torch_available()
							    else ()
							)
							_SCREAMING_SNAKE_CASE	    =(
							    {
							        'feature-extraction': AlbertModel,
							        'fill-mask': AlbertForMaskedLM,
							        'question-answering': AlbertForQuestionAnswering,
							        'text-classification': AlbertForSequenceClassification,
							        'token-classification': AlbertForTokenClassification,
							        'zero-shot': AlbertForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_SCREAMING_SNAKE_CASE	    =True




							def  lowercase		(   self:     Any				,		__A:     List[Any]				,		__A:     List[str]				,		__A:     Tuple=False    ):

												'''simple docstring'''

												a__          =  super()._prepare_for_class(__A				,		__A				,		return_labels=__A    )

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




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

												'''simple docstring'''

												a__          =  AlbertModelTester(self    )
												a__          =  ConfigTester(self				,		config_class=__A				,		hidden_size=37    )




							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												self.config_tester.run_common_tests()




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_pretraining(*__A    )




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_lm(*__A    )




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

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_multiple_choice(*__A    )




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*__A    )




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*__A    )




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

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





							@slow
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

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







@require_torch
class        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__          =  AlbertModel.from_pretrained('''albert-base-v2'''    )
												a__          =  torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]    )
												a__          =  torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]    )
												with torch.no_grad():
																	a__          =  model(__A				,		attention_mask=__A    )[0]
												a__          =  torch.Size((1, 11, 768)    )
												self.assertEqual(output.shape				,		__A    )
												a__          =  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]				,		__A				,		atol=1e-4    )    )










"""simple docstring"""







import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
	from .tokenization_albert import AlbertTokenizer
else:
	__a       :	int             = None

__a       :	List[str]             = logging.get_logger(__name__)
__a       :	Union[str, Any]             = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

__a       :	str             = {
    'vocab_file': {
        'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model',
        'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model',
        'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model',
        'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model',
        'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model',
        'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model',
        'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model',
        'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json',
        'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json',
        'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json',
        'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json',
        'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json',
        'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json',
        'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json',
        'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json',
    },
}

__a       :	Optional[int]             = {
    'albert-base-v1': 512,
    'albert-large-v1': 512,
    'albert-xlarge-v1': 512,
    'albert-xxlarge-v1': 512,
    'albert-base-v2': 512,
    'albert-large-v2': 512,
    'albert-xlarge-v2': 512,
    'albert-xxlarge-v2': 512,
}

__a       :	Union[str, Any]             = '▁'







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =VOCAB_FILES_NAMES
							_SCREAMING_SNAKE_CASE    =PRETRAINED_VOCAB_FILES_MAP
							_SCREAMING_SNAKE_CASE    =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_SCREAMING_SNAKE_CASE    =AlbertTokenizer




							def __init__(   self:     List[Any]				,		__A:     List[Any]=None				,		__A:     Tuple=None				,		__A:     Union[str, Any]=True				,		__A:     int=True				,		__A:     Optional[int]=False				,		__A:     List[Any]="[CLS]"				,		__A:     Optional[int]="[SEP]"				,		__A:     Union[str, Any]="<unk>"				,		__A:     int="[SEP]"				,		__A:     Optional[Any]="<pad>"				,		__A:     Optional[int]="[CLS]"				,		__A:     str="[MASK]"				,		**__A:     List[Any]				,		):

												'''simple docstring'''

												a__          =  (
												    AddedToken(__A				,		lstrip=__A				,		rstrip=__A				,		normalized=__A    )
												    if isinstance(__A				,		__A    )
												    else mask_token
												)

												super().__init__(
												    __A				,		tokenizer_file=__A				,		do_lower_case=__A				,		remove_space=__A				,		keep_accents=__A				,		bos_token=__A				,		eos_token=__A				,		unk_token=__A				,		sep_token=__A				,		pad_token=__A				,		cls_token=__A				,		mask_token=__A				,		**__A				,		)

												a__          =  do_lower_case
												a__          =  remove_space
												a__          =  keep_accents
												a__          =  vocab_file
												a__          =  False if not self.vocab_file else True




							def  lowercase		(   self:     Union[str, Any]				,		__A:     List[int]				,		__A:     Optional[List[int]] = None    ):

												'''simple docstring'''

												a__          =  [self.sep_token_id]
												a__          =  [self.cls_token_id]
												if token_ids_a is None:
																	return cls + token_ids_a + sep
												return cls + token_ids_a + sep + token_ids_a + sep




							def  lowercase		(   self:     List[Any]				,		__A:     List[int]				,		__A:     Optional[List[int]] = None    ):

												'''simple docstring'''

												a__          =  [self.sep_token_id]
												a__          =  [self.cls_token_id]

												if token_ids_a is None:
																	return len(cls + token_ids_a + sep    ) * [0]
												return len(cls + token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1]





							def  lowercase		(   self:     Union[str, Any]				,		__A:     str				,		__A:     Optional[str] = None    ):

												'''simple docstring'''

												if not self.can_save_slow_tokenizer:
																	raise ValueError(
																	    '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
																	    '''tokenizer.'''    )

												if not os.path.isdir(__A    ):
																	logger.error(F'Vocabulary path ({save_directory}) should be a directory'    )
																	return
												a__          =  os.path.join(
												    __A				,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']    )

												if os.path.abspath(self.vocab_file    ) != os.path.abspath(__A    ):
																	copyfile(self.vocab_file				,		__A    )

												return (out_vocab_file,)


