
'''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			      =      logging.get_logger(__name__)




@add_end_docstrings(
    a__    ,   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     __snake_case		(   a__):
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									if self.framework == "tf":
													lowerCamelCase					:			Any									= tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
									elif self.framework == "pt":
													lowerCamelCase					:			Union[str, Any]									= torch.nonzero(input_ids == self.tokenizer.mask_token_id,    as_tuple=A      )
									else:
													raise ValueError('Unsupported framework'      )
									return masked_index
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			List[str]									= self.get_masked_index(A      )
									lowerCamelCase					:			Optional[int]									= 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     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									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     UpperCAmelCase_							(     self,    A,    A=None,    **A      ):

									"""simple docstring"""


									if return_tensors is None:
													lowerCamelCase					:			Dict									= self.framework
									lowerCamelCase					:			str									= self.tokenizer(A,    return_tensors=A      )
									self.ensure_exactly_one_mask_token(A      )
									return model_inputs
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			Any									= self.model(**A      )
									lowerCamelCase					:			Any									= model_inputs['input_ids']
									return model_outputs
					def     UpperCAmelCase_							(     self,    A,    A=5,    A=None      ):

									"""simple docstring"""


									if target_ids is not None and target_ids.shape[0] < top_k:
													lowerCamelCase					:			List[str]									= target_ids.shape[0]
									lowerCamelCase					:			str									= model_outputs['input_ids'][0]
									lowerCamelCase					:			List[str]									= model_outputs['logits']

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

													lowerCamelCase					:			Optional[int]									= outputs.numpy()

													lowerCamelCase					:			Optional[Any]									= outputs[0, masked_index, :]
													lowerCamelCase					:			Union[str, Any]									= stable_softmax(A,    axis=-1      )
													if target_ids is not None:
																	lowerCamelCase					:			Dict									= tf.gather_nd(tf.squeeze(A,    0      ),    target_ids.reshape(-1,    1      )      )
																	lowerCamelCase					:			Tuple									= tf.expand_dims(A,    0      )

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

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

													lowerCamelCase			, lowerCamelCase					:			int									= probs.topk(A      )

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

																	lowerCamelCase					:			str									= p
																	# Filter padding out:
																	lowerCamelCase					:			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
																	lowerCamelCase					:			Any									= self.tokenizer.decode(A,    skip_special_tokens=A      )
																	lowerCamelCase					:			str									= {'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     UpperCAmelCase_							(     self,    A,    A=None      ):

									"""simple docstring"""


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

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= {}

									if targets is not None:
													lowerCamelCase					:			List[str]									= self.get_target_ids(A,    A      )
													lowerCamelCase					:			Dict									= 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,    A,    *A,    **A      ):

									"""simple docstring"""


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


'''simple docstring'''






import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
					import torch

					from transformers import AutoModelForCausalLM




@require_torch
class     __snake_case		(   unittest.TestCase):
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Any									= AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'      )
									lowerCamelCase					:			Optional[int]									= AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'      ).to(A      )
									lowerCamelCase					:			Union[str, Any]									= -1

									lowerCamelCase					:			Optional[Any]									= ids_tensor((1, 5),    vocab_size=model.config.vocab_size      ).to(A      )
									lowerCamelCase					:			List[Any]									= model.generate(A,    max_new_tokens=10,    do_sample=A      )
									lowerCamelCase					:			int									= tokenizer.decode(greedy_ids[0]      )

									with CaptureStdout() as cs:
													lowerCamelCase					:			Optional[int]									= TextStreamer(A      )
													model.generate(A,    max_new_tokens=10,    do_sample=A,    streamer=A      )
									# The greedy text should be printed to stdout, except for the final "\n" in the streamer
									lowerCamelCase					:			int									= cs.out[:-1]

									self.assertEqual(A,    A      )
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			List[str]									= AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'      )
									lowerCamelCase					:			Dict									= AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'      ).to(A      )
									lowerCamelCase					:			List[Any]									= -1

									lowerCamelCase					:			Optional[int]									= ids_tensor((1, 5),    vocab_size=model.config.vocab_size      ).to(A      )
									lowerCamelCase					:			Any									= model.generate(A,    max_new_tokens=10,    do_sample=A      )
									lowerCamelCase					:			Optional[int]									= tokenizer.decode(greedy_ids[0]      )

									lowerCamelCase					:			Union[str, Any]									= TextIteratorStreamer(A      )
									lowerCamelCase					:			Tuple									= {'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer}
									lowerCamelCase					:			List[Any]									= Thread(target=model.generate,    kwargs=A      )
									thread.start()
									lowerCamelCase					:			List[Any]									= ''
									for new_text in streamer:
													streamer_text += new_text

									self.assertEqual(A,    A      )
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[int]									= AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'      )
									lowerCamelCase					:			int									= AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'      ).to(A      )
									lowerCamelCase					:			Optional[Any]									= -1

									lowerCamelCase					:			Union[str, Any]									= ids_tensor((1, 5),    vocab_size=model.config.vocab_size      ).to(A      )
									lowerCamelCase					:			Union[str, Any]									= model.generate(A,    max_new_tokens=10,    do_sample=A      )
									lowerCamelCase					:			int									= greedy_ids[:, input_ids.shape[1] :]
									lowerCamelCase					:			Dict									= tokenizer.decode(new_greedy_ids[0]      )

									with CaptureStdout() as cs:
													lowerCamelCase					:			Tuple									= TextStreamer(A,    skip_prompt=A      )
													model.generate(A,    max_new_tokens=10,    do_sample=A,    streamer=A      )
									# The greedy text should be printed to stdout, except for the final "\n" in the streamer
									lowerCamelCase					:			Optional[int]									= cs.out[:-1]

									self.assertEqual(A,    A      )
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[Any]									= AutoTokenizer.from_pretrained('distilgpt2'      )
									lowerCamelCase					:			Dict									= AutoModelForCausalLM.from_pretrained('distilgpt2'      ).to(A      )
									lowerCamelCase					:			Dict									= -1

									lowerCamelCase					:			Any									= torch.ones((1, 5),    device=A      ).long() * model.config.bos_token_id
									with CaptureStdout() as cs:
													lowerCamelCase					:			int									= TextStreamer(A,    skip_special_tokens=A      )
													model.generate(A,    max_new_tokens=1,    do_sample=A,    streamer=A      )

									# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
									# re-tokenized, must only contain one token
									lowerCamelCase					:			List[str]									= cs.out[:-1]  # Remove the final "\n"
									lowerCamelCase					:			Optional[Any]									= tokenizer(A,    return_tensors='pt'      )
									self.assertEqual(streamer_text_tokenized.input_ids.shape,    (1, 1)      )




					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'      )
									lowerCamelCase					:			List[str]									= AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2'      ).to(A      )
									lowerCamelCase					:			Any									= -1

									lowerCamelCase					:			int									= ids_tensor((1, 5),    vocab_size=model.config.vocab_size      ).to(A      )
									lowerCamelCase					:			int									= TextIteratorStreamer(A,    timeout=0.001      )
									lowerCamelCase					:			Any									= {'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer}
									lowerCamelCase					:			Optional[Any]									= Thread(target=model.generate,    kwargs=A      )
									thread.start()

									# The streamer will timeout after 0.001 seconds, so an exception will be raised
									with self.assertRaises(A      ):
													lowerCamelCase					:			Dict									= ''
													for new_text in streamer:
																	streamer_text += new_text
