


import argparse
import shutil
import time
from json import JSONDecodeError
from logging import getLogger
from pathlib import Path
from typing import Dict, List

import torch
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from utils import (
    SeqaSeqDataset,
    calculate_bleu,
    calculate_rouge,
    chunks,
    lmap,
    load_json,
    parse_numeric_n_bool_cl_kwargs,
    save_json,
    use_task_specific_params,
    write_txt_file,
)


A   :					Any	=      getLogger(__name__)

def    lowercase_	(	_A    :					str					,      _A    :					str					,      _A    :					str					,      _A    :					int = 8					,      _A    :					int = 1024					,      _A    :					List[str]="val"					,      _A    :					Tuple=None					,      _A    :					Union[str, Any]=False					,      _A    :					Dict="summarization"					,      _A    :					str=None					,      _A    :					List[Any]=1					,      _A    :					Dict = None					,      _A    :					int=""					,      **_A    :					str					,      ):

      """simple docstring"""




      lowerCamelCase__	:       Tuple					=						str(_A		)
      assert local_rank is not None
      torch.distributed.init_process_group(backend="nccl"					,      rank=_A		)

      lowerCamelCase__	:       Optional[Any]					=						Path(_A		)
      lowerCamelCase__	:       Tuple					=						save_dir.joinpath(F"rank_{local_rank}_output.json"		)
      torch.cuda.set_device(_A		)
      lowerCamelCase__	:       int					=						AutoModelForSeqaSeqLM.from_pretrained(_A		).cuda()
      if fpaa:
            lowerCamelCase__	:       Dict					=						model.half()
      # determine if we need to increase num_beams
      use_task_specific_params(_A					,      _A		)  # update config with task specific params
      lowerCamelCase__	:       Tuple					=						generate_kwargs.pop("num_beams"					,      model.config.num_beams		)  # AttributeError risk?
      if num_return_sequences > num_beams:
            lowerCamelCase__	:       List[Any]					=						num_return_sequences

      lowerCamelCase__	:       Optional[Any]					=						AutoTokenizer.from_pretrained(_A		)
      logger.info(F"Inferred tokenizer type: {tokenizer.__class__}"		)  # if this is wrong, check config.model_type.

      if max_source_length is None:
            lowerCamelCase__	:       List[str]					=						tokenizer.model_max_length
      if prefix is None:
            lowerCamelCase__	:       Union[str, Any]					=						prefix or getattr(model.config					,      "prefix"					,      ""		) or ""
      lowerCamelCase__	:       Dict					=						SeqaSeqDataset(
          _A					,      _A					,      _A					,      max_target_length=1024					,      type_path=_A					,      n_obs=_A					,      prefix=_A					,      **_A					,      )
      # I set shuffle=True for a more accurate progress bar.
      # If all the longest samples are first, the prog bar estimate is too high at the beginning.
      lowerCamelCase__	:       Optional[Any]					=						ds.make_sortish_sampler(_A					,      distributed=_A					,      add_extra_examples=_A					,      shuffle=_A		)
      lowerCamelCase__	:       str					=						DataLoader(_A					,      sampler=_A					,      batch_size=_A					,      collate_fn=ds.collate_fn		)
      lowerCamelCase__	:       List[str]					=						[]
      for batch in tqdm(_A		):
            lowerCamelCase__	:       Optional[Any]					=						model.generate(
                input_ids=batch["input_ids"].to(model.device		)					,      attention_mask=batch["attention_mask"].to(model.device		)					,      num_return_sequences=_A					,      num_beams=_A					,      **_A					,      )
            lowerCamelCase__	:       Any					=						tokenizer.batch_decode(_A					,      skip_special_tokens=_A					,      clean_up_tokenization_spaces=_A		)
            lowerCamelCase__	:       str					=						batch["ids"]
            if num_return_sequences > 1:
                  lowerCamelCase__	:       str					=						chunks(_A					,      _A		)  # batch size chunks, each of size num_return_seq
            for i, pred in enumerate(_A		):
                  results.append({"pred": pred, "id": ids[i].item()}		)
      save_json(_A					,      _A		)
      return results, sampler.num_replicas

