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


UpperCAmelCase        =				logging.get_logger(__name__)



@add_end_docstrings(
    lowercase__   ,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 			lowercase					( lowercase__		):






			def 					UpperCAmelCase							(self  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	GenericTensor			)       ->	np.ndarray:





				"""simple docstring"""


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






			def 					UpperCAmelCase							(self  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	GenericTensor			)       ->	np.ndarray:





				"""simple docstring"""


				lowerCAmelCase												=  self.get_masked_index(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  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 					UpperCAmelCase							(self  :	Any      ,SCREAMING_SNAKE_CASE_  :	GenericTensor			)       ->	str:





				"""simple docstring"""


				if isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
					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(SCREAMING_SNAKE_CASE_			)






			def 					UpperCAmelCase							(self  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]=None      ,**SCREAMING_SNAKE_CASE_  :	Tuple			)       ->	Dict[str, GenericTensor]:





				"""simple docstring"""


				if return_tensors is None:
					lowerCAmelCase												=  self.framework
				lowerCAmelCase												=  self.tokenizer(SCREAMING_SNAKE_CASE_      ,return_tensors=SCREAMING_SNAKE_CASE_			)
				self.ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE_			)
				return model_inputs






			def 					UpperCAmelCase							(self  :	Optional[int]      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	int:





				"""simple docstring"""


				lowerCAmelCase												=  self.model(**SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  model_inputs['''input_ids''']
				return model_outputs






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	Dict=5      ,SCREAMING_SNAKE_CASE_  :	List[Any]=None			)       ->	Tuple:





				"""simple docstring"""


				if target_ids is not None and target_ids.shape[0] < top_k:
					lowerCAmelCase												=  target_ids.shape[0]
				lowerCAmelCase												=  model_outputs['''input_ids'''][0]
				lowerCAmelCase												=  model_outputs['''logits''']

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

					lowerCAmelCase												=  outputs.numpy()

					lowerCAmelCase												=  outputs[0, masked_index, :]
					lowerCAmelCase												=  stable_softmax(SCREAMING_SNAKE_CASE_      ,axis=-1			)
					if target_ids is not None:
						lowerCAmelCase												=  tf.gather_nd(tf.squeeze(SCREAMING_SNAKE_CASE_      ,0			)      ,target_ids.reshape(-1      ,1			)			)
						lowerCAmelCase												=  tf.expand_dims(SCREAMING_SNAKE_CASE_      ,0			)

					lowerCAmelCase												=  tf.math.top_k(SCREAMING_SNAKE_CASE_      ,k=SCREAMING_SNAKE_CASE_			)
					lowerCAmelCase							,       lowerCAmelCase												=  topk.values.numpy(), topk.indices.numpy()
				else:
					lowerCAmelCase												=  torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,as_tuple=SCREAMING_SNAKE_CASE_			).squeeze(-1			)
					# Fill mask pipeline supports only one ${mask_token} per sample

					lowerCAmelCase												=  outputs[0, masked_index, :]
					lowerCAmelCase												=  logits.softmax(dim=-1			)
					if target_ids is not None:
						lowerCAmelCase												=  probs[..., target_ids]

					lowerCAmelCase							,       lowerCAmelCase												=  probs.topk(SCREAMING_SNAKE_CASE_			)

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

						lowerCAmelCase												=  p
						# Filter padding out:
						lowerCAmelCase												=  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
						lowerCAmelCase												=  self.tokenizer.decode(SCREAMING_SNAKE_CASE_      ,skip_special_tokens=SCREAMING_SNAKE_CASE_			)
						lowerCAmelCase												=  {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]			), '''sequence''': sequence}
						row.append(SCREAMING_SNAKE_CASE_			)
					result.append(SCREAMING_SNAKE_CASE_			)
				if single_mask:
					return result[0]
				return result






			def 					UpperCAmelCase							(self  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	List[str]=None			)       ->	Dict:





				"""simple docstring"""


				if isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
					lowerCAmelCase												=  [targets]
				try:
					lowerCAmelCase												=  self.tokenizer.get_vocab()
				except Exception:
					lowerCAmelCase												=  {}
				lowerCAmelCase												=  []
				for target in targets:
					lowerCAmelCase												=  vocab.get(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)
					if id_ is None:
						lowerCAmelCase												=  self.tokenizer(
						    SCREAMING_SNAKE_CASE_      ,add_special_tokens=SCREAMING_SNAKE_CASE_      ,return_attention_mask=SCREAMING_SNAKE_CASE_      ,return_token_type_ids=SCREAMING_SNAKE_CASE_      ,max_length=1      ,truncation=SCREAMING_SNAKE_CASE_      ,)['''input_ids''']
						if len(SCREAMING_SNAKE_CASE_			) == 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
						lowerCAmelCase												=  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_			)
				lowerCAmelCase												=  list(set(SCREAMING_SNAKE_CASE_			)			)
				if len(SCREAMING_SNAKE_CASE_			) == 0:
					raise ValueError('''At least one target must be provided when passed.'''			)
				lowerCAmelCase												=  np.array(SCREAMING_SNAKE_CASE_			)
				return target_ids






			def 					UpperCAmelCase							(self  :	List[str]      ,SCREAMING_SNAKE_CASE_  :	Any=None      ,SCREAMING_SNAKE_CASE_  :	List[Any]=None			)       ->	Union[str, Any]:





				"""simple docstring"""


				lowerCAmelCase												=  {}

				if targets is not None:
					lowerCAmelCase												=  self.get_target_ids(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)
					lowerCAmelCase												=  target_ids

				if top_k is not None:
					lowerCAmelCase												=  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  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	Tuple      ,*SCREAMING_SNAKE_CASE_  :	List[Any]      ,**SCREAMING_SNAKE_CASE_  :	List[str]			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  super().__call__(SCREAMING_SNAKE_CASE_      ,**SCREAMING_SNAKE_CASE_			)
				if isinstance(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			) and len(SCREAMING_SNAKE_CASE_			) == 1:
					return outputs[0]
				return outputs




