






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







	"""simple docstring"""



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

							lowercase_      :   Optional[int]        =			None
							if self.use_input_mask:
													lowercase_      :   int        =			random_attention_mask([self.batch_size, self.seq_length]       )

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

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

							lowercase_      :   Dict        =			self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
	def        lowerCamelCase__		(							self       )						->  str:
							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=A__  ,      initializer_range=self.initializer_range  ,      )
	def        lowerCamelCase__		(							self       )						->  Dict:
							(
							    lowercase_     
							)      :   List[Any]        =			self.prepare_config_and_inputs()

							lowercase_      :   Union[str, Any]        =			True
							lowercase_      :   Tuple        =			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
							lowercase_      :   str        =			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  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Dict:
							lowercase_      :   List[Any]        =			NezhaModel(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			model(A__  ,      attention_mask=A__  ,      token_type_ids=A__       )
							lowercase_      :   str        =			model(A__  ,      token_type_ids=A__       )
							lowercase_      :   Optional[int]        =			model(A__       )
							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  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      )						->  List[str]:
							lowercase_      :   List[str]        =			True
							lowercase_      :   List[Any]        =			NezhaModel(A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   Tuple        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      encoder_hidden_states=A__  ,      encoder_attention_mask=A__  ,      )
							lowercase_      :   Optional[Any]        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      encoder_hidden_states=A__  ,      )
							lowercase_      :   Dict        =			model(A__  ,      attention_mask=A__  ,      token_type_ids=A__       )
							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  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  int:
							lowercase_      :   Any        =			NezhaForMaskedLM(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   int        =			model(A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.vocab_size)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Dict:
							lowercase_      :   Optional[Any]        =			NezhaForNextSentencePrediction(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   int        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__  ,      )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, 2)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Dict:
							lowercase_      :   str        =			NezhaForPreTraining(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__  ,      next_sentence_label=A__  ,      )
							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  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Dict:
							lowercase_      :   str        =			NezhaForQuestionAnswering(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   str        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Union[str, Any]:
							lowercase_      :   Optional[int]        =			self.num_labels
							lowercase_      :   Optional[int]        =			NezhaForSequenceClassification(A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   List[Any]        =			model(A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[Any]:
							lowercase_      :   Union[str, Any]        =			self.num_labels
							lowercase_      :   List[Any]        =			NezhaForTokenClassification(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   List[str]        =			model(A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  List[Any]:
							lowercase_      :   int        =			self.num_choices
							lowercase_      :   Optional[int]        =			NezhaForMultipleChoice(config=A__       )
							model.to(A__       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			input_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   int        =			token_type_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   Tuple        =			input_mask.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   int        =			model(
							    A__  ,      attention_mask=A__  ,      token_type_ids=A__  ,      labels=A__  ,      )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_choices)       )







	def        lowerCamelCase__		(							self       )						->  int:
							lowercase_      :   Any        =			self.prepare_config_and_inputs()
							(
							    lowercase_     
							)      :   List[str]        =			config_and_inputs
							lowercase_      :   Optional[Any]        =			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
							return config, inputs_dict






@require_torch
class 							__magic_name__     (	UpperCAmelCase_,						UpperCAmelCase_,						UpperCAmelCase_,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Any        =  (
	    (
	        NezhaModel,
	        NezhaForMaskedLM,
	        NezhaForMultipleChoice,
	        NezhaForNextSentencePrediction,
	        NezhaForPreTraining,
	        NezhaForQuestionAnswering,
	        NezhaForSequenceClassification,
	        NezhaForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE_					:      List[Any]        =  (
	    {
	        '''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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase=False       )						->  int:
							lowercase_      :   Tuple        =			super()._prepare_for_class(A__  ,      A__  ,      return_labels=A__       )

							if return_labels:
													if model_class in get_values(A__       ):
																			lowercase_      :   List[Any]        =			torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.seq_length)  ,      dtype=torch.long  ,      device=A__       )
																			lowercase_      :   Tuple        =			torch.zeros(
																			    self.model_tester.batch_size  ,      dtype=torch.long  ,      device=A__       )
							return inputs_dict
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							lowercase_      :   Optional[int]        =			NezhaModelTester(self       )
							lowercase_      :   List[Any]        =			ConfigTester(self  ,      config_class=A__  ,      hidden_size=37       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							self.config_tester.run_common_tests()
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   Union[str, Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*A__       )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   Dict        =			self.model_tester.prepare_config_and_inputs_for_decoder()
							self.model_tester.create_and_check_model_as_decoder(*A__       )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							# This regression test was failing with PyTorch < 1.3
							(
							    lowercase_     
							)      :   Tuple        =			self.model_tester.prepare_config_and_inputs_for_decoder()

							lowercase_      :   Optional[Any]        =			None

							self.model_tester.create_and_check_model_as_decoder(
							    A__  ,      A__  ,      A__  ,      A__  ,      A__  ,      A__  ,      A__  ,      A__  ,      A__  ,      )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*A__       )
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*A__       )
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   List[Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_next_sequence_prediction(*A__       )
	def        lowerCamelCase__		(							self       )						->  List[str]:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*A__       )
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							lowercase_      :   Optional[int]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*A__       )
	def        lowerCamelCase__		(							self       )						->  Optional[int]:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*A__       )
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*A__       )
	@slow
	def        lowerCamelCase__		(							self       )						->  Tuple:
							for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_      :   Union[str, Any]        =			NezhaModel.from_pretrained(A__       )
													self.assertIsNotNone(A__       )







	@slow
	@require_torch_gpu
	def        lowerCamelCase__		(							self       )						->  int:
							lowercase_      :   Optional[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

													lowercase_      :   Optional[Any]        =			True
													lowercase_      :   Dict        =			model_class(config=A__       )

													lowercase_      :   Optional[Any]        =			self._prepare_for_class(A__  ,      A__       )
													lowercase_      :   List[Any]        =			torch.jit.trace(
													    A__  ,      (inputs_dict['input_ids'].to('cpu'       ), inputs_dict['attention_mask'].to('cpu'       ))       )

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






@require_torch
class 							__magic_name__     (	unittest.TestCase				):







	"""simple docstring"""



	@slow
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_      :   Optional[int]        =			NezhaModel.from_pretrained('sijunhe/nezha-cn-base'       )
							lowercase_      :   List[str]        =			torch.tensor([[0, 1, 2, 3, 4, 5]]       )
							lowercase_      :   Tuple        =			torch.tensor([[0, 1, 1, 1, 1, 1]]       )
							with torch.no_grad():
													lowercase_      :   Any        =			model(A__  ,      attention_mask=A__       )[0]
							lowercase_      :   str        =			torch.Size((1, 6, 768)       )
							self.assertEqual(output.shape  ,      A__       )
							lowercase_      :   Optional[Any]        =			torch.tensor([[[0.06_85, 0.24_41, 0.11_02], [0.06_00, 0.19_06, 0.13_49], [0.02_21, 0.08_19, 0.05_86]]]       )

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







	@slow
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[Any]        =			NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base'       )
							lowercase_      :   Union[str, Any]        =			torch.tensor([[0, 1, 2, 3, 4, 5]]       )
							lowercase_      :   Tuple        =			torch.tensor([[1, 1, 1, 1, 1, 1]]       )
							with torch.no_grad():
													lowercase_      :   List[Any]        =			model(A__  ,      attention_mask=A__       )[0]
							lowercase_      :   Union[str, Any]        =			torch.Size((1, 6, 2_1128)       )
							self.assertEqual(output.shape  ,      A__       )
							lowercase_      :   Optional[int]        =			torch.tensor(
							    [[-2.79_39, -1.79_02, -2.21_89], [-2.85_85, -1.89_08, -2.37_23], [-2.64_99, -1.77_50, -2.25_58]]       )

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








'''simple docstring'''

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A:      int  				=				logging.get_logger(__name__)

A:      int  				=				{
    "bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json",
}






class 							__magic_name__     (	UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      List[str]        =  'gpt_bigcode'
	SCREAMING_SNAKE_CASE_					:      int        =  ['past_key_values']
	SCREAMING_SNAKE_CASE_					:      Any        =  {
	    'hidden_size': 'n_embd',
	    'max_position_embeddings': 'n_positions',
	    'num_attention_heads': 'n_head',
	    'num_hidden_layers': 'n_layer',
	}
	def __init__(							self  ,      _lowercase=5_0257  ,      _lowercase=1024  ,      _lowercase=768  ,      _lowercase=12  ,      _lowercase=12  ,      _lowercase=None  ,      _lowercase="gelu_pytorch_tanh"  ,      _lowercase=0.1  ,      _lowercase=0.1  ,      _lowercase=0.1  ,      _lowercase=1E-5  ,      _lowercase=0.02  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=5_0256  ,      _lowercase=5_0256  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=True  ,      **_lowercase  ,      )						->  Any:
							lowercase_      :   Tuple        =			vocab_size
							lowercase_      :   str        =			n_positions
							lowercase_      :   List[str]        =			n_embd
							lowercase_      :   str        =			n_layer
							lowercase_      :   Optional[Any]        =			n_head
							lowercase_      :   Optional[int]        =			n_inner
							lowercase_      :   Union[str, Any]        =			activation_function
							lowercase_      :   Dict        =			resid_pdrop
							lowercase_      :   str        =			embd_pdrop
							lowercase_      :   Optional[Any]        =			attn_pdrop
							lowercase_      :   List[Any]        =			layer_norm_epsilon
							lowercase_      :   Optional[int]        =			initializer_range
							lowercase_      :   List[Any]        =			scale_attn_weights
							lowercase_      :   Any        =			use_cache
							lowercase_      :   List[str]        =			attention_softmax_in_fpaa
							lowercase_      :   Any        =			scale_attention_softmax_in_fpaa
							lowercase_      :   Optional[Any]        =			multi_query

							lowercase_      :   Optional[Any]        =			bos_token_id
							lowercase_      :   Optional[Any]        =			eos_token_id

							super().__init__(bos_token_id=_lowercase  ,      eos_token_id=_lowercase  ,      **_lowercase       )
