



"""simple docstring"""


import unittest

from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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 (
				    MPNetForMaskedLM,
				    MPNetForMultipleChoice,
				    MPNetForQuestionAnswering,
				    MPNetForSequenceClassification,
				    MPNetForTokenClassification,
				    MPNetModel,
				)







class       A_			:



						"""simple docstring"""






						def __init__(					self :str   ,  lowercase_ :str   ,  lowercase_ :int=13   ,  lowercase_ :Optional[Any]=7   ,  lowercase_ :List[Any]=True   ,  lowercase_ :List[Any]=True   ,  lowercase_ :List[str]=False   ,  lowercase_ :Optional[Any]=True   ,  lowercase_ :List[Any]=99   ,  lowercase_ :List[str]=64   ,  lowercase_ :int=5   ,  lowercase_ :List[str]=4   ,  lowercase_ :Any=64   ,  lowercase_ :int="gelu"   ,  lowercase_ :Optional[int]=0.1   ,  lowercase_ :Union[str, Any]=0.1   ,  lowercase_ :Union[str, Any]=5_12   ,  lowercase_ :List[Any]=16   ,  lowercase_ :Optional[Any]=2   ,  lowercase_ :str=0.02   ,  lowercase_ :Any=3   ,  lowercase_ :Tuple=4   ,  lowercase_ :Optional[Any]=None   ,  )				->			int:
												UpperCAmelCase             = parent
												UpperCAmelCase             = batch_size
												UpperCAmelCase             = seq_length
												UpperCAmelCase             = is_training
												UpperCAmelCase             = use_input_mask
												UpperCAmelCase             = use_token_type_ids
												UpperCAmelCase             = use_labels
												UpperCAmelCase             = vocab_size
												UpperCAmelCase             = hidden_size
												UpperCAmelCase             = num_hidden_layers
												UpperCAmelCase             = num_attention_heads
												UpperCAmelCase             = intermediate_size
												UpperCAmelCase             = hidden_act
												UpperCAmelCase             = hidden_dropout_prob
												UpperCAmelCase             = attention_probs_dropout_prob
												UpperCAmelCase             = max_position_embeddings
												UpperCAmelCase             = type_vocab_size
												UpperCAmelCase             = type_sequence_label_size
												UpperCAmelCase             = initializer_range
												UpperCAmelCase             = num_labels
												UpperCAmelCase             = num_choices
												UpperCAmelCase             = scope






						def 	UpperCAmelCase__     (					self :Union[str, Any]					)				->			Union[str, Any]:
												return MPNetConfig.from_pretrained('microsoft/mpnet-base'					)






						def 	UpperCAmelCase__     (					self :Tuple					)				->			int:
												UpperCAmelCase             = ids_tensor([self.batch_size, self.seq_length]   ,  self.vocab_size					)

												UpperCAmelCase             = None
												if self.use_input_mask:
																		UpperCAmelCase             = random_attention_mask([self.batch_size, self.seq_length]					)

												UpperCAmelCase             = None
												UpperCAmelCase             = None
												UpperCAmelCase             = None
												if self.use_labels:
																		UpperCAmelCase             = ids_tensor([self.batch_size]   ,  self.type_sequence_label_size					)
																		UpperCAmelCase             = ids_tensor([self.batch_size, self.seq_length]   ,  self.num_labels					)
																		UpperCAmelCase             = ids_tensor([self.batch_size]   ,  self.num_choices					)

												UpperCAmelCase             = self.get_config()
												return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






						def 	UpperCAmelCase__     (					self :List[str]					)				->			List[str]:
												return MPNetConfig(
												    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   ,  initializer_range=self.initializer_range   ,  )






						def 	UpperCAmelCase__     (					self :Optional[int]   ,  lowercase_ :Optional[int]   ,  lowercase_ :List[Any]   ,  lowercase_ :Tuple   ,  lowercase_ :Union[str, Any]   ,  lowercase_ :str   ,  lowercase_ :Any					)				->			Any:
												UpperCAmelCase             = MPNetModel(config=lowercase_					)
												model.to(lowercase_					)
												model.eval()
												UpperCAmelCase             = model(lowercase_   ,  lowercase_					)
												UpperCAmelCase             = model(lowercase_					)
												self.parent.assertEqual(result.last_hidden_state.shape   ,  (self.batch_size, self.seq_length, self.hidden_size)					)
												self.parent.assertEqual(result.pooler_output.shape   ,  (self.batch_size, self.hidden_size)					)






						def 	UpperCAmelCase__     (					self :Dict   ,  lowercase_ :str   ,  lowercase_ :Any   ,  lowercase_ :Any   ,  lowercase_ :Union[str, Any]   ,  lowercase_ :str   ,  lowercase_ :int					)				->			int:
												UpperCAmelCase             = MPNetForQuestionAnswering(config=lowercase_					)
												model.to(lowercase_					)
												model.eval()
												UpperCAmelCase             = model(
												    lowercase_   ,  attention_mask=lowercase_   ,  start_positions=lowercase_   ,  end_positions=lowercase_   ,  )
												self.parent.assertEqual(result.start_logits.shape   ,  (self.batch_size, self.seq_length)					)
												self.parent.assertEqual(result.end_logits.shape   ,  (self.batch_size, self.seq_length)					)






						def 	UpperCAmelCase__     (					self :Dict   ,  lowercase_ :str   ,  lowercase_ :List[Any]   ,  lowercase_ :Optional[int]   ,  lowercase_ :Dict   ,  lowercase_ :List[Any]   ,  lowercase_ :List[str]					)				->			Optional[int]:
												UpperCAmelCase             = self.num_labels
												UpperCAmelCase             = MPNetForSequenceClassification(lowercase_					)
												model.to(lowercase_					)
												model.eval()
												UpperCAmelCase             = model(lowercase_   ,  attention_mask=lowercase_   ,  labels=lowercase_					)
												self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_labels)					)






						def 	UpperCAmelCase__     (					self :List[str]   ,  lowercase_ :Any   ,  lowercase_ :Union[str, Any]   ,  lowercase_ :Dict   ,  lowercase_ :Optional[Any]   ,  lowercase_ :Optional[int]   ,  lowercase_ :Optional[int]					)				->			Any:
												UpperCAmelCase             = self.num_choices
												UpperCAmelCase             = MPNetForMultipleChoice(config=lowercase_					)
												model.to(lowercase_					)
												model.eval()
												UpperCAmelCase             = input_ids.unsqueeze(1					).expand(-1   ,  self.num_choices   ,  -1					).contiguous()
												UpperCAmelCase             = input_mask.unsqueeze(1					).expand(-1   ,  self.num_choices   ,  -1					).contiguous()
												UpperCAmelCase             = model(
												    lowercase_   ,  attention_mask=lowercase_   ,  labels=lowercase_   ,  )
												self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_choices)					)






						def 	UpperCAmelCase__     (					self :List[Any]   ,  lowercase_ :Tuple   ,  lowercase_ :str   ,  lowercase_ :Tuple   ,  lowercase_ :Any   ,  lowercase_ :str   ,  lowercase_ :Union[str, Any]					)				->			Dict:
												UpperCAmelCase             = self.num_labels
												UpperCAmelCase             = MPNetForTokenClassification(config=lowercase_					)
												model.to(lowercase_					)
												model.eval()
												UpperCAmelCase             = model(lowercase_   ,  attention_mask=lowercase_   ,  labels=lowercase_					)
												self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.seq_length, self.num_labels)					)






						def 	UpperCAmelCase__     (					self :Any					)				->			Dict:
												UpperCAmelCase             = self.prepare_config_and_inputs()
												((UpperCAmelCase)      ,    (UpperCAmelCase)      ,    (UpperCAmelCase)      ,    (UpperCAmelCase)      ,    (UpperCAmelCase)      ,    (UpperCAmelCase))             = config_and_inputs
												UpperCAmelCase             = {'input_ids': input_ids, 'attention_mask': input_mask}
												return config, inputs_dict







