






'''simple docstring'''

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







	"""simple docstring"""



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

							lowercase_      :   Union[str, Any]        =			None
							if self.use_input_mask:
													lowercase_      :   Tuple        =			random_attention_mask([self.batch_size, self.seq_length]       )

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

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

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

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
	def        lowerCamelCase__		(							self       )						->  List[str]:
							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=_lowercase  ,      initializer_range=self.initializer_range  ,      )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[Any]:
							lowercase_      :   Union[str, Any]        =			MegatronBertModel(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Tuple        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase       )
							lowercase_      :   List[str]        =			model(_lowercase  ,      token_type_ids=_lowercase       )
							lowercase_      :   List[Any]        =			model(_lowercase       )

							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       )						->  Optional[int]:
							lowercase_      :   Optional[Any]        =			MegatronBertForMaskedLM(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							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       )						->  int:
							lowercase_      :   Dict        =			MegatronBertForCausalLM(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							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       )						->  Union[str, Any]:
							lowercase_      :   Optional[Any]        =			MegatronBertForNextSentencePrediction(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Dict        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase  ,      )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, 2)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Any:
							lowercase_      :   Tuple        =			MegatronBertForPreTraining(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase  ,      next_sentence_label=_lowercase  ,      )
							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       )						->  Optional[int]:
							lowercase_      :   Optional[Any]        =			MegatronBertForQuestionAnswering(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   List[str]        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      start_positions=_lowercase  ,      end_positions=_lowercase  ,      )
							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       )						->  List[str]:
							lowercase_      :   Dict        =			self.num_labels
							lowercase_      :   Optional[int]        =			MegatronBertForSequenceClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Union[str, Any]:
							lowercase_      :   str        =			self.num_labels
							lowercase_      :   List[str]        =			MegatronBertForTokenClassification(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[int]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							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       )						->  Union[str, Any]:
							lowercase_      :   Dict        =			self.num_choices
							lowercase_      :   Tuple        =			MegatronBertForMultipleChoice(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			input_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   Optional[Any]        =			token_type_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   List[str]        =			input_mask.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   Tuple        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase  ,      )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_choices)       )







	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   Optional[int]        =			self.prepare_config_and_inputs()
							(
							    lowercase_      
							)      :   Tuple        =			config_and_inputs
							lowercase_      :   List[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_,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Dict        =  (
	    (
	        MegatronBertModel,
	        MegatronBertForMaskedLM,
	        MegatronBertForCausalLM,
	        MegatronBertForMultipleChoice,
	        MegatronBertForNextSentencePrediction,
	        MegatronBertForPreTraining,
	        MegatronBertForQuestionAnswering,
	        MegatronBertForSequenceClassification,
	        MegatronBertForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE_					:      List[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 {}
	)
	SCREAMING_SNAKE_CASE_					:      Any        =  True
	# test_resize_embeddings = False
	SCREAMING_SNAKE_CASE_					:      List[str]        =  False
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase=False       )						->  Dict:
							lowercase_      :   Any        =			super()._prepare_for_class(_lowercase  ,      _lowercase  ,      return_labels=_lowercase       )

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







	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   Tuple        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_megatron_bert_for_token_classification(*_lowercase       )






def 	_UpperCAmelCase    (  a		:	List[Any]							)			->			List[Any]:





						"""simple docstring"""
						return torch.tensor(
						    a						,			dtype=torch.long						,			device=a						,			)


A:      Any  				=				1E-4






@require_torch
@require_sentencepiece
@require_tokenizers
class 							__magic_name__     (	unittest.TestCase				):







	"""simple docstring"""



	@slow
	@unittest.skip('Model is not available.'       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							lowercase_      :   Optional[int]        =			'nvidia/megatron-bert-uncased-345m'
							if "MYDIR" in os.environ:
													lowercase_      :   Optional[Any]        =			os.path.join(os.environ['MYDIR']  ,      _lowercase       )
							lowercase_      :   List[str]        =			MegatronBertModel.from_pretrained(_lowercase       )
							model.to(_lowercase       )
							model.half()
							lowercase_      :   Tuple        =			_long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]       )
							with torch.no_grad():
													lowercase_      :   List[Any]        =			model(_lowercase       )[0]
							lowercase_      :   int        =			torch.Size((1, 9, 1024)       )
							self.assertEqual(output.shape  ,      _lowercase       )

							lowercase_      :   Union[str, Any]        =			[-0.60_40, -0.25_17, -0.10_25, 0.34_20, -0.67_58, -0.00_17, -0.10_89, -0.19_90, 0.57_28]
							for ii in range(3       ):
													for jj in range(3       ):
																			lowercase_      :   int        =			output[0, ii, jj]
																			lowercase_      :   Any        =			expected[3 * ii + jj]
																			lowercase_      :   int        =			'ii={} jj={} a={} b={}'.format(_lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )
																			self.assertTrue(math.isclose(_lowercase  ,      _lowercase  ,      rel_tol=_lowercase  ,      abs_tol=_lowercase       )  ,      msg=_lowercase       )








'''simple docstring'''

import argparse


A:      List[Any]  				=				"docs/source/_static/js/custom.js"






def 	_UpperCAmelCase    (  a		:	Optional[Any]							)			->			Optional[Any]:





						"""simple docstring"""
						with open(a						,			encoding='utf-8'						,			newline='\n'							) as f:
												lowercase_      :   List[Any]        =			f.readlines()
						lowercase_      :   Dict        =			0

						# First let's put the right version
						while not lines[index].startswith('const stableVersion ='							):
												index += 1
						lowercase_      :   Dict        =			f"const stableVersion = \"v{version}\"\n"

						# Then update the dictionary
						while not lines[index].startswith('const versionMapping = {'							):
												index += 1

						# We go until the end
						while not lines[index].startswith('}'							):
												index += 1
						# We add the new version at the end
						lines[index - 1] += f"    \"v{version}\": \"v{version}\",\n"

						with open(a						,			'w'						,			encoding='utf-8'						,			newline='\n'							) as f:
												f.writelines(a							)


if __name__ == "__main__":
						A:      str  				=				argparse.ArgumentParser()
						parser.add_argument("--version", help="Release version.")
						A:      List[str]  				=				parser.parse_args()
						update_custom_js(args.version)
