



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


lowerCAmelCase__              =							logging.get_logger(__name__)






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




  def 		SCREAMING_SNAKE_CASE							(					self	:		str		,   __lowerCAmelCase	:		GenericTensor						):






         """simple docstring"""






         if self.framework == "tf":
                _lowerCamelCase		:							Optional[int]            =					tf.where(input_ids == self.tokenizer.mask_token_id						).numpy()
         elif self.framework == "pt":
                _lowerCamelCase		:							List[str]            =					torch.nonzero(input_ids == self.tokenizer.mask_token_id		,   as_tuple=__lowerCAmelCase						)
         else:
                raise ValueError('''Unsupported framework'''						)
         return masked_index




  def 		SCREAMING_SNAKE_CASE							(					self	:		Any		,   __lowerCAmelCase	:		GenericTensor						):






         """simple docstring"""






         _lowerCamelCase		:							Union[str, Any]            =					self.get_masked_index(__lowerCAmelCase						)
         _lowerCamelCase		:							Any            =					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	:		str		,   __lowerCAmelCase	:		GenericTensor						):






         """simple docstring"""






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




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[int]		,   __lowerCAmelCase	:		Optional[int]		,   __lowerCAmelCase	:		Union[str, Any]=None		,   **__lowerCAmelCase	:		Tuple						):






         """simple docstring"""






         if return_tensors is None:
                _lowerCamelCase		:							Dict            =					self.framework
         _lowerCamelCase		:							Dict            =					self.tokenizer(__lowerCAmelCase		,   return_tensors=__lowerCAmelCase						)
         self.ensure_exactly_one_mask_token(__lowerCAmelCase						)
         return model_inputs




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[Any]		,   __lowerCAmelCase	:		str						):






         """simple docstring"""






         _lowerCamelCase		:							str            =					self.model(**__lowerCAmelCase						)
         _lowerCamelCase		:							Union[str, Any]            =					model_inputs['''input_ids''']
         return model_outputs




  def 		SCREAMING_SNAKE_CASE							(					self	:		Tuple		,   __lowerCAmelCase	:		Dict		,   __lowerCAmelCase	:		List[Any]=5		,   __lowerCAmelCase	:		Tuple=None						):






         """simple docstring"""






         if target_ids is not None and target_ids.shape[0] < top_k:
                _lowerCamelCase		:							int            =					target_ids.shape[0]
         _lowerCamelCase		:							List[str]            =					model_outputs['''input_ids'''][0]
         _lowerCamelCase		:							int            =					model_outputs['''logits''']

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

                _lowerCamelCase		:							Union[str, Any]            =					outputs.numpy()

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

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

                _lowerCamelCase		:							Optional[int]            =					outputs[0, masked_index, :]
                _lowerCamelCase		:							int            =					logits.softmax(dim=-1						)
                if target_ids is not None:
                       _lowerCamelCase		:							List[str]            =					probs[..., target_ids]

                _lowerCamelCase     ,       _lowerCamelCase		:							Any            =					probs.topk(__lowerCAmelCase						)

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

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




  def 		SCREAMING_SNAKE_CASE							(					self	:		Tuple		,   __lowerCAmelCase	:		Any		,   __lowerCAmelCase	:		Tuple=None						):






         """simple docstring"""






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




  def 		SCREAMING_SNAKE_CASE							(					self	:		List[str]		,   __lowerCAmelCase	:		Optional[int]=None		,   __lowerCAmelCase	:		Optional[Any]=None						):






         """simple docstring"""






         _lowerCamelCase		:							str            =					{}

         if targets is not None:
                _lowerCamelCase		:							Dict            =					self.get_target_ids(__lowerCAmelCase		,   __lowerCAmelCase						)
                _lowerCamelCase		:							Dict            =					target_ids

         if top_k is not None:
                _lowerCamelCase		:							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	:		List[Any]		,   __lowerCAmelCase	:		Union[str, Any]		,   *__lowerCAmelCase	:		Dict		,   **__lowerCAmelCase	:		int						):






         """simple docstring"""






         _lowerCamelCase		:							Optional[Any]            =					super().__call__(__lowerCAmelCase		,   **__lowerCAmelCase						)
         if isinstance(__lowerCAmelCase		,   __lowerCAmelCase						) and len(__lowerCAmelCase						) == 1:
                return outputs[0]
         return outputs








'''simple docstring'''
import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE			=						{
    "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json",
}
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		"""mvp"""
					_UpperCamelCase							=		["""past_key_values"""]
					_UpperCamelCase							=		{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}



					def __init__(	self     :						List[str]      ,       _lowercase     :						int=50_267      ,       _lowercase     :						str=1_024      ,       _lowercase     :						int=12      ,       _lowercase     :						int=4_096      ,       _lowercase     :						Tuple=16      ,       _lowercase     :						Optional[Any]=12      ,       _lowercase     :						Union[str, Any]=4_096      ,       _lowercase     :						List[Any]=16      ,       _lowercase     :						str=0.0      ,       _lowercase     :						List[str]=0.0      ,       _lowercase     :						Dict="gelu"      ,       _lowercase     :						Union[str, Any]=1_024      ,       _lowercase     :						str=0.1      ,       _lowercase     :						List[Any]=0.0      ,       _lowercase     :						Any=0.0      ,       _lowercase     :						List[str]=0.02      ,       _lowercase     :						List[Any]=0.0      ,       _lowercase     :						List[str]=False      ,       _lowercase     :						Tuple=True      ,       _lowercase     :						Any=1      ,       _lowercase     :						Optional[Any]=0      ,       _lowercase     :						Dict=2      ,       _lowercase     :						int=True      ,       _lowercase     :						Any=2      ,       _lowercase     :						Tuple=2      ,       _lowercase     :						Optional[Any]=False      ,       _lowercase     :						List[str]=100      ,       _lowercase     :						List[str]=800      ,       **_lowercase     :						Dict      ,       )    ->							Dict:
								A_									= vocab_size
								A_									= max_position_embeddings
								A_									= d_model
								A_									= encoder_ffn_dim
								A_									= encoder_layers
								A_									= encoder_attention_heads
								A_									= decoder_ffn_dim
								A_									= decoder_layers
								A_									= decoder_attention_heads
								A_									= dropout
								A_									= attention_dropout
								A_									= activation_dropout
								A_									= activation_function
								A_									= init_std
								A_									= encoder_layerdrop
								A_									= decoder_layerdrop
								A_									= classifier_dropout
								A_									= use_cache
								A_									= encoder_layers
								A_									= scale_embedding  # scale factor will be sqrt(d_model) if True
								A_									= use_prompt
								A_									= prompt_length
								A_									= prompt_mid_dim

								super().__init__(
								    pad_token_id=_lowercase      ,       bos_token_id=_lowercase      ,       eos_token_id=_lowercase      ,       is_encoder_decoder=_lowercase      ,       decoder_start_token_id=_lowercase      ,       forced_eos_token_id=_lowercase      ,       **_lowercase      ,       )

								if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated'      ,       _lowercase):
											A_									= self.bos_token_id
											warnings.warn(
											    F'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. '
											    'The config can simply be saved and uploaded again to be fixed.')




