





'''simple docstring'''




from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
  import tensorflow as tf

  from ..tf_utils import stable_softmax


if is_torch_available():
  import torch


lowercase__   :				Optional[int] 		=   logging.get_logger(__name__)


@add_end_docstrings(
    a__ ,		r'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    ''' ,		)
class 			SCREAMING_SNAKE_CASE   (a__							):


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          if self.framework == "tf":
               __A						:			Tuple								=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
          elif self.framework == "pt":
               __A						:			str								=	torch.nonzero(input_ids == self.tokenizer.mask_token_id						,     as_tuple=_UpperCAmelCase)
          else:
               raise ValueError('Unsupported framework')
          return masked_index


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Optional[Any]								=	self.get_masked_index(_UpperCAmelCase)
          __A						:			List[str]								=	np.prod(masked_index.shape)
          if numel < 1:
               raise PipelineException(
                   'fill-mask'						,     self.model.base_model_prefix						,     F'No mask_token ({self.tokenizer.mask_token}) found on the input'						,     )


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase):
               for model_input in model_inputs:
                    self._ensure_exactly_one_mask_token(model_input['input_ids'][0])
          else:
               for input_ids in model_inputs["input_ids"]:
                    self._ensure_exactly_one_mask_token(_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=None						,     **_UpperCAmelCase):

          '''simple docstring'''






          if return_tensors is None:
               __A						:			List[Any]								=	self.framework
          __A						:			List[str]								=	self.tokenizer(_UpperCAmelCase						,     return_tensors=_UpperCAmelCase)
          self.ensure_exactly_one_mask_token(_UpperCAmelCase)
          return model_inputs


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Dict								=	self.model(**_UpperCAmelCase)
          __A						:			Optional[Any]								=	model_inputs['input_ids']
          return model_outputs


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=5						,     _UpperCAmelCase=None):

          '''simple docstring'''






          if target_ids is not None and target_ids.shape[0] < top_k:
               __A						:			Any								=	target_ids.shape[0]
          __A						:			Optional[Any]								=	model_outputs['input_ids'][0]
          __A						:			Dict								=	model_outputs['logits']

          if self.framework == "tf":
               __A						:			Tuple								=	tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

               __A						:			str								=	outputs.numpy()

               __A						:			Union[str, Any]								=	outputs[0, masked_index, :]
               __A						:			str								=	stable_softmax(_UpperCAmelCase						,     axis=-1)
               if target_ids is not None:
                    __A						:			Tuple								=	tf.gather_nd(tf.squeeze(_UpperCAmelCase						,     0)						,     target_ids.reshape(-1						,     1))
                    __A						:			Optional[int]								=	tf.expand_dims(_UpperCAmelCase						,     0)

               __A						:			int								=	tf.math.top_k(_UpperCAmelCase						,     k=_UpperCAmelCase)
               __A						:			str								=	topk.values.numpy(), topk.indices.numpy()
          else:
               __A						:			Optional[Any]								=	torch.nonzero(input_ids == self.tokenizer.mask_token_id						,     as_tuple=_UpperCAmelCase).squeeze(-1)
               # Fill mask pipeline supports only one ${mask_token} per sample

               __A						:			Tuple								=	outputs[0, masked_index, :]
               __A						:			Dict								=	logits.softmax(dim=-1)
               if target_ids is not None:
                    __A						:			Optional[Any]								=	probs[..., target_ids]

               __A						:			List[Any]								=	probs.topk(_UpperCAmelCase)

          __A						:			Dict								=	[]
          __A						:			Optional[int]								=	values.shape[0] == 1
          for i, (_values, _predictions) in enumerate(zip(values.tolist()						,     predictions.tolist())):
               __A						:			Dict								=	[]
               for v, p in zip(_values						,     _predictions):
                    # Copy is important since we're going to modify this array in place
                    __A						:			Optional[int]								=	input_ids.numpy().copy()
                    if target_ids is not None:
                         __A						:			Optional[int]								=	target_ids[p].tolist()

                    __A						:			List[Any]								=	p
                    # Filter padding out:
                    __A						:			Dict								=	tokens[np.where(tokens != self.tokenizer.pad_token_id)]
                    # Originally we skip special tokens to give readable output.
                    # For multi masks though, the other [MASK] would be removed otherwise
                    # making the output look odd, so we add them back
                    __A						:			Any								=	self.tokenizer.decode(_UpperCAmelCase						,     skip_special_tokens=_UpperCAmelCase)
                    __A						:			str								=	{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]), 'sequence': sequence}
                    row.append(_UpperCAmelCase)
               result.append(_UpperCAmelCase)
          if single_mask:
               return result[0]
          return result


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase						,     _UpperCAmelCase=None):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase):
               __A						:			Dict								=	[targets]
          try:
               __A						:			Optional[Any]								=	self.tokenizer.get_vocab()
          except Exception:
               __A						:			str								=	{}
          __A						:			List[str]								=	[]
          for target in targets:
               __A						:			Any								=	vocab.get(_UpperCAmelCase						,     _UpperCAmelCase)
               if id_ is None:
                    __A						:			str								=	self.tokenizer(
                        _UpperCAmelCase						,     add_special_tokens=_UpperCAmelCase						,     return_attention_mask=_UpperCAmelCase						,     return_token_type_ids=_UpperCAmelCase						,     max_length=1						,     truncation=_UpperCAmelCase						,     )['input_ids']
                    if len(_UpperCAmelCase) == 0:
                         logger.warning(
                             F'The specified target token `{target}` does not exist in the model vocabulary. '
                             'We cannot replace it with anything meaningful, ignoring it')
                         continue
                    __A						:			Dict								=	input_ids[0]
                    # XXX: If users encounter this pass
                    # it becomes pretty slow, so let's make sure
                    # The warning enables them to fix the input to
                    # get faster performance.
                    logger.warning(
                        F'The specified target token `{target}` does not exist in the model vocabulary. '
                        F'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.')
               target_ids.append(id_)
          __A						:			Dict								=	list(set(_UpperCAmelCase))
          if len(_UpperCAmelCase) == 0:
               raise ValueError('At least one target must be provided when passed.')
          __A						:			List[str]								=	np.array(_UpperCAmelCase)
          return target_ids


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase=None						,     _UpperCAmelCase=None):

          '''simple docstring'''






          __A						:			Optional[int]								=	{}

          if targets is not None:
               __A						:			Union[str, Any]								=	self.get_target_ids(_UpperCAmelCase						,     _UpperCAmelCase)
               __A						:			Dict								=	target_ids

          if top_k is not None:
               __A						:			Optional[int]								=	top_k

          if self.tokenizer.mask_token_id is None:
               raise PipelineException(
                   'fill-mask'						,     self.model.base_model_prefix						,     'The tokenizer does not define a `mask_token`.')
          return {}, {}, postprocess_params


     def __call__(						self						,     _UpperCAmelCase						,     *_UpperCAmelCase						,     **_UpperCAmelCase):

          '''simple docstring'''






          __A						:			Dict								=	super().__call__(_UpperCAmelCase						,     **_UpperCAmelCase)
          if isinstance(_UpperCAmelCase						,     _UpperCAmelCase) and len(_UpperCAmelCase) == 1:
               return outputs[0]
          return outputs






