




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


SCREAMING_SNAKE_CASE__			: Tuple    =  logging.get_logger(__name__)




@add_end_docstrings(
    SCREAMING_SNAKE_CASE_       ,							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 						UpperCamelCase__      (SCREAMING_SNAKE_CASE_	):

    '''simple docstring'''



    def        _lowercase	(       self	,    UpperCamelCase__	)	-> str:


           if self.framework == "tf":
                  lowerCamelCase  : str     					=   tf.where(input_ids == self.tokenizer.mask_token_id	).numpy()
           elif self.framework == "pt":
                  lowerCamelCase  : List[Any]     					=   torch.nonzero(input_ids == self.tokenizer.mask_token_id	,    as_tuple=UpperCamelCase__	)
           else:
                  raise ValueError("Unsupported framework"	)
           return masked_index







    def        _lowercase	(       self	,    UpperCamelCase__	)	-> Optional[Any]:
           lowerCamelCase  : List[str]     					=   self.get_masked_index(UpperCamelCase__	)
           lowerCamelCase  : Union[str, 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        _lowercase	(       self	,    UpperCamelCase__	)	-> Dict:


           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        _lowercase	(       self	,    UpperCamelCase__	,    UpperCamelCase__=None	,    **UpperCamelCase__	)	-> List[Any]:


           if return_tensors is None:
                  lowerCamelCase  : Optional[int]     					=   self.framework
           lowerCamelCase  : List[Any]     					=   self.tokenizer(UpperCamelCase__	,    return_tensors=UpperCamelCase__	)
           self.ensure_exactly_one_mask_token(UpperCamelCase__	)
           return model_inputs







    def        _lowercase	(       self	,    UpperCamelCase__	)	-> List[Any]:
           lowerCamelCase  : List[Any]     					=   self.model(**UpperCamelCase__	)
           lowerCamelCase  : Optional[int]     					=   model_inputs['input_ids']
           return model_outputs







    def        _lowercase	(       self	,    UpperCamelCase__	,    UpperCamelCase__=5	,    UpperCamelCase__=None	)	-> Tuple:


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

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

                  lowerCamelCase  : int     					=   outputs.numpy()

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

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

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

                  lowerCamelCase  : str     					=   probs.topk(UpperCamelCase__	)

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

                         lowerCamelCase  : Optional[Any]     					=   p
                         # Filter padding out:
                         lowerCamelCase  : Tuple     					=   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  : List[str]     					=   self.tokenizer.decode(UpperCamelCase__	,    skip_special_tokens=UpperCamelCase__	)
                         lowerCamelCase  : List[Any]     					=   {'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        _lowercase	(       self	,    UpperCamelCase__	,    UpperCamelCase__=None	)	-> Optional[Any]:


           if isinstance(UpperCamelCase__	,    UpperCamelCase__	):
                  lowerCamelCase  : Dict     					=   [targets]
           try:
                  lowerCamelCase  : Tuple     					=   self.tokenizer.get_vocab()
           except Exception:
                  lowerCamelCase  : Dict     					=   {}
           lowerCamelCase  : Union[str, Any]     					=   []
           for target in targets:
                  lowerCamelCase  : Union[str, Any]     					=   vocab.get(UpperCamelCase__	,    UpperCamelCase__	)
                  if id_ is None:
                         lowerCamelCase  : 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
                         lowerCamelCase  : 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_	)
           lowerCamelCase  : List[str]     					=   list(set(UpperCamelCase__	)	)
           if len(UpperCamelCase__	) == 0:
                  raise ValueError("At least one target must be provided when passed."	)
           lowerCamelCase  : List[Any]     					=   np.array(UpperCamelCase__	)
           return target_ids







    def        _lowercase	(       self	,    UpperCamelCase__=None	,    UpperCamelCase__=None	)	-> str:
           lowerCamelCase  : Any     					=   {}

           if targets is not None:
                  lowerCamelCase  : Dict     					=   self.get_target_ids(UpperCamelCase__	,    UpperCamelCase__	)
                  lowerCamelCase  : Optional[int]     					=   target_ids

           if top_k is not None:
                  lowerCamelCase  : List[Any]     					=   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__	)	-> Any:
           lowerCamelCase  : List[Any]     					=   super().__call__(UpperCamelCase__	,    **UpperCamelCase__	)
           if isinstance(UpperCamelCase__	,    UpperCamelCase__	) and len(UpperCamelCase__	) == 1:
                  return outputs[0]
           return outputs











import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
			import jax.numpy as jnp

			from transformers.models.distilbert.modeling_flax_distilbert import (
			    FlaxDistilBertForMaskedLM,
			    FlaxDistilBertForMultipleChoice,
			    FlaxDistilBertForQuestionAnswering,
			    FlaxDistilBertForSequenceClassification,
			    FlaxDistilBertForTokenClassification,
			    FlaxDistilBertModel,
			)


class 						lowercase    (							unittest.TestCase):
						'''simple docstring'''


						def __init__(  self    :				int       ,	snake_case    :				Optional[Any]       ,	snake_case    :				Optional[Any]=13       ,	snake_case    :				str=7       ,	snake_case    :				Optional[Any]=True       ,	snake_case    :				int=True       ,	snake_case    :				str=True       ,	snake_case    :				List[str]=True       ,	snake_case    :				Optional[Any]=99       ,	snake_case    :				Optional[int]=32       ,	snake_case    :				Optional[int]=5       ,	snake_case    :				Optional[Any]=4       ,	snake_case    :				Optional[Any]=37       ,	snake_case    :				str="gelu"       ,	snake_case    :				List[str]=0.1       ,	snake_case    :				List[str]=0.1       ,	snake_case    :				int=512       ,	snake_case    :				Union[str, Any]=16       ,	snake_case    :				Optional[Any]=2       ,	snake_case    :				int=0.02       ,	snake_case    :				str=4       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				parent
											SCREAMING_SNAKE_CASE							:     str						=				batch_size
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				seq_length
											SCREAMING_SNAKE_CASE							:     int						=				is_training
											SCREAMING_SNAKE_CASE							:     List[str]						=				use_attention_mask
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				use_token_type_ids
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				use_labels
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				vocab_size
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				hidden_size
											SCREAMING_SNAKE_CASE							:     Any						=				num_hidden_layers
											SCREAMING_SNAKE_CASE							:     Tuple						=				num_attention_heads
											SCREAMING_SNAKE_CASE							:     Any						=				intermediate_size
											SCREAMING_SNAKE_CASE							:     Tuple						=				hidden_act
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				hidden_dropout_prob
											SCREAMING_SNAKE_CASE							:     str						=				attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE							:     Tuple						=				max_position_embeddings
											SCREAMING_SNAKE_CASE							:     Any						=				type_vocab_size
											SCREAMING_SNAKE_CASE							:     List[Any]						=				type_sequence_label_size
											SCREAMING_SNAKE_CASE							:     Tuple						=				initializer_range
											SCREAMING_SNAKE_CASE							:     List[str]						=				num_choices







						def       lowerCamelCase_				(  self    :				List[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				ids_tensor([self.batch_size, self.seq_length]       ,	self.vocab_size	)

											SCREAMING_SNAKE_CASE							:     Optional[int]						=				None
											if self.use_attention_mask:
																SCREAMING_SNAKE_CASE							:     Any						=				random_attention_mask([self.batch_size, self.seq_length]	)

											SCREAMING_SNAKE_CASE							:     Tuple						=				DistilBertConfig(
											    vocab_size=self.vocab_size       ,	dim=self.hidden_size       ,	n_layers=self.num_hidden_layers       ,	n_heads=self.num_attention_heads       ,	hidden_dim=self.intermediate_size       ,	hidden_act=self.hidden_act       ,	dropout=self.hidden_dropout_prob       ,	attention_dropout=self.attention_probs_dropout_prob       ,	max_position_embeddings=self.max_position_embeddings       ,	initializer_range=self.initializer_range       ,	tie_weights_=snake_case       ,	)

											return config, input_ids, attention_mask







						def       lowerCamelCase_				(  self    :				int	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE					,  SCREAMING_SNAKE_CASE					,  SCREAMING_SNAKE_CASE							:     Optional[int]						=				config_and_inputs
											SCREAMING_SNAKE_CASE							:     int						=				{'input_ids': input_ids, 'attention_mask': attention_mask}
											return config, inputs_dict


@require_flax
class 						lowercase    (							SCREAMING_SNAKE_CASE_      ,    unittest.TestCase):
						'''simple docstring'''


						UpperCAmelCase			:		int		=		(
						    (
						        FlaxDistilBertModel,
						        FlaxDistilBertForMaskedLM,
						        FlaxDistilBertForMultipleChoice,
						        FlaxDistilBertForQuestionAnswering,
						        FlaxDistilBertForSequenceClassification,
						        FlaxDistilBertForTokenClassification,
						        FlaxDistilBertForQuestionAnswering,
						    )
						    if is_flax_available()
						    else ()
						)







						def       lowerCamelCase_				(  self    :				Optional[int]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				FlaxDistilBertModelTester(self	)







						@slow
						def       lowerCamelCase_				(  self    :				Any	):



											'''simple docstring'''


											for model_class_name in self.all_model_classes:
																SCREAMING_SNAKE_CASE							:     Dict						=				model_class_name.from_pretrained('distilbert-base-uncased'	)
																SCREAMING_SNAKE_CASE							:     Dict						=				model(np.ones((1, 1)	)	)
																self.assertIsNotNone(snake_case	)


@require_flax
class 						lowercase    (							unittest.TestCase):
						'''simple docstring'''


						@slow
						def       lowerCamelCase_				(  self    :				Tuple	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[Any]						=				FlaxDistilBertModel.from_pretrained('distilbert-base-uncased'	)
											SCREAMING_SNAKE_CASE							:     List[str]						=				np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]	)
											SCREAMING_SNAKE_CASE							:     Dict						=				np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
											SCREAMING_SNAKE_CASE							:     str						=				model(snake_case       ,	attention_mask=snake_case	)[0]
											SCREAMING_SNAKE_CASE							:     int						=				(1, 11, 768)
											self.assertEqual(output.shape       ,	snake_case	)
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]	)

											self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]       ,	snake_case       ,	atol=1E-4	)	)