


'''simple docstring'''




import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


UpperCAmelCase_      :		List[Any]          =		logging.getLogger(__name__)







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: Optional[int]							  =		"""summarization"""
 __lowerCAmelCase						: str							  =		["""loss"""]
 __lowerCAmelCase						: Optional[int]							  =		ROUGE_KEYS
 __lowerCAmelCase						: Any							  =		"""rouge2"""




 def __init__(    self		,      lowerCamelCase_		,      **lowerCamelCase_      )      ->    str:
    if hparams.sortish_sampler and hparams.gpus > 1:
       _a					:  List[str]						=  False
    elif hparams.max_tokens_per_batch is not None:
       if hparams.gpus > 1:
          raise NotImplementedError('Dynamic Batch size does not work for multi-gpu training'      )
       if hparams.sortish_sampler:
          raise ValueError('--sortish_sampler and --max_tokens_per_batch may not be used simultaneously'      )

    super().__init__(lowerCamelCase_		,      num_labels=lowerCamelCase_		,      mode=self.mode		,      **lowerCamelCase_      )
    use_task_specific_params(self.model		,      'summarization'      )
    save_git_info(self.hparams.output_dir      )
    _a					:  List[str]						=  Path(self.output_dir      ) / 'metrics.json'
    _a					:  Optional[Any]						=  Path(self.output_dir      ) / 'hparams.pkl'
    pickle_save(self.hparams		,      self.hparams_save_path      )
    _a					:  Union[str, Any]						=  0
    _a					:  Any						=  defaultdict(lowerCamelCase_      )
    _a					:  List[str]						=  self.config.model_type
    _a					:  List[Any]						=  self.config.tgt_vocab_size if self.model_type == 'fsmt' else self.config.vocab_size

    _a					:  dict						=  {
        "data_dir": self.hparams.data_dir,
        "max_source_length": self.hparams.max_source_length,
        "prefix": self.model.config.prefix or "",
    }
    _a					:  List[Any]						=  {
        'train': self.hparams.n_train,
        'val': self.hparams.n_val,
        'test': self.hparams.n_test,
    }
    _a					:  Optional[int]						=  {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

    _a					:  Optional[Any]						=  {
        'train': self.hparams.max_target_length,
        'val': self.hparams.val_max_target_length,
        'test': self.hparams.test_max_target_length,
    }
    assert self.target_lens["train"] <= self.target_lens["val"], F'''target_lens: {self.target_lens}'''
    assert self.target_lens["train"] <= self.target_lens["test"], F'''target_lens: {self.target_lens}'''
    if self.hparams.freeze_embeds:
       freeze_embeds(self.model      )
    if self.hparams.freeze_encoder:
       freeze_params(self.model.get_encoder()      )
       assert_all_frozen(self.model.get_encoder()      )

    _a					:  Optional[Any]						=  get_git_info()['repo_sha']
    _a					:  str						=  hparams.num_workers
    _a					:  Optional[int]						=  None  # default to config
    if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer		,      lowerCamelCase_      ):
       _a					:  Tuple						=  self.tokenizer.lang_code_to_id[hparams.tgt_lang]
       _a					:  Union[str, Any]						=  self.decoder_start_token_id
    _a					:  Any						=  (
        SeqaSeqDataset if hasattr(self.tokenizer		,      'prepare_seq2seq_batch'      ) else LegacySeqaSeqDataset
    )
    _a					:  List[Any]						=  False
    _a					:  Tuple						=  self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
    if self.hparams.eval_max_gen_length is not None:
       _a					:  int						=  self.hparams.eval_max_gen_length
    else:
       _a					:  List[Any]						=  self.model.config.max_length
    _a					:  List[str]						=  self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    Dict[str, List[str]]:
    _a					:  int						=  {
        k: self.tokenizer.batch_decode(v.tolist()      ) if 'mask' not in k else v.shape for k, v in batch.items()
    }
    save_json(lowerCamelCase_		,      Path(self.output_dir      ) / 'text_batch.json'      )
    save_json({k: v.tolist() for k, v in batch.items()}		,      Path(self.output_dir      ) / 'tok_batch.json'      )

    _a					:  str						=  True
    return readable_batch




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      **lowerCamelCase_      )      ->    int:
    return self.model(lowerCamelCase_		,      **lowerCamelCase_      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    Tuple:
    _a					:  Optional[Any]						=  self.tokenizer.batch_decode(
        lowerCamelCase_		,      skip_special_tokens=lowerCamelCase_		,      clean_up_tokenization_spaces=lowerCamelCase_      )
    return lmap(str.strip		,      lowerCamelCase_      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    Tuple:
    _a					:  Optional[Any]						=  self.tokenizer.pad_token_id
    _a		,						_a					:  List[str]						=  batch['input_ids'], batch['attention_mask']
    _a					:  Union[str, Any]						=  batch['labels']
    if isinstance(self.model		,      lowerCamelCase_      ):
       _a					:  Optional[int]						=  self.model._shift_right(lowerCamelCase_      )
    else:
       _a					:  Optional[Any]						=  shift_tokens_right(lowerCamelCase_		,      lowerCamelCase_      )
    if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
       _a					:  Dict						=  decoder_input_ids
       self.save_readable_batch(lowerCamelCase_      )

    _a					:  Tuple						=  self(lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      decoder_input_ids=lowerCamelCase_		,      use_cache=lowerCamelCase_      )
    _a					:  str						=  outputs['logits']
    if self.hparams.label_smoothing == 0:
       # Same behavior as modeling_bart.py, besides ignoring pad_token_id
       _a					:  str						=  nn.CrossEntropyLoss(ignore_index=lowerCamelCase_      )

       assert lm_logits.shape[-1] == self.vocab_size
       _a					:  Dict						=  ce_loss_fct(lm_logits.view(-1		,      lm_logits.shape[-1]      )		,      tgt_ids.view(-1      )      )
    else:
       _a					:  Tuple						=  nn.functional.log_softmax(lowerCamelCase_		,      dim=-1      )
       _a		,						_a					:  Optional[int]						=  label_smoothed_nll_loss(
           lowerCamelCase_		,      lowerCamelCase_		,      self.hparams.label_smoothing		,      ignore_index=lowerCamelCase_      )
    return (loss,)




 @property
 def   __UpperCamelCase   (    self      )      ->    int:
    return self.tokenizer.pad_token_id




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Dict:
    _a					:  int						=  self._step(lowerCamelCase_      )

    _a					:  Any						=  dict(zip(self.loss_names		,      lowerCamelCase_      )      )
    # tokens per batch
    _a					:  int						=  batch['input_ids'].ne(self.pad      ).sum() + batch['labels'].ne(self.pad      ).sum()
    _a					:  List[str]						=  batch['input_ids'].shape[0]
    _a					:  str						=  batch['input_ids'].eq(self.pad      ).sum()
    _a					:  List[str]						=  batch['input_ids'].eq(self.pad      ).float().mean()
    # TODO(SS): make a wandb summary metric for this
    return {"loss": loss_tensors[0], "log": logs}




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Dict:
    return self._generative_step(lowerCamelCase_      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_="val"      )      ->    Dict:
    self.step_count += 1
    _a					:  Union[str, Any]						=  {k: torch.stack([x[k] for x in outputs]      ).mean() for k in self.loss_names}
    _a					:  Optional[int]						=  losses['loss']
    _a					:  Dict						=  {
        k: np.array([x[k] for x in outputs]      ).mean() for k in self.metric_names + ['gen_time', 'gen_len']
    }
    _a					:  str						=  (
        generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
    )
    _a					:  torch.FloatTensor						=  torch.tensor(lowerCamelCase_      ).type_as(lowerCamelCase_      )
    generative_metrics.update({k: v.item() for k, v in losses.items()}      )
    losses.update(lowerCamelCase_      )
    _a					:  Optional[int]						=  {F'''{prefix}_avg_{k}''': x for k, x in losses.items()}
    _a					:  List[str]						=  self.step_count
    self.metrics[prefix].append(lowerCamelCase_      )  # callback writes this to self.metrics_save_path
    _a					:  Tuple						=  flatten_list([x['preds'] for x in outputs]      )
    return {
        "log": all_metrics,
        "preds": preds,
        F'''{prefix}_loss''': loss,
        F'''{prefix}_{self.val_metric}''': metric_tensor,
    }




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Dict:
    return calculate_rouge(lowerCamelCase_		,      lowerCamelCase_      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    dict:
    _a					:  Union[str, Any]						=  time.time()

    # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
    _a					:  Optional[int]						=  self.model.generate(
        batch['input_ids']		,      attention_mask=batch['attention_mask']		,      use_cache=lowerCamelCase_		,      decoder_start_token_id=self.decoder_start_token_id		,      num_beams=self.eval_beams		,      max_length=self.eval_max_length		,      )
    _a					:  str						=  (time.time() - ta) / batch['input_ids'].shape[0]
    _a					:  List[str]						=  self.ids_to_clean_text(lowerCamelCase_      )
    _a					:  List[str]						=  self.ids_to_clean_text(batch['labels']      )
    _a					:  List[Any]						=  self._step(lowerCamelCase_      )
    _a					:  int						=  dict(zip(self.loss_names		,      lowerCamelCase_      )      )
    _a					:  Dict						=  self.calc_generative_metrics(lowerCamelCase_		,      lowerCamelCase_      )
    _a					:  Any						=  np.mean(lmap(lowerCamelCase_		,      lowerCamelCase_      )      )
    base_metrics.update(gen_time=lowerCamelCase_		,      gen_len=lowerCamelCase_		,      preds=lowerCamelCase_		,      target=lowerCamelCase_		,      **lowerCamelCase_      )
    return base_metrics




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    str:
    return self._generative_step(lowerCamelCase_      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    Tuple:
    return self.validation_epoch_end(lowerCamelCase_		,      prefix='test'      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    SeqaSeqDataset:
    _a					:  Union[str, Any]						=  self.n_obs[type_path]
    _a					:  str						=  self.target_lens[type_path]
    _a					:  Union[str, Any]						=  self.dataset_class(
        self.tokenizer		,      type_path=lowerCamelCase_		,      n_obs=lowerCamelCase_		,      max_target_length=lowerCamelCase_		,      **self.dataset_kwargs		,      )
    return dataset




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_ = False      )      ->    DataLoader:
    _a					:  Optional[int]						=  self.get_dataset(lowerCamelCase_      )

    if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
       _a					:  Tuple						=  dataset.make_sortish_sampler(lowerCamelCase_		,      distributed=self.hparams.gpus > 1      )
       return DataLoader(
           lowerCamelCase_		,      batch_size=lowerCamelCase_		,      collate_fn=dataset.collate_fn		,      shuffle=lowerCamelCase_		,      num_workers=self.num_workers		,      sampler=lowerCamelCase_		,      )

    elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
       _a					:  Union[str, Any]						=  dataset.make_dynamic_sampler(
           self.hparams.max_tokens_per_batch		,      distributed=self.hparams.gpus > 1      )
       return DataLoader(
           lowerCamelCase_		,      batch_sampler=lowerCamelCase_		,      collate_fn=dataset.collate_fn		,      num_workers=self.num_workers		,      )
    else:
       return DataLoader(
           lowerCamelCase_		,      batch_size=lowerCamelCase_		,      collate_fn=dataset.collate_fn		,      shuffle=lowerCamelCase_		,      num_workers=self.num_workers		,      sampler=lowerCamelCase_		,      )




 def   __UpperCamelCase   (    self      )      ->    DataLoader:
    _a					:  Tuple						=  self.get_dataloader('train'		,      batch_size=self.hparams.train_batch_size		,      shuffle=lowerCamelCase_      )
    return dataloader




 def   __UpperCamelCase   (    self      )      ->    DataLoader:
    return self.get_dataloader('val'		,      batch_size=self.hparams.eval_batch_size      )




 def   __UpperCamelCase   (    self      )      ->    DataLoader:
    return self.get_dataloader('test'		,      batch_size=self.hparams.eval_batch_size      )




 @staticmethod
 def   __UpperCamelCase   (    lowerCamelCase_		,      lowerCamelCase_      )      ->    Tuple:
    BaseTransformer.add_model_specific_args(lowerCamelCase_		,      lowerCamelCase_      )
    add_generic_args(lowerCamelCase_		,      lowerCamelCase_      )
    parser.add_argument(
        '--max_source_length'		,      default=1_0_2_4		,      type=lowerCamelCase_		,      help=(
            'The maximum total input sequence length after tokenization. Sequences longer '
            'than this will be truncated, sequences shorter will be padded.'
        )		,      )
    parser.add_argument(
        '--max_target_length'		,      default=5_6		,      type=lowerCamelCase_		,      help=(
            'The maximum total input sequence length after tokenization. Sequences longer '
            'than this will be truncated, sequences shorter will be padded.'
        )		,      )
    parser.add_argument(
        '--val_max_target_length'		,      default=1_4_2		,      type=lowerCamelCase_		,      help=(
            'The maximum total input sequence length after tokenization. Sequences longer '
            'than this will be truncated, sequences shorter will be padded.'
        )		,      )
    parser.add_argument(
        '--test_max_target_length'		,      default=1_4_2		,      type=lowerCamelCase_		,      help=(
            'The maximum total input sequence length after tokenization. Sequences longer '
            'than this will be truncated, sequences shorter will be padded.'
        )		,      )
    parser.add_argument('--freeze_encoder'		,      action='store_true'      )
    parser.add_argument('--freeze_embeds'		,      action='store_true'      )
    parser.add_argument('--sortish_sampler'		,      action='store_true'		,      default=lowerCamelCase_      )
    parser.add_argument('--overwrite_output_dir'		,      action='store_true'		,      default=lowerCamelCase_      )
    parser.add_argument('--max_tokens_per_batch'		,      type=lowerCamelCase_		,      default=lowerCamelCase_      )
    parser.add_argument('--logger_name'		,      type=lowerCamelCase_		,      choices=['default', 'wandb', 'wandb_shared']		,      default='default'      )
    parser.add_argument('--n_train'		,      type=lowerCamelCase_		,      default=-1		,      required=lowerCamelCase_		,      help='# examples. -1 means use all.'      )
    parser.add_argument('--n_val'		,      type=lowerCamelCase_		,      default=5_0_0		,      required=lowerCamelCase_		,      help='# examples. -1 means use all.'      )
    parser.add_argument('--n_test'		,      type=lowerCamelCase_		,      default=-1		,      required=lowerCamelCase_		,      help='# examples. -1 means use all.'      )
    parser.add_argument(
        '--task'		,      type=lowerCamelCase_		,      default='summarization'		,      required=lowerCamelCase_		,      help='# examples. -1 means use all.'      )
    parser.add_argument('--label_smoothing'		,      type=lowerCamelCase_		,      default=0.0		,      required=lowerCamelCase_      )
    parser.add_argument('--src_lang'		,      type=lowerCamelCase_		,      default=''		,      required=lowerCamelCase_      )
    parser.add_argument('--tgt_lang'		,      type=lowerCamelCase_		,      default=''		,      required=lowerCamelCase_      )
    parser.add_argument('--eval_beams'		,      type=lowerCamelCase_		,      default=lowerCamelCase_		,      required=lowerCamelCase_      )
    parser.add_argument(
        '--val_metric'		,      type=lowerCamelCase_		,      default=lowerCamelCase_		,      required=lowerCamelCase_		,      choices=['bleu', 'rouge2', 'loss', None]      )
    parser.add_argument('--eval_max_gen_length'		,      type=lowerCamelCase_		,      default=lowerCamelCase_		,      help='never generate more than n tokens'      )
    parser.add_argument('--save_top_k'		,      type=lowerCamelCase_		,      default=1		,      required=lowerCamelCase_		,      help='How many checkpoints to save'      )
    parser.add_argument(
        '--early_stopping_patience'		,      type=lowerCamelCase_		,      default=-1		,      required=lowerCamelCase_		,      help=(
            '-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So'
            ' val_check_interval will effect it.'
        )		,      )
    return parser







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: Optional[Any]							  =		"""translation"""
 __lowerCAmelCase						: Union[str, Any]							  =		["""loss"""]
 __lowerCAmelCase						: str							  =		["""bleu"""]
 __lowerCAmelCase						: Optional[int]							  =		"""bleu"""




 def __init__(    self		,      lowerCamelCase_		,      **lowerCamelCase_      )      ->    str:
    super().__init__(lowerCamelCase_		,      **lowerCamelCase_      )
    _a					:  Tuple						=  hparams.src_lang
    _a					:  Tuple						=  hparams.tgt_lang




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    dict:
    return calculate_bleu(lowerCamelCase_		,      lowerCamelCase_      )





def    UpperCAmelCase_  (       A		,	A=None      ):
   '''simple docstring'''





   Path(args.output_dir      ).mkdir(exist_ok=A      )
   check_output_dir(A		,	expected_items=3      )

   if model is None:
      if "summarization" in args.task:
         _a					:  SummarizationModule						=  SummarizationModule(A      )
      else:
         _a					:  SummarizationModule						=  TranslationModule(A      )
   _a					:  Dict						=  Path(args.data_dir      ).name
   if (
       args.logger_name == "default"
       or args.fast_dev_run
       or str(args.output_dir      ).startswith('/tmp'      )
       or str(args.output_dir      ).startswith('/var'      )
   ):
      _a					:  Union[str, Any]						=  True  # don't pollute wandb logs unnecessarily
   elif args.logger_name == "wandb":
      from pytorch_lightning.loggers import WandbLogger

      _a					:  List[Any]						=  os.environ.get('WANDB_PROJECT'		,	A      )
      _a					:  Any						=  WandbLogger(name=model.output_dir.name		,	project=A      )

   elif args.logger_name == "wandb_shared":
      from pytorch_lightning.loggers import WandbLogger

      _a					:  Union[str, Any]						=  WandbLogger(name=model.output_dir.name		,	project=f'''hf_{dataset}'''      )

   if args.early_stopping_patience >= 0:
      _a					:  Tuple						=  get_early_stopping_callback(model.val_metric		,	args.early_stopping_patience      )
   else:
      _a					:  Any						=  False

   _a					:  Union[str, Any]						=  args.val_metric == 'loss'
   _a					:  pl.Trainer						=  generic_train(
       A		,	A		,	logging_callback=SeqaSeqLoggingCallback()		,	checkpoint_callback=get_checkpoint_callback(
           args.output_dir		,	model.val_metric		,	args.save_top_k		,	A      )		,	early_stopping_callback=A		,	logger=A		,	)
   pickle_save(model.hparams		,	model.output_dir / 'hparams.pkl'      )
   if not args.do_predict:
      return model

   _a					:  List[Any]						=  ''
   _a					:  Tuple						=  sorted(glob.glob(os.path.join(args.output_dir		,	'*.ckpt'      )		,	recursive=A      )      )
   if checkpoints:
      _a					:  int						=  checkpoints[-1]
      _a					:  List[Any]						=  checkpoints[-1]
   trainer.logger.log_hyperparams(model.hparams      )

   # test() without a model tests using the best checkpoint automatically
   trainer.test()
   return model


if __name__ == "__main__":
 UpperCAmelCase_      :		int          =		argparse.ArgumentParser()
 UpperCAmelCase_      :		Optional[Any]          =		pl.Trainer.add_argparse_args(parser)
 UpperCAmelCase_      :		Optional[Any]          =		SummarizationModule.add_model_specific_args(parser, os.getcwd())

 UpperCAmelCase_      :		int          =		parser.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 					a			:
 '''simple docstring'''




 def __init__(    self		,      lowerCamelCase_		,      lowerCamelCase_=1_3		,      lowerCamelCase_=7		,      lowerCamelCase_=True		,      lowerCamelCase_=True		,      lowerCamelCase_=True		,      lowerCamelCase_=True		,      lowerCamelCase_=9_9		,      lowerCamelCase_=1_6		,      lowerCamelCase_=3_6		,      lowerCamelCase_=6		,      lowerCamelCase_=6		,      lowerCamelCase_=6		,      lowerCamelCase_=3_7		,      lowerCamelCase_="gelu"		,      lowerCamelCase_=0.1		,      lowerCamelCase_=0.1		,      lowerCamelCase_=5_1_2		,      lowerCamelCase_=1_6		,      lowerCamelCase_=2		,      lowerCamelCase_=0.02		,      lowerCamelCase_=3		,      lowerCamelCase_=4		,      lowerCamelCase_=None		,      )      ->    Dict:
    _a					:  Dict						=  parent
    _a					:  Tuple						=  batch_size
    _a					:  Optional[int]						=  seq_length
    _a					:  List[str]						=  is_training
    _a					:  Tuple						=  use_input_mask
    _a					:  Dict						=  use_token_type_ids
    _a					:  List[str]						=  use_labels
    _a					:  Optional[int]						=  vocab_size
    _a					:  int						=  embedding_size
    _a					:  Tuple						=  hidden_size
    _a					:  str						=  num_hidden_layers
    _a					:  List[str]						=  num_hidden_groups
    _a					:  Union[str, Any]						=  num_attention_heads
    _a					:  Dict						=  intermediate_size
    _a					:  List[str]						=  hidden_act
    _a					:  Tuple						=  hidden_dropout_prob
    _a					:  Any						=  attention_probs_dropout_prob
    _a					:  Tuple						=  max_position_embeddings
    _a					:  Dict						=  type_vocab_size
    _a					:  Tuple						=  type_sequence_label_size
    _a					:  Dict						=  initializer_range
    _a					:  str						=  num_labels
    _a					:  Optional[Any]						=  num_choices
    _a					:  Optional[int]						=  scope




 def   __UpperCamelCase   (    self      )      ->    Optional[int]:
    _a					:  Optional[int]						=  ids_tensor([self.batch_size, self.seq_length]		,      self.vocab_size      )

    _a					:  List[str]						=  None
    if self.use_input_mask:
       _a					:  Tuple						=  random_attention_mask([self.batch_size, self.seq_length]      )

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

    _a					:  List[str]						=  None
    _a					:  Optional[int]						=  None
    _a					:  List[Any]						=  None
    if self.use_labels:
       _a					:  Optional[int]						=  ids_tensor([self.batch_size]		,      self.type_sequence_label_size      )
       _a					:  Any						=  ids_tensor([self.batch_size, self.seq_length]		,      self.num_labels      )
       _a					:  str						=  ids_tensor([self.batch_size]		,      self.num_choices      )

    _a					:  int						=  self.get_config()

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




 def   __UpperCamelCase   (    self      )      ->    Any:
    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		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    List[str]:
    _a					:  str						=  AlbertModel(config=lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  Tuple						=  model(lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_      )
    _a					:  Dict						=  model(lowerCamelCase_		,      token_type_ids=lowerCamelCase_      )
    _a					:  List[str]						=  model(lowerCamelCase_      )
    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		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Any:
    _a					:  Optional[int]						=  AlbertForPreTraining(config=lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  Optional[Any]						=  model(
        lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_		,      labels=lowerCamelCase_		,      sentence_order_label=lowerCamelCase_		,      )
    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		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Tuple:
    _a					:  Union[str, Any]						=  AlbertForMaskedLM(config=lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  int						=  model(lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_		,      labels=lowerCamelCase_      )
    self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size)      )




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Tuple:
    _a					:  Union[str, Any]						=  AlbertForQuestionAnswering(config=lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  Tuple						=  model(
        lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_		,      start_positions=lowerCamelCase_		,      end_positions=lowerCamelCase_		,      )
    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		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    int:
    _a					:  str						=  self.num_labels
    _a					:  str						=  AlbertForSequenceClassification(lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  str						=  model(lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_		,      labels=lowerCamelCase_      )
    self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)      )




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




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_      )      ->    Union[str, Any]:
    _a					:  Optional[int]						=  self.num_choices
    _a					:  Any						=  AlbertForMultipleChoice(config=lowerCamelCase_      )
    model.to(lowerCamelCase_      )
    model.eval()
    _a					:  str						=  input_ids.unsqueeze(1      ).expand(-1		,      self.num_choices		,      -1      ).contiguous()
    _a					:  Dict						=  token_type_ids.unsqueeze(1      ).expand(-1		,      self.num_choices		,      -1      ).contiguous()
    _a					:  List[Any]						=  input_mask.unsqueeze(1      ).expand(-1		,      self.num_choices		,      -1      ).contiguous()
    _a					:  Optional[Any]						=  model(
        lowerCamelCase_		,      attention_mask=lowerCamelCase_		,      token_type_ids=lowerCamelCase_		,      labels=lowerCamelCase_		,      )
    self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_choices)      )




 def   __UpperCamelCase   (    self      )      ->    Optional[Any]:
    _a					:  Optional[int]						=  self.prepare_config_and_inputs()
    (
        (
        _a
    )		,						(
        _a
    )		,						(
        _a
    )		,						(
        _a
    )		,						(
        _a
    )		,						(
        _a
    )		,						(
        _a
    )		,						
    )					:  Optional[int]						=  config_and_inputs
    _a					:  Optional[Any]						=  {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
    return config, inputs_dict







@require_torch
class 					a			(				snake_case__			,							snake_case__			,							unittest.TestCase  ):
 '''simple docstring'''




 __lowerCAmelCase						: str							  =		(
     (
         AlbertModel,
         AlbertForPreTraining,
         AlbertForMaskedLM,
         AlbertForMultipleChoice,
         AlbertForSequenceClassification,
         AlbertForTokenClassification,
         AlbertForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 __lowerCAmelCase						: 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 {}
 )
 __lowerCAmelCase						: Optional[int]							  =		True




 def   __UpperCamelCase   (    self		,      lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_=False      )      ->    List[str]:
    _a					:  Optional[Any]						=  super()._prepare_for_class(lowerCamelCase_		,      lowerCamelCase_		,      return_labels=lowerCamelCase_      )

    if return_labels:
       if model_class in get_values(lowerCamelCase_      ):
          _a					:  str						=  torch.zeros(
              (self.model_tester.batch_size, self.model_tester.seq_length)		,      dtype=torch.long		,      device=lowerCamelCase_      )
          _a					:  int						=  torch.zeros(
              self.model_tester.batch_size		,      dtype=torch.long		,      device=lowerCamelCase_      )
    return inputs_dict




 def   __UpperCamelCase   (    self      )      ->    List[Any]:
    _a					:  int						=  AlbertModelTester(self      )
    _a					:  Union[str, Any]						=  ConfigTester(self		,      config_class=lowerCamelCase_		,      hidden_size=3_7      )




 def   __UpperCamelCase   (    self      )      ->    Tuple:
    self.config_tester.run_common_tests()




 def   __UpperCamelCase   (    self      )      ->    Optional[int]:
    _a					:  Tuple						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Tuple:
    _a					:  str						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Any:
    _a					:  Optional[int]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Union[str, Any]:
    _a					:  Any						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Tuple:
    _a					:  Union[str, Any]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Union[str, Any]:
    _a					:  Optional[int]						=  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_      )




 def   __UpperCamelCase   (    self      )      ->    Dict:
    _a					:  str						=  self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
       _a					:  Optional[Any]						=  type
       self.model_tester.create_and_check_model(*lowerCamelCase_      )




 @slow
 def   __UpperCamelCase   (    self      )      ->    Optional[Any]:
    for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _a					:  int						=  AlbertModel.from_pretrained(lowerCamelCase_      )
       self.assertIsNotNone(lowerCamelCase_      )







@require_torch
class 					a			(				unittest.TestCase  ):
 '''simple docstring'''




 @slow
 def   __UpperCamelCase   (    self      )      ->    Union[str, Any]:
    _a					:  Dict						=  AlbertModel.from_pretrained('albert-base-v2'      )
    _a					:  Optional[Any]						=  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]]      )
    _a					:  List[str]						=  torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]      )
    with torch.no_grad():
       _a					:  int						=  model(lowerCamelCase_		,      attention_mask=lowerCamelCase_      )[0]
    _a					:  str						=  torch.Size((1, 1_1, 7_6_8)      )
    self.assertEqual(output.shape		,      lowerCamelCase_      )
    _a					:  int						=  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]		,      lowerCamelCase_		,      atol=1e-4      )      )