'''simple docstring'''




import os
from pathlib import Path

import numpy as np
import pytest
from pack_dataset import pack_data_dir
from parameterized import parameterized
from save_len_file import save_len_file
from torch.utils.data import DataLoader

from transformers import AutoTokenizer
from transformers.models.mbart.modeling_mbart import shift_tokens_right
from transformers.testing_utils import TestCasePlus, slow
from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset


lowercase__   :				List[Any]      =   '''bert-base-cased'''
lowercase__   :				Union[str, Any]      =   '''google/pegasus-xsum'''
lowercase__   :				str      =   [''' Sam ate lunch today.''', '''Sams lunch ingredients.''']
lowercase__   :				Optional[Any]      =   ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee''']
lowercase__   :				str      =   '''patrickvonplaten/t5-tiny-random'''
lowercase__   :				List[str]      =   '''sshleifer/bart-tiny-random'''
lowercase__   :				List[str]      =   '''sshleifer/tiny-mbart'''
lowercase__   :				str      =   '''sshleifer/tiny-marian-en-de'''






def 	_lowerCAmelCase      (  __snake_case  :			Path			,							__snake_case  :			list      )					->					str:
     __A						:			Any								=	'\n'.join(__snake_case      )
     Path(__snake_case      ).open('w'      ).writelines(__snake_case      )






def 	_lowerCAmelCase      (  __snake_case  :			Optional[int]      )					->					Tuple:
     for split in ["train", "val", "test"]:
          _dump_articles(os.path.join(__snake_case			,							f'{split}.source'      )			,							__snake_case      )
          _dump_articles(os.path.join(__snake_case			,							f'{split}.target'      )			,							__snake_case      )
     return tmp_dir







class 			SCREAMING_SNAKE_CASE   (a__							):


     @parameterized.expand(
         [
             MBART_TINY,
             MARIAN_TINY,
             T5_TINY,
             BART_TINY,
             PEGASUS_XSUM,
         ]						,     )
     @slow
     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			str								=	AutoTokenizer.from_pretrained(_UpperCAmelCase)
          __A						:			int								=	make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
          __A						:			int								=	max(len(tokenizer.encode(_UpperCAmelCase)) for a in ARTICLES)
          __A						:			str								=	max(len(tokenizer.encode(_UpperCAmelCase)) for a in SUMMARIES)
          __A						:			Dict								=	4
          __A						:			Optional[Any]								=	8
          assert max_len_target > max_src_len  # Will be truncated
          assert max_len_source > max_src_len  # Will be truncated
          __A			,__A						:			Any								=	'ro_RO', 'de_DE'  # ignored for all but mbart, but never causes error.
          __A						:			List[str]								=	SeqaSeqDataset(
              _UpperCAmelCase						,     data_dir=_UpperCAmelCase						,     type_path='train'						,     max_source_length=_UpperCAmelCase						,     max_target_length=_UpperCAmelCase						,     src_lang=_UpperCAmelCase						,     tgt_lang=_UpperCAmelCase						,     )
          __A						:			Any								=	DataLoader(_UpperCAmelCase						,     batch_size=2						,     collate_fn=train_dataset.collate_fn)
          for batch in dataloader:
               assert isinstance(_UpperCAmelCase						,     _UpperCAmelCase)
               assert batch["attention_mask"].shape == batch["input_ids"].shape
               # show that articles were trimmed.
               assert batch["input_ids"].shape[1] == max_src_len
               # show that targets are the same len
               assert batch["labels"].shape[1] == max_tgt_len
               if tok_name != MBART_TINY:
                    continue
               # check language codes in correct place
               __A						:			Optional[Any]								=	shift_tokens_right(batch['labels']						,     tokenizer.pad_token_id)
               assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang]
               assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id
               assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id
               assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang]

               break  # No need to test every batch


     @parameterized.expand([BART_TINY, BERT_BASE_CASED])
     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			str								=	AutoTokenizer.from_pretrained(_UpperCAmelCase)
          __A						:			Optional[int]								=	make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())
          __A						:			Tuple								=	max(len(tokenizer.encode(_UpperCAmelCase)) for a in ARTICLES)
          __A						:			Any								=	max(len(tokenizer.encode(_UpperCAmelCase)) for a in SUMMARIES)
          __A						:			Optional[int]								=	4
          __A						:			Any								=	LegacySeqaSeqDataset(
              _UpperCAmelCase						,     data_dir=_UpperCAmelCase						,     type_path='train'						,     max_source_length=20						,     max_target_length=_UpperCAmelCase						,     )
          __A						:			Union[str, Any]								=	DataLoader(_UpperCAmelCase						,     batch_size=2						,     collate_fn=train_dataset.collate_fn)
          for batch in dataloader:
               assert batch["attention_mask"].shape == batch["input_ids"].shape
               # show that articles were trimmed.
               assert batch["input_ids"].shape[1] == max_len_source
               assert 20 >= batch["input_ids"].shape[1]  # trimmed significantly
               # show that targets were truncated
               assert batch["labels"].shape[1] == trunc_target  # Truncated
               assert max_len_target > trunc_target  # Truncated
               break  # No need to test every batch


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						:			Dict								=	AutoTokenizer.from_pretrained('facebook/mbart-large-cc25')

          __A						:			int								=	Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()))
          __A						:			List[str]								=	tmp_dir.joinpath('train.source').open().readlines()
          __A						:			Optional[Any]								=	Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()))
          pack_data_dir(_UpperCAmelCase						,     _UpperCAmelCase						,     128						,     _UpperCAmelCase)
          __A						:			Dict								=	{x.name for x in tmp_dir.iterdir()}
          __A						:			Dict								=	{x.name for x in save_dir.iterdir()}
          __A						:			str								=	save_dir.joinpath('train.source').open().readlines()
          # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.']
          # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.']
          assert len(_UpperCAmelCase) < len(_UpperCAmelCase)
          assert len(_UpperCAmelCase) == 1
          assert len(packed_examples[0]) == sum(len(_UpperCAmelCase) for x in orig_examples)
          assert orig_paths == new_paths


     @pytest.mark.skipif(not FAIRSEQ_AVAILABLE						,     reason='This test requires fairseq')
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          if not FAIRSEQ_AVAILABLE:
               return
          __A			,__A			,__A						:			List[Any]								=	self._get_dataset(max_len=64)
          __A						:			Union[str, Any]								=	64
          __A						:			List[Any]								=	ds.make_dynamic_sampler(_UpperCAmelCase						,     required_batch_size_multiple=_UpperCAmelCase)
          __A						:			Union[str, Any]								=	[len(_UpperCAmelCase) for x in batch_sampler]
          assert len(set(_UpperCAmelCase)) > 1  # it's not dynamic batch size if every batch is the same length
          assert sum(_UpperCAmelCase) == len(_UpperCAmelCase)  # no dropped or added examples
          __A						:			List[Any]								=	DataLoader(_UpperCAmelCase						,     batch_sampler=_UpperCAmelCase						,     collate_fn=ds.collate_fn						,     num_workers=2)
          __A						:			Optional[int]								=	[]
          __A						:			Tuple								=	[]
          for batch in data_loader:
               __A						:			Optional[int]								=	batch['input_ids'].shape
               __A						:			Any								=	src_shape[0]
               assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple
               __A						:			Tuple								=	np.product(batch['input_ids'].shape)
               num_src_per_batch.append(_UpperCAmelCase)
               if num_src_tokens > (max_tokens * 1.1):
                    failures.append(_UpperCAmelCase)
          assert num_src_per_batch[0] == max(_UpperCAmelCase)
          if failures:
               raise AssertionError(F'too many tokens in {len(_UpperCAmelCase)} batches')


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A			,__A			,__A						:			Optional[int]								=	self._get_dataset(max_len=512)
          __A						:			Optional[int]								=	2
          __A						:			Dict								=	ds.make_sortish_sampler(_UpperCAmelCase						,     shuffle=_UpperCAmelCase)

          __A						:			Tuple								=	DataLoader(_UpperCAmelCase						,     batch_size=_UpperCAmelCase						,     collate_fn=ds.collate_fn						,     num_workers=2)
          __A						:			Union[str, Any]								=	DataLoader(_UpperCAmelCase						,     batch_size=_UpperCAmelCase						,     collate_fn=ds.collate_fn						,     num_workers=2						,     sampler=_UpperCAmelCase)

          __A						:			str								=	tokenizer.pad_token_id

          def count_pad_tokens(_UpperCAmelCase						,     _UpperCAmelCase="input_ids"):
               return [batch[k].eq(_UpperCAmelCase).sum().item() for batch in data_loader]

          assert sum(count_pad_tokens(_UpperCAmelCase						,     k='labels')) < sum(count_pad_tokens(_UpperCAmelCase						,     k='labels'))
          assert sum(count_pad_tokens(_UpperCAmelCase)) < sum(count_pad_tokens(_UpperCAmelCase))
          assert len(_UpperCAmelCase) == len(_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase=1000						,     _UpperCAmelCase=128):

          '''simple docstring'''






          if os.getenv('USE_REAL_DATA'						,     _UpperCAmelCase):
               __A						:			Dict								=	'examples/seq2seq/wmt_en_ro'
               __A						:			Any								=	max_len * 2 * 64
               if not Path(_UpperCAmelCase).joinpath('train.len').exists():
                    save_len_file(_UpperCAmelCase						,     _UpperCAmelCase)
          else:
               __A						:			int								=	'examples/seq2seq/test_data/wmt_en_ro'
               __A						:			Any								=	max_len * 4
               save_len_file(_UpperCAmelCase						,     _UpperCAmelCase)

          __A						:			Tuple								=	AutoTokenizer.from_pretrained(_UpperCAmelCase)
          __A						:			Optional[int]								=	SeqaSeqDataset(
              _UpperCAmelCase						,     data_dir=_UpperCAmelCase						,     type_path='train'						,     max_source_length=_UpperCAmelCase						,     max_target_length=_UpperCAmelCase						,     n_obs=_UpperCAmelCase						,     )
          return ds, max_tokens, tokenizer


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A			,__A			,__A						:			Tuple								=	self._get_dataset()
          __A						:			Optional[int]								=	set(DistributedSortishSampler(_UpperCAmelCase						,     256						,     num_replicas=2						,     rank=0						,     add_extra_examples=_UpperCAmelCase))
          __A						:			List[str]								=	set(DistributedSortishSampler(_UpperCAmelCase						,     256						,     num_replicas=2						,     rank=1						,     add_extra_examples=_UpperCAmelCase))
          assert idsa.intersection(_UpperCAmelCase) == set()


     @parameterized.expand(
         [
             MBART_TINY,
             MARIAN_TINY,
             T5_TINY,
             BART_TINY,
             PEGASUS_XSUM,
         ]						,     )
     def 							SCREAMING_SNAKE_CASE  (						self						,     _UpperCAmelCase):

          '''simple docstring'''






          __A						:			Union[str, Any]								=	AutoTokenizer.from_pretrained(_UpperCAmelCase						,     use_fast=_UpperCAmelCase)
          if tok_name == MBART_TINY:
               __A						:			Dict								=	SeqaSeqDataset(
                   _UpperCAmelCase						,     data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())						,     type_path='train'						,     max_source_length=4						,     max_target_length=8						,     src_lang='EN'						,     tgt_lang='FR'						,     )
               __A						:			List[Any]								=	train_dataset.dataset_kwargs
               assert "src_lang" in kwargs and "tgt_lang" in kwargs
          else:
               __A						:			Any								=	SeqaSeqDataset(
                   _UpperCAmelCase						,     data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir())						,     type_path='train'						,     max_source_length=4						,     max_target_length=8						,     )
               __A						:			List[str]								=	train_dataset.dataset_kwargs
               assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs
               assert len(_UpperCAmelCase) == 1 if tok_name == BART_TINY else len(_UpperCAmelCase) == 0