"""simple docstring"""
import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

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


if is_torch_available():
					import torch

					from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
					from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder





def       lowerCAmelCase__			(	_UpperCamelCase				: List[Any]       ,	_UpperCamelCase				: List[str]       ,	_UpperCamelCase				: str       ,	_UpperCamelCase				: List[str]=None       ,	_UpperCamelCase				: Optional[Any]=None       ,	_UpperCamelCase				: List[str]=None       ,	_UpperCamelCase				: List[str]=None       ,	_UpperCamelCase				: Dict=None       ,	)    -> Any:





						"""simple docstring"""






						if attention_mask is None:
												snake_case	    =	input_ids.ne(config.pad_token_id    )
						if decoder_attention_mask is None:
												snake_case	    =	decoder_input_ids.ne(config.pad_token_id    )
						if head_mask is None:
												snake_case	    =	torch.ones(config.encoder_layers       ,	config.encoder_attention_heads       ,	device=SCREAMING_SNAKE_CASE_    )
						if decoder_head_mask is None:
												snake_case	    =	torch.ones(config.decoder_layers       ,	config.decoder_attention_heads       ,	device=SCREAMING_SNAKE_CASE_    )
						if cross_attn_head_mask is None:
												snake_case	    =	torch.ones(config.decoder_layers       ,	config.decoder_attention_heads       ,	device=SCREAMING_SNAKE_CASE_    )
						return {
						    "input_ids": input_ids,
						    "decoder_input_ids": decoder_input_ids,
						    "attention_mask": attention_mask,
						    "decoder_attention_mask": attention_mask,
						    "head_mask": head_mask,
						    "decoder_head_mask": decoder_head_mask,
						    "cross_attn_head_mask": cross_attn_head_mask,
						}