"""simple docstring"""






import tempfile
import unittest

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
    is_torch_available,
    require_optimum,
    require_torch,
    slow,
)


if is_torch_available():
					import torch



@require_torch
@require_optimum
@slow
class 			lowercase					( unittest.TestCase		):






			def 					UpperCAmelCase							(self  :	Tuple			)       ->	Optional[int]:





				"""simple docstring"""


				lowerCAmelCase												=  '''hf-internal-testing/tiny-random-t5'''
				lowerCAmelCase												=  AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  tokenizer('''This is me'''      ,return_tensors='''pt'''			)

				lowerCAmelCase												=  model.to_bettertransformer()

				self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules()			)			)

				lowerCAmelCase												=  model.generate(**SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  model.reverse_bettertransformer()

				self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules()			)			)

				with tempfile.TemporaryDirectory() as tmpdirname:
					model.save_pretrained(SCREAMING_SNAKE_CASE_			)

					lowerCAmelCase												=  AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_			)

					self.assertFalse(
					    any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules()			)			)

					lowerCAmelCase												=  model_reloaded.generate(**SCREAMING_SNAKE_CASE_			)
					self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)			)






			def 					UpperCAmelCase							(self  :	str			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  '''hf-internal-testing/tiny-random-t5'''
				lowerCAmelCase												=  AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE_			)

				lowerCAmelCase												=  model.to_bettertransformer()

				with tempfile.TemporaryDirectory() as tmpdirname:
					with self.assertRaises(SCREAMING_SNAKE_CASE_			):
						model.save_pretrained(SCREAMING_SNAKE_CASE_			)

					lowerCAmelCase												=  model.reverse_bettertransformer()
					model.save_pretrained(SCREAMING_SNAKE_CASE_			)


