






import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

snake_case__   :						List[str]													=   logging.getLogger(__name__)


@dataclass
class     _a							:






  """simple docstring"""





  A_						       = field(
      metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}     )
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}     )
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}     )
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}    ,							)
  A_						       = field(
      default="""main"""    ,							metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={
          """help""": (
              """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
              """with private models)."""
          )
      }    ,							)




@dataclass
class     _a							:






  """simple docstring"""





  A_						       = field(default=UpperCAmelCase__    ,							metadata={"""help""": """The input training data file (a text file)."""}     )
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={"""help""": """The number of processes to use for the preprocessing."""}    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. If passed, sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={
          """help""": (
              """Whether to pad all samples to the maximum sentence length. """
              """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """
              """efficient on GPU but very bad for TPU."""
          )
      }    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={
          """help""": (
              """For debugging purposes or quicker training, truncate the number of training examples to this """
              """value if set."""
          )
      }    ,							)
  A_						       = field(
      default=UpperCAmelCase__    ,							metadata={
          """help""": (
              """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
              """value if set."""
          )
      }    ,							)




  def  _UpperCAmelCase  (  self			)      ->			Union[str, Any]:
     if self.train_file is not None:
        UpperCamelCase_						=  self.train_file.split('.'			)[-1]
        assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
     if self.validation_file is not None:
        UpperCamelCase_						=  self.validation_file.split('.'			)[-1]
        assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."




@dataclass
class     _a							:






  """simple docstring"""





  A_						       = 42
  A_						       = True
  A_						       = None
  A_						       = None




  def __call__(  self		,		_UpperCAmelCase			)      ->			List[Any]:
     UpperCamelCase_						=  'label' if 'label' in features[0].keys() else 'labels'
     UpperCamelCase_						=  [feature.pop(_UpperCAmelCase			) for feature in features]
     UpperCamelCase_						=  len(_UpperCAmelCase			)
     UpperCamelCase_						=  len(features[0]['input_ids']			)
     UpperCamelCase_						=  [
         [{k: v[i] for k, v in feature.items()} for i in range(_UpperCAmelCase			)] for feature in features
     ]
     UpperCamelCase_						=  list(chain(*_UpperCAmelCase			)			)

     UpperCamelCase_						=  self.tokenizer.pad(
         _UpperCAmelCase		,		padding=self.padding		,		max_length=self.max_length		,		pad_to_multiple_of=self.pad_to_multiple_of		,		return_tensors='pt'		,		)

     # Un-flatten
     UpperCamelCase_						=  {k: v.view(_UpperCAmelCase		,		_UpperCAmelCase		,		-1			) for k, v in batch.items()}
     # Add back labels
     UpperCamelCase_						=  torch.tensor(_UpperCAmelCase		,		dtype=torch.intaa			)
     return batch






