




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				,							lowerCamelCase__ :     Tuple				,							lowerCamelCase__ :     Optional[int]=13				,							lowerCamelCase__ :     Optional[int]=7				,							lowerCamelCase__ :     Tuple=True				,							lowerCamelCase__ :     str=True				,							lowerCamelCase__ :     int=False				,							lowerCamelCase__ :     Any=True				,							lowerCamelCase__ :     Optional[int]=99				,							lowerCamelCase__ :     int=64				,							lowerCamelCase__ :     List[Any]=5				,							lowerCamelCase__ :     Optional[Any]=4				,							lowerCamelCase__ :     Union[str, Any]=64				,							lowerCamelCase__ :     str="gelu"				,							lowerCamelCase__ :     int=0.1				,							lowerCamelCase__ :     int=0.1				,							lowerCamelCase__ :     List[str]=512				,							lowerCamelCase__ :     int=16				,							lowerCamelCase__ :     Tuple=2				,							lowerCamelCase__ :     Any=0.0_2				,							lowerCamelCase__ :     str=3				,							lowerCamelCase__ :     List[Any]=4				,							lowerCamelCase__ :     Optional[Any]=None				,							)    ->						Any:
													"""simple docstring"""


													__lowercase      =    parent
													__lowercase      =    batch_size
													__lowercase      =    seq_length
													__lowercase      =    is_training
													__lowercase      =    use_input_mask
													__lowercase      =    use_token_type_ids
													__lowercase      =    use_labels
													__lowercase      =    vocab_size
													__lowercase      =    hidden_size
													__lowercase      =    num_hidden_layers
													__lowercase      =    num_attention_heads
													__lowercase      =    intermediate_size
													__lowercase      =    hidden_act
													__lowercase      =    hidden_dropout_prob
													__lowercase      =    attention_probs_dropout_prob
													__lowercase      =    max_position_embeddings
													__lowercase      =    type_vocab_size
													__lowercase      =    type_sequence_label_size
													__lowercase      =    initializer_range
													__lowercase      =    num_labels
													__lowercase      =    num_choices
													__lowercase      =    scope






						def     UpperCAmelCase_      ( self :     Any				)    ->						str:
													"""simple docstring"""


													return MPNetConfig.from_pretrained('''microsoft/mpnet-base'''				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    ids_tensor([self.batch_size, self.seq_length]				,							self.vocab_size				)

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

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

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






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Optional[int]:
													"""simple docstring"""


													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[Any]				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     Union[str, Any]				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    MPNetModel(config=snake_case__				)
													model.to(snake_case__				)
													model.eval()
													__lowercase      =    model(snake_case__				,							snake_case__				)
													__lowercase      =    model(snake_case__				)
													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				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Tuple				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     int				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    MPNetForQuestionAnswering(config=snake_case__				)
													model.to(snake_case__				)
													model.eval()
													__lowercase      =    model(
													    snake_case__				,							attention_mask=snake_case__				,							start_positions=snake_case__				,							end_positions=snake_case__				,							)
													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 :     Any				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     Dict				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     Union[str, Any]				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    self.num_labels
													__lowercase      =    MPNetForSequenceClassification(snake_case__				)
													model.to(snake_case__				)
													model.eval()
													__lowercase      =    model(snake_case__				,							attention_mask=snake_case__				,							labels=snake_case__				)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Tuple				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Optional[int]				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    self.num_choices
													__lowercase      =    MPNetForMultipleChoice(config=snake_case__				)
													model.to(snake_case__				)
													model.eval()
													__lowercase      =    input_ids.unsqueeze(1				).expand(-1				,							self.num_choices				,							-1				).contiguous()
													__lowercase      =    input_mask.unsqueeze(1				).expand(-1				,							self.num_choices				,							-1				).contiguous()
													__lowercase      =    model(
													    snake_case__				,							attention_mask=snake_case__				,							labels=snake_case__				,							)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_choices)				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     Optional[int]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.num_labels
													__lowercase      =    MPNetForTokenClassification(config=snake_case__				)
													model.to(snake_case__				)
													model.eval()
													__lowercase      =    model(snake_case__				,							attention_mask=snake_case__				,							labels=snake_case__				)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.seq_length, self.num_labels)				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    self.prepare_config_and_inputs()
													(__lowercase)      =    config_and_inputs
													__lowercase      =    {"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_	:       Dict       	=		(
						    (
						        MPNetForMaskedLM,
						        MPNetForMultipleChoice,
						        MPNetForQuestionAnswering,
						        MPNetForSequenceClassification,
						        MPNetForTokenClassification,
						        MPNetModel,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase_	:       Any       	=		(
						    {
						        'feature-extraction': MPNetModel,
						        'fill-mask': MPNetForMaskedLM,
						        'question-answering': MPNetForQuestionAnswering,
						        'text-classification': MPNetForSequenceClassification,
						        'token-classification': MPNetForTokenClassification,
						        'zero-shot': MPNetForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						UpperCamelCase_	:       Tuple       	=		False
						UpperCamelCase_	:       int       	=		True






						def     UpperCAmelCase_      ( self :     Any				)    ->						int:
													"""simple docstring"""


													__lowercase      =    MPNetModelTester(self				)
													__lowercase      =    ConfigTester(self				,							config_class=snake_case__				,							hidden_size=37				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Dict:
													"""simple docstring"""


													self.config_tester.run_common_tests()






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_mpnet_model(*snake_case__				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						Optional[Any]:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_mpnet_for_sequence_classification(*snake_case__				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_mpnet_for_multiple_choice(*snake_case__				)






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_mpnet_for_token_classification(*snake_case__				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_mpnet_for_question_answering(*snake_case__				)







@require_torch
class a (     unittest.TestCase  ):
						"""simple docstring"""

						@slow
						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Union[str, Any]:
													"""simple docstring"""


													__lowercase      =    MPNetModel.from_pretrained('''microsoft/mpnet-base'''				)
													__lowercase      =    torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]				)
													__lowercase      =    model(snake_case__				)[0]
													__lowercase      =    torch.Size((1, 11, 768)				)
													self.assertEqual(output.shape				,							snake_case__				)
													__lowercase      =    torch.tensor(
													    [[[-0.0_5_5_0, 0.1_9_4_3, -0.0_7_4_0], [-0.0_5_6_2, 0.2_2_1_1, -0.0_5_7_9], [-0.0_4_3_7, 0.3_3_3_7, -0.0_6_4_1]]]				)
													# compare the actual values for a slice.
													self.assertTrue(torch.allclose(output[:, :3, :3]				,							snake_case__				,							atol=1e-4				)				)











# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile







def 		_A(       UpperCamelCase__							:			Any				,       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			int				)    -> List[Any]:
							'''simple docstring'''


							__lowercase      =    multiprocessing.Manager()
							__lowercase      =    manager.list()

							__lowercase      =    multiprocessing.Process(target=UpperCamelCase__				,       args=(check_program, result, timeout)				)
							p.start()
							p.join(timeout=timeout + 1				)
							if p.is_alive():
														p.kill()

							if not result:
														result.append('''timed out'''				)

							return {
							    "task_id": task_id,
							    "passed": result[0] == "passed",
							    "result": result[0],
							    "completion_id": completion_id,
							}







def 		_A(       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			Optional[int]				)    -> List[Any]:
							'''simple docstring'''


							with create_tempdir():
														# These system calls are needed when cleaning up tempdir.
														import os
														import shutil

														__lowercase      =    shutil.rmtree
														__lowercase      =    os.rmdir
														__lowercase      =    os.chdir

														# Disable functionalities that can make destructive changes to the test.
														reliability_guard()

														# Run program.
														try:
																					__lowercase      =    {}
																					with swallow_io():
																												with time_limit(UpperCamelCase__				):
																																			exec(UpperCamelCase__				,       UpperCamelCase__				)
																					result.append('''passed'''				)
														except TimeoutException:
																					result.append('''timed out'''				)
														except BaseException as e:
																					result.append(F'failed: {e}'				)

														# Needed for cleaning up.
														__lowercase      =    rmtree
														__lowercase      =    rmdir
														__lowercase      =    chdir







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			Union[str, Any]				)    -> Optional[int]:
							'''simple docstring'''


							def signal_handler(UpperCamelCase__							:			List[str]				,       UpperCamelCase__							:			Optional[Any]				):
														raise TimeoutException('''Timed out!'''				)

							signal.setitimer(signal.ITIMER_REAL				,       UpperCamelCase__				)
							signal.signal(signal.SIGALRM				,       UpperCamelCase__				)
							try:
														yield
							finally:
														signal.setitimer(signal.ITIMER_REAL				,       0				)







@contextlib.contextmanager
def 		_A(       )    -> Any:
							'''simple docstring'''


							__lowercase      =    WriteOnlyStringIO()
							with contextlib.redirect_stdout(UpperCamelCase__				):
														with contextlib.redirect_stderr(UpperCamelCase__				):
																					with redirect_stdin(UpperCamelCase__				):
																												yield







@contextlib.contextmanager
def 		_A(       )    -> Tuple:
							'''simple docstring'''


							with tempfile.TemporaryDirectory() as dirname:
														with chdir(UpperCamelCase__				):
																					yield dirname







class a (     __SCREAMING_SNAKE_CASE  ):
						"""simple docstring"""

						pass







class a (     io.StringIO  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     str				,							**lowerCamelCase__ :     str				)    ->						Tuple:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     List[str]				,							**lowerCamelCase__ :     Dict				)    ->						List[Any]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     Dict				,							**lowerCamelCase__ :     Dict				)    ->						Optional[int]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     Tuple				,							*lowerCamelCase__ :     Optional[Any]				,							**lowerCamelCase__ :     Tuple				)    ->						Optional[Any]:
													"""simple docstring"""


													return False







class a (     contextlib._RedirectStream  ):  # type: ignore
						"""simple docstring"""

						UpperCamelCase_	:       str       	=		'stdin'







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			int				)    -> Any:
							'''simple docstring'''


							if root == ".":
														yield
														return
							__lowercase      =    os.getcwd()
							os.chdir(UpperCamelCase__				)
							try:
														yield
							except BaseException as exc:
														raise exc
							finally:
														os.chdir(UpperCamelCase__				)







def 		_A(       UpperCamelCase__							:			Optional[Any]=None				)    -> Any:
							'''simple docstring'''


							if maximum_memory_bytes is not None:
														import resource

														resource.setrlimit(resource.RLIMIT_AS				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														resource.setrlimit(resource.RLIMIT_DATA				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														if not platform.uname().system == "Darwin":
																					resource.setrlimit(resource.RLIMIT_STACK				,       (maximum_memory_bytes, maximum_memory_bytes)				)

							faulthandler.disable()

							import builtins

							__lowercase      =    None
							__lowercase      =    None

							import os

							__lowercase      =    '''1'''

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import shutil

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import subprocess

							__lowercase      =    None  # type: ignore

							__lowercase      =    None

							import sys

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None






