





"""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  _SCREAMING_SNAKE_CASE:




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





													"""simple docstring"""






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




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





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  ids_tensor([self.batch_size, self.seq_length]		,self.vocab_size							)

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

													__SCREAMING_SNAKE_CASE       :List[str]		    =  None
													if self.use_token_type_ids:
																			__SCREAMING_SNAKE_CASE       :List[str]		    =  ids_tensor([self.batch_size, self.seq_length]		,self.type_vocab_size							)

													__SCREAMING_SNAKE_CASE       :str		    =  None
													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  None
													__SCREAMING_SNAKE_CASE       :List[Any]		    =  None
													if self.use_labels:
																			__SCREAMING_SNAKE_CASE       :Optional[int]		    =  ids_tensor([self.batch_size]		,self.type_sequence_label_size							)
																			__SCREAMING_SNAKE_CASE       :List[Any]		    =  ids_tensor([self.batch_size, self.seq_length]		,self.num_labels							)
																			__SCREAMING_SNAKE_CASE       :Optional[int]		    =  ids_tensor([self.batch_size]		,self.num_choices							)

													__SCREAMING_SNAKE_CASE       :Tuple		    =  self.get_config()

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




							def    _UpperCamelCase					(						self							)      ->				List[Any]:





													"""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=SCREAMING_SNAKE_CASE__		,initializer_range=self.initializer_range		,)




							def    _UpperCamelCase					(						self							)      ->				int:





													"""simple docstring"""






													(
													    __SCREAMING_SNAKE_CASE
													)       :str		    =  self.prepare_config_and_inputs()

													__SCREAMING_SNAKE_CASE       :int		    =  True
													__SCREAMING_SNAKE_CASE       :int		    =  floats_tensor([self.batch_size, self.seq_length, self.hidden_size]							)
													__SCREAMING_SNAKE_CASE       :Optional[int]		    =  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    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				int:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  NezhaModel(config=SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__							)
													__SCREAMING_SNAKE_CASE       :Tuple		    =  model(SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__							)
													__SCREAMING_SNAKE_CASE       :List[str]		    =  model(SCREAMING_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		,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__		,)      ->				Any:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  True
													__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  NezhaModel(SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :Dict		    =  model(
													    SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,encoder_hidden_states=SCREAMING_SNAKE_CASE__		,encoder_attention_mask=SCREAMING_SNAKE_CASE__		,)
													__SCREAMING_SNAKE_CASE       :Dict		    =  model(
													    SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,encoder_hidden_states=SCREAMING_SNAKE_CASE__		,)
													__SCREAMING_SNAKE_CASE       :List[Any]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_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		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				int:





													"""simple docstring"""






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




							def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				List[str]:





													"""simple docstring"""






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




							def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :int		    =  NezhaForPreTraining(config=SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  model(
													    SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,labels=SCREAMING_SNAKE_CASE__		,next_sentence_label=SCREAMING_SNAKE_CASE__		,)
													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    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Any		    =  NezhaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :int		    =  model(
													    SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,start_positions=SCREAMING_SNAKE_CASE__		,end_positions=SCREAMING_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		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Tuple:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Optional[int]		    =  self.num_labels
													__SCREAMING_SNAKE_CASE       :str		    =  NezhaForSequenceClassification(SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :List[Any]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,labels=SCREAMING_SNAKE_CASE__							)
													self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.num_labels)							)




							def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				List[str]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  self.num_labels
													__SCREAMING_SNAKE_CASE       :Optional[int]		    =  NezhaForTokenClassification(config=SCREAMING_SNAKE_CASE__							)
													model.to(SCREAMING_SNAKE_CASE__							)
													model.eval()
													__SCREAMING_SNAKE_CASE       :List[str]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__		,token_type_ids=SCREAMING_SNAKE_CASE__		,labels=SCREAMING_SNAKE_CASE__							)
													self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.seq_length, self.num_labels)							)




							def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Dict:





													"""simple docstring"""






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




							def    _UpperCamelCase					(						self							)      ->				Dict:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Any		    =  self.prepare_config_and_inputs()
													(
													    __SCREAMING_SNAKE_CASE
													)       :int		    =  config_and_inputs
													__SCREAMING_SNAKE_CASE       :Tuple		    =  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
													return config, inputs_dict






