




"""simple docstring"""



import argparse
import logging
import os
import re

import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    PushToHubCallback,
    TFAutoModelForMaskedLM,
    create_optimizer,
)


SCREAMING_SNAKE_CASE    =	logging.getLogger(__name__)

SCREAMING_SNAKE_CASE    =	tf.data.AUTOTUNE







def   _SCREAMING_SNAKE_CASE       (							)						->		Union[str, Any]:
 A__	=    argparse.ArgumentParser(description="Train a masked language model on TPU."						)
 parser.add_argument(
     "--pretrained_model_config"      ,			type=a__      ,			default="roberta-base"      ,			help="The model config to use. Note that we don't copy the model's weights, only the config!"      ,			)
 parser.add_argument(
     "--tokenizer"      ,			type=a__      ,			default="unigram-tokenizer-wikitext"      ,			help="The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size."      ,			)

 parser.add_argument(
     "--per_replica_batch_size"      ,			type=a__      ,			default=8      ,			help="Batch size per TPU core."      ,			)

 parser.add_argument(
     "--no_tpu"      ,			action="store_true"      ,			help="If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances."      ,			)

 parser.add_argument(
     "--tpu_name"      ,			type=a__      ,			help="Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs."      ,			default="local"      ,			)

 parser.add_argument(
     "--tpu_zone"      ,			type=a__      ,			help="Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes."      ,			)

 parser.add_argument(
     "--gcp_project"      ,			type=a__      ,			help="Google cloud project name. Only used for non-Colab TPU nodes."						)

 parser.add_argument(
     "--bfloat16"      ,			action="store_true"      ,			help="Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU."      ,			)

 parser.add_argument(
     "--train_dataset"      ,			type=a__      ,			help="Path to training dataset to load. If the path begins with `gs://`"
     " then the dataset will be loaded from a Google Cloud Storage bucket."      ,			)

 parser.add_argument(
     "--shuffle_buffer_size"      ,			type=a__      ,			default=2**18      ,			help="Size of the shuffle buffer (in samples)"      ,			)

 parser.add_argument(
     "--eval_dataset"      ,			type=a__      ,			help="Path to evaluation dataset to load. If the path begins with `gs://`"
     " then the dataset will be loaded from a Google Cloud Storage bucket."      ,			)

 parser.add_argument(
     "--num_epochs"      ,			type=a__      ,			default=1      ,			help="Number of epochs to train for."      ,			)

 parser.add_argument(
     "--learning_rate"      ,			type=a__      ,			default=1E-4      ,			help="Learning rate to use for training."      ,			)

 parser.add_argument(
     "--weight_decay_rate"      ,			type=a__      ,			default=1E-3      ,			help="Weight decay rate to use for training."      ,			)

 parser.add_argument(
     "--max_length"      ,			type=a__      ,			default=5_12      ,			help="Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py"      ,			)

 parser.add_argument(
     "--mlm_probability"      ,			type=a__      ,			default=0.1_5      ,			help="Fraction of tokens to mask during training."      ,			)

 parser.add_argument("--output_dir"      ,			type=a__      ,			required=a__      ,			help="Path to save model checkpoints to."						)
 parser.add_argument("--hub_model_id"      ,			type=a__      ,			help="Model ID to upload to on the Hugging Face Hub."						)

 A__	=    parser.parse_args()
 return args







def   _SCREAMING_SNAKE_CASE       (							lowercase_						)						->		Union[str, Any]:

 try:
  if args.tpu_name:
   A__	=    tf.distribute.cluster_resolver.TPUClusterResolver(
       args.tpu_name      ,			zone=args.tpu_zone      ,			project=args.gcp_project						)
  else:
   A__	=    tf.distribute.cluster_resolver.TPUClusterResolver()
 except ValueError:
  raise RuntimeError(
      "Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or "
      "--gcp_project. When running on a TPU VM, use --tpu_name local."						)

 tf.config.experimental_connect_to_cluster(a__						)
 tf.tpu.experimental.initialize_tpu_system(a__						)

 return tpu







def   _SCREAMING_SNAKE_CASE       (							lowercase_						)						->		Any:
 A__	=    0
 for file in file_list:
  A__	=    file.split("/"						)[-1]
  A__	=    re.search(R"-\d+-(\d+)\.tfrecord"      ,			a__						).group(1						)
  A__	=    int(a__						)
  num_samples += sample_count

 return num_samples