class      lowerCAmelCase_			:



				"""simple docstring"""

				def __init__( self						,			lowerCAmelCase						,			lowerCAmelCase=13						,			lowerCAmelCase=7						,			lowerCAmelCase=True						,			lowerCAmelCase=False						,			lowerCAmelCase=99						,			lowerCAmelCase=16						,			lowerCAmelCase=2						,			lowerCAmelCase=4						,			lowerCAmelCase=4						,			lowerCAmelCase="relu"						,			lowerCAmelCase=0.1						,			lowerCAmelCase=0.1						,			lowerCAmelCase=0.0						,			lowerCAmelCase=0.0						,			lowerCAmelCase=20						,			lowerCAmelCase=2						,			lowerCAmelCase=1						,			lowerCAmelCase=0						,			):






										"""simple docstring"""

										snake_case	    =	parent
										snake_case	    =	batch_size
										snake_case	    =	seq_length
										snake_case	    =	is_training
										snake_case	    =	use_labels
										snake_case	    =	vocab_size
										snake_case	    =	hidden_size
										snake_case	    =	num_hidden_layers
										snake_case	    =	num_attention_heads
										snake_case	    =	intermediate_size
										snake_case	    =	hidden_act
										snake_case	    =	hidden_dropout_prob
										snake_case	    =	attention_probs_dropout_prob
										snake_case	    =	encoder_layerdrop
										snake_case	    =	decoder_layerdrop
										snake_case	    =	max_position_embeddings
										snake_case	    =	eos_token_id
										snake_case	    =	pad_token_id
										snake_case	    =	bos_token_id

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	ids_tensor([self.batch_size, self.seq_length]						,			self.vocab_size			)
										snake_case	    =	self.eos_token_id  # Eos Token
										snake_case	    =	ids_tensor([self.batch_size, self.seq_length]						,			self.vocab_size			)

										# we need to clamp the input ids here to avoid having pad token in between
										# this is because for M2M100 the position_ids are prepared such that
										# all pad tokens have pos id = 2 and rest are between 2..seq_length
										# and the seq_length here is seq_length - num_pad_tokens
										# but when using past, there is no way of knowing if the past input ids had
										# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
										# position_ids being off by num_pad_tokens in past input
										snake_case	    =	input_ids.clamp(self.pad_token_id + 1			)
										snake_case	    =	decoder_input_ids.clamp(self.pad_token_id + 1			)

										snake_case	    =	self.get_config()
										snake_case	    =	prepare_mam_aaa_inputs_dict(lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			)
										return config, inputs_dict

				def 						snake_case       ( self			):






										"""simple docstring"""

										return MaMaaaConfig(
										    vocab_size=self.vocab_size						,			d_model=self.hidden_size						,			encoder_layers=self.num_hidden_layers						,			decoder_layers=self.num_hidden_layers						,			encoder_attention_heads=self.num_attention_heads						,			decoder_attention_heads=self.num_attention_heads						,			encoder_ffn_dim=self.intermediate_size						,			decoder_ffn_dim=self.intermediate_size						,			dropout=self.hidden_dropout_prob						,			attention_dropout=self.attention_probs_dropout_prob						,			encoder_layerdrop=self.encoder_layerdrop						,			decoder_layerdrop=self.decoder_layerdrop						,			max_position_embeddings=self.max_position_embeddings						,			eos_token_id=self.eos_token_id						,			bos_token_id=self.bos_token_id						,			pad_token_id=self.pad_token_id						,			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.prepare_config_and_inputs()
										return config, inputs_dict

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										snake_case	    =	MaMaaaModel(config=lowerCAmelCase			).get_decoder().to(lowerCAmelCase			).eval()
										snake_case	    =	inputs_dict['input_ids']
										snake_case	    =	inputs_dict['attention_mask']
										snake_case	    =	inputs_dict['head_mask']

										# first forward pass
										snake_case	    =	model(lowerCAmelCase						,			attention_mask=lowerCAmelCase						,			head_mask=lowerCAmelCase						,			use_cache=lowerCAmelCase			)

										snake_case	    =	outputs.to_tuple()

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

										# append to next input_ids and
										snake_case	    =	torch.cat([input_ids, next_tokens]						,			dim=-1			)
										snake_case	    =	torch.cat([attention_mask, next_attn_mask]						,			dim=-1			)

										snake_case	    =	model(lowerCAmelCase						,			attention_mask=lowerCAmelCase			)['last_hidden_state']
										snake_case	    =	model(lowerCAmelCase						,			attention_mask=lowerCAmelCase						,			past_key_values=lowerCAmelCase			)[
										    'last_hidden_state'
										]

										# select random slice
										snake_case	    =	ids_tensor((1,)						,			output_from_past.shape[-1]			).item()
										snake_case	    =	output_from_no_past[:, -3:, random_slice_idx].detach()
										snake_case	    =	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(lowerCAmelCase						,			lowerCAmelCase						,			atol=1E-2			)			)

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										snake_case	    =	MaMaaaModel(config=lowerCAmelCase			).to(lowerCAmelCase			).eval()
										snake_case	    =	model(**lowerCAmelCase			)

										snake_case	    =	outputs.encoder_last_hidden_state
										snake_case	    =	outputs.last_hidden_state

										with tempfile.TemporaryDirectory() as tmpdirname:
																snake_case	    =	model.get_encoder()
																encoder.save_pretrained(lowerCAmelCase			)
																snake_case	    =	MaMaaaEncoder.from_pretrained(lowerCAmelCase			).to(lowerCAmelCase			)

										snake_case	    =	encoder(inputs_dict['input_ids']						,			attention_mask=inputs_dict['attention_mask']			)[
										    0
										]

										self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3			)

										with tempfile.TemporaryDirectory() as tmpdirname:
																snake_case	    =	model.get_decoder()
																decoder.save_pretrained(lowerCAmelCase			)
																snake_case	    =	MaMaaaDecoder.from_pretrained(lowerCAmelCase			).to(lowerCAmelCase			)

										snake_case	    =	decoder(
										    input_ids=inputs_dict['decoder_input_ids']						,			attention_mask=inputs_dict['decoder_attention_mask']						,			encoder_hidden_states=lowerCAmelCase						,			encoder_attention_mask=inputs_dict['attention_mask']						,			)[0]

										self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3			)





