





'''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   : Union[str, 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 			lowerCamelCase					(						__UpperCAmelCase  ):


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ,     __snake_case	:  GenericTensor       ):





											'''simple docstring'''





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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ,     __snake_case	:  GenericTensor       ):





											'''simple docstring'''





											_snake_case:   int  					=		self.get_masked_index(__snake_case       )
											_snake_case:   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    SCREAMING_SNAKE_CASE_		(					self	:  Any       ,     __snake_case	:  GenericTensor       ):





											'''simple docstring'''





											if isinstance(__snake_case       ,     __snake_case       ):
																	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(__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Tuple=None       ,     **__snake_case	:  Any       ):





											'''simple docstring'''





											if return_tensors is None:
																	_snake_case:   Optional[int]  					=		self.framework
											_snake_case:   str  					=		self.tokenizer(__snake_case       ,     return_tensors=__snake_case       )
											self.ensure_exactly_one_mask_token(__snake_case       )
											return model_inputs


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  Dict       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		self.model(**__snake_case       )
											_snake_case:   str  					=		model_inputs['input_ids']
											return model_outputs


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ,     __snake_case	:  List[str]       ,     __snake_case	:  Union[str, Any]=5       ,     __snake_case	:  Any=None       ):





											'''simple docstring'''





											if target_ids is not None and target_ids.shape[0] < top_k:
																	_snake_case:   Tuple  					=		target_ids.shape[0]
											_snake_case:   Union[str, Any]  					=		model_outputs['input_ids'][0]
											_snake_case:   int  					=		model_outputs['logits']

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

																	_snake_case:   int  					=		outputs.numpy()

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

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

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

																	_snake_case					,						_snake_case:   Dict  					=		probs.topk(__snake_case       )

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

																							_snake_case:   Optional[int]  					=		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:   Union[str, Any]  					=		self.tokenizer.decode(__snake_case       ,     skip_special_tokens=__snake_case       )
																							_snake_case:   Dict  					=		{'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]       ), 'sequence': sequence}
																							row.append(__snake_case       )
																	result.append(__snake_case       )
											if single_mask:
																	return result[0]
											return result


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  str       ,     __snake_case	:  List[str]=None       ):





											'''simple docstring'''





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


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ,     __snake_case	:  Optional[Any]=None       ,     __snake_case	:  Tuple=None       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		{}

											if targets is not None:
																	_snake_case:   Tuple  					=		self.get_target_ids(__snake_case       ,     __snake_case       )
																	_snake_case:   List[str]  					=		target_ids

											if top_k is not None:
																	_snake_case:   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	:  Optional[int]       ,     __snake_case	:  Optional[Any]       ,     *__snake_case	:  Tuple       ,     **__snake_case	:  str       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		super().__call__(__snake_case       ,     **__snake_case       )
											if isinstance(__snake_case       ,     __snake_case       ) and len(__snake_case       ) == 1:
																	return outputs[0]
											return outputs












'''simple docstring'''






from ...configuration_utils import PretrainedConfig
from ...utils import logging


A   : Tuple             =			logging.get_logger(__name__)

A   : Any             =			{
    'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/config.json',
    # See all BioGPT models at https://huggingface.co/models?filter=biogpt
}







class 			lowerCamelCase					(						__UpperCAmelCase  ):
					_SCREAMING_SNAKE_CASE							   =    "biogpt"


					def __init__(					self	:  Union[str, Any]       ,     __snake_case	:  Tuple=4_23_84       ,     __snake_case	:  Any=10_24       ,     __snake_case	:  Optional[int]=24       ,     __snake_case	:  int=16       ,     __snake_case	:  str=40_96       ,     __snake_case	:  Dict="gelu"       ,     __snake_case	:  List[str]=0.1       ,     __snake_case	:  List[Any]=0.1       ,     __snake_case	:  List[Any]=10_24       ,     __snake_case	:  Optional[int]=0.02       ,     __snake_case	:  Union[str, Any]=1e-12       ,     __snake_case	:  List[Any]=True       ,     __snake_case	:  Union[str, Any]=True       ,     __snake_case	:  Any=0.0       ,     __snake_case	:  int=0.0       ,     __snake_case	:  Dict=1       ,     __snake_case	:  str=0       ,     __snake_case	:  List[str]=2       ,     **__snake_case	:  Optional[int]       ,     ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		vocab_size
											_snake_case:   Optional[int]  					=		max_position_embeddings
											_snake_case:   Dict  					=		hidden_size
											_snake_case:   Union[str, Any]  					=		num_hidden_layers
											_snake_case:   str  					=		num_attention_heads
											_snake_case:   Any  					=		intermediate_size
											_snake_case:   List[Any]  					=		hidden_act
											_snake_case:   int  					=		hidden_dropout_prob
											_snake_case:   List[str]  					=		attention_probs_dropout_prob
											_snake_case:   Optional[Any]  					=		initializer_range
											_snake_case:   Union[str, Any]  					=		layer_norm_eps
											_snake_case:   Dict  					=		scale_embedding
											_snake_case:   Dict  					=		use_cache
											_snake_case:   List[Any]  					=		layerdrop
											_snake_case:   int  					=		activation_dropout
											super().__init__(pad_token_id=__snake_case       ,     bos_token_id=__snake_case       ,     eos_token_id=__snake_case       ,     **__snake_case       )





