


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_				:			Dict   =	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 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      np.ndarray:
             if self.framework == "tf":
                    a_ :		Optional[Any]							=  tf.where(input_ids == self.tokenizer.mask_token_id					).numpy()
             elif self.framework == "pt":
                    a_ :		Dict							=  torch.nonzero(input_ids == self.tokenizer.mask_token_id					,							as_tuple=SCREAMING_SNAKE_CASE__					)
             else:
                    raise ValueError('Unsupported framework'					)
             return masked_index
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      np.ndarray:
             a_ :		List[str]							=  self.get_masked_index(SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[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    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      Tuple:
             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 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	int=None					,							**SCREAMING_SNAKE_CASE__    :	Tuple					)		->      Dict[str, GenericTensor]:
             if return_tensors is None:
                    a_ :		str							=  self.framework
             a_ :		Tuple							=  self.tokenizer(SCREAMING_SNAKE_CASE__					,							return_tensors=SCREAMING_SNAKE_CASE__					)
             self.ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__					)
             return model_inputs
      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					)		->      str:
             a_ :		Dict							=  self.model(**SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  model_inputs['input_ids']
             return model_outputs
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	str=5					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=None					)		->      Optional[Any]:
             # Cap top_k if there are targets
             if target_ids is not None and target_ids.shape[0] < top_k:
                    a_ :		str							=  target_ids.shape[0]
             a_ :		Dict							=  model_outputs['input_ids'][0]
             a_ :		Tuple							=  model_outputs['logits']

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

                    a_ :		Any							=  outputs.numpy()

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

                    a_ :		Dict							=  tf.math.top_k(SCREAMING_SNAKE_CASE__					,							k=SCREAMING_SNAKE_CASE__					)
                    a_							,		a_ :		Union[str, Any]							=  topk.values.numpy(), topk.indices.numpy()
             else:
                    a_ :		Dict							=  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

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

                    a_							,		a_ :		str							=  probs.topk(SCREAMING_SNAKE_CASE__					)

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

                           a_ :		Optional[int]							=  p
                           # Filter padding out:
                           a_ :		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
                           a_ :		Union[str, Any]							=  self.tokenizer.decode(SCREAMING_SNAKE_CASE__					,							skip_special_tokens=SCREAMING_SNAKE_CASE__					)
                           a_ :		List[str]							=  {'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 	SCREAMING_SNAKE_CASE							(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	int=None					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    a_ :		Union[str, Any]							=  [targets]
             try:
                    a_ :		Union[str, Any]							=  self.tokenizer.get_vocab()
             except Exception:
                    a_ :		Optional[int]							=  {}
             a_ :		Any							=  []
             for target in targets:
                    a_ :		Optional[int]							=  vocab.get(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                    if id_ is None:
                           a_ :		str							=  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
                           a_ :		Optional[Any]							=  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_ :		Optional[int]							=  list(set(SCREAMING_SNAKE_CASE__					)					)
             if len(SCREAMING_SNAKE_CASE__					) == 0:
                    raise ValueError('At least one target must be provided when passed.'					)
             a_ :		List[str]							=  np.array(SCREAMING_SNAKE_CASE__					)
             return target_ids
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Any=None					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=None					)		->      List[str]:
             a_ :		Any							=  {}

             if targets is not None:
                    a_ :		List[str]							=  self.get_target_ids(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                    a_ :		Any							=  target_ids

             if top_k is not None:
                    a_ :		Tuple							=  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    :	int					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							*SCREAMING_SNAKE_CASE__    :	List[Any]					,							**SCREAMING_SNAKE_CASE__    :	Dict					)		->      Dict:
             a_ :		Optional[Any]							=  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






import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
   import torch

   from transformers.activations import gelu_new, gelu_python, get_activation
@require_torch
class 			SCREAMING_SNAKE_CASE__  (    unittest.TestCase      ):
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      List[str]:
             a_ :		List[str]							=  torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]					)
             a_ :		Union[str, Any]							=  get_activation('gelu'					)
             self.assertTrue(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__					)					,							torch_builtin(SCREAMING_SNAKE_CASE__					)					)					)
             self.assertFalse(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__					)					,							gelu_new(SCREAMING_SNAKE_CASE__					)					)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      Any:
             a_ :		List[str]							=  torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0]					)
             a_ :		Union[str, Any]							=  get_activation('gelu'					)
             a_ :		str							=  get_activation('gelu_10'					)

             a_ :		Tuple							=  torch_builtin(SCREAMING_SNAKE_CASE__					)
             a_ :		str							=  geluaa(SCREAMING_SNAKE_CASE__					)

             a_ :		List[Any]							=  torch.where(y_gelu_aa < 10.0					,							1					,							0					)

             self.assertTrue(torch.max(SCREAMING_SNAKE_CASE__					).item() == 10.0					)
             self.assertTrue(torch.allclose(y_gelu * clipped_mask					,							y_gelu_aa * clipped_mask					)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      List[Any]:
             get_activation('gelu'					)
             get_activation('gelu_10'					)
             get_activation('gelu_fast'					)
             get_activation('gelu_new'					)
             get_activation('gelu_python'					)
             get_activation('gelu_pytorch_tanh'					)
             get_activation('linear'					)
             get_activation('mish'					)
             get_activation('quick_gelu'					)
             get_activation('relu'					)
             get_activation('sigmoid'					)
             get_activation('silu'					)
             get_activation('swish'					)
             get_activation('tanh'					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    get_activation('bogus'					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    get_activation(SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	str					)		->      str:
             a_ :		Any							=  get_activation('gelu'					)
             a_ :		Any							=  1
             a_ :		int							=  get_activation('gelu'					)
             self.assertEqual(acta.a					,							1					)
             with self.assertRaises(SCREAMING_SNAKE_CASE__					):
                    a_ :		Tuple							=  acta.a


