




'''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


a       :						str								=		logging.getLogger(__name__)



class 		SCREAMING_SNAKE_CASE__  (			UpperCAmelCase__	):
			__SCREAMING_SNAKE_CASE    =			"""summarization"""
			__SCREAMING_SNAKE_CASE    =			["""loss"""]
			__SCREAMING_SNAKE_CASE    =			ROUGE_KEYS
			__SCREAMING_SNAKE_CASE    =			"""rouge2"""





			def __init__(      self						:    Any      ,		a_						:    List[Any]      ,		**a_						:    Union[str, Any]							):



						"""simple docstring"""




						if hparams.sortish_sampler and hparams.gpus > 1:
									__snake_case			=		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__(_UpperCAmelCase      ,		num_labels=_UpperCAmelCase      ,		mode=self.mode      ,		**_UpperCAmelCase							)
						use_task_specific_params(self.model      ,		"summarization"							)
						save_git_info(self.hparams.output_dir							)
						__snake_case			=		Path(self.output_dir							) / "metrics.json"
						__snake_case			=		Path(self.output_dir							) / "hparams.pkl"
						pickle_save(self.hparams      ,		self.hparams_save_path							)
						__snake_case			=		0
						__snake_case			=		defaultdict(_UpperCAmelCase							)
						__snake_case			=		self.config.model_type
						__snake_case			=		self.config.tgt_vocab_size if self.model_type == "fsmt" else self.config.vocab_size

						__snake_case			=		{
						    "data_dir": self.hparams.data_dir,
						    "max_source_length": self.hparams.max_source_length,
						    "prefix": self.model.config.prefix or "",
						}
						__snake_case			=		{
						    "train": self.hparams.n_train,
						    "val": self.hparams.n_val,
						    "test": self.hparams.n_test,
						}
						__snake_case			=		{k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

						__snake_case			=		{
						    "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()							)

						__snake_case			=		get_git_info()["repo_sha"]
						__snake_case			=		hparams.num_workers
						__snake_case			=		None  # default to config
						if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer      ,		_UpperCAmelCase							):
									__snake_case			=		self.tokenizer.lang_code_to_id[hparams.tgt_lang]
									__snake_case			=		self.decoder_start_token_id
						__snake_case			=		(
						    SeqaSeqDataset if hasattr(self.tokenizer      ,		"prepare_seq2seq_batch"							) else LegacySeqaSeqDataset
						)
						__snake_case			=		False
						__snake_case			=		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:
									__snake_case			=		self.hparams.eval_max_gen_length
						else:
									__snake_case			=		self.model.config.max_length
						__snake_case			=		self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric





			def 							A (      self						:    Dict      ,		a_						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		{
						    k: self.tokenizer.batch_decode(v.tolist()							) if "mask" not in k else v.shape for k, v in batch.items()
						}
						save_json(_UpperCAmelCase      ,		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"							)

						__snake_case			=		True
						return readable_batch





			def 							A (      self						:    Optional[Any]      ,		a_						:    Optional[Any]      ,		**a_						:    int							):



						"""simple docstring"""




						return self.model(_UpperCAmelCase      ,		**_UpperCAmelCase							)





			def 							A (      self						:    Union[str, Any]      ,		a_						:    Any							):



						"""simple docstring"""




						__snake_case			=		self.tokenizer.batch_decode(
						    _UpperCAmelCase      ,		skip_special_tokens=_UpperCAmelCase      ,		clean_up_tokenization_spaces=_UpperCAmelCase							)
						return lmap(str.strip      ,		_UpperCAmelCase							)





			def 							A (      self						:    Tuple      ,		a_						:    str							):



						"""simple docstring"""




						__snake_case			=		self.tokenizer.pad_token_id
						__snake_case		,     __snake_case			=		batch["input_ids"], batch["attention_mask"]
						__snake_case			=		batch["labels"]
						if isinstance(self.model      ,		_UpperCAmelCase							):
									__snake_case			=		self.model._shift_right(_UpperCAmelCase							)
						else:
									__snake_case			=		shift_tokens_right(_UpperCAmelCase      ,		_UpperCAmelCase							)
						if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
									__snake_case			=		decoder_input_ids
									self.save_readable_batch(_UpperCAmelCase							)

						__snake_case			=		self(_UpperCAmelCase      ,		attention_mask=_UpperCAmelCase      ,		decoder_input_ids=_UpperCAmelCase      ,		use_cache=_UpperCAmelCase							)
						__snake_case			=		outputs["logits"]
						if self.hparams.label_smoothing == 0:
									# Same behavior as modeling_bart.py, besides ignoring pad_token_id
									__snake_case			=		nn.CrossEntropyLoss(ignore_index=_UpperCAmelCase							)

									assert lm_logits.shape[-1] == self.vocab_size
									__snake_case			=		ce_loss_fct(lm_logits.view(-1      ,		lm_logits.shape[-1]							)      ,		tgt_ids.view(-1							)							)
						else:
									__snake_case			=		nn.functional.log_softmax(_UpperCAmelCase      ,		dim=-1							)
									__snake_case		,     __snake_case			=		label_smoothed_nll_loss(
									    _UpperCAmelCase      ,		_UpperCAmelCase      ,		self.hparams.label_smoothing      ,		ignore_index=_UpperCAmelCase							)
						return (loss,)





			@property
			def 							A (      self						:    Union[str, Any]							):



						"""simple docstring"""




						return self.tokenizer.pad_token_id





			def 							A (      self						:    Optional[int]      ,		a_						:    str      ,		a_						:    Any							):



						"""simple docstring"""




						__snake_case			=		self._step(_UpperCAmelCase							)

						__snake_case			=		dict(zip(self.loss_names      ,		_UpperCAmelCase							)							)
						# tokens per batch
						__snake_case			=		batch["input_ids"].ne(self.pad							).sum() + batch["labels"].ne(self.pad							).sum()
						__snake_case			=		batch["input_ids"].shape[0]
						__snake_case			=		batch["input_ids"].eq(self.pad							).sum()
						__snake_case			=		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 							A (      self						:    List[str]      ,		a_						:    Optional[Any]      ,		a_						:    str							):



						"""simple docstring"""




						return self._generative_step(_UpperCAmelCase							)





			def 							A (      self						:    int      ,		a_						:    Tuple      ,		a_						:    List[Any]="val"							):



						"""simple docstring"""




						self.step_count += 1
						__snake_case			=		{k: torch.stack([x[k] for x in outputs]							).mean() for k in self.loss_names}
						__snake_case			=		losses["loss"]
						__snake_case			=		{
						    k: np.array([x[k] for x in outputs]							).mean() for k in self.metric_names + ["gen_time", "gen_len"]
						}
						__snake_case			=		(
						    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
						)
						__snake_case			=		torch.tensor(_UpperCAmelCase							).type_as(_UpperCAmelCase							)
						generative_metrics.update({k: v.item() for k, v in losses.items()}							)
						losses.update(_UpperCAmelCase							)
						__snake_case			=		{f'''{prefix}_avg_{k}''': x for k, x in losses.items()}
						__snake_case			=		self.step_count
						self.metrics[prefix].append(_UpperCAmelCase							)  # callback writes this to self.metrics_save_path
						__snake_case			=		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 							A (      self						:    Union[str, Any]      ,		a_						:    int      ,		a_						:    int							):



						"""simple docstring"""




						return calculate_rouge(_UpperCAmelCase      ,		_UpperCAmelCase							)





			def 							A (      self						:    Any      ,		a_						:    Optional[int]							):



						"""simple docstring"""




						__snake_case			=		time.time()

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





			def 							A (      self						:    List[str]      ,		a_						:    Optional[Any]      ,		a_						:    Any							):



						"""simple docstring"""




						return self._generative_step(_UpperCAmelCase							)





			def 							A (      self						:    Dict      ,		a_						:    str							):



						"""simple docstring"""




						return self.validation_epoch_end(_UpperCAmelCase      ,		prefix="test"							)





			def 							A (      self						:    int      ,		a_						:    str							):



						"""simple docstring"""




						__snake_case			=		self.n_obs[type_path]
						__snake_case			=		self.target_lens[type_path]
						__snake_case			=		self.dataset_class(
						    self.tokenizer      ,		type_path=_UpperCAmelCase      ,		n_obs=_UpperCAmelCase      ,		max_target_length=_UpperCAmelCase      ,		**self.dataset_kwargs      ,		)
						return dataset





			def 							A (      self						:    List[str]      ,		a_						:    Tuple      ,		a_						:    List[Any]      ,		a_						:    Tuple = False							):



						"""simple docstring"""




						__snake_case			=		self.get_dataset(_UpperCAmelCase							)

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

						elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
									__snake_case			=		dataset.make_dynamic_sampler(
									    self.hparams.max_tokens_per_batch      ,		distributed=self.hparams.gpus > 1							)
									return DataLoader(
									    _UpperCAmelCase      ,		batch_sampler=_UpperCAmelCase      ,		collate_fn=dataset.collate_fn      ,		num_workers=self.num_workers      ,		)
						else:
									return DataLoader(
									    _UpperCAmelCase      ,		batch_size=_UpperCAmelCase      ,		collate_fn=dataset.collate_fn      ,		shuffle=_UpperCAmelCase      ,		num_workers=self.num_workers      ,		sampler=_UpperCAmelCase      ,		)





			def 							A (      self						:    Optional[Any]							):



						"""simple docstring"""




						__snake_case			=		self.get_dataloader("train"      ,		batch_size=self.hparams.train_batch_size      ,		shuffle=_UpperCAmelCase							)
						return dataloader





			def 							A (      self						:    Optional[int]							):



						"""simple docstring"""




						return self.get_dataloader("val"      ,		batch_size=self.hparams.eval_batch_size							)





			def 							A (      self						:    int							):



						"""simple docstring"""




						return self.get_dataloader("test"      ,		batch_size=self.hparams.eval_batch_size							)






			@staticmethod
			def 							A (      a_						:    int      ,		a_						:    Optional[int]							):



						"""simple docstring"""




						BaseTransformer.add_model_specific_args(_UpperCAmelCase      ,		_UpperCAmelCase							)
						add_generic_args(_UpperCAmelCase      ,		_UpperCAmelCase							)
						parser.add_argument(
						    "--max_source_length"      ,		default=1_024      ,		type=_UpperCAmelCase      ,		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=56      ,		type=_UpperCAmelCase      ,		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=142      ,		type=_UpperCAmelCase      ,		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=142      ,		type=_UpperCAmelCase      ,		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=_UpperCAmelCase							)
						parser.add_argument("--overwrite_output_dir"      ,		action="store_true"      ,		default=_UpperCAmelCase							)
						parser.add_argument("--max_tokens_per_batch"      ,		type=_UpperCAmelCase      ,		default=_UpperCAmelCase							)
						parser.add_argument("--logger_name"      ,		type=_UpperCAmelCase      ,		choices=["default", "wandb", "wandb_shared"]      ,		default="default"							)
						parser.add_argument("--n_train"      ,		type=_UpperCAmelCase      ,		default=-1      ,		required=_UpperCAmelCase      ,		help="# examples. -1 means use all."							)
						parser.add_argument("--n_val"      ,		type=_UpperCAmelCase      ,		default=500      ,		required=_UpperCAmelCase      ,		help="# examples. -1 means use all."							)
						parser.add_argument("--n_test"      ,		type=_UpperCAmelCase      ,		default=-1      ,		required=_UpperCAmelCase      ,		help="# examples. -1 means use all."							)
						parser.add_argument(
						    "--task"      ,		type=_UpperCAmelCase      ,		default="summarization"      ,		required=_UpperCAmelCase      ,		help="# examples. -1 means use all."							)
						parser.add_argument("--label_smoothing"      ,		type=_UpperCAmelCase      ,		default=0.0      ,		required=_UpperCAmelCase							)
						parser.add_argument("--src_lang"      ,		type=_UpperCAmelCase      ,		default=""      ,		required=_UpperCAmelCase							)
						parser.add_argument("--tgt_lang"      ,		type=_UpperCAmelCase      ,		default=""      ,		required=_UpperCAmelCase							)
						parser.add_argument("--eval_beams"      ,		type=_UpperCAmelCase      ,		default=_UpperCAmelCase      ,		required=_UpperCAmelCase							)
						parser.add_argument(
						    "--val_metric"      ,		type=_UpperCAmelCase      ,		default=_UpperCAmelCase      ,		required=_UpperCAmelCase      ,		choices=["bleu", "rouge2", "loss", None]							)
						parser.add_argument("--eval_max_gen_length"      ,		type=_UpperCAmelCase      ,		default=_UpperCAmelCase      ,		help="never generate more than n tokens"							)
						parser.add_argument("--save_top_k"      ,		type=_UpperCAmelCase      ,		default=1      ,		required=_UpperCAmelCase      ,		help="How many checkpoints to save"							)
						parser.add_argument(
						    "--early_stopping_patience"      ,		type=_UpperCAmelCase      ,		default=-1      ,		required=_UpperCAmelCase      ,		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 		SCREAMING_SNAKE_CASE__  (			UpperCAmelCase__	):
			__SCREAMING_SNAKE_CASE    =			"""translation"""
			__SCREAMING_SNAKE_CASE    =			["""loss"""]
			__SCREAMING_SNAKE_CASE    =			["""bleu"""]
			__SCREAMING_SNAKE_CASE    =			"""bleu"""





			def __init__(      self						:    str      ,		a_						:    Tuple      ,		**a_						:    Union[str, Any]							):



						"""simple docstring"""




						super().__init__(_UpperCAmelCase      ,		**_UpperCAmelCase							)
						__snake_case			=		hparams.src_lang
						__snake_case			=		hparams.tgt_lang






			def 							A (      self						:    Tuple      ,		a_						:    Union[str, Any]      ,		a_						:    int							):



						"""simple docstring"""




						return calculate_bleu(_UpperCAmelCase      ,		_UpperCAmelCase							)







def __UpperCAmelCase	(   _UpperCAmelCase		:   Optional[Any]		,				_UpperCAmelCase		:   Tuple=None						)      ->      Dict:
			Path(args.output_dir						).mkdir(exist_ok=__lowercase						)
			check_output_dir(__lowercase		,				expected_items=3						)

			if model is None:
						if "summarization" in args.task:
									__snake_case			=		SummarizationModule(__lowercase						)
						else:
									__snake_case			=		TranslationModule(__lowercase						)
			__snake_case			=		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"						)
			):
						__snake_case			=		True  # don't pollute wandb logs unnecessarily
			elif args.logger_name == "wandb":
						from pytorch_lightning.loggers import WandbLogger

						__snake_case			=		os.environ.get("WANDB_PROJECT"		,				__lowercase						)
						__snake_case			=		WandbLogger(name=model.output_dir.name		,				project=__lowercase						)

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

						__snake_case			=		WandbLogger(name=model.output_dir.name		,				project=F'''hf_{dataset}'''						)

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

			__snake_case			=		args.val_metric == "loss"
			__snake_case			=		generic_train(
			    __lowercase		,				__lowercase		,				logging_callback=SeqaSeqLoggingCallback()		,				checkpoint_callback=get_checkpoint_callback(
			        args.output_dir		,				model.val_metric		,				args.save_top_k		,				__lowercase						)		,				early_stopping_callback=__lowercase		,				logger=__lowercase		,				)
			pickle_save(model.hparams		,				model.output_dir / "hparams.pkl"						)
			if not args.do_predict:
						return model

			__snake_case			=		""
			__snake_case			=		sorted(glob.glob(os.path.join(args.output_dir		,				"*.ckpt"						)		,				recursive=__lowercase						)						)
			if checkpoints:
						__snake_case			=		checkpoints[-1]
						__snake_case			=		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__":
						a       :						Union[str, Any]								=		argparse.ArgumentParser()
						a       :						Dict								=		pl.Trainer.add_argparse_args(parser)
						a       :						List[str]								=		SummarizationModule.add_model_specific_args(parser, os.getcwd())

						a       :						Optional[Any]								=		parser.parse_args()

						main(args)













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			)},
             ],
         ]		,		)