@require_torch
class      lowerCAmelCase_			(	__snake_case   ,			__snake_case   ,			__snake_case   ,			unittest.TestCase    ):



				"""simple docstring"""
				_lowerCAmelCase   :			str	     =  (
				    (
				        MaMaaaModel,
				        MaMaaaForConditionalGeneration,
				    )
				    if is_torch_available()
				    else ()
				)
				_lowerCAmelCase   :			Optional[int]	     =  (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
				_lowerCAmelCase   :			Optional[int]	     =  (
				    {
				        """conversational""": MaMaaaForConditionalGeneration,
				        """feature-extraction""": MaMaaaModel,
				        """summarization""": MaMaaaForConditionalGeneration,
				        """text2text-generation""": MaMaaaForConditionalGeneration,
				        """translation""": MaMaaaForConditionalGeneration,
				    }
				    if is_torch_available()
				    else {}
				)
				_lowerCAmelCase   :			List[str]	     =  True
				_lowerCAmelCase   :			Union[str, Any]	     =  True
				_lowerCAmelCase   :			Union[str, Any]	     =  False
				_lowerCAmelCase   :			int	     =  False

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										if pipeline_test_casse_name == "TranslationPipelineTests":
																# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
																# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
																return True

										return False

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	MaMaaaModelTester(self			)
										snake_case	    =	ConfigTester(self						,			config_class=lowerCAmelCase			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										self.config_tester.run_common_tests()

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										for model_class in self.all_model_classes:
																snake_case	    =	model_class(lowerCAmelCase			)

																with tempfile.TemporaryDirectory() as tmpdirname:
																						model.save_pretrained(lowerCAmelCase			)
																						snake_case	    =	model_class.from_pretrained(lowerCAmelCase						,			output_loading_info=lowerCAmelCase			)
																self.assertEqual(info['missing_keys']						,			[]			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																snake_case	    =	model_class(lowerCAmelCase			)
																model.to(lowerCAmelCase			)
																model.eval()

																snake_case	    =	copy.deepcopy(self._prepare_for_class(lowerCAmelCase						,			lowerCAmelCase			)			)

																if not self.is_encoder_decoder:
																						snake_case	    =	inputs['input_ids']
																						del inputs["input_ids"]
																else:
																						snake_case	    =	inputs['input_ids']
																						snake_case	    =	inputs.get('decoder_input_ids'						,			lowerCAmelCase			)
																						del inputs["input_ids"]
																						inputs.pop('decoder_input_ids'						,			lowerCAmelCase			)

																snake_case	    =	model.get_input_embeddings()
																if not self.is_encoder_decoder:
																						snake_case	    =	wte(lowerCAmelCase			)
																else:
																						snake_case	    =	wte(lowerCAmelCase			)
																						snake_case	    =	wte(lowerCAmelCase			)

																with torch.no_grad():
																						model(**lowerCAmelCase			)[0]

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	self.model_tester.prepare_config_and_inputs()
										snake_case	    =	input_dict['input_ids']
										snake_case	    =	input_ids.ne(1			).to(lowerCAmelCase			)
										snake_case	    =	MaMaaaForConditionalGeneration(lowerCAmelCase			).eval().to(lowerCAmelCase			)
										if torch_device == "cuda":
																model.half()
										model.generate(lowerCAmelCase						,			attention_mask=lowerCAmelCase			)
										model.generate(num_beams=4						,			do_sample=lowerCAmelCase						,			early_stopping=lowerCAmelCase						,			num_return_sequences=3			)





def       lowerCAmelCase__			(	_UpperCamelCase				: str    )    -> Dict:





						"""simple docstring"""






						return torch.tensor(SCREAMING_SNAKE_CASE_       ,	dtype=torch.long       ,	device=SCREAMING_SNAKE_CASE_    )


SCREAMING_SNAKE_CASE__					  =     1E-4



@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class      lowerCAmelCase_			(	unittest.TestCase    ):



				"""simple docstring"""

				@cached_property
				def 						snake_case       ( self			):






										"""simple docstring"""

										return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	MaMaaaModel.from_pretrained('facebook/m2m100_418M'			).to(lowerCAmelCase			)
										snake_case	    =	_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]			)
										snake_case	    =	_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]			)
										snake_case	    =	prepare_mam_aaa_inputs_dict(model.config						,			lowerCAmelCase						,			lowerCAmelCase			)
										with torch.no_grad():
																snake_case	    =	model(**lowerCAmelCase			)[0]
										snake_case	    =	torch.Size((1, 11, 10_24)			)
										self.assertEqual(output.shape						,			lowerCAmelCase			)
										# change to expected output here
										snake_case	    =	torch.tensor(
										    [[-0.77_80, -0.16_76, 0.10_38], [-6.75_56, -1.39_92, 0.05_67], [-7.53_83, -0.59_20, -0.27_79]]						,			device=lowerCAmelCase			)
										self.assertTrue(torch.allclose(output[:, :3, :3]						,			lowerCAmelCase						,			atol=lowerCAmelCase			)			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(lowerCAmelCase			)

										# change to intended input
										snake_case	    =	_long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]			)
										snake_case	    =	_long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]			)
										snake_case	    =	prepare_mam_aaa_inputs_dict(model.config						,			lowerCAmelCase						,			lowerCAmelCase			)
										with torch.no_grad():
																snake_case	    =	model(**lowerCAmelCase			)[0]
										snake_case	    =	torch.Size((1, 11, model.config.vocab_size)			)
										self.assertEqual(output.shape						,			lowerCAmelCase			)
										# change to expected output here
										snake_case	    =	torch.tensor(
										    [[-1.04_48, -1.04_11, 3.79_92], [-3.21_91, -3.23_86, -1.34_51], [-3.62_10, -3.59_93, 0.49_25]]						,			device=lowerCAmelCase			)
										self.assertTrue(torch.allclose(output[:, :3, :3]						,			lowerCAmelCase						,			atol=lowerCAmelCase			)			)

				def 						snake_case       ( self			):






										"""simple docstring"""

										snake_case	    =	MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'			).to(lowerCAmelCase			)
										snake_case	    =	MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'						,			src_lang='fr'						,			tgt_lang='en'			)

										snake_case	    =	[
										    'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
										    'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
										    'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
										    ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
										    ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
										]

										# The below article tests that we don't add any hypotheses outside of the top n_beams
										snake_case	    =	tokenizer(lowerCAmelCase						,			padding=lowerCAmelCase						,			return_tensors='pt'			)

										snake_case	    =	model.generate(
										    input_ids=dct['input_ids'].to(lowerCAmelCase			)						,			attention_mask=dct['attention_mask'].to(lowerCAmelCase			)						,			num_beams=5						,			forced_bos_token_id=tokenizer.get_lang_id('en'			)						,			)

										snake_case	    =	[
										    'The NSA case highlights the total absence of intelligence debate',
										    'I think there are two levels of response from the French government.',
										    'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
										    ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
										    ' communications in France.',
										]

										snake_case	    =	tokenizer.batch_decode(
										    hypotheses_batch.tolist()						,			clean_up_tokenization_spaces=lowerCAmelCase						,			skip_special_tokens=lowerCAmelCase			)
										assert generated == expected_en