@require_torch
class       A_			(     SCREAMING_SNAKE_CASE_	,   SCREAMING_SNAKE_CASE_	,   unittest.TestCase				):



						"""simple docstring"""
						__UpperCamelCase						=							(
						    (
						        MPNetForMaskedLM,
						        MPNetForMultipleChoice,
						        MPNetForQuestionAnswering,
						        MPNetForSequenceClassification,
						        MPNetForTokenClassification,
						        MPNetModel,
						    )
						    if is_torch_available()
						    else ()
						)
						__UpperCamelCase						=							(
						    {
						        """feature-extraction""": MPNetModel,
						        """fill-mask""": MPNetForMaskedLM,
						        """question-answering""": MPNetForQuestionAnswering,
						        """text-classification""": MPNetForSequenceClassification,
						        """token-classification""": MPNetForTokenClassification,
						        """zero-shot""": MPNetForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						__UpperCamelCase						=							False
						__UpperCamelCase						=							True






						def 	UpperCAmelCase__     (					self :Optional[Any]					)				->			int:
												UpperCAmelCase             = MPNetModelTester(self					)
												UpperCAmelCase             = ConfigTester(self   ,  config_class=lowercase_   ,  hidden_size=37					)






						def 	UpperCAmelCase__     (					self :Optional[int]					)				->			Dict:
												self.config_tester.run_common_tests()






						def 	UpperCAmelCase__     (					self :int					)				->			Optional[int]:
												UpperCAmelCase             = self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_mpnet_model(*lowercase_					)






						def 	UpperCAmelCase__     (					self :Optional[Any]					)				->			List[str]:
												UpperCAmelCase             = self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase_					)






						def 	UpperCAmelCase__     (					self :Any					)				->			int:
												UpperCAmelCase             = self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase_					)






						def 	UpperCAmelCase__     (					self :List[Any]					)				->			List[str]:
												UpperCAmelCase             = self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase_					)






						def 	UpperCAmelCase__     (					self :Dict					)				->			List[str]:
												UpperCAmelCase             = self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase_					)







