




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


__SCREAMING_SNAKE_CASE 						=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  __magic_name__						(  _UpperCamelCase):
				'''simple docstring'''







				def     _A							(							self:   str		,					_lowerCamelCase:   Tuple		):
											if self.framework == "tf":
																		SCREAMING_SNAKE_CASE_   	=    tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
											elif self.framework == "pt":
																		SCREAMING_SNAKE_CASE_   	=    torch.nonzero(input_ids == self.tokenizer.mask_token_id		,					as_tuple=_UpperCAmelCase		)
											else:
																		raise ValueError('''Unsupported framework'''		)
											return masked_index


				def     _A							(							self:   Optional[Any]		,					_lowerCamelCase:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.get_masked_index(_UpperCAmelCase		)
											SCREAMING_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     _A							(							self:   Any		,					_lowerCamelCase:   Optional[Any]		):
											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     _A							(							self:   List[Any]		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Union[str, Any]=None		,					**_lowerCamelCase:   List[str]		):
											if return_tensors is None:
																		SCREAMING_SNAKE_CASE_   	=    self.framework
											SCREAMING_SNAKE_CASE_   	=    self.tokenizer(_UpperCAmelCase		,					return_tensors=_UpperCAmelCase		)
											self.ensure_exactly_one_mask_token(_UpperCAmelCase		)
											return model_inputs


				def     _A							(							self:   Dict		,					_lowerCamelCase:   List[str]		):
											SCREAMING_SNAKE_CASE_   	=    self.model(**_UpperCAmelCase		)
											SCREAMING_SNAKE_CASE_   	=    model_inputs['''input_ids''']
											return model_outputs


				def     _A							(							self:   int		,					_lowerCamelCase:   str		,					_lowerCamelCase:   str=5		,					_lowerCamelCase:   Tuple=None		):
											# Cap top_k if there are targets
											if target_ids is not None and target_ids.shape[0] < top_k:
																		SCREAMING_SNAKE_CASE_   	=    target_ids.shape[0]
											SCREAMING_SNAKE_CASE_   	=    model_outputs['''input_ids'''][0]
											SCREAMING_SNAKE_CASE_   	=    model_outputs['''logits''']

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

																		SCREAMING_SNAKE_CASE_   	=    outputs.numpy()

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

																		SCREAMING_SNAKE_CASE_   	=    tf.math.top_k(_UpperCAmelCase		,					k=_UpperCAmelCase		)
																		SCREAMING_SNAKE_CASE_   	=    topk.values.numpy(), topk.indices.numpy()
											else:
																		SCREAMING_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

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

																		SCREAMING_SNAKE_CASE_   	=    probs.topk(_UpperCAmelCase		)

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

																									SCREAMING_SNAKE_CASE_   	=    p
																									# Filter padding out:
																									SCREAMING_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
																									SCREAMING_SNAKE_CASE_   	=    self.tokenizer.decode(_UpperCAmelCase		,					skip_special_tokens=_UpperCAmelCase		)
																									SCREAMING_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     _A							(							self:   Any		,					_lowerCamelCase:   Any		,					_lowerCamelCase:   List[str]=None		):
											if isinstance(_UpperCAmelCase		,					_UpperCAmelCase		):
																		SCREAMING_SNAKE_CASE_   	=    [targets]
											try:
																		SCREAMING_SNAKE_CASE_   	=    self.tokenizer.get_vocab()
											except Exception:
																		SCREAMING_SNAKE_CASE_   	=    {}
											SCREAMING_SNAKE_CASE_   	=    []
											for target in targets:
																		SCREAMING_SNAKE_CASE_   	=    vocab.get(_UpperCAmelCase		,					_UpperCAmelCase		)
																		if id_ is None:
																									SCREAMING_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
																									SCREAMING_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_		)
											SCREAMING_SNAKE_CASE_   	=    list(set(_UpperCAmelCase		)		)
											if len(_UpperCAmelCase		) == 0:
																		raise ValueError('''At least one target must be provided when passed.'''		)
											SCREAMING_SNAKE_CASE_   	=    np.array(_UpperCAmelCase		)
											return target_ids


				def     _A							(							self:   int		,					_lowerCamelCase:   Optional[Any]=None		,					_lowerCamelCase:   List[str]=None		):
											SCREAMING_SNAKE_CASE_   	=    {}

											if targets is not None:
																		SCREAMING_SNAKE_CASE_   	=    self.get_target_ids(_UpperCAmelCase		,					_UpperCAmelCase		)
																		SCREAMING_SNAKE_CASE_   	=    target_ids

											if top_k is not None:
																		SCREAMING_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:   Optional[Any]		,					_lowerCamelCase:   Union[str, Any]		,					*_lowerCamelCase:   Optional[Any]		,					**_lowerCamelCase:   List[Any]		):
											SCREAMING_SNAKE_CASE_   	=    super().__call__(_UpperCAmelCase		,					**_UpperCAmelCase		)
											if isinstance(_UpperCAmelCase		,					_UpperCAmelCase		) and len(_UpperCAmelCase		) == 1:
																		return outputs[0]
											return outputs