def      _snake_case     ():
   # See all possible arguments in src/transformers/training_args.py
   # or by passing the --help flag to this script.
   # We now keep distinct sets of args, for a cleaner separation of concerns.

   UpperCamelCase_						=  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
   if len(sys.argv) == 2 and sys.argv[1].endswith('.json'):
      # If we pass only one argument to the script and it's the path to a json file,
      # let's parse it to get our arguments.
      UpperCamelCase_		,   UpperCamelCase_		,   UpperCamelCase_						=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
   else:
      UpperCamelCase_		,   UpperCamelCase_		,   UpperCamelCase_						=  parser.parse_args_into_dataclasses()

   # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
   # information sent is the one passed as arguments along with your Python/PyTorch versions.
   send_example_telemetry('run_swag'     ,   __lowercase     ,   __lowercase)

   # Setup logging
   logging.basicConfig(
       format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,   datefmt='%m/%d/%Y %H:%M:%S'     ,   handlers=[logging.StreamHandler(sys.stdout)]     ,   )

   if training_args.should_log:
      # The default of training_args.log_level is passive, so we set log level at info here to have that default.
      transformers.utils.logging.set_verbosity_info()

   UpperCamelCase_						=  training_args.get_process_log_level()
   logger.setLevel(__lowercase)
   datasets.utils.logging.set_verbosity(__lowercase)
   transformers.utils.logging.set_verbosity(__lowercase)
   transformers.utils.logging.enable_default_handler()
   transformers.utils.logging.enable_explicit_format()

   # Log on each process the small summary:
   logger.warning(
       f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
       + f"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""")
   logger.info(f"""Training/evaluation parameters {training_args}""")

   # Detecting last checkpoint.
   UpperCamelCase_						=  None
   if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
      UpperCamelCase_						=  get_last_checkpoint(training_args.output_dir)
      if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
         raise ValueError(
             f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
             'Use --overwrite_output_dir to overcome.')
      elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
         logger.info(
             f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
             'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.')

    # Set seed before initializing model.
   set_seed(training_args.seed)

   # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
   # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
   # (the dataset will be downloaded automatically from the datasets Hub).

   # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
   # 'text' is found. You can easily tweak this behavior (see below).

   # In distributed training, the load_dataset function guarantee that only one local process can concurrently
   # download the dataset.
   if data_args.train_file is not None or data_args.validation_file is not None:
      UpperCamelCase_						=  {}
      if data_args.train_file is not None:
         UpperCamelCase_						=  data_args.train_file
      if data_args.validation_file is not None:
         UpperCamelCase_						=  data_args.validation_file
      UpperCamelCase_						=  data_args.train_file.split('.')[-1]
      UpperCamelCase_						=  load_dataset(
          __lowercase     ,   data_files=__lowercase     ,   cache_dir=model_args.cache_dir     ,   use_auth_token=True if model_args.use_auth_token else None     ,   )
   else:
      # Downloading and loading the swag dataset from the hub.
      UpperCamelCase_						=  load_dataset(
          'swag'     ,   'regular'     ,   cache_dir=model_args.cache_dir     ,   use_auth_token=True if model_args.use_auth_token else None     ,   )
   # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
   # https://huggingface.co/docs/datasets/loading_datasets.html.

   # Load pretrained model and tokenizer

   # Distributed training:
   # The .from_pretrained methods guarantee that only one local process can concurrently
   # download model & vocab.
   UpperCamelCase_						=  AutoConfig.from_pretrained(
       model_args.config_name if model_args.config_name else model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir     ,   revision=model_args.model_revision     ,   use_auth_token=True if model_args.use_auth_token else None     ,   )
   UpperCamelCase_						=  AutoTokenizer.from_pretrained(
       model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir     ,   use_fast=model_args.use_fast_tokenizer     ,   revision=model_args.model_revision     ,   use_auth_token=True if model_args.use_auth_token else None     ,   )
   UpperCamelCase_						=  AutoModelForMultipleChoice.from_pretrained(
       model_args.model_name_or_path     ,   from_tf=bool('.ckpt' in model_args.model_name_or_path)     ,   config=__lowercase     ,   cache_dir=model_args.cache_dir     ,   revision=model_args.model_revision     ,   use_auth_token=True if model_args.use_auth_token else None     ,   )

   # When using your own dataset or a different dataset from swag, you will probably need to change this.
   UpperCamelCase_						=  [f"""ending{i}""" for i in range(4)]
   UpperCamelCase_						=  'sent1'
   UpperCamelCase_						=  'sent2'

   if data_args.max_seq_length is None:
      UpperCamelCase_						=  tokenizer.model_max_length
      if max_seq_length > 1024:
         logger.warning(
             'The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value'
             ' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can'
             ' override this default with `--block_size xxx`.')
         UpperCamelCase_						=  1024
   else:
      if data_args.max_seq_length > tokenizer.model_max_length:
         logger.warning(
             f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
             f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""")
      UpperCamelCase_						=  min(data_args.max_seq_length     ,   tokenizer.model_max_length)

   # Preprocessing the datasets.
   def preprocess_function(__lowercase):
      UpperCamelCase_						=  [[context] * 4 for context in examples[context_name]]
      UpperCamelCase_						=  examples[question_header_name]
      UpperCamelCase_						=  [
          [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(__lowercase)
      ]

      # Flatten out
      UpperCamelCase_						=  list(chain(*__lowercase))
      UpperCamelCase_						=  list(chain(*__lowercase))

      # Tokenize
      UpperCamelCase_						=  tokenizer(
          __lowercase     ,   __lowercase     ,   truncation=__lowercase     ,   max_length=__lowercase     ,   padding='max_length' if data_args.pad_to_max_length else False     ,   )
      # Un-flatten
      return {k: [v[i : i + 4] for i in range(0     ,   len(__lowercase)     ,   4)] for k, v in tokenized_examples.items()}

   if training_args.do_train:
      if "train" not in raw_datasets:
         raise ValueError('--do_train requires a train dataset')
      UpperCamelCase_						=  raw_datasets['train']
      if data_args.max_train_samples is not None:
         UpperCamelCase_						=  min(len(__lowercase)     ,   data_args.max_train_samples)
         UpperCamelCase_						=  train_dataset.select(range(__lowercase))
      with training_args.main_process_first(desc='train dataset map pre-processing'):
         UpperCamelCase_						=  train_dataset.map(
             __lowercase     ,   batched=__lowercase     ,   num_proc=data_args.preprocessing_num_workers     ,   load_from_cache_file=not data_args.overwrite_cache     ,   )

   if training_args.do_eval:
      if "validation" not in raw_datasets:
         raise ValueError('--do_eval requires a validation dataset')
      UpperCamelCase_						=  raw_datasets['validation']
      if data_args.max_eval_samples is not None:
         UpperCamelCase_						=  min(len(__lowercase)     ,   data_args.max_eval_samples)
         UpperCamelCase_						=  eval_dataset.select(range(__lowercase))
      with training_args.main_process_first(desc='validation dataset map pre-processing'):
         UpperCamelCase_						=  eval_dataset.map(
             __lowercase     ,   batched=__lowercase     ,   num_proc=data_args.preprocessing_num_workers     ,   load_from_cache_file=not data_args.overwrite_cache     ,   )

    # Data collator
   UpperCamelCase_						=  (
       default_data_collator
       if data_args.pad_to_max_length
       else DataCollatorForMultipleChoice(tokenizer=__lowercase     ,   pad_to_multiple_of=8 if training_args.fpaa else None)
   )

   # Metric
   def compute_metrics(__lowercase):
      UpperCamelCase_		,   UpperCamelCase_						=  eval_predictions
      UpperCamelCase_						=  np.argmax(__lowercase     ,   axis=1)
      return {"accuracy": (preds == label_ids).astype(np.floataa).mean().item()}

   # Initialize our Trainer
   UpperCamelCase_						=  Trainer(
       model=__lowercase     ,   args=__lowercase     ,   train_dataset=train_dataset if training_args.do_train else None     ,   eval_dataset=eval_dataset if training_args.do_eval else None     ,   tokenizer=__lowercase     ,   data_collator=__lowercase     ,   compute_metrics=__lowercase     ,   )

   # Training
   if training_args.do_train:
      UpperCamelCase_						=  None
      if training_args.resume_from_checkpoint is not None:
         UpperCamelCase_						=  training_args.resume_from_checkpoint
      elif last_checkpoint is not None:
         UpperCamelCase_						=  last_checkpoint
      UpperCamelCase_						=  trainer.train(resume_from_checkpoint=__lowercase)
      trainer.save_model()  # Saves the tokenizer too for easy upload
      UpperCamelCase_						=  train_result.metrics

      UpperCamelCase_						=  (
          data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowercase)
      )
      UpperCamelCase_						=  min(__lowercase     ,   len(__lowercase))

      trainer.log_metrics('train'     ,   __lowercase)
      trainer.save_metrics('train'     ,   __lowercase)
      trainer.save_state()

   # Evaluation
   if training_args.do_eval:
      logger.info('*** Evaluate ***')

      UpperCamelCase_						=  trainer.evaluate()
      UpperCamelCase_						=  data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowercase)
      UpperCamelCase_						=  min(__lowercase     ,   len(__lowercase))

      trainer.log_metrics('eval'     ,   __lowercase)
      trainer.save_metrics('eval'     ,   __lowercase)

   UpperCamelCase_						=  {
       'finetuned_from': model_args.model_name_or_path,
       'tasks': 'multiple-choice',
       'dataset_tags': 'swag',
       'dataset_args': 'regular',
       'dataset': 'SWAG',
       'language': 'en',
   }

   if training_args.push_to_hub:
      trainer.push_to_hub(**__lowercase)
   else:
      trainer.create_model_card(**__lowercase)






def      _snake_case     (__lowercase):
   # For xla_spawn (TPUs)
   main()


if __name__ == "__main__":
 main()













import gc
import unittest

from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_gpu,
    slow,
)

from .test_pipelines_common import ANY


@is_pipeline_test
class     _a							(	unittest.TestCase     ):






  """simple docstring"""





  A_						       = MODEL_FOR_MASKED_LM_MAPPING
  A_						       = TF_MODEL_FOR_MASKED_LM_MAPPING




  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     super().tearDown()
     # clean-up as much as possible GPU memory occupied by PyTorch
     gc.collect()
     if is_torch_available():
        import torch

        torch.cuda.empty_cache()




  @require_tf
  def  _UpperCAmelCase  (  self			)      ->			str:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		top_k=2		,		framework='tf'			)
     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {'sequence': 'My name is grouped', 'score': 2.1e-05, 'token': 38015, 'token_str': ' grouped'},
             {'sequence': 'My name is accuser', 'score': 2.1e-05, 'token': 25506, 'token_str': ' accuser'},
         ]		,		)

     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {
                 'sequence': 'The largest city in France is grouped',
                 'score': 2.1e-05,
                 'token': 38015,
                 'token_str': ' grouped',
             },
             {
                 'sequence': 'The largest city in France is accuser',
                 'score': 2.1e-05,
                 'token': 25506,
                 'token_str': ' accuser',
             },
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {'sequence': 'My name is Clara', 'score': 2e-05, 'token': 13606, 'token_str': ' Clara'},
             {'sequence': 'My name is Patrick', 'score': 2e-05, 'token': 3499, 'token_str': ' Patrick'},
             {'sequence': 'My name is Te', 'score': 1.9e-05, 'token': 2941, 'token_str': ' Te'},
         ]		,		)




  @require_torch
  def  _UpperCAmelCase  (  self			)      ->			Union[str, Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		top_k=2		,		framework='pt'			)

     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {'sequence': 'My name is Maul', 'score': 2.2e-05, 'token': 35676, 'token_str': ' Maul'},
             {'sequence': 'My name isELS', 'score': 2.2e-05, 'token': 16416, 'token_str': 'ELS'},
         ]		,		)

     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {
                 'sequence': 'The largest city in France is Maul',
                 'score': 2.2e-05,
                 'token': 35676,
                 'token_str': ' Maul',
             },
             {'sequence': 'The largest city in France isELS', 'score': 2.2e-05, 'token': 16416, 'token_str': 'ELS'},
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             {'sequence': 'My name is Patrick', 'score': 2.1e-05, 'token': 3499, 'token_str': ' Patrick'},
             {'sequence': 'My name is Te', 'score': 2e-05, 'token': 2941, 'token_str': ' Te'},
             {'sequence': 'My name is Clara', 'score': 2e-05, 'token': 13606, 'token_str': ' Clara'},
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask> <mask>'		,		top_k=2			)

     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		decimals=6			)		,		[
             [
                 {
                     'score': 2.2e-05,
                     'token': 35676,
                     'token_str': ' Maul',
                     'sequence': '<s>My name is Maul<mask></s>',
                 },
                 {'score': 2.2e-05, 'token': 16416, 'token_str': 'ELS', 'sequence': '<s>My name isELS<mask></s>'},
             ],
             [
                 {
                     'score': 2.2e-05,
                     'token': 35676,
                     'token_str': ' Maul',
                     'sequence': '<s>My name is<mask> Maul</s>',
                 },
                 {'score': 2.2e-05, 'token': 16416, 'token_str': 'ELS', 'sequence': '<s>My name is<mask>ELS</s>'},
             ],
         ]		,		)




  @require_torch_gpu
  def  _UpperCAmelCase  (  self			)      ->			Optional[Any]:
     UpperCamelCase_						=  pipeline('fill-mask'		,		model='hf-internal-testing/tiny-random-distilbert'		,		device=0		,		framework='pt'			)

     # convert model to fp16
     pipe.model.half()

     UpperCamelCase_						=  pipe('Paris is the [MASK] of France.'			)
     # We actually don't care about the result, we just want to make sure
     # it works, meaning the float16 tensor got casted back to float32
     # for postprocessing.
     self.assertIsInstance(_UpperCAmelCase		,		_UpperCAmelCase			)




  @slow
  @require_torch
  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='distilroberta-base'		,		top_k=2		,		framework='pt'			)
     self.run_large_test(_UpperCAmelCase			)




  @slow
  @require_tf
  def  _UpperCAmelCase  (  self			)      ->			Union[str, Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='distilroberta-base'		,		top_k=2		,		framework='tf'			)
     self.run_large_test(_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase			)      ->			Tuple:
     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {'sequence': 'My name is John', 'score': 0.0_0_8, 'token': 610, 'token_str': ' John'},
             {'sequence': 'My name is Chris', 'score': 0.0_0_7, 'token': 1573, 'token_str': ' Chris'},
         ]		,		)
     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {
                 'sequence': 'The largest city in France is Paris',
                 'score': 0.2_5_1,
                 'token': 2201,
                 'token_str': ' Paris',
             },
             {
                 'sequence': 'The largest city in France is Lyon',
                 'score': 0.2_1_4,
                 'token': 12790,
                 'token_str': ' Lyon',
             },
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {'sequence': 'My name is Patrick', 'score': 0.0_0_5, 'token': 3499, 'token_str': ' Patrick'},
             {'sequence': 'My name is Clara', 'score': 0.0_0_0, 'token': 13606, 'token_str': ' Clara'},
             {'sequence': 'My name is Te', 'score': 0.0_0_0, 'token': 2941, 'token_str': ' Te'},
         ]		,		)




  @require_torch
  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		framework='pt'			)
     UpperCamelCase_						=  None
     UpperCamelCase_						=  None
     self.run_pipeline_test(_UpperCAmelCase		,		[]			)




  @require_tf
  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		framework='tf'			)
     UpperCamelCase_						=  None
     UpperCamelCase_						=  None
     self.run_pipeline_test(_UpperCAmelCase		,		[]			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[Any]:
     if tokenizer is None or tokenizer.mask_token_id is None:
        self.skipTest('The provided tokenizer has no mask token, (probably reformer or wav2vec2)'			)

     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)
     UpperCamelCase_						=  [
         f"""This is another {tokenizer.mask_token} test""",
     ]
     return fill_masker, examples




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Union[str, Any]:
     UpperCamelCase_						=  fill_masker.tokenizer
     UpperCamelCase_						=  fill_masker.model

     UpperCamelCase_						=  fill_masker(
         f"""This is a {tokenizer.mask_token}"""		,		)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)

     UpperCamelCase_						=  fill_masker([f"""This is a {tokenizer.mask_token}"""]			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)

     UpperCamelCase_						=  fill_masker([f"""This is a {tokenizer.mask_token}""", f"""Another {tokenizer.mask_token} great test."""]			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             [
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             ],
             [
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             ],
         ]		,		)

     with self.assertRaises(_UpperCAmelCase			):
        fill_masker([None]			)
     # No mask_token is not supported
     with self.assertRaises(_UpperCAmelCase			):
        fill_masker('This is'			)

     self.run_test_top_k(_UpperCAmelCase		,		_UpperCAmelCase			)
     self.run_test_targets(_UpperCAmelCase		,		_UpperCAmelCase			)
     self.run_test_top_k_targets(_UpperCAmelCase		,		_UpperCAmelCase			)
     self.fill_mask_with_duplicate_targets_and_top_k(_UpperCAmelCase		,		_UpperCAmelCase			)
     self.fill_mask_with_multiple_masks(_UpperCAmelCase		,		_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[Any]:
     UpperCamelCase_						=  tokenizer.get_vocab()
     UpperCamelCase_						=  sorted(vocab.keys()			)[:2]
     # Pipeline argument
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase		,		targets=_UpperCAmelCase			)
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)
     UpperCamelCase_						=  {vocab[el] for el in targets}
     self.assertEqual({el['token'] for el in outputs}		,		_UpperCAmelCase			)
     UpperCamelCase_						=  [tokenizer.decode([x]			) for x in target_ids]
     self.assertEqual({el['token_str'] for el in outputs}		,		set(_UpperCAmelCase			)			)

     # Call argument
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)
     UpperCamelCase_						=  {vocab[el] for el in targets}
     self.assertEqual({el['token'] for el in outputs}		,		_UpperCAmelCase			)
     UpperCamelCase_						=  [tokenizer.decode([x]			) for x in target_ids]
     self.assertEqual({el['token_str'] for el in outputs}		,		set(_UpperCAmelCase			)			)

     # Score equivalence
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase			)
     UpperCamelCase_						=  [top_mask['token_str'] for top_mask in outputs]
     UpperCamelCase_						=  [top_mask['score'] for top_mask in outputs]

     # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
     if set(_UpperCAmelCase			) == set(_UpperCAmelCase			):
        UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase			)
        UpperCamelCase_						=  [top_mask['score'] for top_mask in unmasked_targets]
        self.assertEqual(nested_simplify(_UpperCAmelCase			)		,		nested_simplify(_UpperCAmelCase			)			)

     # Raises with invalid
     with self.assertRaises(_UpperCAmelCase			):
        UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=[]			)
     # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
     if "" not in tokenizer.get_vocab():
        with self.assertRaises(_UpperCAmelCase			):
           UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=['']			)
        with self.assertRaises(_UpperCAmelCase			):
           UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=''			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Tuple:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase		,		top_k=2			)
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)

     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		top_k=2			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)
     self.assertEqual(nested_simplify(_UpperCAmelCase			)		,		nested_simplify(_UpperCAmelCase			)			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[Any]:
     UpperCamelCase_						=  tokenizer.get_vocab()
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)

     # top_k=2, ntargets=3
     UpperCamelCase_						=  sorted(vocab.keys()			)[:3]
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		top_k=2		,		targets=_UpperCAmelCase			)

     # If we use the most probably targets, and filter differently, we should still
     # have the same results
     UpperCamelCase_						=  [el['token_str'] for el in sorted(_UpperCAmelCase		,		key=lambda _UpperCAmelCase			: x["score"]		,		reverse=_UpperCAmelCase			)]
     # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
     if set(_UpperCAmelCase			).issubset(_UpperCAmelCase			):
        UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		top_k=3		,		targets=_UpperCAmelCase			)
        # They should yield exactly the same result
        self.assertEqual(nested_simplify(_UpperCAmelCase			)		,		nested_simplify(_UpperCAmelCase			)			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[int]:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)
     UpperCamelCase_						=  tokenizer.get_vocab()
     # String duplicates + id duplicates
     UpperCamelCase_						=  sorted(vocab.keys()			)[:3]
     UpperCamelCase_						=  [targets[0], targets[1], targets[0], targets[2], targets[1]]
     UpperCamelCase_						=  fill_masker(f"""My name is {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase		,		top_k=10			)

     # The target list contains duplicates, so we can't output more
     # than them
     self.assertEqual(len(_UpperCAmelCase			)		,		3			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[str]:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)

     UpperCamelCase_						=  fill_masker(
         f"""This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}"""		,		top_k=2			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             [
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             ],
             [
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             ],
             [
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
                 {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             ],
         ]		,		)





