
'''simple docstring'''


from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


__SCREAMING_SNAKE_CASE						=      {
    '''id''': '''5733be284776f41900661182''',
    '''title''': '''University_of_Notre_Dame''',
    '''context''': '''Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.''',
    '''question''': '''To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?''',
    '''answers''': {'''text''': ['''Saint Bernadette Soubirous'''], '''answer_start''': [515]},
}
@pytest.mark.parametrize(
    """task_cls"""							,				[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]							,				)
def 					__magic_name__(       UpperCAmelCase__ :       Union[str, Any]	):
						UpperCamelCase_     :	int					     =     task_cls()
						UpperCamelCase_     :	Dict					     =     asdict(_snake_case	)
						UpperCamelCase_     :	str					     =     task_template_from_dict(_snake_case	)
						assert task == reloaded




class     __snake_case			:




		def 	_snake_case	(  self					:List[str])					->			Any:






								'''simple docstring'''






								UpperCamelCase_     :	Any					     =     LanguageModeling(text_column="""input_text""")
								assert {"input_text": "text"} == task.column_mapping





		def 	_snake_case	(  self					:str)					->			Dict:






								'''simple docstring'''






								UpperCamelCase_     :	Tuple					     =     Features({"""text""": Value("""string""")})
								UpperCamelCase_     :	Optional[int]					     =     {'''text_column''': '''input_text'''}
								UpperCamelCase_     :	str					     =     LanguageModeling.from_dict(UpperCamelCase_)
								assert "language-modeling" == task.task
								assert input_schema == task.input_schema







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:List[Any])					->			str:






								'''simple docstring'''






								UpperCamelCase_     :	Union[str, Any]					     =     sorted(["""pos""", """neg"""])




		def 	_snake_case	(  self					:List[str])					->			Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	List[Any]					     =     TextClassification(text_column="""input_text"""			,    label_column="""input_label""")
								self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""}			,    task.column_mapping)




		def 	_snake_case	(  self					:Dict)					->			Optional[int]:






								'''simple docstring'''






								UpperCamelCase_     :	Dict					     =     Features({"""text""": Value("""string""")})
								# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
								UpperCamelCase_     :	Tuple					     =     Features({"""labels""": ClassLabel})
								UpperCamelCase_     :	Any					     =     {'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
								UpperCamelCase_     :	str					     =     TextClassification.from_dict(UpperCamelCase_)
								self.assertEqual("""text-classification"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)





		def 	_snake_case	(  self					:Union[str, Any])					->			Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	str					     =     TextClassification(text_column="""input_text"""			,    label_column="""input_label""")
								self.assertEqual(task.label_schema["""labels"""]			,    UpperCamelCase_)
								UpperCamelCase_     :	int					     =     task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels)}))
								self.assertEqual(task.label_schema["""labels"""]			,    ClassLabel(names=self.labels))







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:Any)					->			Optional[int]:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[int]					     =     QuestionAnsweringExtractive(
								    context_column="""input_context"""			,    question_column="""input_question"""			,    answers_column="""input_answers""")
								self.assertDictEqual(
								    {"""input_context""": """context""", """input_question""": """question""", """input_answers""": """answers"""}			,    task.column_mapping)





		def 	_snake_case	(  self					:Any)					->			Tuple:






								'''simple docstring'''






								UpperCamelCase_     :	Tuple					     =     Features({"""question""": Value("""string"""), """context""": Value("""string""")})
								UpperCamelCase_     :	List[str]					     =     Features(
								    {
								        """answers""": Sequence(
								            {
								                """text""": Value("""string"""),
								                """answer_start""": Value("""int32"""),
								            })
								    })
								UpperCamelCase_     :	Dict					     =     {
								    '''context_column''': '''input_input_context''',
								    '''question_column''': '''input_question''',
								    '''answers_column''': '''input_answers''',
								}
								UpperCamelCase_     :	Optional[Any]					     =     QuestionAnsweringExtractive.from_dict(UpperCamelCase_)
								self.assertEqual("""question-answering-extractive"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:Optional[Any])					->			Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Dict					     =     Summarization(text_column="""input_text"""			,    summary_column="""input_summary""")
								self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""}			,    task.column_mapping)





		def 	_snake_case	(  self					:Union[str, Any])					->			Union[str, Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[int]					     =     Features({"""text""": Value("""string""")})
								UpperCamelCase_     :	List[str]					     =     Features({"""summary""": Value("""string""")})
								UpperCamelCase_     :	Dict					     =     {'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
								UpperCamelCase_     :	Optional[int]					     =     Summarization.from_dict(UpperCamelCase_)
								self.assertEqual("""summarization"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:Any)					->			int:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[Any]					     =     AutomaticSpeechRecognition(audio_column="""input_audio"""			,    transcription_column="""input_transcription""")
								self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""}			,    task.column_mapping)





		def 	_snake_case	(  self					:List[Any])					->			Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Union[str, Any]					     =     Features({"""audio""": Audio()})
								UpperCamelCase_     :	str					     =     Features({"""transcription""": Value("""string""")})
								UpperCamelCase_     :	Tuple					     =     {
								    '''audio_column''': '''input_audio''',
								    '''transcription_column''': '''input_transcription''',
								}
								UpperCamelCase_     :	Any					     =     AutomaticSpeechRecognition.from_dict(UpperCamelCase_)
								self.assertEqual("""automatic-speech-recognition"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:Dict)					->			Dict:






								'''simple docstring'''






								UpperCamelCase_     :	Dict					     =     sorted(["""pos""", """neg"""])




		def 	_snake_case	(  self					:int)					->			Dict:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[Any]					     =     AudioClassification(audio_column="""input_audio"""			,    label_column="""input_label""")
								self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""}			,    task.column_mapping)




		def 	_snake_case	(  self					:str)					->			Dict:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[int]					     =     Features({"""audio""": Audio()})
								UpperCamelCase_     :	int					     =     Features({"""labels""": ClassLabel})
								UpperCamelCase_     :	Optional[Any]					     =     {
								    '''audio_column''': '''input_image''',
								    '''label_column''': '''input_label''',
								}
								UpperCamelCase_     :	str					     =     AudioClassification.from_dict(UpperCamelCase_)
								self.assertEqual("""audio-classification"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)





		def 	_snake_case	(  self					:str)					->			int:






								'''simple docstring'''






								UpperCamelCase_     :	Any					     =     AudioClassification(audio_column="""input_audio"""			,    label_column="""input_label""")
								self.assertEqual(task.label_schema["""labels"""]			,    UpperCamelCase_)
								UpperCamelCase_     :	Union[str, Any]					     =     task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels)}))
								self.assertEqual(task.label_schema["""labels"""]			,    ClassLabel(names=self.labels))







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:int)					->			List[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[int]					     =     sorted(["""pos""", """neg"""])




		def 	_snake_case	(  self					:Tuple)					->			int:






								'''simple docstring'''






								UpperCamelCase_     :	int					     =     ImageClassification(image_column="""input_image"""			,    label_column="""input_label""")
								self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""}			,    task.column_mapping)




		def 	_snake_case	(  self					:Optional[Any])					->			str:






								'''simple docstring'''






								UpperCamelCase_     :	List[Any]					     =     Features({"""image""": Image()})
								UpperCamelCase_     :	str					     =     Features({"""labels""": ClassLabel})
								UpperCamelCase_     :	Optional[Any]					     =     {
								    '''image_column''': '''input_image''',
								    '''label_column''': '''input_label''',
								}
								UpperCamelCase_     :	int					     =     ImageClassification.from_dict(UpperCamelCase_)
								self.assertEqual("""image-classification"""			,    task.task)
								self.assertEqual(UpperCamelCase_			,    task.input_schema)
								self.assertEqual(UpperCamelCase_			,    task.label_schema)





		def 	_snake_case	(  self					:Dict)					->			List[str]:






								'''simple docstring'''






								UpperCamelCase_     :	int					     =     ImageClassification(image_column="""input_image"""			,    label_column="""input_label""")
								self.assertEqual(task.label_schema["""labels"""]			,    UpperCamelCase_)
								UpperCamelCase_     :	Dict					     =     task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels)}))
								self.assertEqual(task.label_schema["""labels"""]			,    ClassLabel(names=self.labels))







class     __snake_case			(    a__	):




		def 	_snake_case	(  self					:List[str])					->			List[Any]:






								'''simple docstring'''






								UpperCamelCase_     :	Any					     =     DatasetInfo(task_templates=QuestionAnsweringExtractive())
								UpperCamelCase_     :	str					     =     Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}			,    info=UpperCamelCase_)
								assert isinstance(dataset.info.task_templates			,    UpperCamelCase_)
								assert len(dataset.info.task_templates) == 1

								def keep_task(_SCREAMING_SNAKE_CASE					:Union[str, Any]):
														return x

								def dont_keep_task(_SCREAMING_SNAKE_CASE					:Union[str, Any]):
														UpperCamelCase_     :	List[str]					     =     deepcopy(UpperCamelCase_)
														UpperCamelCase_     :	Tuple					     =     0
														return out

								UpperCamelCase_     :	Any					     =     dataset.map(UpperCamelCase_)
								assert mapped_dataset.info.task_templates == dataset.info.task_templates
								# reload from cache
								UpperCamelCase_     :	int					     =     dataset.map(UpperCamelCase_)
								assert mapped_dataset.info.task_templates == dataset.info.task_templates

								UpperCamelCase_     :	Optional[int]					     =     dataset.map(UpperCamelCase_)
								assert mapped_dataset.info.task_templates == []
								# reload from cache
								UpperCamelCase_     :	int					     =     dataset.map(UpperCamelCase_)
								assert mapped_dataset.info.task_templates == []





		def 	_snake_case	(  self					:List[Any])					->			Optional[int]:






								'''simple docstring'''






								UpperCamelCase_     :	Union[str, Any]					     =     Features({"""text""": Value("""string"""), """label""": ClassLabel(names=("""pos""", """neg"""))})
								UpperCamelCase_     :	Union[str, Any]					     =     TextClassification(text_column="""text"""			,    label_column="""label""")
								UpperCamelCase_     :	Tuple					     =     DatasetInfo(features=UpperCamelCase_			,    task_templates=UpperCamelCase_)
								UpperCamelCase_     :	Optional[Any]					     =     Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]}			,    info=UpperCamelCase_)

								def process(_SCREAMING_SNAKE_CASE					:List[str]):
														return example

								UpperCamelCase_     :	Union[str, Any]					     =     dataset.remove_columns("""label""")
								UpperCamelCase_     :	List[str]					     =     modified_dataset.map(UpperCamelCase_)
								assert mapped_dataset.info.task_templates == []








"""simple docstring"""





import unittest

from transformers import ErnieMConfig, 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 (
     ErnieMForInformationExtraction,
     ErnieMForMultipleChoice,
     ErnieMForQuestionAnswering,
     ErnieMForSequenceClassification,
     ErnieMForTokenClassification,
     ErnieMModel,
 )
 from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST



class 		snake_case_:






     def __init__(						self	:       Optional[int]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Optional[int]=1_3       ,					UpperCamelCase_	:       Dict=7       ,					UpperCamelCase_	:       Dict=True       ,					UpperCamelCase_	:       str=True       ,					UpperCamelCase_	:       int=True       ,					UpperCamelCase_	:       Optional[Any]=9_9       ,					UpperCamelCase_	:       Optional[int]=3_2       ,					UpperCamelCase_	:       Any=5       ,					UpperCamelCase_	:       Any=4       ,					UpperCamelCase_	:       Tuple=3_7       ,					UpperCamelCase_	:       Tuple="gelu"       ,					UpperCamelCase_	:       Union[str, Any]=0.1       ,					UpperCamelCase_	:       List[Any]=0.1       ,					UpperCamelCase_	:       int=5_1_2       ,					UpperCamelCase_	:       int=1_6       ,					UpperCamelCase_	:       List[Any]=2       ,					UpperCamelCase_	:       str=0.02       ,					UpperCamelCase_	:       int=3       ,					UpperCamelCase_	:       str=4       ,					UpperCamelCase_	:       Union[str, Any]=None       ,					):
           lowerCAmelCase       :						List[str]							= parent
           lowerCAmelCase       :						str							= batch_size
           lowerCAmelCase       :						Dict							= seq_length
           lowerCAmelCase       :						Dict							= is_training
           lowerCAmelCase       :						Tuple							= use_input_mask
           lowerCAmelCase       :						str							= use_labels
           lowerCAmelCase       :						Optional[Any]							= vocab_size
           lowerCAmelCase       :						Optional[Any]							= hidden_size
           lowerCAmelCase       :						Optional[int]							= num_hidden_layers
           lowerCAmelCase       :						List[Any]							= num_attention_heads
           lowerCAmelCase       :						Tuple							= intermediate_size
           lowerCAmelCase       :						Tuple							= hidden_act
           lowerCAmelCase       :						Optional[int]							= hidden_dropout_prob
           lowerCAmelCase       :						str							= attention_probs_dropout_prob
           lowerCAmelCase       :						str							= max_position_embeddings
           lowerCAmelCase       :						List[str]							= type_vocab_size
           lowerCAmelCase       :						str							= type_sequence_label_size
           lowerCAmelCase       :						int							= initializer_range
           lowerCAmelCase       :						Optional[Any]							= num_labels
           lowerCAmelCase       :						Any							= num_choices
           lowerCAmelCase       :						str							= scope






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

           lowerCAmelCase       :						List[Any]							= None
           if self.use_input_mask:
                 lowerCAmelCase       :						str							= random_attention_mask([self.batch_size, self.seq_length]					)

           lowerCAmelCase       :						List[Any]							= None
           lowerCAmelCase       :						str							= None
           lowerCAmelCase       :						str							= None
           if self.use_labels:
                 lowerCAmelCase       :						Tuple							= ids_tensor([self.batch_size]       ,					self.type_sequence_label_size					)
                 lowerCAmelCase       :						Dict							= ids_tensor([self.batch_size, self.seq_length]       ,					self.num_labels					)
                 lowerCAmelCase       :						List[Any]							= ids_tensor([self.batch_size]       ,					self.num_choices					)

           lowerCAmelCase       :						Any							= self.get_config()

           return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






     def   lowerCamelCase__  (						self	:       str					):
           lowerCAmelCase       :						Tuple							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

           lowerCAmelCase       :						Optional[Any]							= None
           if self.use_input_mask:
                 lowerCAmelCase       :						Union[str, Any]							= random_attention_mask([self.batch_size, self.seq_length]					)
           lowerCAmelCase       :						Dict							= self.get_config()

           return config, input_ids, input_mask






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           return ErnieMConfig(
               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       ,					type_vocab_size=self.type_vocab_size       ,					initializer_range=self.initializer_range       ,					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						List[str]							= ErnieMModel(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= model(UpperCamelCase_       ,					return_dict=UpperCamelCase_					)
           self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size)					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						Optional[int]							= ErnieMForQuestionAnswering(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					start_positions=UpperCamelCase_       ,					end_positions=UpperCamelCase_       ,					)
           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   lowerCamelCase__  (						self	:       Dict       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Union[str, Any]					):
           lowerCAmelCase       :						Tuple							= ErnieMForInformationExtraction(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Tuple							= torch.ones_like(UpperCamelCase_       ,					dtype=torch.floataa					)
           lowerCAmelCase       :						str							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					start_positions=UpperCamelCase_       ,					end_positions=UpperCamelCase_       ,					)
           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   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Any					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						Tuple							= ErnieMForSequenceClassification(UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Union[str, Any]							= model(UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)					)






     def   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[str]					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						List[Any]							= ErnieMForTokenClassification(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           input_ids.to(UpperCamelCase_					)
           input_mask.to(UpperCamelCase_					)
           token_labels.to(UpperCamelCase_					)

           lowerCAmelCase       :						Optional[Any]							= model(UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_					)

           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.seq_length, self.num_labels)					)






     def   lowerCamelCase__  (						self	:       Any       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_choices
           lowerCAmelCase       :						Any							= ErnieMForMultipleChoice(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Any							= input_ids.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						int							= input_mask.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						Any							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_       ,					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_choices)					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[Any]							= self.prepare_config_and_inputs()
           (
               (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   
           )       :						str							= config_and_inputs
           lowerCAmelCase       :						Dict							= {'''input_ids''': input_ids, '''attention_mask''': input_mask}
           return config, inputs_dict



@require_torch
class 		snake_case_(							a__				,       a__				,       unittest.TestCase      ):
     __UpperCamelCase	=       (
         (
             ErnieMModel,
             ErnieMForMultipleChoice,
             ErnieMForQuestionAnswering,
             ErnieMForSequenceClassification,
             ErnieMForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     __UpperCamelCase	=       ()
     __UpperCamelCase	=       (
         {
             '''feature-extraction''': ErnieMModel,
             '''question-answering''': ErnieMForQuestionAnswering,
             '''text-classification''': ErnieMForSequenceClassification,
             '''token-classification''': ErnieMForTokenClassification,
             '''zero-shot''': ErnieMForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __UpperCamelCase	=       False






     def   lowerCamelCase__  (						self	:       Optional[Any]       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Any					):
           if pipeline_test_casse_name == "QAPipelineTests":
                 return True

           return False






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ErnieMModelTester(self					)
           lowerCAmelCase       :						Optional[Any]							= ConfigTester(self       ,					config_class=UpperCamelCase_       ,					hidden_size=3_7					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           self.config_tester.run_common_tests()






     def   lowerCamelCase__  (						self	:       List[str]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           lowerCAmelCase       :						Optional[Any]							= self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                 lowerCAmelCase       :						Union[str, Any]							= type
                 self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						Dict							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						int							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Optional[int]					):
           lowerCAmelCase       :						Tuple							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[str]							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_information_extraction(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       List[Any]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*UpperCamelCase_					)






     @slow
     def   lowerCamelCase__  (						self	:       List[str]					):
           for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCAmelCase       :						int							= ErnieMModel.from_pretrained(UpperCamelCase_					)
                 self.assertIsNotNone(UpperCamelCase_					)



@require_torch
class 		snake_case_(							unittest.TestCase      ):






     @slow
     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						Optional[int]							= ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''					)
           model.eval()
           lowerCAmelCase       :						Optional[int]							= torch.tensor([[0, 1, 2, 3, 4, 5]]					)
           lowerCAmelCase       :						str							= model(UpperCamelCase_					)[0]

           # TODO Replace vocab size
           lowerCAmelCase       :						Any							= 7_6_8

           lowerCAmelCase       :						int							= torch.Size((1, 6, hidden_size)					)
           self.assertEqual(output.shape       ,					UpperCamelCase_					)

           lowerCAmelCase       :						str							= torch.tensor(
               [[[-0.0_012, 0.1_245, -0.0_214], [-0.0_742, 0.0_244, -0.0_771], [-0.0_333, 0.1_164, -0.1_554]]]					)

           self.assertTrue(torch.allclose(output[:, :3, :3]       ,					UpperCamelCase_       ,					atol=1E-3					)					)


