






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 :      List[Any]										=				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 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					def 	_lowercase					( self					:  Union[str, Any]							,		__A					:  GenericTensor	):
						if self.framework == "tf":
							snake_case__			:				int       =  tf.where(input_ids == self.tokenizer.mask_token_id	).numpy()
						elif self.framework == "pt":
							snake_case__			:				List[str]       =  torch.nonzero(input_ids == self.tokenizer.mask_token_id							,		as_tuple=__A	)
						else:
							raise ValueError("Unsupported framework"	)
						return masked_index



					def 	_lowercase					( self					:  str							,		__A					:  GenericTensor	):
						snake_case__			:				Tuple       =  self.get_masked_index(__A	)
						snake_case__			:				str       =  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					:  List[Any]							,		__A					:  GenericTensor	):
						if isinstance(__A							,		__A	):
							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(__A	)



					def 	_lowercase					( self					:  Union[str, Any]							,		__A					:  Union[str, Any]							,		__A					:  List[str]=None							,		**__A					:  List[str]	):
						if return_tensors is None:
							snake_case__			:				Tuple       =  self.framework
						snake_case__			:				Union[str, Any]       =  self.tokenizer(__A							,		return_tensors=__A	)
						self.ensure_exactly_one_mask_token(__A	)
						return model_inputs



					def 	_lowercase					( self					:  List[Any]							,		__A					:  Dict	):
						snake_case__			:				int       =  self.model(**__A	)
						snake_case__			:				str       =  model_inputs["input_ids"]
						return model_outputs



					def 	_lowercase					( self					:  List[str]							,		__A					:  List[Any]							,		__A					:  str=5							,		__A					:  Union[str, Any]=None	):
						# Cap top_k if there are targets
						if target_ids is not None and target_ids.shape[0] < top_k:
							snake_case__			:				List[Any]       =  target_ids.shape[0]
						snake_case__			:				int       =  model_outputs["input_ids"][0]
						snake_case__			:				Dict       =  model_outputs["logits"]

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

							snake_case__			:				List[Any]       =  outputs.numpy()

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

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

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

							snake_case__			:				Optional[Any]       =  probs.topk(__A	)

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

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



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



					def 	_lowercase					( self					:  Tuple							,		__A					:  List[str]=None							,		__A					:  Any=None	):
						snake_case__			:				Optional[int]       =  {}

						if targets is not None:
							snake_case__			:				Union[str, Any]       =  self.get_target_ids(__A							,		__A	)
							snake_case__			:				List[str]       =  target_ids

						if top_k is not None:
							snake_case__			:				Dict       =  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[str]							,		__A					:  List[Any]							,		*__A					:  List[str]							,		**__A					:  Optional[int]	):
						snake_case__			:				Optional[int]       =  super().__call__(__A							,		**__A	)
						if isinstance(__A							,		__A	) and len(__A	) == 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


__lowerCamelCase :      Optional[int]										=				logging.get_logger(__name__)

__lowerCamelCase :      str										=				{
    """andreasmadsen/efficient_mlm_m0.40""": (
        """https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json"""
    ),
}



class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					a_     =		"roberta-prelayernorm"



					def __init__( self					:  Tuple							,		__A					:  Any=5_0_2_6_5							,		__A					:  Optional[int]=7_6_8							,		__A					:  Dict=1_2							,		__A					:  Union[str, Any]=1_2							,		__A					:  List[Any]=3_0_7_2							,		__A					:  Optional[Any]="gelu"							,		__A					:  Optional[int]=0.1							,		__A					:  Tuple=0.1							,		__A					:  Optional[Any]=5_1_2							,		__A					:  List[str]=2							,		__A					:  Optional[int]=0.0_2							,		__A					:  Tuple=1e-1_2							,		__A					:  Any=1							,		__A					:  str=0							,		__A					:  int=2							,		__A					:  List[str]="absolute"							,		__A					:  Optional[Any]=True							,		__A					:  List[Any]=None							,		**__A					:  Optional[Any]							,		):
						super().__init__(pad_token_id=__A							,		bos_token_id=__A							,		eos_token_id=__A							,		**__A	)

						snake_case__			:				Tuple       =  vocab_size
						snake_case__			:				Optional[Any]       =  hidden_size
						snake_case__			:				List[Any]       =  num_hidden_layers
						snake_case__			:				List[Any]       =  num_attention_heads
						snake_case__			:				Dict       =  hidden_act
						snake_case__			:				Union[str, Any]       =  intermediate_size
						snake_case__			:				List[Any]       =  hidden_dropout_prob
						snake_case__			:				Any       =  attention_probs_dropout_prob
						snake_case__			:				int       =  max_position_embeddings
						snake_case__			:				Tuple       =  type_vocab_size
						snake_case__			:				Optional[int]       =  initializer_range
						snake_case__			:				int       =  layer_norm_eps
						snake_case__			:				Dict       =  position_embedding_type
						snake_case__			:				int       =  use_cache
						snake_case__			:				Dict       =  classifier_dropout



class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					@property
					def 	_lowercase					( self					:  Optional[int]	):
						if self.task == "multiple-choice":
							snake_case__			:				List[str]       =  {0: "batch", 1: "choice", 2: "sequence"}
						else:
							snake_case__			:				Tuple       =  {0: "batch", 1: "sequence"}
						return OrderedDict(
						    [
						        ("input_ids", dynamic_axis),
						        ("attention_mask", dynamic_axis),
						    ]	)



