






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					:






						def __init__(	self     ,						_UpperCamelCase     ,						_UpperCamelCase=13     ,						_UpperCamelCase=7     ,						_UpperCamelCase=True     ,						_UpperCamelCase=True     ,						_UpperCamelCase=True     ,						_UpperCamelCase=True     ,						_UpperCamelCase=99     ,						_UpperCamelCase=16     ,						_UpperCamelCase=36     ,						_UpperCamelCase=6     ,						_UpperCamelCase=6     ,						_UpperCamelCase=6     ,						_UpperCamelCase=37     ,						_UpperCamelCase="gelu"     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=5_12     ,						_UpperCamelCase=16     ,						_UpperCamelCase=2     ,						_UpperCamelCase=0.02     ,						_UpperCamelCase=3     ,						_UpperCamelCase=4     ,						_UpperCamelCase=None     ,						):






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






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						ids_tensor([self.batch_size, self.seq_length]     ,						self.vocab_size   )

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

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

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

												lowerCAmelCase__    						=						self.get_config()

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






						def       UpperCamelCase__      (	self   ):






												"""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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertModel(config=_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						model(_lowercase     ,						attention_mask=_lowercase     ,						token_type_ids=_lowercase   )
												lowerCAmelCase__    						=						model(_lowercase     ,						token_type_ids=_lowercase   )
												lowerCAmelCase__    						=						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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertForPreTraining(config=_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertForMaskedLM(config=_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertForQuestionAnswering(config=_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.num_labels
												lowerCAmelCase__    						=						AlbertForSequenceClassification(_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						model(_lowercase     ,						attention_mask=_lowercase     ,						token_type_ids=_lowercase     ,						labels=_lowercase   )
												self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_labels)   )






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.num_labels
												lowerCAmelCase__    						=						AlbertForTokenClassification(config=_lowercase   )
												model.to(_lowercase   )
												model.eval()
												lowerCAmelCase__    						=						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       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






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







						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.prepare_config_and_inputs()
												(
												    lowerCAmelCase__      
												)    						=						config_and_inputs
												lowerCAmelCase__    						=						{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
												return config, inputs_dict




@require_torch
class     __SCREAMING_SNAKE_CASE					(   UpperCAmelCase_		,					UpperCAmelCase_		,					unittest.TestCase):
						_SCREAMING_SNAKE_CASE	:       Optional[Any]   =					(
						    (
						        AlbertModel,
						        AlbertForPreTraining,
						        AlbertForMaskedLM,
						        AlbertForMultipleChoice,
						        AlbertForSequenceClassification,
						        AlbertForTokenClassification,
						        AlbertForQuestionAnswering,
						    )
						    if is_torch_available()
						    else ()
						)
						_SCREAMING_SNAKE_CASE	:       Union[str, Any]   =					(
						    {
						        '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	:       Optional[Any]   =					True






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase=False   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						super()._prepare_for_class(_lowercase     ,						_lowercase     ,						return_labels=_lowercase   )

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






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertModelTester(self   )
												lowerCAmelCase__    						=						ConfigTester(self     ,						config_class=_lowercase     ,						hidden_size=37   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												self.config_tester.run_common_tests()






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_pretraining(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_lm(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_multiple_choice(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*_lowercase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												for type in ["absolute", "relative_key", "relative_key_query"]:
																		lowerCAmelCase__    						=						type
																		self.model_tester.create_and_check_model(*_lowercase   )







						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowerCAmelCase__    						=						AlbertModel.from_pretrained(_lowercase   )
																		self.assertIsNotNone(_lowercase   )




@require_torch
class     __SCREAMING_SNAKE_CASE					(   unittest.TestCase):






						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AlbertModel.from_pretrained('albert-base-v2'   )
												lowerCAmelCase__    						=						torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]   )
												lowerCAmelCase__    						=						torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]   )
												with torch.no_grad():
																		lowerCAmelCase__    						=						model(_lowercase     ,						attention_mask=_lowercase   )[0]
												lowerCAmelCase__    						=						torch.Size((1, 11, 7_68)   )
												self.assertEqual(output.shape     ,						_lowercase   )
												lowerCAmelCase__    						=						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]     ,						_lowercase     ,						atol=1E-4   )   )













# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
# This gives ~3MB in total for all files.
#
# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
#
#
# It will be used then as "stas/tiny-wmt19-en-de"

# Build
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration

__snake_case    :    Optional[int]         =     """facebook/wmt19-en-de"""
__snake_case    :    Optional[Any]         =     FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
__snake_case    :    List[str]         =     FSMTConfig.from_pretrained(mname)
config.update(
    dict(
        d_model=4,
        encoder_layers=1,
        decoder_layers=1,
        encoder_ffn_dim=4,
        decoder_ffn_dim=4,
        encoder_attention_heads=1,
        decoder_attention_heads=1,
    )
)

__snake_case    :    Optional[Any]         =     FSMTForConditionalGeneration(config)
print(f'num of params {tiny_model.num_parameters()}')

# Test
__snake_case    :    List[Any]         =     tokenizer(["""Making tiny model"""], return_tensors="""pt""")
__snake_case    :    Any         =     tiny_model(**batch)

print("""test output:""", len(outputs.logits[0]))

# Save
__snake_case    :    Any         =     """tiny-wmt19-en-de"""
tiny_model.half()  # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)

print(f'Generated {mname_tiny}')

# Upload
# transformers-cli upload tiny-wmt19-en-de





