






import math
import os
import unittest

from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    MODEL_FOR_PRETRAINING_MAPPING,
		    MegatronBertForCausalLM,
		    MegatronBertForMaskedLM,
		    MegatronBertForMultipleChoice,
		    MegatronBertForNextSentencePrediction,
		    MegatronBertForPreTraining,
		    MegatronBertForQuestionAnswering,
		    MegatronBertForSequenceClassification,
		    MegatronBertForTokenClassification,
		    MegatronBertModel,
		)





class 	snake_case__ :
	def __init__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=13      ,       lowerCAmelCase__=7      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=99      ,       lowerCAmelCase__=64      ,       lowerCAmelCase__=32      ,       lowerCAmelCase__=5      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=37      ,       lowerCAmelCase__="gelu"      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=5_12      ,       lowerCAmelCase__=16      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=0.0_2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=None      ,       )							->				List[Any]:
							__magic_name__      :       List[str]       						= parent
							__magic_name__      :       List[str]       						= batch_size
							__magic_name__      :       List[Any]       						= seq_length
							__magic_name__      :       Tuple       						= is_training
							__magic_name__      :       Optional[Any]       						= use_input_mask
							__magic_name__      :       List[str]       						= use_token_type_ids
							__magic_name__      :       Tuple       						= use_labels
							__magic_name__      :       int       						= vocab_size
							__magic_name__      :       int       						= hidden_size
							__magic_name__      :       str       						= embedding_size
							__magic_name__      :       Union[str, Any]       						= num_hidden_layers
							__magic_name__      :       Tuple       						= num_attention_heads
							__magic_name__      :       int       						= intermediate_size
							__magic_name__      :       Optional[Any]       						= hidden_act
							__magic_name__      :       int       						= hidden_dropout_prob
							__magic_name__      :       Union[str, Any]       						= attention_probs_dropout_prob
							__magic_name__      :       Any       						= max_position_embeddings
							__magic_name__      :       Optional[int]       						= type_vocab_size
							__magic_name__      :       List[str]       						= type_sequence_label_size
							__magic_name__      :       List[Any]       						= initializer_range
							__magic_name__      :       int       						= num_labels
							__magic_name__      :       Tuple       						= num_choices
							__magic_name__      :       Any       						= scope
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       Tuple       						= ids_tensor([self.batch_size, self.seq_length]      ,       self.vocab_size			)

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

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

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

							__magic_name__      :       Union[str, Any]       						= self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
	def       __magic_name__    (    self			)							->				Optional[int]:
							return MegatronBertConfig(
							    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      ,       embedding_size=self.embedding_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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Union[str, Any]:
							__magic_name__      :       List[str]       						= MegatronBertModel(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       List[Any]       						= model(lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       Optional[int]       						= model(lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       List[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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Optional[int]:
							__magic_name__      :       Optional[int]       						= MegatronBertForMaskedLM(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       List[Any]       						= 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       Tuple       						= MegatronBertForCausalLM(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       List[Any]       						= 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       Dict       						= MegatronBertForNextSentencePrediction(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       Optional[int]       						= model(
							    lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       labels=lowerCAmelCase__      ,       )
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, 2)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Union[str, Any]:
							__magic_name__      :       Any       						= MegatronBertForPreTraining(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       List[str]       						= 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       List[str]       						= MegatronBertForQuestionAnswering(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       Union[str, Any]       						= 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Any:
							__magic_name__      :       Union[str, Any]       						= self.num_labels
							__magic_name__      :       Dict       						= MegatronBertForSequenceClassification(lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       str       						= model(lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       labels=lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.num_labels)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[str]:
							__magic_name__      :       str       						= self.num_labels
							__magic_name__      :       Any       						= MegatronBertForTokenClassification(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       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.num_labels)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Dict:
							__magic_name__      :       Optional[Any]       						= self.num_choices
							__magic_name__      :       Optional[int]       						= MegatronBertForMultipleChoice(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       Optional[int]       						= input_ids.unsqueeze(1			).expand(-1      ,       self.num_choices      ,       -1			).contiguous()
							__magic_name__      :       int       						= token_type_ids.unsqueeze(1			).expand(-1      ,       self.num_choices      ,       -1			).contiguous()
							__magic_name__      :       List[Any]       						= input_mask.unsqueeze(1			).expand(-1      ,       self.num_choices      ,       -1			).contiguous()
							__magic_name__      :       List[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       __magic_name__    (    self			)							->				Any:
							__magic_name__      :       Optional[Any]       						= self.prepare_config_and_inputs()
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       List[str]       						= config_and_inputs
							__magic_name__      :       Union[str, Any]       						= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
							return config, inputs_dict





@require_torch
class 	snake_case__ (							_lowerCAmelCase						,  _lowerCAmelCase						,  unittest.TestCase				):
	lowercase__						:					str											=   (
	    (
	        MegatronBertModel,
	        MegatronBertForMaskedLM,
	        MegatronBertForCausalLM,
	        MegatronBertForMultipleChoice,
	        MegatronBertForNextSentencePrediction,
	        MegatronBertForPreTraining,
	        MegatronBertForQuestionAnswering,
	        MegatronBertForSequenceClassification,
	        MegatronBertForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__						:					str											=   (
	    {
	        '''feature-extraction''': MegatronBertModel,
	        '''fill-mask''': MegatronBertForMaskedLM,
	        '''question-answering''': MegatronBertForQuestionAnswering,
	        '''text-classification''': MegatronBertForSequenceClassification,
	        '''text-generation''': MegatronBertForCausalLM,
	        '''token-classification''': MegatronBertForTokenClassification,
	        '''zero-shot''': MegatronBertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	lowercase__						:					Optional[Any]											=   True
	# test_resize_embeddings = False
	lowercase__						:					List[Any]											=   False
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__=False			)							->				List[str]:
							__magic_name__      :       List[str]       						= super()._prepare_for_class(lowerCAmelCase__      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)

							if return_labels:
													if model_class in get_values(lowerCAmelCase__			):
																			__magic_name__      :       List[str]       						= torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.seq_length)      ,       dtype=torch.long      ,       device=lowerCAmelCase__			)
																			__magic_name__      :       Tuple       						= torch.zeros(
																			    self.model_tester.batch_size      ,       dtype=torch.long      ,       device=lowerCAmelCase__			)
							return inputs_dict
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__      :       Tuple       						= MegatronBertModelTester(self			)
							__magic_name__      :       Optional[Any]       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       hidden_size=37			)
	def       __magic_name__    (    self			)							->				Tuple:
							self.config_tester.run_common_tests()
	def       __magic_name__    (    self			)							->				int:
							__magic_name__      :       List[Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_model(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				List[str]:
							__magic_name__      :       Union[str, Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_masked_lm(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				int:
							__magic_name__      :       str       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				List[str]:
							__magic_name__      :       List[str]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_pretraining(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Any:
							__magic_name__      :       Optional[Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_question_answering(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Dict:
							__magic_name__      :       int       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*lowerCAmelCase__			)







	def       __magic_name__    (    self			)							->				Any:
							__magic_name__      :       Any       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_token_classification(*lowerCAmelCase__			)



def    UpperCamelCase						(	_A			):






						"""simple docstring"""







						return torch.tensor(
						    _A,   dtype=torch.long,   device=_A,   )


__magic_name__:					List[str]							=     1E-4





@require_torch
@require_sentencepiece
@require_tokenizers
class 	snake_case__ (							unittest.TestCase				):
	@slow
	@unittest.skip("""Model is not available."""			)
	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__      :       List[str]       						= """nvidia/megatron-bert-uncased-345m"""
							if "MYDIR" in os.environ:
													__magic_name__      :       Optional[Any]       						= os.path.join(os.environ["""MYDIR"""]      ,       lowerCAmelCase__			)
							__magic_name__      :       str       						= MegatronBertModel.from_pretrained(lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.half()
							__magic_name__      :       str       						= _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]]			)
							with torch.no_grad():
													__magic_name__      :       Union[str, Any]       						= model(lowerCAmelCase__			)[0]
							__magic_name__      :       str       						= torch.Size((1, 9, 10_24)			)
							self.assertEqual(output.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       str       						= [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8]
							for ii in range(3			):
													for jj in range(3			):
																			__magic_name__      :       str       						= output[0, ii, jj]
																			__magic_name__      :       Union[str, Any]       						= expected[3 * ii + jj]
																			__magic_name__      :       Dict       						= """ii={} jj={} a={} b={}""".format(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
																			self.assertTrue(math.isclose(lowerCAmelCase__      ,       lowerCAmelCase__      ,       rel_tol=lowerCAmelCase__      ,       abs_tol=lowerCAmelCase__			)      ,       msg=lowerCAmelCase__			)








__magic_name__:					List[Any]							=     "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"

__magic_name__:					Dict							=     [{"type": "code", "content": INSTALL_CONTENT}]
__magic_name__:					Optional[Any]							=     {
    "{processor_class}": "FakeProcessorClass",
    "{model_class}": "FakeModelClass",
    "{object_class}": "FakeObjectClass",
}
