

import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						import jax.numpy as jnp

						from transformers.models.distilbert.modeling_flax_distilbert import (
						    FlaxDistilBertForMaskedLM,
						    FlaxDistilBertForMultipleChoice,
						    FlaxDistilBertForQuestionAnswering,
						    FlaxDistilBertForSequenceClassification,
						    FlaxDistilBertForTokenClassification,
						    FlaxDistilBertModel,
						)



class 					lowercase						(  unittest.TestCase ):


							def __init__(			self    ,			_snake_case    ,			_snake_case=13    ,			_snake_case=7    ,			_snake_case=True    ,			_snake_case=True    ,			_snake_case=True    ,			_snake_case=True    ,			_snake_case=99    ,			_snake_case=32    ,			_snake_case=5    ,			_snake_case=4    ,			_snake_case=37    ,			_snake_case="gelu"    ,			_snake_case=0.1    ,			_snake_case=0.1    ,			_snake_case=512    ,			_snake_case=16    ,			_snake_case=2    ,			_snake_case=0.02    ,			_snake_case=4    ,			)							->				Dict:
								UpperCAmelCase_		:      Tuple       	=					parent
								UpperCAmelCase_		:      str       	=					batch_size
								UpperCAmelCase_		:      Any       	=					seq_length
								UpperCAmelCase_		:      Tuple       	=					is_training
								UpperCAmelCase_		:      Dict       	=					use_attention_mask
								UpperCAmelCase_		:      Tuple       	=					use_token_type_ids
								UpperCAmelCase_		:      List[Any]       	=					use_labels
								UpperCAmelCase_		:      List[str]       	=					vocab_size
								UpperCAmelCase_		:      Union[str, Any]       	=					hidden_size
								UpperCAmelCase_		:      Union[str, Any]       	=					num_hidden_layers
								UpperCAmelCase_		:      Dict       	=					num_attention_heads
								UpperCAmelCase_		:      List[str]       	=					intermediate_size
								UpperCAmelCase_		:      Optional[int]       	=					hidden_act
								UpperCAmelCase_		:      List[str]       	=					hidden_dropout_prob
								UpperCAmelCase_		:      Dict       	=					attention_probs_dropout_prob
								UpperCAmelCase_		:      str       	=					max_position_embeddings
								UpperCAmelCase_		:      int       	=					type_vocab_size
								UpperCAmelCase_		:      Optional[int]       	=					type_sequence_label_size
								UpperCAmelCase_		:      int       	=					initializer_range
								UpperCAmelCase_		:      str       	=					num_choices


							def 						_snake_case							(			self)							->				int:
								UpperCAmelCase_		:      Any       	=					ids_tensor([self.batch_size, self.seq_length]    ,			self.vocab_size)

								UpperCAmelCase_		:      List[str]       	=					None
								if self.use_attention_mask:
									UpperCAmelCase_		:      int       	=					random_attention_mask([self.batch_size, self.seq_length])

								UpperCAmelCase_		:      Optional[Any]       	=					DistilBertConfig(
								    vocab_size=self.vocab_size    ,			dim=self.hidden_size    ,			n_layers=self.num_hidden_layers    ,			n_heads=self.num_attention_heads    ,			hidden_dim=self.intermediate_size    ,			hidden_act=self.hidden_act    ,			dropout=self.hidden_dropout_prob    ,			attention_dropout=self.attention_probs_dropout_prob    ,			max_position_embeddings=self.max_position_embeddings    ,			initializer_range=self.initializer_range    ,			tie_weights_=_snake_case    ,			)

								return config, input_ids, attention_mask





							def 						_snake_case							(			self)							->				Optional[Any]:
								UpperCAmelCase_		:      List[Any]       	=					self.prepare_config_and_inputs()
								UpperCAmelCase_		:      List[str]       	=					config_and_inputs
								UpperCAmelCase_		:      Optional[Any]       	=					{'input_ids': input_ids, 'attention_mask': attention_mask}
								return config, inputs_dict



