





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


a_			=      logging.get_logger(__name__)






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





	"""simple docstring"""


	def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



					'''simple docstring'''




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

	def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



					'''simple docstring'''




					__A   :						List[str]									=					self.get_masked_index(_lowerCAmelCase  )
					__A   :						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  UpperCamelCase__(   self ,						__lowerCamelCase  ):



					'''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  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=None ,						**__lowerCamelCase  ):



					'''simple docstring'''




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

	def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



					'''simple docstring'''




					__A   :						List[str]									=					self.model(**_lowerCAmelCase  )
					__A   :						Optional[int]									=					model_inputs["""input_ids"""]
					return model_outputs

	def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=5 ,						__lowerCamelCase=None  ):



					'''simple docstring'''




					if target_ids is not None and target_ids.shape[0] < top_k:
									__A   :						Optional[int]									=					target_ids.shape[0]
					__A   :						Dict									=					model_outputs["""input_ids"""][0]
					__A   :						List[str]									=					model_outputs["""logits"""]

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

									__A   :						Optional[Any]									=					outputs.numpy()

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

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

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

									__A   :						Tuple									=					probs.topk(_lowerCAmelCase  )

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

													__A   :						Any									=					p
													# Filter padding out:
													__A   :						List[Any]									=					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   :						int									=					self.tokenizer.decode(_lowerCAmelCase ,						skip_special_tokens=_lowerCAmelCase  )
													__A   :						str									=					{"""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  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase=None  ):



					'''simple docstring'''




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

	def  UpperCamelCase__(   self ,						__lowerCamelCase=None ,						__lowerCamelCase=None  ):



					'''simple docstring'''




					__A   :						Tuple									=					{}

					if targets is not None:
									__A   :						int									=					self.get_target_ids(_lowerCAmelCase ,						_lowerCAmelCase  )
									__A   :						Optional[int]									=					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 ,						__lowerCamelCase ,						*__lowerCamelCase ,						**__lowerCamelCase  ):



					'''simple docstring'''




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











"""simple docstring"""



from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable


a_			=      {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_			=      ["""GPTNeoXTokenizerFast"""]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_			=      [
           """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """GPTNeoXForCausalLM""",
           """GPTNeoXForQuestionAnswering""",
           """GPTNeoXForSequenceClassification""",
           """GPTNeoXForTokenClassification""",
           """GPTNeoXLayer""",
           """GPTNeoXModel""",
           """GPTNeoXPreTrainedModel""",
       ]


if TYPE_CHECKING:
       from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_gpt_neox import (
                  GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
                  GPTNeoXForCausalLM,
                  GPTNeoXForQuestionAnswering,
                  GPTNeoXForSequenceClassification,
                  GPTNeoXForTokenClassification,
                  GPTNeoXLayer,
                  GPTNeoXModel,
                  GPTNeoXPreTrainedModel,
              )


else:
       import sys

       a_			=      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