@require_torch
class  _SCREAMING_SNAKE_CASE(       A   ,     A   ,     A   ,     unittest.TestCase  ):
							SCREAMING_SNAKE_CASE_       :				List[Any]     						=  (
							    (
							        NezhaModel,
							        NezhaForMaskedLM,
							        NezhaForMultipleChoice,
							        NezhaForNextSentencePrediction,
							        NezhaForPreTraining,
							        NezhaForQuestionAnswering,
							        NezhaForSequenceClassification,
							        NezhaForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							SCREAMING_SNAKE_CASE_       :				int     						=  (
							    {
							        '''feature-extraction''': NezhaModel,
							        '''fill-mask''': NezhaForMaskedLM,
							        '''question-answering''': NezhaForQuestionAnswering,
							        '''text-classification''': NezhaForSequenceClassification,
							        '''token-classification''': NezhaForTokenClassification,
							        '''zero-shot''': NezhaForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							SCREAMING_SNAKE_CASE_       :				List[Any]     						=  True




							def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=False							)      ->				Dict:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :List[Any]		    =  super()._prepare_for_class(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,return_labels=SCREAMING_SNAKE_CASE__							)

													if return_labels:
																			if model_class in get_values(SCREAMING_SNAKE_CASE__							):
																									__SCREAMING_SNAKE_CASE       :int		    =  torch.zeros(
																									    (self.model_tester.batch_size, self.model_tester.seq_length)		,dtype=torch.long		,device=SCREAMING_SNAKE_CASE__							)
																									__SCREAMING_SNAKE_CASE       :Any		    =  torch.zeros(
																									    self.model_tester.batch_size		,dtype=torch.long		,device=SCREAMING_SNAKE_CASE__							)
													return inputs_dict




							def    _UpperCamelCase					(						self							)      ->				Dict:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  NezhaModelTester(self							)
													__SCREAMING_SNAKE_CASE       :List[str]		    =  ConfigTester(self		,config_class=SCREAMING_SNAKE_CASE__		,hidden_size=37							)




							def    _UpperCamelCase					(						self							)      ->				Dict:





													"""simple docstring"""






													self.config_tester.run_common_tests()




							def    _UpperCamelCase					(						self							)      ->				Dict:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Any		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__							)




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





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :int		    =  self.model_tester.prepare_config_and_inputs_for_decoder()
													self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE__							)




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





													"""simple docstring"""






													(
													    __SCREAMING_SNAKE_CASE
													)       :Optional[int]		    =  self.model_tester.prepare_config_and_inputs_for_decoder()

													__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  None

													self.model_tester.create_and_check_model_as_decoder(
													    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__		,)




							def    _UpperCamelCase					(						self							)      ->				List[str]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Tuple		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__							)




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





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__							)




							def    _UpperCamelCase					(						self							)      ->				List[Any]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :List[Any]		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE__							)




							def    _UpperCamelCase					(						self							)      ->				List[str]:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE__							)




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





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Optional[int]		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__							)




							def    _UpperCamelCase					(						self							)      ->				Tuple:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :int		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__							)




							def    _UpperCamelCase					(						self							)      ->				str:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__							)




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





													"""simple docstring"""






													for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__SCREAMING_SNAKE_CASE       :str		    =  NezhaModel.from_pretrained(SCREAMING_SNAKE_CASE__							)
																			self.assertIsNotNone(SCREAMING_SNAKE_CASE__							)




							@slow
							@require_torch_gpu
							def    _UpperCamelCase					(						self							)      ->				Tuple:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  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[int]		    =  model_class(config=SCREAMING_SNAKE_CASE__							)

																			__SCREAMING_SNAKE_CASE       :List[Any]		    =  self._prepare_for_class(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
																			__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  torch.jit.trace(
																			    SCREAMING_SNAKE_CASE__		,(inputs_dict['''input_ids'''].to('''cpu'''							), inputs_dict['''attention_mask'''].to('''cpu'''							))							)

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






@require_torch
class  _SCREAMING_SNAKE_CASE(       unittest.TestCase  ):




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





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :str		    =  NezhaModel.from_pretrained('''sijunhe/nezha-cn-base'''							)
													__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  torch.tensor([[0, 1, 2, 3, 4, 5]]							)
													__SCREAMING_SNAKE_CASE       :int		    =  torch.tensor([[0, 1, 1, 1, 1, 1]]							)
													with torch.no_grad():
																			__SCREAMING_SNAKE_CASE       :List[Any]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__							)[0]
													__SCREAMING_SNAKE_CASE       :int		    =  torch.Size((1, 6, 7_68)							)
													self.assertEqual(output.shape		,SCREAMING_SNAKE_CASE__							)
													__SCREAMING_SNAKE_CASE       :Optional[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]		,SCREAMING_SNAKE_CASE__		,atol=1E-4							)							)




							@slow
							def    _UpperCamelCase					(						self							)      ->				int:





													"""simple docstring"""






													__SCREAMING_SNAKE_CASE       :Any		    =  NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base'''							)
													__SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  torch.tensor([[0, 1, 2, 3, 4, 5]]							)
													__SCREAMING_SNAKE_CASE       :int		    =  torch.tensor([[1, 1, 1, 1, 1, 1]]							)
													with torch.no_grad():
																			__SCREAMING_SNAKE_CASE       :Optional[int]		    =  model(SCREAMING_SNAKE_CASE__		,attention_mask=SCREAMING_SNAKE_CASE__							)[0]
													__SCREAMING_SNAKE_CASE       :List[Any]		    =  torch.Size((1, 6, 2_11_28)							)
													self.assertEqual(output.shape		,SCREAMING_SNAKE_CASE__							)
													__SCREAMING_SNAKE_CASE       :List[str]		    =  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]		,SCREAMING_SNAKE_CASE__		,atol=1E-4							)							)






"""simple docstring"""
import baseaa
import io
import json
import os
from copy import deepcopy

from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				int:





             """simple docstring"""






             if isinstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							):
                   # Don't modify user's data should they want to reuse it (e.g. in tests), because once we
                   # modified it, it will not be accepted here again, since `auto` values would have been overridden
                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  deepcopy(SCREAMING_SNAKE_CASE__							)
             elif os.path.exists(SCREAMING_SNAKE_CASE__							):
                   with io.open(SCREAMING_SNAKE_CASE__		,'''r'''		,encoding='''utf-8'''							) as f:
                         __SCREAMING_SNAKE_CASE       :Dict		    =  json.load(SCREAMING_SNAKE_CASE__							)
             else:
                   try:
                         __SCREAMING_SNAKE_CASE       :str		    =  baseaa.urlsafe_baadecode(SCREAMING_SNAKE_CASE__							).decode('''utf-8'''							)
                         __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  json.loads(SCREAMING_SNAKE_CASE__							)
                   except (UnicodeDecodeError, AttributeError, ValueError):
                         raise ValueError(
                             f'''Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}'''							)

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  config

             self.set_stage_and_offload()




       def    _UpperCamelCase					(						self							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  self.get_value('''zero_optimization.stage'''		,-1							)

             # offload
             __SCREAMING_SNAKE_CASE       :Any		    =  False
             if self.is_zeroa() or self.is_zeroa():
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  set(['''cpu''', '''nvme''']							)
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  set(
                       [
                           self.get_value('''zero_optimization.offload_optimizer.device'''							),
                           self.get_value('''zero_optimization.offload_param.device'''							),
                       ]							)
                   if len(offload_devices & offload_devices_valid							) > 0:
                         __SCREAMING_SNAKE_CASE       :int		    =  True




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  self.config

             # find the config node of interest if it exists
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  ds_key_long.split('''.'''							)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  nodes.pop()
             for node in nodes:
                   __SCREAMING_SNAKE_CASE       :Dict		    =  config.get(SCREAMING_SNAKE_CASE__							)
                   if config is None:
                         return None, ds_key

             return config, ds_key




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Optional[Any]		    =  self.find_config_node(SCREAMING_SNAKE_CASE__							)
             if config is None:
                   return default
             return config.get(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=False							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  self.config

             # find the config node of interest if it exists
             __SCREAMING_SNAKE_CASE       :str		    =  ds_key_long.split('''.'''							)
             for node in nodes:
                   __SCREAMING_SNAKE_CASE       :Any		    =  config
                   __SCREAMING_SNAKE_CASE       :int		    =  config.get(SCREAMING_SNAKE_CASE__							)
                   if config is None:
                         if must_exist:
                               raise ValueError(f'''Can\'t find {ds_key_long} entry in the config: {self.config}'''							)
                         else:
                               return

        # if found remove it
             if parent_config is not None:
                   parent_config.pop(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  self.get_value(SCREAMING_SNAKE_CASE__							)
             return False if value is None else bool(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :str		    =  self.get_value(SCREAMING_SNAKE_CASE__							)
             return False if value is None else not bool(SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self							)      ->				List[str]:





             """simple docstring"""






             return self._stage == 2




       def    _UpperCamelCase					(						self							)      ->				List[Any]:





             """simple docstring"""






             return self._stage == 3




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





             """simple docstring"""






             return self._offload






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				Optional[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  engine




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)      ->				List[Any]:





             """simple docstring"""






             self.engine.backward(SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)

             # Deepspeed's `engine.step` performs the following operations:
             # - gradient accumulation check
             # - gradient clipping
             # - optimizer step
             # - zero grad
             # - checking overflow
             # - lr_scheduler step (only if engine.lr_scheduler is not None)
             self.engine.step()
             # and this plugin overrides the above calls with no-ops when Accelerate runs under
             # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
             # training loop that works transparently under many training regimes.






class  _SCREAMING_SNAKE_CASE(       A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__							)      ->				str:





             """simple docstring"""






             super().__init__(SCREAMING_SNAKE_CASE__		,device_placement=SCREAMING_SNAKE_CASE__		,scaler=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :int		    =  hasattr(self.optimizer		,'''overflow'''							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__=None							)      ->				Union[str, Any]:





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed




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





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed




       @property
       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             if self.__has_overflow__:
                   return self.optimizer.overflow
             return False






class  _SCREAMING_SNAKE_CASE(       A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Optional[int]:





             """simple docstring"""






             super().__init__(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0.0_0_1		,SCREAMING_SNAKE_CASE__=0		,**SCREAMING_SNAKE_CASE__							)      ->				List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  params
             __SCREAMING_SNAKE_CASE       :str		    =  lr
             __SCREAMING_SNAKE_CASE       :str		    =  weight_decay
             __SCREAMING_SNAKE_CASE       :int		    =  kwargs






class  _SCREAMING_SNAKE_CASE:




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__=0		,**SCREAMING_SNAKE_CASE__							)      ->				str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  optimizer
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  total_num_steps
             __SCREAMING_SNAKE_CASE       :Any		    =  warmup_num_steps
             __SCREAMING_SNAKE_CASE       :int		    =  kwargs