import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				def __init__(							self:   List[Any]		,					*_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Optional[Any]=None		,					_lowerCamelCase:   Dict=None		,					**_lowerCamelCase:   Dict		):
											super().__init__(*_lowerCamelCase		,					**_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    eval_examples
											SCREAMING_SNAKE_CASE_   	=    post_process_function


				def     _A							(							self:   Tuple		,					_lowerCamelCase:   Optional[Dataset] = None		,					_lowerCamelCase:   List[str]=None		,					_lowerCamelCase:   Optional[List[str]] = None		,					_lowerCamelCase:   str = "eval"		,					**_lowerCamelCase:   Union[str, Any]		,					):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''		) is not None else self.args.generation_max_length
											)
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''		) is not None else self.args.generation_num_beams
											)
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs

											SCREAMING_SNAKE_CASE_   	=    self.eval_dataset if eval_dataset is None else eval_dataset
											SCREAMING_SNAKE_CASE_   	=    self.get_eval_dataloader(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    self.eval_examples if eval_examples is None else eval_examples

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Evaluation'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics
											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)

											if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
																		# Only the main node write the results by default
																		SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

																		# Prefix all keys with metric_key_prefix + '_'
																		for key in list(metrics.keys()		):
																									if not key.startswith(f"{metric_key_prefix}_"		):
																																SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)

																		metrics.update(output.metrics		)
											else:
																		SCREAMING_SNAKE_CASE_   	=    output.metrics

											if self.args.should_log:
																		# Only the main node log the results by default
																		self.log(_lowerCamelCase		)

											if self.args.tpu_metrics_debug or self.args.debug:
																		# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
																		xm.master_print(met.metrics_report()		)

											SCREAMING_SNAKE_CASE_   	=    self.callback_handler.on_evaluate(self.args		,					self.state		,					self.control		,					_lowerCamelCase		)
											return metrics





				def     _A							(							self:   List[str]		,					_lowerCamelCase:   int		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Optional[int]=None		,					_lowerCamelCase:   str = "test"		,					**_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()

											SCREAMING_SNAKE_CASE_   	=    self.get_test_dataloader(_lowerCamelCase		)

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Prediction'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics

											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)
											if self.post_process_function is None or self.compute_metrics is None:
																		return output

											SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		,					'''predict'''		)
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

											# Prefix all keys with metric_key_prefix + '_'
											for key in list(metrics.keys()		):
																		if not key.startswith(f"{metric_key_prefix}_"		):
																									SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)
											metrics.update(output.metrics		)
											return PredictionOutput(predictions=predictions.predictions		,					label_ids=predictions.label_ids		,					metrics=_lowerCamelCase		)