@require_torch
class       A_			(     unittest.TestCase				):



						"""simple docstring"""






						@slow
						def 	UpperCAmelCase__     (					self :Dict					)				->			List[str]:
												UpperCAmelCase             = MPNetModel.from_pretrained('microsoft/mpnet-base'					)
												UpperCAmelCase             = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]					)
												UpperCAmelCase             = model(lowercase_					)[0]
												UpperCAmelCase             = torch.Size((1, 11, 7_68)					)
												self.assertEqual(output.shape   ,  lowercase_					)
												UpperCAmelCase             = torch.tensor(
												    [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]]					)
												# compare the actual values for a slice.
												self.assertTrue(torch.allclose(output[:, :3, :3]   ,  lowercase_   ,  atol=1E-4					)					)













# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool





class 			__a  (    A__       ):
 _lowerCAmelCase       :       str        = '''facebook/bart-large-mnli'''
 _lowerCAmelCase       :       Tuple        = (
     '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '''
     '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. '''
     '''It returns the most likely label in the list of provided `labels` for the input text.'''
 )
 _lowerCAmelCase       :       Any        = '''text_classifier'''
 _lowerCAmelCase       :       int        = AutoTokenizer
 _lowerCAmelCase       :       Union[str, Any]        = AutoModelForSequenceClassification

 _lowerCAmelCase       :       Union[str, Any]        = ['''text''', ['''text''']]
 _lowerCAmelCase       :       Dict        = ['''text''']







 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      super().setup()
      UpperCamelCase__			:   Dict       				=  self.model.config
      UpperCamelCase__			:   Union[str, Any]       				=  -1
      for idx, label in config.idalabel.items():
           if label.lower().startswith("entail"						):
                UpperCamelCase__			:   List[str]       				=  int(SCREAMING_SNAKE_CASE						)
      if self.entailment_id == -1:
           raise ValueError("Could not determine the entailment ID from the model config, please pass it at init."						)







 def 					__lowercase					(		self					:   Tuple							,   SCREAMING_SNAKE_CASE					:   Tuple							,   SCREAMING_SNAKE_CASE					:   List[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Any       				=  labels
      return self.pre_processor(
          [text] * len(SCREAMING_SNAKE_CASE						)							,   [F'This example is {label}' for label in labels]							,   return_tensors="pt"							,   padding="max_length"							,   )







 def 					__lowercase					(		self					:   Optional[Any]							,   SCREAMING_SNAKE_CASE					:   Dict						):


      '''simple docstring'''






      UpperCamelCase__			:   List[Any]       				=  outputs.logits
      UpperCamelCase__			:   Any       				=  torch.argmax(logits[:, 2]						).item()
      return self._labels[label_id]