
"""simple docstring"""






import os
import tempfile
import unittest

from transformers import NezhaConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

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


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_PRETRAINING_MAPPING,
					    NezhaForMaskedLM,
					    NezhaForMultipleChoice,
					    NezhaForNextSentencePrediction,
					    NezhaForPreTraining,
					    NezhaForQuestionAnswering,
					    NezhaForSequenceClassification,
					    NezhaForTokenClassification,
					    NezhaModel,
					)
					from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST




class 				lowercase__:
	'''simple docstring'''

	def __init__(						self    :Any		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Union[str, Any]=13		, lowerCamelCase_    :Tuple=7		, lowerCamelCase_    :Optional[int]=True		, lowerCamelCase_    :str=True		, lowerCamelCase_    :Optional[Any]=True		, lowerCamelCase_    :List[Any]=True		, lowerCamelCase_    :List[Any]=99		, lowerCamelCase_    :int=32		, lowerCamelCase_    :str=5		, lowerCamelCase_    :Dict=4		, lowerCamelCase_    :Any=37		, lowerCamelCase_    :Dict="gelu"		, lowerCamelCase_    :Optional[Any]=0.1		, lowerCamelCase_    :Any=0.1		, lowerCamelCase_    :Tuple=1_28		, lowerCamelCase_    :List[Any]=32		, lowerCamelCase_    :str=16		, lowerCamelCase_    :Dict=2		, lowerCamelCase_    :List[str]=0.0_2		, lowerCamelCase_    :Tuple=3		, lowerCamelCase_    :List[str]=4		, lowerCamelCase_    :List[Any]=None		, )							->			List[str]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[str]				= parent
			SCREAMING_SNAKE_CASE       :     Any				= batch_size
			SCREAMING_SNAKE_CASE       :     Dict				= seq_length
			SCREAMING_SNAKE_CASE       :     Any				= is_training
			SCREAMING_SNAKE_CASE       :     Tuple				= use_input_mask
			SCREAMING_SNAKE_CASE       :     int				= use_token_type_ids
			SCREAMING_SNAKE_CASE       :     str				= use_labels
			SCREAMING_SNAKE_CASE       :     List[Any]				= vocab_size
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= hidden_size
			SCREAMING_SNAKE_CASE       :     List[str]				= num_hidden_layers
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= num_attention_heads
			SCREAMING_SNAKE_CASE       :     Any				= intermediate_size
			SCREAMING_SNAKE_CASE       :     Any				= hidden_act
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= hidden_dropout_prob
			SCREAMING_SNAKE_CASE       :     Tuple				= attention_probs_dropout_prob
			SCREAMING_SNAKE_CASE       :     Dict				= max_position_embeddings
			SCREAMING_SNAKE_CASE       :     Optional[int]				= type_vocab_size
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= type_sequence_label_size
			SCREAMING_SNAKE_CASE       :     Tuple				= initializer_range
			SCREAMING_SNAKE_CASE       :     Any				= num_labels
			SCREAMING_SNAKE_CASE       :     str				= num_choices
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= scope





	def   __lowerCAmelCase (						self    :Dict					)							->			Tuple:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= ids_tensor([self.batch_size, self.seq_length]		, self.vocab_size					)

			SCREAMING_SNAKE_CASE       :     Dict				= None
			if self.use_input_mask:
					SCREAMING_SNAKE_CASE       :     Tuple				= random_attention_mask([self.batch_size, self.seq_length]					)

			SCREAMING_SNAKE_CASE       :     Dict				= None
			if self.use_token_type_ids:
					SCREAMING_SNAKE_CASE       :     Optional[int]				= ids_tensor([self.batch_size, self.seq_length]		, self.type_vocab_size					)

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

			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.get_config()

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





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







			'''simple docstring'''




			return NezhaConfig(
			    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		, is_decoder=lowerCamelCase_		, initializer_range=self.initializer_range		, )





	def   __lowerCAmelCase (						self    :List[str]					)							->			Optional[int]:







			'''simple docstring'''




			(
			    (
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					
			)       :     Optional[Any]				= self.prepare_config_and_inputs()

			SCREAMING_SNAKE_CASE       :     Optional[int]				= True
			SCREAMING_SNAKE_CASE       :     int				= floats_tensor([self.batch_size, self.seq_length, self.hidden_size]					)
			SCREAMING_SNAKE_CASE       :     List[Any]				= ids_tensor([self.batch_size, self.seq_length]		, vocab_size=2					)

			return (
			    config,
			    input_ids,
			    token_type_ids,
			    input_mask,
			    sequence_labels,
			    token_labels,
			    choice_labels,
			    encoder_hidden_states,
			    encoder_attention_mask,
			)





	def   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :int		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :int					)							->			List[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[str]				= NezhaModel(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Any				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Any				= model(lowerCamelCase_		, token_type_ids=lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= model(lowerCamelCase_					)
			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   __lowerCAmelCase (						self    :List[Any]		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :Any		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :int		, lowerCamelCase_    :Dict		, )							->			List[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= True
			SCREAMING_SNAKE_CASE       :     str				= NezhaModel(lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, encoder_hidden_states=lowerCamelCase_		, encoder_attention_mask=lowerCamelCase_		, )
			SCREAMING_SNAKE_CASE       :     int				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, encoder_hidden_states=lowerCamelCase_		, )
			SCREAMING_SNAKE_CASE       :     str				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_					)
			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   __lowerCAmelCase (						self    :List[Any]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :int		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :List[Any]					)							->			List[str]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= NezhaForMaskedLM(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     str				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_					)
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.seq_length, self.vocab_size)					)





	def   __lowerCAmelCase (						self    :Tuple		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :str		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :int		, lowerCamelCase_    :List[Any]					)							->			str:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= NezhaForNextSentencePrediction(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     str				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_		, )
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, 2)					)





	def   __lowerCAmelCase (						self    :str		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Optional[Any]					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= NezhaForPreTraining(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Dict				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_		, next_sentence_label=lowerCamelCase_		, )
			self.parent.assertEqual(result.prediction_logits.shape		, (self.batch_size, self.seq_length, self.vocab_size)					)
			self.parent.assertEqual(result.seq_relationship_logits.shape		, (self.batch_size, 2)					)





	def   __lowerCAmelCase (						self    :Optional[Any]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :str		, lowerCamelCase_    :List[str]		, lowerCamelCase_    :Union[str, Any]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :int		, lowerCamelCase_    :Dict					)							->			Optional[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[str]				= NezhaForQuestionAnswering(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Tuple				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, start_positions=lowerCamelCase_		, end_positions=lowerCamelCase_		, )
			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    :Tuple		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Optional[Any]					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Any				= self.num_labels
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= NezhaForSequenceClassification(lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Any				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_					)
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.num_labels)					)





	def   __lowerCAmelCase (						self    :Optional[Any]		, lowerCamelCase_    :str		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Any		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :List[Any]					)							->			List[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= self.num_labels
			SCREAMING_SNAKE_CASE       :     Any				= NezhaForTokenClassification(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Tuple				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_					)
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.seq_length, self.num_labels)					)





	def   __lowerCAmelCase (						self    :Optional[Any]		, lowerCamelCase_    :str		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :Optional[int]		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :Tuple		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Dict					)							->			List[Any]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= self.num_choices
			SCREAMING_SNAKE_CASE       :     List[str]				= NezhaForMultipleChoice(config=lowerCamelCase_					)
			model.to(lowerCamelCase_					)
			model.eval()
			SCREAMING_SNAKE_CASE       :     Optional[int]				= input_ids.unsqueeze(1					).expand(-1		, self.num_choices		, -1					).contiguous()
			SCREAMING_SNAKE_CASE       :     Optional[int]				= token_type_ids.unsqueeze(1					).expand(-1		, self.num_choices		, -1					).contiguous()
			SCREAMING_SNAKE_CASE       :     Optional[Any]				= input_mask.unsqueeze(1					).expand(-1		, self.num_choices		, -1					).contiguous()
			SCREAMING_SNAKE_CASE       :     str				= model(
			    lowerCamelCase_		, attention_mask=lowerCamelCase_		, token_type_ids=lowerCamelCase_		, labels=lowerCamelCase_		, )
			self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.num_choices)					)







	def   __lowerCAmelCase (						self    :List[str]					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[Any]				= self.prepare_config_and_inputs()
			(
			    (
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					
			)       :     List[str]				= config_and_inputs
			SCREAMING_SNAKE_CASE       :     int				= {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
			return config, inputs_dict





@require_torch
class 				lowercase__(				_UpperCAmelCase		,						_UpperCAmelCase		,						_UpperCAmelCase		,						unittest.TestCase   ):
	'''simple docstring'''

	UpperCamelCase				=  (
	    (
	        NezhaModel,
	        NezhaForMaskedLM,
	        NezhaForMultipleChoice,
	        NezhaForNextSentencePrediction,
	        NezhaForPreTraining,
	        NezhaForQuestionAnswering,
	        NezhaForSequenceClassification,
	        NezhaForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	UpperCamelCase				=  (
	    {
	        """feature-extraction""": NezhaModel,
	        """fill-mask""": NezhaForMaskedLM,
	        """question-answering""": NezhaForQuestionAnswering,
	        """text-classification""": NezhaForSequenceClassification,
	        """token-classification""": NezhaForTokenClassification,
	        """zero-shot""": NezhaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	UpperCamelCase				=  True





	def   __lowerCAmelCase (						self    :List[Any]		, lowerCamelCase_    :List[Any]		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Tuple=False					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[Any]				= super()._prepare_for_class(lowerCamelCase_		, lowerCamelCase_		, return_labels=lowerCamelCase_					)

			if return_labels:
					if model_class in get_values(lowerCamelCase_					):
							SCREAMING_SNAKE_CASE       :     int				= torch.zeros(
							    (self.model_tester.batch_size, self.model_tester.seq_length)		, dtype=torch.long		, device=lowerCamelCase_					)
							SCREAMING_SNAKE_CASE       :     Optional[int]				= torch.zeros(
							    self.model_tester.batch_size		, dtype=torch.long		, device=lowerCamelCase_					)
			return inputs_dict





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     str				= NezhaModelTester(self					)
			SCREAMING_SNAKE_CASE       :     Any				= ConfigTester(self		, config_class=lowerCamelCase_		, hidden_size=37					)





	def   __lowerCAmelCase (						self    :List[str]					)							->			int:







			'''simple docstring'''




			self.config_tester.run_common_tests()





	def   __lowerCAmelCase (						self    :Any					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Any					)							->			Tuple:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Any				= self.model_tester.prepare_config_and_inputs_for_decoder()
			self.model_tester.create_and_check_model_as_decoder(*lowerCamelCase_					)





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







			'''simple docstring'''




			(
			    (
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					(
			    SCREAMING_SNAKE_CASE
			),					
			)       :     List[Any]				= self.model_tester.prepare_config_and_inputs_for_decoder()

			SCREAMING_SNAKE_CASE       :     List[str]				= None

			self.model_tester.create_and_check_model_as_decoder(
			    lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_		, )





	def   __lowerCAmelCase (						self    :Dict					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Optional[int]					)							->			Optional[int]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase_					)





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







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_next_sequence_prediction(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :List[Any]					)							->			Dict:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Any				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_pretraining(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Dict					)							->			str:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[str]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :List[Any]					)							->			Dict:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_					)





	def   __lowerCAmelCase (						self    :Tuple					)							->			Optional[int]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     List[str]				= self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_					)





	@slow
	def   __lowerCAmelCase (						self    :List[Any]					)							->			List[Any]:







			'''simple docstring'''




			for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					SCREAMING_SNAKE_CASE       :     Optional[int]				= NezhaModel.from_pretrained(lowerCamelCase_					)
					self.assertIsNotNone(lowerCamelCase_					)







	@slow
	@require_torch_gpu
	def   __lowerCAmelCase (						self    :List[str]					)							->			str:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE       :     List[Any]				= self.model_tester.prepare_config_and_inputs_for_common()
			for model_class in self.all_model_classes:
					# NezhaForMultipleChoice behaves incorrectly in JIT environments.
					if model_class == NezhaForMultipleChoice:
							return

					SCREAMING_SNAKE_CASE       :     Union[str, Any]				= True
					SCREAMING_SNAKE_CASE       :     Optional[Any]				= model_class(config=lowerCamelCase_					)

					SCREAMING_SNAKE_CASE       :     Optional[int]				= self._prepare_for_class(lowerCamelCase_		, lowerCamelCase_					)
					SCREAMING_SNAKE_CASE       :     Optional[Any]				= torch.jit.trace(
					    lowerCamelCase_		, (inputs_dict['''input_ids'''].to('''cpu'''					), inputs_dict['''attention_mask'''].to('''cpu'''					))					)

					with tempfile.TemporaryDirectory() as tmp:
							torch.jit.save(lowerCamelCase_		, os.path.join(lowerCamelCase_		, '''bert.pt'''					)					)
							SCREAMING_SNAKE_CASE       :     Optional[Any]				= torch.jit.load(os.path.join(lowerCamelCase_		, '''bert.pt'''					)		, map_location=lowerCamelCase_					)
							loaded(inputs_dict['''input_ids'''].to(lowerCamelCase_					)		, inputs_dict['''attention_mask'''].to(lowerCamelCase_					)					)





@require_torch
class 				lowercase__(				unittest.TestCase   ):
	'''simple docstring'''

	@slow
	def   __lowerCAmelCase (						self    :Union[str, Any]					)							->			Any:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Dict				= NezhaModel.from_pretrained('''sijunhe/nezha-cn-base'''					)
			SCREAMING_SNAKE_CASE       :     List[str]				= torch.tensor([[0, 1, 2, 3, 4, 5]]					)
			SCREAMING_SNAKE_CASE       :     Optional[int]				= torch.tensor([[0, 1, 1, 1, 1, 1]]					)
			with torch.no_grad():
					SCREAMING_SNAKE_CASE       :     Any				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_					)[0]
			SCREAMING_SNAKE_CASE       :     Tuple				= torch.Size((1, 6, 7_68)					)
			self.assertEqual(output.shape		, lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]]					)

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







	@slow
	def   __lowerCAmelCase (						self    :Optional[Any]					)							->			Optional[int]:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     Optional[int]				= NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base'''					)
			SCREAMING_SNAKE_CASE       :     Union[str, Any]				= torch.tensor([[0, 1, 2, 3, 4, 5]]					)
			SCREAMING_SNAKE_CASE       :     Dict				= torch.tensor([[1, 1, 1, 1, 1, 1]]					)
			with torch.no_grad():
					SCREAMING_SNAKE_CASE       :     int				= model(lowerCamelCase_		, attention_mask=lowerCamelCase_					)[0]
			SCREAMING_SNAKE_CASE       :     List[str]				= torch.Size((1, 6, 2_11_28)					)
			self.assertEqual(output.shape		, lowerCamelCase_					)
			SCREAMING_SNAKE_CASE       :     Any				= torch.tensor(
			    [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]]					)

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







"""simple docstring"""






from sklearn.metrics import fa_score

import datasets


lowerCamelCase__ :       List[Any]						     =			"\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n"


lowerCamelCase__ :       str						     =			"\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {'f1': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results['f1'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> f1_metric = datasets.load_metric(\"f1\")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(round(results['f1'], 2))\n        0.35\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n        >>> print(round(results['f1'], 2))\n        0.33\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n        >>> print(round(results['f1'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'f1': array([0.8, 0. , 0. ])}\n"


lowerCamelCase__ :       int						     =			"\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,						_KWARGS_DESCRIPTION   )
class 				lowercase__(				datasets.Metric   ):
	'''simple docstring'''

	def   __lowerCAmelCase (						self    :str					)							->			Any:







			'''simple docstring'''




			return datasets.MetricInfo(
			    description=_DESCRIPTION		, citation=_CITATION		, inputs_description=_KWARGS_DESCRIPTION		, features=datasets.Features(
			        {
			            '''predictions''': datasets.Sequence(datasets.Value('''int32'''					)					),
			            '''references''': datasets.Sequence(datasets.Value('''int32'''					)					),
			        }
			        if self.config_name == '''multilabel'''
			        else {
			            '''predictions''': datasets.Value('''int32'''					),
			            '''references''': datasets.Value('''int32'''					),
			        }					)		, reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html''']		, )







	def   __lowerCAmelCase (						self    :Any		, lowerCamelCase_    :Dict		, lowerCamelCase_    :Optional[Any]		, lowerCamelCase_    :int=None		, lowerCamelCase_    :str=1		, lowerCamelCase_    :Union[str, Any]="binary"		, lowerCamelCase_    :Dict=None					)							->			int:







			'''simple docstring'''




			SCREAMING_SNAKE_CASE       :     int				= fa_score(
			    lowerCamelCase_		, lowerCamelCase_		, labels=lowerCamelCase_		, pos_label=lowerCamelCase_		, average=lowerCamelCase_		, sample_weight=lowerCamelCase_					)
			return {"f1": float(lowerCamelCase_					) if score.size == 1 else score}