def    lowercase_	(	):

      """simple docstring"""




      lowerCamelCase__	:       int					=						argparse.ArgumentParser(
          epilog="Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate"		)
      parser.add_argument("--data_dir"					,      type=_A					,      help="like cnn_dm/test.source"		)
      parser.add_argument(
          "--model_name"					,      type=_A					,      help="like facebook/bart-large-cnn,t5-base, etc."					,      default="sshleifer/distilbart-xsum-12-3"					,      )
      parser.add_argument("--save_dir"					,      type=_A					,      help="where to save"					,      default="tmp_gen"		)
      parser.add_argument("--max_source_length"					,      type=_A					,      default=_A		)
      parser.add_argument(
          "--type_path"					,      type=_A					,      default="test"					,      help="which subset to evaluate typically train/val/test"		)
      parser.add_argument("--task"					,      type=_A					,      default="summarization"					,      help="used for task_specific_params + metrics"		)
      parser.add_argument("--bs"					,      type=_A					,      default=8					,      required=_A					,      help="batch size"		)
      parser.add_argument(
          "--local_rank"					,      type=_A					,      default=-1					,      required=_A					,      help="should be passed by distributed.launch"		)

      parser.add_argument(
          "--n_obs"					,      type=_A					,      default=_A					,      required=_A					,      help="How many observations. Defaults to all."		)
      parser.add_argument(
          "--num_return_sequences"					,      type=_A					,      default=1					,      required=_A					,      help="How many sequences to return"		)
      parser.add_argument(
          "--sync_timeout"					,      type=_A					,      default=600					,      required=_A					,      help="How long should master process wait for other processes to finish."					,      )
      parser.add_argument("--src_lang"					,      type=_A					,      default=_A					,      required=_A		)
      parser.add_argument("--tgt_lang"					,      type=_A					,      default=_A					,      required=_A		)
      parser.add_argument(
          "--prefix"					,      type=_A					,      required=_A					,      default=_A					,      help="will be added to the begininng of src examples"		)
      parser.add_argument("--fp16"					,      action="store_true"		)
      parser.add_argument("--debug"					,      action="store_true"		)
      lowerCamelCase__	:       List[Any]					=						time.time()
      lowerCamelCase__	:       List[str]					=						parser.parse_known_args()
      lowerCamelCase__	:       Optional[int]					=						parse_numeric_n_bool_cl_kwargs(_A		)
      if generate_kwargs and args.local_rank <= 0:
            print(F"parsed the following generate kwargs: {generate_kwargs}"		)
      lowerCamelCase__	:       int					=						Path(args.save_dir + "_tmp"		)
      Path(_A		).mkdir(exist_ok=_A		)  # this handles locking.
      lowerCamelCase__	:       Any					=						list(json_save_dir.glob("rank_*.json"		)		)
      if intermediate_files:
            raise ValueError(F"Found files at {json_save_dir} please move or remove them."		)
            # In theory, a node could finish and save before another node hits this. If this happens, we can address later.
      lowerCamelCase__	:       Dict					=						{}
      if args.src_lang is not None:
            lowerCamelCase__	:       Dict					=						args.src_lang
      if args.tgt_lang is not None:
            lowerCamelCase__	:       Any					=						args.tgt_lang

      Path(args.save_dir		).mkdir(exist_ok=_A		)
      lowerCamelCase__	:       Dict					=						eval_data_dir(
          args.data_dir					,      _A					,      args.model_name					,      type_path=args.type_path					,      bs=args.bs					,      fpaa=args.fpaa					,      task=args.task					,      local_rank=args.local_rank					,      n_obs=args.n_obs					,      max_source_length=args.max_source_length					,      num_return_sequences=args.num_return_sequences					,      prefix=args.prefix					,      dataset_kwargs=_A					,      **_A					,      )

      if args.local_rank <= 0:
            lowerCamelCase__	:       Tuple					=						Path(args.save_dir		)
            save_dir.mkdir(exist_ok=_A		)
            lowerCamelCase__	:       Optional[int]					=						gather_results_from_each_node(_A					,      _A					,      args.sync_timeout		)
            lowerCamelCase__	:       int					=						combine_partial_results(_A		)
            if args.num_return_sequences > 1:
                  lowerCamelCase__	:       int					=						save_dir.joinpath("pseudolabel_results.json"		)
                  print(F"Saving aggregated results at {save_path}, intermediate in {json_save_dir}/"		)
                  save_json(_A					,      _A		)
                  return
            lowerCamelCase__	:       Union[str, Any]					=						Path(args.data_dir		).joinpath(args.type_path + ".target"		)
            with open(_A		) as f:
                  lowerCamelCase__	:       Union[str, Any]					=						[x.rstrip() for x in f.readlines()][: len(_A		)]

            # Calculate metrics, save metrics,  and save _generations.txt
            lowerCamelCase__	:       Optional[Any]					=						"translation" in args.task
            lowerCamelCase__	:       int					=						calculate_bleu if calc_bleu else calculate_rouge
            lowerCamelCase__	:       List[str]					=						"bleu" if calc_bleu else "rouge"
            lowerCamelCase__	:       Dict					=						score_fn(_A					,      _A		)
            lowerCamelCase__	:       int					=						len(_A		)
            lowerCamelCase__	:       Optional[int]					=						time.time() - start_time
            lowerCamelCase__	:       str					=						round(runtime / metrics["n_obs"]					,      4		)
            lowerCamelCase__	:       Any					=						num_replicas
            # TODO(@stas00): add whatever metadata to metrics
            lowerCamelCase__	:       Any					=						save_dir.joinpath(F"{args.type_path}_{metric_name}.json"		)
            save_json(_A					,      _A					,      indent=_A		)
            print(_A		)
            write_txt_file(_A					,      save_dir.joinpath(F"{args.type_path}_generations.txt"		)		)
            if args.debug:
                  write_txt_file(_A					,      save_dir.joinpath(F"{args.type_path}.target"		)		)
            else:
                  shutil.rmtree(_A		)