@require_flax
class 					lowercase						(  a_,					unittest.TestCase ):
							_lowerCamelCase		:      str=   (
							    (
							        FlaxDistilBertModel,
							        FlaxDistilBertForMaskedLM,
							        FlaxDistilBertForMultipleChoice,
							        FlaxDistilBertForQuestionAnswering,
							        FlaxDistilBertForSequenceClassification,
							        FlaxDistilBertForTokenClassification,
							        FlaxDistilBertForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)


							def 						_snake_case							(			self)							->				str:
								UpperCAmelCase_		:      List[str]       	=					FlaxDistilBertModelTester(self)





							@slow
							def 						_snake_case							(			self)							->				List[Any]:
								for model_class_name in self.all_model_classes:
									UpperCAmelCase_		:      Tuple       	=					model_class_name.from_pretrained('distilbert-base-uncased')
									UpperCAmelCase_		:      Tuple       	=					model(np.ones((1, 1)))
									self.assertIsNotNone(_snake_case)



@require_flax
class 					lowercase						(  unittest.TestCase ):


							@slow
							def 						_snake_case							(			self)							->				str:
								UpperCAmelCase_		:      str       	=					FlaxDistilBertModel.from_pretrained('distilbert-base-uncased')
								UpperCAmelCase_		:      int       	=					np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
								UpperCAmelCase_		:      Dict       	=					np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
								UpperCAmelCase_		:      List[str]       	=					model(_snake_case    ,			attention_mask=_snake_case)[0]
								UpperCAmelCase_		:      List[str]       	=					(1, 11, 768)
								self.assertEqual(output.shape    ,			_snake_case)
								UpperCAmelCase_		:      Union[str, Any]       	=					np.array([[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]])

								self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]    ,			_snake_case    ,			atol=1e-4))









'''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__										= 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 					lowercase						(  a_ ):


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								if self.framework == "tf":
									UpperCAmelCase_		:      Dict       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
								elif self.framework == "pt":
									UpperCAmelCase_		:      Any       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case)
								else:
									raise ValueError('Unsupported framework')
								return masked_index


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								UpperCAmelCase_		:      Optional[int]       	=					self.get_masked_index(_snake_case)
								UpperCAmelCase_		:      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 						_snake_case							(			self    ,			_snake_case)							->				int:
								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 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None    ,			**_snake_case)							->				Dict[str, GenericTensor]:
								if return_tensors is None:
									UpperCAmelCase_		:      Optional[Any]       	=					self.framework
								UpperCAmelCase_		:      str       	=					self.tokenizer(_snake_case    ,			return_tensors=_snake_case)
								self.ensure_exactly_one_mask_token(_snake_case)
								return model_inputs


							def 						_snake_case							(			self    ,			_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      List[str]       	=					self.model(**_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					model_inputs['input_ids']
								return model_outputs


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=5    ,			_snake_case=None)							->				str:
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
									UpperCAmelCase_		:      Optional[int]       	=					target_ids.shape[0]
								UpperCAmelCase_		:      Union[str, Any]       	=					model_outputs['input_ids'][0]
								UpperCAmelCase_		:      Optional[Any]       	=					model_outputs['logits']

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

									UpperCAmelCase_		:      Tuple       	=					outputs.numpy()

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

									UpperCAmelCase_		:      int       	=					tf.math.top_k(_snake_case    ,			k=_snake_case)
									UpperCAmelCase_	,    UpperCAmelCase_		:      Dict       	=					topk.values.numpy(), topk.indices.numpy()
								else:
									UpperCAmelCase_		:      List[str]       	=					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

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

									UpperCAmelCase_	,    UpperCAmelCase_		:      Union[str, Any]       	=					probs.topk(_snake_case)

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

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


							def 						_snake_case							(			self    ,			_snake_case=None    ,			_snake_case=None)							->				Dict:
								UpperCAmelCase_		:      str       	=					{}

								if targets is not None:
									UpperCAmelCase_		:      Dict       	=					self.get_target_ids(_snake_case    ,			_snake_case)
									UpperCAmelCase_		:      Optional[int]       	=					target_ids

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






