

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


__UpperCamelCase  :      str							      =		logging.get_logger(__name__)







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






					"""simple docstring"""



					def        __lowerCAmelCase (       self			:				int   ,lowercase_			:				GenericTensor		):
						if self.framework == "tf":
							lowerCAmelCase__	:						str  				=	tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
						elif self.framework == "pt":
							lowerCAmelCase__	:						Optional[Any]  				=	torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,as_tuple=lowercase_		)
						else:
							raise ValueError('''Unsupported framework'''		)
						return masked_index







					def        __lowerCAmelCase (       self			:				str   ,lowercase_			:				GenericTensor		):
						lowerCAmelCase__	:						str  				=	self.get_masked_index(lowercase_		)
						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        __lowerCAmelCase (       self			:				Dict   ,lowercase_			:				GenericTensor		):
						if isinstance(lowercase_   ,lowercase_		):
							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(lowercase_		)







					def        __lowerCAmelCase (       self			:				List[str]   ,lowercase_			:				Tuple   ,lowercase_			:				int=None   ,**lowercase_			:				Union[str, Any]		):
						if return_tensors is None:
							lowerCAmelCase__	:						int  				=	self.framework
						lowerCAmelCase__	:						Dict  				=	self.tokenizer(lowercase_   ,return_tensors=lowercase_		)
						self.ensure_exactly_one_mask_token(lowercase_		)
						return model_inputs







					def        __lowerCAmelCase (       self			:				str   ,lowercase_			:				List[Any]		):
						lowerCAmelCase__	:						Optional[int]  				=	self.model(**lowercase_		)
						lowerCAmelCase__	:						Union[str, Any]  				=	model_inputs["input_ids"]
						return model_outputs







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

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

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

							lowerCAmelCase__	:						int  				=	outputs[0, masked_index, :]
							lowerCAmelCase__	:						Optional[int]  				=	stable_softmax(lowercase_   ,axis=-1		)
							if target_ids is not None:
								lowerCAmelCase__	:						str  				=	tf.gather_nd(tf.squeeze(lowercase_   ,0		)   ,target_ids.reshape(-1   ,1		)		)
								lowerCAmelCase__	:						Dict  				=	tf.expand_dims(lowercase_   ,0		)

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

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

							lowerCAmelCase__	:						str  				=	probs.topk(lowercase_		)

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

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







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







					def        __lowerCAmelCase (       self			:				str   ,lowercase_			:				List[str]=None   ,lowercase_			:				str=None		):
						lowerCAmelCase__	:						List[str]  				=	{}

						if targets is not None:
							lowerCAmelCase__	:						Tuple  				=	self.get_target_ids(lowercase_   ,lowercase_		)
							lowerCAmelCase__	:						str  				=	target_ids

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


UpperCamelCase  							=						logging.get_logger(__name__)

UpperCamelCase  							=						{
    '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''',
    '''YituTech/conv-bert-medium-small''': (
        '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json'''
    ),
    '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''',
    # See all ConvBERT models at https://huggingface.co/models?filter=convbert
}



class   snake_case_       (		__A       ):
   __A	:		List[str]         =				"convbert"






   def __init__(      self				:     Union[str, Any]	,						lowercase_				:     str=3_05_22	,						lowercase_				:     Any=7_68	,						lowercase_				:     Tuple=12	,						lowercase_				:     List[str]=12	,						lowercase_				:     Optional[int]=30_72	,						lowercase_				:     Union[str, Any]="gelu"	,						lowercase_				:     str=0.1	,						lowercase_				:     List[str]=0.1	,						lowercase_				:     Optional[Any]=5_12	,						lowercase_				:     Dict=2	,						lowercase_				:     Union[str, Any]=0.02	,						lowercase_				:     Optional[Any]=1E-12	,						lowercase_				:     Optional[int]=1	,						lowercase_				:     List[Any]=0	,						lowercase_				:     Optional[int]=2	,						lowercase_				:     str=7_68	,						lowercase_				:     Dict=2	,						lowercase_				:     Optional[Any]=9	,						lowercase_				:     Union[str, Any]=1	,						lowercase_				:     Any=None	,						**lowercase_				:     Optional[Any]	,						)					->						Dict:
       super().__init__(
           pad_token_id=lowercase_	,						bos_token_id=lowercase_	,						eos_token_id=lowercase_	,						**lowercase_	,						)

       lowercase__ :   List[str]    					=				vocab_size
       lowercase__ :   Union[str, Any]    					=				hidden_size
       lowercase__ :   Any    					=				num_hidden_layers
       lowercase__ :   List[str]    					=				num_attention_heads
       lowercase__ :   Union[str, Any]    					=				intermediate_size
       lowercase__ :   Optional[Any]    					=				hidden_act
       lowercase__ :   int    					=				hidden_dropout_prob
       lowercase__ :   str    					=				attention_probs_dropout_prob
       lowercase__ :   Union[str, Any]    					=				max_position_embeddings
       lowercase__ :   Optional[int]    					=				type_vocab_size
       lowercase__ :   Tuple    					=				initializer_range
       lowercase__ :   List[str]    					=				layer_norm_eps
       lowercase__ :   List[Any]    					=				embedding_size
       lowercase__ :   Optional[Any]    					=				head_ratio
       lowercase__ :   Dict    					=				conv_kernel_size
       lowercase__ :   Tuple    					=				num_groups
       lowercase__ :   Optional[int]    					=				classifier_dropout



class   snake_case_       (		__A       ):






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