import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
       from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





     return 1.0 / (1.0 + np.exp(-_outputs			))

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     lowercase__    :   int      =       np.max(_outputs	,     axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   int      =       np.exp(_outputs - maxes			)
     return shifted_exp / shifted_exp.sum(axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Optional[int]														=     """sigmoid"""
    __lowerCamelCase						:       List[Any]														=     """softmax"""
    __lowerCamelCase						:       Optional[Any]														=     """none"""



@add_end_docstrings(
    __snake_case		,       r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """		,       )
class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Dict														=     False
    __lowerCamelCase						:       List[str]														=     ClassificationFunction.NONE





    def __init__(      self						,   **a):
         super().__init__(**a)

         self.check_model_type(
             TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
             if self.framework == 'tf'
             else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING)





    def       snake_case_				(      self						,   a=None						,   a=None						,   a=""						,   **a):
         # Using "" as default argument because we're going to use `top_k=None` in user code to declare
         # "No top_k"
         lowercase__    :   List[str]      =       tokenizer_kwargs

         lowercase__    :   Dict      =       {}
         if hasattr(self.model.config						,   'return_all_scores') and return_all_scores is None:
              lowercase__    :   Union[str, Any]      =       self.model.config.return_all_scores

         if isinstance(a						,   a) or top_k is None:
              lowercase__    :   Tuple      =       top_k
              lowercase__    :   Any      =       False
         elif return_all_scores is not None:
              warnings.warn(
                  '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
                  ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'						,   a						,   )
              if return_all_scores:
                   lowercase__    :   Union[str, Any]      =       None
              else:
                   lowercase__    :   Union[str, Any]      =       1

         if isinstance(a						,   a):
              lowercase__    :   Tuple      =       ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
              lowercase__    :   List[str]      =       function_to_apply
         return preprocess_params, {}, postprocess_params





    def __call__(      self						,   *a						,   **a):
         lowercase__    :   int      =       super().__call__(*a						,   **a)
         # TODO try and retrieve it in a nicer way from _sanitize_parameters.
         lowercase__    :   Any      =       'top_k' not in kwargs
         if isinstance(args[0]						,   a) and _legacy:
              # This pipeline is odd, and return a list when single item is run
              return [result]
         else:
              return result





    def       snake_case_				(      self						,   a						,   **a):
         lowercase__    :   List[str]      =       self.framework
         if isinstance(a						,   a):
              return self.tokenizer(**a						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a) and len(a) == 1 and isinstance(inputs[0]						,   a) and len(inputs[0]) == 2:
              # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
              return self.tokenizer(
                  text=inputs[0][0]						,   text_pair=inputs[0][1]						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a):
              # This is likely an invalid usage of the pipeline attempting to pass text pairs.
              raise ValueError(
                  'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
                  ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.')
         return self.tokenizer(a						,   return_tensors=a						,   **a)





    def       snake_case_				(      self						,   a):
         return self.model(**a)





    def       snake_case_				(      self						,   a						,   a=None						,   a=1						,   a=True):
         # `_legacy` is used to determine if we're running the naked pipeline and in backward
         # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
         # the more natural result containing the list.
         # Default value before `set_parameters`
         if function_to_apply is None:
              if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SIGMOID
              elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SOFTMAX
              elif hasattr(self.model.config						,   'function_to_apply') and function_to_apply is None:
                   lowercase__    :   List[str]      =       self.model.config.function_to_apply
              else:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.NONE

         lowercase__    :   str      =       model_outputs['logits'][0]
         lowercase__    :   Dict      =       outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
              lowercase__    :   int      =       sigmoid(a)
         elif function_to_apply == ClassificationFunction.SOFTMAX:
              lowercase__    :   List[Any]      =       softmax(a)
         elif function_to_apply == ClassificationFunction.NONE:
              lowercase__    :   Any      =       outputs
         else:
              raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""")

         if top_k == 1 and _legacy:
              return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

         lowercase__    :   Any      =       [
             {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a)
         ]
         if not _legacy:
              dict_scores.sort(key=lambda a: x["score"]						,   reverse=a)
              if top_k is not None:
                   lowercase__    :   Optional[Any]      =       dict_scores[:top_k]
         return dict_scores

