



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(
    lowercase__,     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      (						lowercase__  ):







					'''simple docstring'''







					def    A__		(			self    ,	lowerCAmelCase     ):
							if self.framework == "tf":
									UpperCAmelCase_						=				tf.where(input_ids == self.tokenizer.mask_token_id     ).numpy()
							elif self.framework == "pt":
									UpperCAmelCase_						=				torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,	as_tuple=lowerCAmelCase     )
							else:
									raise ValueError("Unsupported framework"     )
							return masked_index



					def    A__		(			self    ,	lowerCAmelCase     ):
							UpperCAmelCase_						=				self.get_masked_index(lowerCAmelCase     )
							UpperCAmelCase_						=				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    ,	lowerCAmelCase     ):
							if isinstance(lowerCAmelCase    ,	lowerCAmelCase     ):
									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(lowerCAmelCase     )



					def    A__		(			self    ,	lowerCAmelCase    ,	lowerCAmelCase=None    ,	**lowerCAmelCase     ):
							if return_tensors is None:
									UpperCAmelCase_						=				self.framework
							UpperCAmelCase_						=				self.tokenizer(lowerCAmelCase    ,	return_tensors=lowerCAmelCase     )
							self.ensure_exactly_one_mask_token(lowerCAmelCase     )
							return model_inputs



					def    A__		(			self    ,	lowerCAmelCase     ):
							UpperCAmelCase_						=				self.model(**lowerCAmelCase     )
							UpperCAmelCase_						=				model_inputs["input_ids"]
							return model_outputs



					def    A__		(			self    ,	lowerCAmelCase    ,	lowerCAmelCase=5    ,	lowerCAmelCase=None     ):
							# Cap top_k if there are targets
							if target_ids is not None and target_ids.shape[0] < top_k:
									UpperCAmelCase_						=				target_ids.shape[0]
							UpperCAmelCase_						=				model_outputs["input_ids"][0]
							UpperCAmelCase_						=				model_outputs["logits"]

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

									UpperCAmelCase_						=				outputs.numpy()

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

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

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

									UpperCAmelCase_					,						UpperCAmelCase_						=				probs.topk(lowerCAmelCase     )

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

											UpperCAmelCase_						=				p
											# Filter padding out:
											UpperCAmelCase_						=				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_						=				self.tokenizer.decode(lowerCAmelCase    ,	skip_special_tokens=lowerCAmelCase     )
											UpperCAmelCase_						=				{"score": v, "token": p, "token_str": self.tokenizer.decode([p]     ), "sequence": sequence}
											row.append(lowerCAmelCase     )
									result.append(lowerCAmelCase     )
							if single_mask:
									return result[0]
							return result



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



					def    A__		(			self    ,	lowerCAmelCase=None    ,	lowerCAmelCase=None     ):
							UpperCAmelCase_						=				{}

							if targets is not None:
									UpperCAmelCase_						=				self.get_target_ids(lowerCAmelCase    ,	lowerCAmelCase     )
									UpperCAmelCase_						=				target_ids

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






from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE     				=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE     				=						{
    "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/config.json",
    "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/config.json",
    "xlm-roberta-large-finetuned-conll02-dutch": (
        "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json"
    ),
    "xlm-roberta-large-finetuned-conll02-spanish": (
        "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json"
    ),
    "xlm-roberta-large-finetuned-conll03-english": (
        "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json"
    ),
    "xlm-roberta-large-finetuned-conll03-german": (
        "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json"
    ),
}



class 	lowerCamelCase      (						lowercase__  ):







					'''simple docstring'''







					lowerCAmelCase_				:    List[str]									=  'xlm-roberta'



					def __init__(			self    ,	lowerCAmelCase=3_0522    ,	lowerCAmelCase=768    ,	lowerCAmelCase=12    ,	lowerCAmelCase=12    ,	lowerCAmelCase=3072    ,	lowerCAmelCase="gelu"    ,	lowerCAmelCase=0.1    ,	lowerCAmelCase=0.1    ,	lowerCAmelCase=512    ,	lowerCAmelCase=2    ,	lowerCAmelCase=0.02    ,	lowerCAmelCase=1e-1_2    ,	lowerCAmelCase=1    ,	lowerCAmelCase=0    ,	lowerCAmelCase=2    ,	lowerCAmelCase="absolute"    ,	lowerCAmelCase=True    ,	lowerCAmelCase=None    ,	**lowerCAmelCase    ,	):
							super().__init__(pad_token_id=lowerCAmelCase    ,	bos_token_id=lowerCAmelCase    ,	eos_token_id=lowerCAmelCase    ,	**lowerCAmelCase     )

							UpperCAmelCase_						=				vocab_size
							UpperCAmelCase_						=				hidden_size
							UpperCAmelCase_						=				num_hidden_layers
							UpperCAmelCase_						=				num_attention_heads
							UpperCAmelCase_						=				hidden_act
							UpperCAmelCase_						=				intermediate_size
							UpperCAmelCase_						=				hidden_dropout_prob
							UpperCAmelCase_						=				attention_probs_dropout_prob
							UpperCAmelCase_						=				max_position_embeddings
							UpperCAmelCase_						=				type_vocab_size
							UpperCAmelCase_						=				initializer_range
							UpperCAmelCase_						=				layer_norm_eps
							UpperCAmelCase_						=				position_embedding_type
							UpperCAmelCase_						=				use_cache
							UpperCAmelCase_						=				classifier_dropout





class 	lowerCamelCase      (						lowercase__  ):







					'''simple docstring'''







					@property
					def    A__		(			self     ):
							if self.task == "multiple-choice":
									UpperCAmelCase_						=				{0: "batch", 1: "choice", 2: "sequence"}
							else:
									UpperCAmelCase_						=				{0: "batch", 1: "sequence"}
							return OrderedDict(
							    [
							        ("input_ids", dynamic_axis),
							        ("attention_mask", dynamic_axis),
							    ]     )