def    lowercase_	(	_A    :					List[str]		):

      """simple docstring"""




      lowerCamelCase__	:       int					=						[]
      for partial_result in partial_results:
            records.extend(_A		)
      lowerCamelCase__	:       Optional[int]					=						sorted(_A					,      key=lambda _A		: x["id"]		)
      lowerCamelCase__	:       Dict					=						[x["pred"] for x in records]
      return preds

def    lowercase_	(	_A    :					str					,      _A    :					str					,      _A    :					Dict		):

      """simple docstring"""




      lowerCamelCase__	:       str					=						time.time()
      logger.info("waiting for all nodes to finish"		)
      lowerCamelCase__	:       Dict					=						None
      while (time.time() - start_wait) < timeout:
            lowerCamelCase__	:       Dict					=						list(save_dir.glob("rank_*.json"		)		)
            if len(_A		) < num_replicas:
                  continue
            try:
                  # make sure all json files are fully saved
                  lowerCamelCase__	:       Tuple					=						lmap(_A					,      _A		)
                  return json_data
            except JSONDecodeError:
                  continue
      else:
            raise TimeoutError("Rank 0 gave up on waiting for other processes"		)
      # Unreachable


if __name__ == "__main__":
     # Usage for MT:
     run_generate()






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     _lowercase				:


       """simple docstring"""




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


             '''simple docstring'''



             lowerCamelCase__	:       Dict					=						parent
             lowerCamelCase__	:       List[Any]					=						batch_size
             lowerCamelCase__	:       Any					=						seq_length
             lowerCamelCase__	:       List[str]					=						is_training
             lowerCamelCase__	:       int					=						use_input_mask
             lowerCamelCase__	:       List[str]					=						use_token_type_ids
             lowerCamelCase__	:       int					=						use_labels
             lowerCamelCase__	:       Dict					=						vocab_size
             lowerCamelCase__	:       List[Any]					=						embedding_size
             lowerCamelCase__	:       Dict					=						hidden_size
             lowerCamelCase__	:       Any					=						num_hidden_layers
             lowerCamelCase__	:       Optional[Any]					=						num_hidden_groups
             lowerCamelCase__	:       Optional[int]					=						num_attention_heads
             lowerCamelCase__	:       List[str]					=						intermediate_size
             lowerCamelCase__	:       Optional[Any]					=						hidden_act
             lowerCamelCase__	:       str					=						hidden_dropout_prob
             lowerCamelCase__	:       Union[str, Any]					=						attention_probs_dropout_prob
             lowerCamelCase__	:       Optional[int]					=						max_position_embeddings
             lowerCamelCase__	:       List[Any]					=						type_vocab_size
             lowerCamelCase__	:       Optional[Any]					=						type_sequence_label_size
             lowerCamelCase__	:       Optional[int]					=						initializer_range
             lowerCamelCase__	:       str					=						num_labels
             lowerCamelCase__	:       List[Any]					=						num_choices
             lowerCamelCase__	:       Any					=						scope





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						ids_tensor([self.batch_size, self.seq_length]      ,   self.vocab_size )

             lowerCamelCase__	:       Optional[int]					=						None
             if self.use_input_mask:
                   lowerCamelCase__	:       Any					=						random_attention_mask([self.batch_size, self.seq_length] )

             lowerCamelCase__	:       Optional[Any]					=						None
             if self.use_token_type_ids:
                   lowerCamelCase__	:       Union[str, Any]					=						ids_tensor([self.batch_size, self.seq_length]      ,   self.type_vocab_size )

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

             lowerCamelCase__	:       Union[str, Any]					=						self.get_config()

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





       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             return AlbertConfig(
                 vocab_size=self.vocab_size      ,   hidden_size=self.hidden_size      ,   num_hidden_layers=self.num_hidden_layers      ,   num_attention_heads=self.num_attention_heads      ,   intermediate_size=self.intermediate_size      ,   hidden_act=self.hidden_act      ,   hidden_dropout_prob=self.hidden_dropout_prob      ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,   max_position_embeddings=self.max_position_embeddings      ,   type_vocab_size=self.type_vocab_size      ,   initializer_range=self.initializer_range      ,   num_hidden_groups=self.num_hidden_groups      ,   )





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    List[Any] ):


             '''simple docstring'''



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


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						AlbertForPreTraining(config=__lowerCamelCase )
             model.to(__lowerCamelCase )
             model.eval()
             lowerCamelCase__	:       Union[str, 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 		lowerCAmelCase  (     self							:    str      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    Optional[int]      ,   __lowerCamelCase							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       Dict					=						AlbertForMaskedLM(config=__lowerCamelCase )
             model.to(__lowerCamelCase )
             model.eval()
             lowerCamelCase__	:       Tuple					=						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 		lowerCAmelCase  (     self							:    Union[str, Any]      ,   __lowerCamelCase							:    Optional[int]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



             lowerCamelCase__	:       str					=						AlbertForQuestionAnswering(config=__lowerCamelCase )
             model.to(__lowerCamelCase )
             model.eval()
             lowerCamelCase__	:       str					=						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 		lowerCAmelCase  (     self							:    Optional[int]      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Optional[int]      ,   __lowerCamelCase							:    Optional[int]      ,   __lowerCamelCase							:    Union[str, Any]      ,   __lowerCamelCase							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						self.num_labels
             lowerCamelCase__	:       Optional[int]					=						AlbertForSequenceClassification(__lowerCamelCase )
             model.to(__lowerCamelCase )
             model.eval()
             lowerCamelCase__	:       Any					=						model(__lowerCamelCase      ,   attention_mask=__lowerCamelCase      ,   token_type_ids=__lowerCamelCase      ,   labels=__lowerCamelCase )
             self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels) )





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    List[Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						self.num_labels
             lowerCamelCase__	:       List[str]					=						AlbertForTokenClassification(config=__lowerCamelCase )
             model.to(__lowerCamelCase )
             model.eval()
             lowerCamelCase__	:       Tuple					=						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 		lowerCAmelCase  (     self							:    Tuple      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



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





       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						self.prepare_config_and_inputs()
             (
                 (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     
             )	:       Union[str, Any]					=						config_and_inputs
             lowerCamelCase__	:       str					=						{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
             return config, inputs_dict







@require_torch
class     _lowercase				(							lowercase__							,						lowercase__							,						unittest.TestCase):


       """simple docstring"""




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





       def 		lowerCAmelCase  (     self							:    List[str]      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    Dict=False ):


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						super()._prepare_for_class(__lowerCamelCase      ,   __lowerCamelCase      ,   return_labels=__lowerCamelCase )

             if return_labels:
                   if model_class in get_values(__lowerCamelCase ):
                         lowerCamelCase__	:       Union[str, Any]					=						torch.zeros(
                             (self.model_tester.batch_size, self.model_tester.seq_length)      ,   dtype=torch.long      ,   device=__lowerCamelCase )
                         lowerCamelCase__	:       List[str]					=						torch.zeros(
                             self.model_tester.batch_size      ,   dtype=torch.long      ,   device=__lowerCamelCase )
             return inputs_dict





       def 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[int]					=						AlbertModelTester(self )
             lowerCamelCase__	:       Optional[Any]					=						ConfigTester(self      ,   config_class=__lowerCamelCase      ,   hidden_size=37 )





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             self.config_tester.run_common_tests()





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__lowerCamelCase )





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


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase )





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


             '''simple docstring'''



             lowerCamelCase__	:       List[str]					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       List[str]					=						self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                   lowerCamelCase__	:       Dict					=						type
                   self.model_tester.create_and_check_model(*__lowerCamelCase )





       @slow
       def 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   lowerCamelCase__	:       List[str]					=						AlbertModel.from_pretrained(__lowerCamelCase )
                   self.assertIsNotNone(__lowerCamelCase )







@require_torch
class     _lowercase				(							unittest.TestCase):


       """simple docstring"""




       @slow
       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						AlbertModel.from_pretrained("albert-base-v2" )
             lowerCamelCase__	:       Any					=						torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
             lowerCamelCase__	:       int					=						torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
             with torch.no_grad():
                   lowerCamelCase__	:       List[Any]					=						model(__lowerCamelCase      ,   attention_mask=__lowerCamelCase )[0]
             lowerCamelCase__	:       Tuple					=						torch.Size((1, 11, 768) )
             self.assertEqual(output.shape      ,   __lowerCamelCase )
             lowerCamelCase__	:       Dict					=						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]      ,   __lowerCamelCase      ,   atol=1E-4 ) )


