




"""simple docstring"""







import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    FalconForCausalLM,
						    FalconForQuestionAnswering,
						    FalconForSequenceClassification,
						    FalconForTokenClassification,
						    FalconModel,
						)




class    lowerCAmelCase__							:


				"""simple docstring"""





				def __init__(  self       :						List[Any]     , lowercase__       :						str     , lowercase__       :						int=3     , lowercase__       :						str=7     , lowercase__       :						Any=True     , lowercase__       :						Optional[int]=True     , lowercase__       :						List[str]=False     , lowercase__       :						Dict=True     , lowercase__       :						int=9_9     , lowercase__       :						Optional[int]=3_2     , lowercase__       :						Optional[Any]=5     , lowercase__       :						Union[str, Any]=4     , lowercase__       :						Optional[Any]=3_7     , lowercase__       :						Optional[int]="gelu"     , lowercase__       :						int=0.1     , lowercase__       :						int=0.1     , lowercase__       :						Any=5_1_2     , lowercase__       :						str=1_6     , lowercase__       :						List[Any]=2     , lowercase__       :						List[str]=0.0_2     , lowercase__       :						Union[str, Any]=3     , lowercase__       :						Union[str, Any]=4     , lowercase__       :						int=None     , ):
						__lowercase					:		int        =					parent
						__lowercase					:		Union[str, Any]        =					batch_size
						__lowercase					:		str        =					seq_length
						__lowercase					:		List[str]        =					is_training
						__lowercase					:		List[str]        =					use_input_mask
						__lowercase					:		str        =					use_token_type_ids
						__lowercase					:		Dict        =					use_labels
						__lowercase					:		List[str]        =					vocab_size
						__lowercase					:		Optional[int]        =					hidden_size
						__lowercase					:		Optional[int]        =					num_hidden_layers
						__lowercase					:		str        =					num_attention_heads
						__lowercase					:		List[Any]        =					intermediate_size
						__lowercase					:		Any        =					hidden_act
						__lowercase					:		str        =					hidden_dropout_prob
						__lowercase					:		Optional[Any]        =					attention_probs_dropout_prob
						__lowercase					:		Dict        =					max_position_embeddings
						__lowercase					:		Optional[Any]        =					type_vocab_size
						__lowercase					:		Tuple        =					type_sequence_label_size
						__lowercase					:		List[Any]        =					initializer_range
						__lowercase					:		Optional[int]        =					num_labels
						__lowercase					:		Optional[int]        =					num_choices
						__lowercase					:		List[str]        =					scope



				def    snake_case     (  self       :						Union[str, Any]    ):
						__lowercase					:		List[Any]        =					ids_tensor([self.batch_size, self.seq_length]     , self.vocab_size    )

						__lowercase					:		Union[str, Any]        =					None
						if self.use_input_mask:
								__lowercase					:		Any        =					random_attention_mask([self.batch_size, self.seq_length]    )

						__lowercase					:		Any        =					None

						__lowercase					:		Tuple        =					None
						__lowercase					:		str        =					None
						__lowercase					:		List[Any]        =					None
						if self.use_labels:
								__lowercase					:		str        =					ids_tensor([self.batch_size]     , self.type_sequence_label_size    )
								__lowercase					:		str        =					ids_tensor([self.batch_size, self.seq_length]     , self.num_labels    )
								__lowercase					:		List[Any]        =					ids_tensor([self.batch_size]     , self.num_choices    )

						__lowercase					:		Optional[int]        =					self.get_config()

						return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



				def    snake_case     (  self       :						List[str]    ):
						return FalconConfig(
						    vocab_size=self.vocab_size     , hidden_size=self.hidden_size     , num_hidden_layers=self.num_hidden_layers     , num_attention_heads=self.num_attention_heads     , intermediate_size=self.intermediate_size     , hidden_act=self.hidden_act     , hidden_dropout_prob=self.hidden_dropout_prob     , attention_probs_dropout_prob=self.attention_probs_dropout_prob     , max_position_embeddings=self.max_position_embeddings     , type_vocab_size=self.type_vocab_size     , is_decoder=_a     , initializer_range=self.initializer_range     , pad_token_id=1     , new_decoder_architecture=_a     , )



				def    snake_case     (  self       :						Tuple     , lowercase__       :						Dict     , lowercase__       :						Any     , lowercase__       :						Optional[int]     , lowercase__       :						Optional[int]     , lowercase__       :						List[str]     , lowercase__       :						Union[str, Any]     , lowercase__       :						Dict    ):
						__lowercase					:		List[Any]        =					FalconModel(config=_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Optional[Any]        =					model(_a     , attention_mask=_a    )
						__lowercase					:		List[str]        =					model(_a    )
						self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)    )



				def    snake_case     (  self       :						Optional[int]     , lowercase__       :						Dict     , lowercase__       :						Any     , lowercase__       :						int     , lowercase__       :						List[Any]     , lowercase__       :						Union[str, Any]     , lowercase__       :						Optional[int]     , lowercase__       :						Optional[int]     , lowercase__       :						List[Any]     , lowercase__       :						int     , ):
						__lowercase					:		List[str]        =					True
						__lowercase					:		List[Any]        =					FalconModel(_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Dict        =					model(
						    _a     , attention_mask=_a     , encoder_hidden_states=_a     , encoder_attention_mask=_a     , )
						__lowercase					:		List[Any]        =					model(
						    _a     , attention_mask=_a     , encoder_hidden_states=_a     , )
						__lowercase					:		Union[str, Any]        =					model(_a     , attention_mask=_a    )
						self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)    )



				def    snake_case     (  self       :						Optional[int]     , lowercase__       :						Union[str, Any]     , lowercase__       :						Tuple     , lowercase__       :						List[str]     , lowercase__       :						Union[str, Any]     , lowercase__       :						Dict     , lowercase__       :						List[Any]     , lowercase__       :						Tuple     , lowercase__       :						Any     , lowercase__       :						List[str]     , ):
						__lowercase					:		Any        =					FalconForCausalLM(config=_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Any        =					model(_a     , attention_mask=_a     , labels=_a    )
						self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)    )



				def    snake_case     (  self       :						Optional[int]     , lowercase__       :						int     , lowercase__       :						Optional[int]     , lowercase__       :						int     , lowercase__       :						Union[str, Any]     , lowercase__       :						Optional[Any]     , lowercase__       :						int     , lowercase__       :						int     , lowercase__       :						Tuple     , lowercase__       :						Union[str, Any]     , ):
						__lowercase					:		str        =					True
						__lowercase					:		Optional[int]        =					True
						__lowercase					:		Union[str, Any]        =					FalconForCausalLM(config=_a    )
						model.to(_a    )
						model.eval()

						# first forward pass
						__lowercase					:		int        =					model(
						    _a     , attention_mask=_a     , encoder_hidden_states=_a     , encoder_attention_mask=_a     , use_cache=_a     , )
						__lowercase					:		Optional[Any]        =					outputs.past_key_values

						# create hypothetical multiple next token and extent to next_input_ids
						__lowercase					:		str        =					ids_tensor((self.batch_size, 3)     , config.vocab_size    )
						__lowercase					:		Tuple        =					ids_tensor((self.batch_size, 3)     , vocab_size=2    )

						# append to next input_ids and
						__lowercase					:		Dict        =					torch.cat([input_ids, next_tokens]     , dim=-1    )
						__lowercase					:		Tuple        =					torch.cat([input_mask, next_mask]     , dim=-1    )

						__lowercase					:		Union[str, Any]        =					model(
						    _a     , attention_mask=_a     , encoder_hidden_states=_a     , encoder_attention_mask=_a     , output_hidden_states=_a     , )["hidden_states"][0]
						__lowercase					:		Tuple        =					model(
						    _a     , attention_mask=_a     , encoder_hidden_states=_a     , encoder_attention_mask=_a     , past_key_values=_a     , output_hidden_states=_a     , )["hidden_states"][0]

						# select random slice
						__lowercase					:		Optional[Any]        =					ids_tensor((1,)     , output_from_past.shape[-1]    ).item()
						__lowercase					:		Union[str, Any]        =					output_from_no_past[:, -3:, random_slice_idx].detach()
						__lowercase					:		List[str]        =					output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]    )

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(_a     , _a     , atol=1e-3    )    )



				def    snake_case     (  self       :						Any    ):
						__lowercase					:		List[Any]        =					self.prepare_config_and_inputs()
						(
						    (
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,(
						    __lowercase  
						)    ,  
						)					:		int        =					config_and_inputs
						__lowercase					:		Any        =					{"input_ids": input_ids, "attention_mask": input_mask}
						return config, inputs_dict





@require_torch
class    lowerCAmelCase__							(      UpperCAmelCase__	,      UpperCAmelCase__	,      UpperCAmelCase__	,      unittest.TestCase     ):


				"""simple docstring"""





				__UpperCAmelCase			:  List[str]			   =   (
				    (
				        FalconModel,
				        FalconForCausalLM,
				        FalconForSequenceClassification,
				        FalconForTokenClassification,
				        FalconForQuestionAnswering,
				    )
				    if is_torch_available()
				    else ()
				)
				__UpperCAmelCase			:  Optional[int]			   =   (FalconForCausalLM,) if is_torch_available() else ()
				__UpperCAmelCase			:  int			   =   (
				    {
				        "feature-extraction": FalconModel,
				        "text-classification": FalconForSequenceClassification,
				        "text-generation": FalconForCausalLM,
				        "question-answering": FalconForQuestionAnswering,
				        "token-classification": FalconForTokenClassification,
				        "zero-shot": FalconForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				__UpperCAmelCase			:  str			   =   False
				__UpperCAmelCase			:  int			   =   False



				def    snake_case     (  self       :						Dict    ):
						__lowercase					:		Dict        =					FalconModelTester(self    )
						__lowercase					:		Optional[int]        =					ConfigTester(self     , config_class=_a     , hidden_size=3_7    )



				def    snake_case     (  self       :						str    ):
						self.config_tester.run_common_tests()



				def    snake_case     (  self       :						Dict    ):
						__lowercase					:		Dict        =					self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_a    )



				def    snake_case     (  self       :						Tuple    ):
						__lowercase    ,*__lowercase					:		List[str]        =					self.model_tester.prepare_config_and_inputs()
						for alibi in [True, False]:
								__lowercase					:		Optional[Any]        =					alibi
								self.model_tester.create_and_check_model(_a     , *_a    )



				def    snake_case     (  self       :						Any    ):
						__lowercase    ,__lowercase					:		List[Any]        =					self.model_tester.prepare_config_and_inputs_for_common()
						__lowercase					:		Optional[int]        =					3
						__lowercase					:		str        =					input_dict["input_ids"]
						__lowercase					:		str        =					input_ids.ne(1    ).to(_a    )
						__lowercase					:		Union[str, Any]        =					ids_tensor([self.model_tester.batch_size]     , self.model_tester.type_sequence_label_size    )
						__lowercase					:		Tuple        =					FalconForSequenceClassification(_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Union[str, Any]        =					model(_a     , attention_mask=_a     , labels=_a    )
						self.assertEqual(result.logits.shape     , (self.model_tester.batch_size, self.model_tester.num_labels)    )



				def    snake_case     (  self       :						Tuple    ):
						__lowercase    ,__lowercase					:		Union[str, Any]        =					self.model_tester.prepare_config_and_inputs_for_common()
						__lowercase					:		List[Any]        =					3
						__lowercase					:		List[str]        =					"single_label_classification"
						__lowercase					:		Optional[int]        =					input_dict["input_ids"]
						__lowercase					:		Tuple        =					input_ids.ne(1    ).to(_a    )
						__lowercase					:		Optional[Any]        =					ids_tensor([self.model_tester.batch_size]     , self.model_tester.type_sequence_label_size    )
						__lowercase					:		Optional[int]        =					FalconForSequenceClassification(_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Union[str, Any]        =					model(_a     , attention_mask=_a     , labels=_a    )
						self.assertEqual(result.logits.shape     , (self.model_tester.batch_size, self.model_tester.num_labels)    )



				def    snake_case     (  self       :						List[Any]    ):
						__lowercase    ,__lowercase					:		Union[str, Any]        =					self.model_tester.prepare_config_and_inputs_for_common()
						__lowercase					:		str        =					input_dict["input_ids"]
						__lowercase					:		Any        =					FalconForCausalLM(_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		Dict        =					model(_a     , use_cache=_a    )
						__lowercase					:		Tuple        =					input_ids.shape[0]
						__lowercase					:		Any        =					model._convert_to_rw_cache(result.past_key_values    )
						__lowercase					:		Optional[int]        =					model._convert_cache_to_standard_format(_a     , _a    )
						for layer in range(len(_a    )    ):
								for tensor_idx in range(2    ):
										self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3    )
										self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4    )
										self.assertTrue(
										    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]    )    )



				def    snake_case     (  self       :						List[str]    ):
						__lowercase    ,__lowercase					:		Tuple        =					self.model_tester.prepare_config_and_inputs_for_common()
						__lowercase					:		str        =					3
						__lowercase					:		List[str]        =					"multi_label_classification"
						__lowercase					:		List[str]        =					input_dict["input_ids"]
						__lowercase					:		Union[str, Any]        =					input_ids.ne(1    ).to(_a    )
						__lowercase					:		Optional[int]        =					ids_tensor(
						    [self.model_tester.batch_size, config.num_labels]     , self.model_tester.type_sequence_label_size    ).to(torch.float    )
						__lowercase					:		List[str]        =					FalconForSequenceClassification(_a    )
						model.to(_a    )
						model.eval()
						__lowercase					:		int        =					model(_a     , attention_mask=_a     , labels=_a    )
						self.assertEqual(result.logits.shape     , (self.model_tester.batch_size, self.model_tester.num_labels)    )



				def    snake_case     (  self       :						str    ):
						# Falcon can have different numbers of KV-heads than the number of query heads, so we need
						# to override this test to use the right head counts.
						for model_class in self.all_generative_model_classes:
								__lowercase    ,__lowercase					:		Tuple        =					self.model_tester.prepare_config_and_inputs_for_common()

								# If it doesn't support cache, pass the test
								if not hasattr(_a     , "use_cache"    ):
										return

								__lowercase					:		int        =					model_class(_a    ).to(_a    )
								if "use_cache" not in inputs:
										__lowercase					:		Optional[Any]        =					True
								__lowercase					:		int        =					model(**_a    )

								# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
								if "past_key_values" not in outputs:
										return

								__lowercase					:		Optional[Any]        =					(
								    getattr(_a     , "decoder_layers"     , _a    )
								    or getattr(_a     , "num_decoder_layers"     , _a    )
								    or config.num_hidden_layers
								)
								__lowercase					:		Union[str, Any]        =					getattr(_a     , "num_kv_heads"     , config.num_attention_heads    )
								__lowercase					:		Optional[int]        =					getattr(_a     , "d_model"     , config.hidden_size    )
								__lowercase					:		int        =					embed_dim // num_attention_heads

								__lowercase					:		List[str]        =					outputs["past_key_values"]
								self.assertEqual(len(_a    )     , _a    )

								__lowercase    ,__lowercase					:		Any        =					inputs["input_ids"].shape
								for i in range(_a    ):
										if config.new_decoder_architecture:
												__lowercase					:		Union[str, Any]        =					config.num_attention_heads
										elif config.multi_query:
												__lowercase					:		List[str]        =					1
										self.assertEqual(len(past_kv[0]    )     , 2    )  # K V for the decoder = 2
										self.assertEqual(
										    past_kv[i][0].shape     , (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
										self.assertEqual(
										    past_kv[i][1].shape     , (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )





@require_torch
class    lowerCAmelCase__							(      unittest.TestCase     ):


				"""simple docstring"""





				@slow
				def    snake_case     (  self       :						Tuple    ):
						__lowercase					:		Any        =					AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"    )
						__lowercase					:		Optional[Any]        =					FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"    )
						model.eval()
						model.to(_a    )
						__lowercase					:		int        =					tokenizer("My favorite food is"     , return_tensors="pt"    ).to(_a    )

						__lowercase					:		str        =					(
						    "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
						)

						__lowercase					:		List[Any]        =					model.generate(**_a     , do_sample=_a     , max_new_tokens=1_9    )
						__lowercase					:		Union[str, Any]        =					tokenizer.batch_decode(_a    )[0]

						self.assertEqual(_a     , _a    )



				@slow
				def    snake_case     (  self       :						Dict    ):
						# The big models are way too big for the CI, so we use tiny random models that resemble their
						# architectures but with much smaller and fewer layers
						for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
								__lowercase					:		Union[str, Any]        =					AutoTokenizer.from_pretrained(_a    )
								__lowercase					:		Any        =					FalconForCausalLM.from_pretrained(_a    )
								model.eval()
								model.to(_a    )
								__lowercase					:		Dict        =					tokenizer("My favorite food is"     , return_tensors="pt"    ).to(_a    )

								# We just test that these run without errors - the models are randomly initialized
								# and so the actual text outputs will be garbage
								model.generate(**_a     , do_sample=_a     , max_new_tokens=4    )
								model.generate(**_a     , do_sample=_a     , max_new_tokens=4    )
								model.generate(**_a     , num_beams=2     , max_new_tokens=4    )



				@slow
				def    snake_case     (  self       :						int    ):
						# The big models are way too big for the CI, so we use tiny random models that resemble their
						# architectures but with much smaller and fewer layers
						with torch.no_grad():
								for repo in [
								    "Rocketknight1/falcon-rw-1b",
								    "Rocketknight1/tiny-random-falcon-7b",
								    "Rocketknight1/tiny-random-falcon-40b",
								]:
										__lowercase					:		Optional[int]        =					AutoTokenizer.from_pretrained(_a    )
										__lowercase					:		Any        =					FalconForCausalLM.from_pretrained(_a    )
										model.eval()
										model.to(device=_a    )
										__lowercase					:		Optional[Any]        =					tokenizer("My favorite food is"     , return_tensors="pt"    ).to(_a    )

										# Test results are the same with and without cache
										__lowercase					:		int        =					model.generate(**_a     , do_sample=_a     , max_new_tokens=2_0     , use_cache=_a    )
										__lowercase					:		Tuple        =					model.generate(**_a     , do_sample=_a     , max_new_tokens=2_0     , use_cache=_a    )
										self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )






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


lowerCAmelCase				:     int					=				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   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							if self.framework == "tf":
										lowerCamelCase      =   tf.where(input_ids == self.tokenizer.mask_token_id					).numpy()
							elif self.framework == "pt":
										lowerCamelCase      =   torch.nonzero(input_ids == self.tokenizer.mask_token_id						,					as_tuple=_a					)
							else:
										raise ValueError("""Unsupported framework"""					)
							return masked_index





				def   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   self.get_masked_index(_a					)
							lowerCamelCase      =   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						,					_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   _lowerCAmelCase							(			self						,					_a						,					_a=None						,					**_a					):





							"""simple docstring"""
							if return_tensors is None:
										lowerCamelCase      =   self.framework
							lowerCamelCase      =   self.tokenizer(_a						,					return_tensors=_a					)
							self.ensure_exactly_one_mask_token(_a					)
							return model_inputs





				def   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   self.model(**_a					)
							lowerCamelCase      =   model_inputs["""input_ids"""]
							return model_outputs





				def   _lowerCAmelCase							(			self						,					_a						,					_a=5						,					_a=None					):





							"""simple docstring"""
							# Cap top_k if there are targets
							if target_ids is not None and target_ids.shape[0] < top_k:
										lowerCamelCase      =   target_ids.shape[0]
							lowerCamelCase      =   model_outputs["""input_ids"""][0]
							lowerCamelCase      =   model_outputs["""logits"""]

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

										lowerCamelCase      =   outputs.numpy()

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

										lowerCamelCase      =   tf.math.top_k(_a						,					k=_a					)
										lowerCamelCase ,  lowerCamelCase      =   topk.values.numpy(), topk.indices.numpy()
							else:
										lowerCamelCase      =   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      =   outputs[0, masked_index, :]
										lowerCamelCase      =   logits.softmax(dim=-1					)
										if target_ids is not None:
													lowerCamelCase      =   probs[..., target_ids]

										lowerCamelCase ,  lowerCamelCase      =   probs.topk(_a					)

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

													lowerCamelCase      =   p
													# Filter padding out:
													lowerCamelCase      =   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      =   self.tokenizer.decode(_a						,					skip_special_tokens=_a					)
													lowerCamelCase      =   {"""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   _lowerCAmelCase							(			self						,					_a						,					_a=None					):





							"""simple docstring"""
							if isinstance(_a						,					_a					):
										lowerCamelCase      =   [targets]
							try:
										lowerCamelCase      =   self.tokenizer.get_vocab()
							except Exception:
										lowerCamelCase      =   {}
							lowerCamelCase      =   []
							for target in targets:
										lowerCamelCase      =   vocab.get(_a						,					_a					)
										if id_ is None:
													lowerCamelCase      =   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      =   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      =   list(set(_a					)					)
							if len(_a					) == 0:
										raise ValueError("""At least one target must be provided when passed."""					)
							lowerCamelCase      =   np.array(_a					)
							return target_ids





				def   _lowerCAmelCase							(			self						,					_a=None						,					_a=None					):





							"""simple docstring"""
							lowerCamelCase      =   {}

							if targets is not None:
										lowerCamelCase      =   self.get_target_ids(_a						,					_a					)
										lowerCamelCase      =   target_ids

							if top_k is not None:
										lowerCamelCase      =   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      =   super().__call__(_a						,					**_a					)
							if isinstance(_a						,					_a					) and len(_a					) == 1:
										return outputs[0]
							return outputs