def   _SCREAMING_SNAKE_CASE       (							lowercase_      ,			lowercase_      ,			lowercase_      ,			lowercase_      ,			lowercase_      ,			lowercase_=None						)						->		Optional[int]:
 A__	=    count_samples(a__						)
 A__	=    tf.data.Dataset.from_tensor_slices(a__						)
 if shuffle:
  A__	=    dataset.shuffle(len(a__						)						)
 A__	=    tf.data.TFRecordDataset(a__      ,			num_parallel_reads=a__						)
 # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here
 A__	=    dataset.apply(tf.data.experimental.assert_cardinality(a__						)						)
 A__	=    dataset.map(a__      ,			num_parallel_calls=a__						)
 if shuffle:
  assert shuffle_buffer_size is not None
  A__	=    dataset.shuffle(args.shuffle_buffer_size						)
 A__	=    dataset.batch(a__      ,			drop_remainder=a__						)
 A__	=    dataset.map(a__      ,			num_parallel_calls=a__						)
 A__	=    dataset.prefetch(a__						)
 return dataset







def   _SCREAMING_SNAKE_CASE       (							lowercase_						)						->		List[str]:

 if not args.no_tpu:
  A__	=    initialize_tpu(a__						)
  A__	=    tf.distribute.TPUStrategy(a__						)
 else:
  A__	=    tf.distribute.OneDeviceStrategy(device="/gpu:0"						)

 if args.bfloataa:
  tf.keras.mixed_precision.set_global_policy("mixed_bfloat16"						)

 A__	=    AutoTokenizer.from_pretrained(args.tokenizer						)
 A__	=    AutoConfig.from_pretrained(args.pretrained_model_config						)
 A__	=    tokenizer.vocab_size

 A__	=    tf.io.gfile.glob(os.path.join(args.train_dataset      ,			"*.tfrecord"						)						)
 if not training_records:
  raise ValueError(f"""No .tfrecord files found in {args.train_dataset}."""						)
 A__	=    tf.io.gfile.glob(os.path.join(args.eval_dataset      ,			"*.tfrecord"						)						)
 if not eval_records:
  raise ValueError(f"""No .tfrecord files found in {args.eval_dataset}."""						)

 A__	=    count_samples(a__						)

 A__	=    num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync)
 A__	=    steps_per_epoch * args.num_epochs

 with strategy.scope():
  A__	=    TFAutoModelForMaskedLM.from_config(a__						)
  model(model.dummy_inputs						)  # Pass some dummy inputs through the model to ensure all the weights are built
  A__,				A__	=    create_optimizer(
      num_train_steps=a__      ,			num_warmup_steps=total_train_steps // 20      ,			init_lr=args.learning_rate      ,			weight_decay_rate=args.weight_decay_rate      ,			)

  # Transformers models compute the right loss for their task by default when labels are passed, and will
  # use this for training unless you specify your own loss function in compile().
  model.compile(optimizer=a__      ,			metrics=["accuracy"]						)

 def decode_fn(lowercase_						):
  A__	=    {
      "input_ids": tf.io.FixedLenFeature(dtype=tf.intaa      ,			shape=(args.max_length,)						),
      "attention_mask": tf.io.FixedLenFeature(dtype=tf.intaa      ,			shape=(args.max_length,)						),
  }
  return tf.io.parse_single_example(a__      ,			a__						)

 # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can
 # use their methods in our data pipeline.
 A__	=    DataCollatorForLanguageModeling(
     tokenizer=a__      ,			mlm_probability=args.mlm_probability      ,			mlm=a__      ,			return_tensors="tf"						)

 def mask_with_collator(lowercase_						):
  # TF really needs an isin() function
  A__	=    (
      ~tf.cast(batch["attention_mask"]      ,			tf.bool						)
      | (batch["input_ids"] == tokenizer.cls_token_id)
      | (batch["input_ids"] == tokenizer.sep_token_id)
  )
  A__,				A__	=    data_collator.tf_mask_tokens(
      batch["input_ids"]      ,			vocab_size=len(a__						)      ,			mask_token_id=tokenizer.mask_token_id      ,			special_tokens_mask=a__      ,			)
  return batch

 A__	=    args.per_replica_batch_size * strategy.num_replicas_in_sync

 A__	=    prepare_dataset(
     a__      ,			decode_fn=a__      ,			mask_fn=a__      ,			batch_size=a__      ,			shuffle=a__      ,			shuffle_buffer_size=args.shuffle_buffer_size      ,			)

 A__	=    prepare_dataset(
     a__      ,			decode_fn=a__      ,			mask_fn=a__      ,			batch_size=a__      ,			shuffle=a__      ,			)

 A__	=    []
 if args.hub_model_id:
  callbacks.append(
      PushToHubCallback(output_dir=args.output_dir      ,			hub_model_id=args.hub_model_id      ,			tokenizer=a__						)						)

 model.fit(
     a__      ,			validation_data=a__      ,			epochs=args.num_epochs      ,			callbacks=a__      ,			)

 model.save_pretrained(args.output_dir						)


if __name__ == "__main__":
  SCREAMING_SNAKE_CASE    =	parse_args()
  main(args)











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




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




     '''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 							__magic_name__							(   self						:	Tuple				)				->							List[str]:




     '''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 							__magic_name__							(   self						:	int				)				->							Dict:




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




     '''simple docstring'''

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




     '''simple docstring'''

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




     '''simple docstring'''

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




    def 							__magic_name__							(   self						:	int     ,			snake_case_						:	Optional[Any]     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Optional[int]     ,			snake_case_						:	Any     ,			snake_case_						:	Tuple     ,			snake_case_						:	List[str]     ,			snake_case_						:	List[str]				)				->							Tuple:




     '''simple docstring'''

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




     '''simple docstring'''

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




    def 							__magic_name__							(   self						:	Tuple     ,			snake_case_						:	Dict     ,			snake_case_						:	int     ,			snake_case_						:	Union[str, Any]     ,			snake_case_						:	int     ,			snake_case_						:	str     ,			snake_case_						:	Optional[Any]     ,			snake_case_						:	Optional[Any]				)				->							List[str]:




     '''simple docstring'''

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




    def 							__magic_name__							(   self						:	Any     ,			snake_case_						:	Tuple     ,			snake_case_						:	Any     ,			snake_case_						:	Any     ,			snake_case_						:	Tuple     ,			snake_case_						:	Any     ,			snake_case_						:	Tuple     ,			snake_case_						:	Any				)				->							Optional[Any]:




     '''simple docstring'''

     A__	=    self.num_choices
     A__	=    AlbertForMultipleChoice(config=snake_case_				)
     model.to(snake_case_				)
     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(
         snake_case_     ,			attention_mask=snake_case_     ,			token_type_ids=snake_case_     ,			labels=snake_case_     ,			)
     self.parent.assertEqual(result.logits.shape     ,			(self.batch_size, self.num_choices)				)




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




     '''simple docstring'''

     A__	=    self.prepare_config_and_inputs()
     (
         (
         A__
     ),				(
         A__
     ),				(
         A__
     ),				(
         A__
     ),				(
         A__
     ),				(
         A__
     ),				(
         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      UpperCAmelCase_  (						A_,       A_,       unittest.TestCase							):
    lowercase__						 =				(
        (
            AlbertModel,
            AlbertForPreTraining,
            AlbertForMaskedLM,
            AlbertForMultipleChoice,
            AlbertForSequenceClassification,
            AlbertForTokenClassification,
            AlbertForQuestionAnswering,
        )
        if is_torch_available()
        else ()
    )
    lowercase__						 =				(
        {
            '''feature-extraction''': AlbertModel,
            '''fill-mask''': AlbertForMaskedLM,
            '''question-answering''': AlbertForQuestionAnswering,
            '''text-classification''': AlbertForSequenceClassification,
            '''token-classification''': AlbertForTokenClassification,
            '''zero-shot''': AlbertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    lowercase__						 =				True




    def 							__magic_name__							(   self						:	Tuple     ,			snake_case_						:	Dict     ,			snake_case_						:	Optional[Any]     ,			snake_case_						:	List[Any]=False				)				->							Optional[int]:




     '''simple docstring'''

     A__	=    super()._prepare_for_class(snake_case_     ,			snake_case_     ,			return_labels=snake_case_				)

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




    def 							__magic_name__							(   self						:	Dict				)				->							List[Any]:




     '''simple docstring'''

     A__	=    AlbertModelTester(self				)
     A__	=    ConfigTester(self     ,			config_class=snake_case_     ,			hidden_size=37				)




    def 							__magic_name__							(   self						:	Union[str, Any]				)				->							Optional[int]:




     '''simple docstring'''

     self.config_tester.run_common_tests()




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




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*snake_case_				)




    def 							__magic_name__							(   self						:	Optional[int]				)				->							Union[str, Any]:




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_pretraining(*snake_case_				)




    def 							__magic_name__							(   self						:	int				)				->							str:




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_lm(*snake_case_				)




    def 							__magic_name__							(   self						:	Any				)				->							str:




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_multiple_choice(*snake_case_				)




    def 							__magic_name__							(   self						:	Optional[Any]				)				->							Any:




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(*snake_case_				)




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




     '''simple docstring'''

     A__	=    self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(*snake_case_				)




    def 							__magic_name__							(   self						:	List[str]				)				->							Optional[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(*snake_case_				)




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




     '''simple docstring'''

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






@require_torch
class      UpperCAmelCase_  (						unittest.TestCase							):




    @slow
    def 							__magic_name__							(   self						:	int				)				->							Tuple:




     '''simple docstring'''

     A__	=    AlbertModel.from_pretrained("albert-base-v2"				)
     A__	=    torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]				)
     A__	=    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]				)
     with torch.no_grad():
      A__	=    model(snake_case_     ,			attention_mask=snake_case_				)[0]
     A__	=    torch.Size((1, 11, 768)				)
     self.assertEqual(output.shape     ,			snake_case_				)
     A__	=    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]     ,			snake_case_     ,			atol=1e-4				)				)





