



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 							UpperCAmelCase   :




	'''simple docstring'''





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






	def        UpperCamelCase_						( self      :				str				):
					__A         =				ids_tensor([self.batch_size, self.seq_length]							,self.vocab_size				)

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

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

					__A         =				self.get_config()

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






	def        UpperCamelCase_						( self      :				Union[str, Any]				):
					__A         =				ids_tensor([self.batch_size, self.seq_length]							,self.vocab_size				)

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

					return config, input_ids, input_mask






	def        UpperCamelCase_						( self      :				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        UpperCamelCase_						( self      :				int							,A      :				Union[str, Any]							,A      :				Optional[int]							,A      :				Any							,A      :				List[Any]							,A      :				int							,A      :				Any				):
					__A         =				ErnieMModel(config=_A				)
					model.to(_A				)
					model.eval()
					__A         =				model(_A							,return_dict=_A				)
					self.parent.assertEqual(result.last_hidden_state.shape							,(self.batch_size, self.seq_length, self.hidden_size)				)






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






	def        UpperCamelCase_						( self      :				Union[str, Any]							,A      :				List[str]							,A      :				Any							,A      :				Tuple							,A      :				Dict							,A      :				str							,A      :				List[str]				):
					__A         =				self.num_labels
					__A         =				ErnieMForTokenClassification(config=_A				)
					model.to(_A				)
					model.eval()
					input_ids.to(_A				)
					input_mask.to(_A				)
					token_labels.to(_A				)

					__A         =				model(_A							,attention_mask=_A							,labels=_A				)

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






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







	def        UpperCamelCase_						( self      :				List[Any]				):
					__A         =				self.prepare_config_and_inputs()
					(
					    __A       
					)         =				config_and_inputs
					__A         =				{'input_ids': input_ids, 'attention_mask': input_mask}
					return config, inputs_dict





@require_torch
class 							UpperCAmelCase   (						lowercase__    ,    lowercase__    ,    unittest.TestCase						):




	'''simple docstring'''





	snake_case_      					=  (
	    (
	        ErnieMModel,
	        ErnieMForMultipleChoice,
	        ErnieMForQuestionAnswering,
	        ErnieMForSequenceClassification,
	        ErnieMForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	snake_case_      					=  ()
	snake_case_      					=  (
	    {
	        """feature-extraction""": ErnieMModel,
	        """question-answering""": ErnieMForQuestionAnswering,
	        """text-classification""": ErnieMForSequenceClassification,
	        """token-classification""": ErnieMForTokenClassification,
	        """zero-shot""": ErnieMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	snake_case_      					=  False






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

					return False






	def        UpperCamelCase_						( self      :				Optional[Any]				):
					__A         =				ErnieMModelTester(self				)
					__A         =				ConfigTester(self							,config_class=_A							,hidden_size=37				)






	def        UpperCamelCase_						( self      :				List[Any]				):
					self.config_tester.run_common_tests()






	def        UpperCamelCase_						( self      :				int				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_A				)






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






	def        UpperCamelCase_						( self      :				int				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_multiple_choice(*_A				)






	def        UpperCamelCase_						( self      :				List[Any]				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_question_answering(*_A				)






	def        UpperCamelCase_						( self      :				Optional[Any]				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_sequence_classification(*_A				)






	def        UpperCamelCase_						( self      :				Dict				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_information_extraction(*_A				)






	def        UpperCamelCase_						( self      :				Dict				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_token_classification(*_A				)







	@slow
	def        UpperCamelCase_						( self      :				int				):
					for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__A         =				ErnieMModel.from_pretrained(_A				)
									self.assertIsNotNone(_A				)





@require_torch
class 							UpperCAmelCase   (						unittest.TestCase						):




	'''simple docstring'''





	@slow
	def        UpperCamelCase_						( self      :				int				):
					__A         =				ErnieMModel.from_pretrained("susnato/ernie-m-base_pytorch"				)
					model.eval()
					__A         =				torch.tensor([[0, 1, 2, 3, 4, 5]]				)
					__A         =				model(_A				)[0]

					# TODO Replace vocab size
					__A         =				7_68

					__A         =				torch.Size((1, 6, hidden_size)				)
					self.assertEqual(output.shape							,_A				)

					__A         =				torch.tensor(
					    [[[-0.00_12, 0.12_45, -0.02_14], [-0.07_42, 0.02_44, -0.07_71], [-0.03_33, 0.11_64, -0.15_54]]]				)

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


def 		UpperCAmelCase    (			a_		)	->			int:







				"""simple docstring"""



				__A         =				str(a_		).strip()
				if not oct_string:
								raise ValueError("Empty string was passed to the function"		)
				__A         =				oct_string[0] == "-"
				if is_negative:
								__A         =				oct_string[1:]
				if not oct_string.isdigit() or not all(0 <= int(a_		) <= 7 for char in oct_string		):
								raise ValueError("Non-octal value was passed to the function"		)
				__A         =				0
				for char in oct_string:
								__A         =				8 * decimal_number + int(a_		)
				if is_negative:
								__A         =				-decimal_number
				return decimal_number


if __name__ == "__main__":
					from doctest import testmod

					testmod()
