




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


lowercase__				:     Union[str, Any] 		=						logging.get_logger(__name__)
@add_end_docstrings(
    _UpperCAmelCase       ,   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 		UpperCAmelCase   (				_UpperCAmelCase			):







						'''simple docstring'''





						def        snake_case__						(						self							:     Any       ,	__lowercase							:     GenericTensor						):






							"""simple docstring"""






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






						def        snake_case__						(						self							:     Optional[Any]       ,	__lowercase							:     GenericTensor						):






							"""simple docstring"""






							snake_case_		    =     self.get_masked_index(UpperCAmelCase_						)
							snake_case_		    =     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        snake_case__						(						self							:     Union[str, Any]       ,	__lowercase							:     GenericTensor						):






							"""simple docstring"""






							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        snake_case__						(						self							:     Any       ,	__lowercase							:     Optional[Any]       ,	__lowercase							:     str=None       ,	**__lowercase							:     Union[str, Any]						):






							"""simple docstring"""






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






						def        snake_case__						(						self							:     Tuple       ,	__lowercase							:     Dict						):






							"""simple docstring"""






							snake_case_		    =     self.model(**UpperCAmelCase_						)
							snake_case_		    =     model_inputs["input_ids"]
							return model_outputs






						def        snake_case__						(						self							:     Optional[int]       ,	__lowercase							:     List[Any]       ,	__lowercase							:     Union[str, Any]=5       ,	__lowercase							:     Dict=None						):






							"""simple docstring"""






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

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

								snake_case_		    =     outputs.numpy()

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

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

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

								snake_case_    ,      snake_case_		    =     probs.topk(UpperCAmelCase_						)

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

									snake_case_		    =     p
									# Filter padding out:
									snake_case_		    =     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
									snake_case_		    =     self.tokenizer.decode(UpperCAmelCase_       ,	skip_special_tokens=UpperCAmelCase_						)
									snake_case_		    =     {"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        snake_case__						(						self							:     Dict       ,	__lowercase							:     Tuple       ,	__lowercase							:     List[Any]=None						):






							"""simple docstring"""






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






						def        snake_case__						(						self							:     List[str]       ,	__lowercase							:     Optional[Any]=None       ,	__lowercase							:     List[Any]=None						):






							"""simple docstring"""






							snake_case_		    =     {}

							if targets is not None:
								snake_case_		    =     self.get_target_ids(UpperCAmelCase_       ,	UpperCAmelCase_						)
								snake_case_		    =     target_ids

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






							"""simple docstring"""






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


from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case								=  logging.get_logger(__name__)

__snake_case								=  {
    """facebook/xmod-base""": """https://huggingface.co/facebook/xmod-base/resolve/main/config.json""",
    """facebook/xmod-large-prenorm""": """https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json""",
    """facebook/xmod-base-13-125k""": """https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-125k""": """https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-195k""": """https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json""",
    """facebook/xmod-base-60-125k""": """https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json""",
    """facebook/xmod-base-60-265k""": """https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json""",
    """facebook/xmod-base-75-125k""": """https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json""",
    """facebook/xmod-base-75-269k""": """https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json""",
}




class 						lowercase__  (						_UpperCAmelCase  ):
	A__    :   int				       ="""xmod"""
	def __init__(			self							:   Optional[Any]       ,   UpperCAmelCase_							:   Optional[int]=30522       ,   UpperCAmelCase_							:   Union[str, Any]=768       ,   UpperCAmelCase_							:   List[str]=12       ,   UpperCAmelCase_							:   List[str]=12       ,   UpperCAmelCase_							:   List[str]=3072       ,   UpperCAmelCase_							:   Dict="gelu"       ,   UpperCAmelCase_							:   str=0.1       ,   UpperCAmelCase_							:   Dict=0.1       ,   UpperCAmelCase_							:   Optional[Any]=512       ,   UpperCAmelCase_							:   Any=2       ,   UpperCAmelCase_							:   Optional[Any]=0.02       ,   UpperCAmelCase_							:   Optional[Any]=1e-1_2       ,   UpperCAmelCase_							:   Any=1       ,   UpperCAmelCase_							:   Dict=0       ,   UpperCAmelCase_							:   Optional[int]=2       ,   UpperCAmelCase_							:   Tuple="absolute"       ,   UpperCAmelCase_							:   Union[str, Any]=True       ,   UpperCAmelCase_							:   Dict=None       ,   UpperCAmelCase_							:   Union[str, Any]=False       ,   UpperCAmelCase_							:   int=2       ,   UpperCAmelCase_							:   int=False       ,   UpperCAmelCase_							:   Optional[int]=True       ,   UpperCAmelCase_							:   List[Any]=True       ,   UpperCAmelCase_							:   Union[str, Any]=("en_XX",)       ,   UpperCAmelCase_							:   int=None       ,   **UpperCAmelCase_							:   str       ,   ):
						super().__init__(pad_token_id=UpperCAmelCase_       ,   bos_token_id=UpperCAmelCase_       ,   eos_token_id=UpperCAmelCase_       ,   **UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= vocab_size
						SCREAMING_SNAKE_CASE__													= hidden_size
						SCREAMING_SNAKE_CASE__													= num_hidden_layers
						SCREAMING_SNAKE_CASE__													= num_attention_heads
						SCREAMING_SNAKE_CASE__													= hidden_act
						SCREAMING_SNAKE_CASE__													= intermediate_size
						SCREAMING_SNAKE_CASE__													= hidden_dropout_prob
						SCREAMING_SNAKE_CASE__													= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__													= max_position_embeddings
						SCREAMING_SNAKE_CASE__													= type_vocab_size
						SCREAMING_SNAKE_CASE__													= initializer_range
						SCREAMING_SNAKE_CASE__													= layer_norm_eps
						SCREAMING_SNAKE_CASE__													= position_embedding_type
						SCREAMING_SNAKE_CASE__													= use_cache
						SCREAMING_SNAKE_CASE__													= classifier_dropout
						SCREAMING_SNAKE_CASE__													= pre_norm
						SCREAMING_SNAKE_CASE__													= adapter_reduction_factor
						SCREAMING_SNAKE_CASE__													= adapter_layer_norm
						SCREAMING_SNAKE_CASE__													= adapter_reuse_layer_norm
						SCREAMING_SNAKE_CASE__													= ln_before_adapter
						SCREAMING_SNAKE_CASE__													= list(UpperCAmelCase_							)
						SCREAMING_SNAKE_CASE__													= default_language





class 						lowercase__  (						_UpperCAmelCase  ):
	@property
	def      A_				(			self							:   List[Any]							):
						if self.task == "multiple-choice":
											SCREAMING_SNAKE_CASE__													= {0: 'batch', 1: 'choice', 2: 'sequence'}
						else:
											SCREAMING_SNAKE_CASE__													= {0: 'batch', 1: 'sequence'}
						return OrderedDict(
						    [
						        ('input_ids', dynamic_axis),
						        ('attention_mask', dynamic_axis),
						    ]							)





