



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      :







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_=13  ,  a_=7  ,  a_=True  ,  a_=True  ,  a_=True  ,  a_=True  ,  a_=99  ,  a_=64  ,  a_=32  ,  a_=5  ,  a_=4  ,  a_=37  ,  a_="gelu"  ,  a_=0.1  ,  a_=0.1  ,  a_=512  ,  a_=16  ,  a_=2  ,  a_=0.02  ,  a_=3  ,  a_=4  ,  a_=None  ,  ):
											a__				      =		parent
											a__				      =		batch_size
											a__				      =		seq_length
											a__				      =		is_training
											a__				      =		use_input_mask
											a__				      =		use_token_type_ids
											a__				      =		use_labels
											a__				      =		vocab_size
											a__				      =		hidden_size
											a__				      =		embedding_size
											a__				      =		num_hidden_layers
											a__				      =		num_attention_heads
											a__				      =		intermediate_size
											a__				      =		hidden_act
											a__				      =		hidden_dropout_prob
											a__				      =		attention_probs_dropout_prob
											a__				      =		max_position_embeddings
											a__				      =		type_vocab_size
											a__				      =		type_sequence_label_size
											a__				      =		initializer_range
											a__				      =		num_labels
											a__				      =		num_choices
											a__				      =		scope


							def _a      (							self		):
											a__				      =		ids_tensor([self.batch_size, self.seq_length]  ,  self.vocab_size		)

											a__				      =		None
											if self.use_input_mask:
															a__				      =		random_attention_mask([self.batch_size, self.seq_length]		)

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

											a__				      =		None
											a__				      =		None
											a__				      =		None
											if self.use_labels:
															a__				      =		ids_tensor([self.batch_size]  ,  self.type_sequence_label_size		)
															a__				      =		ids_tensor([self.batch_size, self.seq_length]  ,  self.num_labels		)
															a__				      =		ids_tensor([self.batch_size]  ,  self.num_choices		)

											a__				      =		self.get_config()

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


							def _a      (							self		):
											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=UpperCAmelCase_  ,  initializer_range=self.initializer_range  ,  )


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertModel(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_		)
											a__				      =		model(UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_		)
											a__				      =		model(UpperCAmelCase_		)

											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 _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertForMaskedLM(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_		)
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.seq_length, self.vocab_size)		)


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertForCausalLM(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_		)
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.seq_length, self.vocab_size)		)


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertForNextSentencePrediction(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(
											    UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_  ,  )
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, 2)		)


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertForPreTraining(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(
											    UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_  ,  next_sentence_label=UpperCAmelCase_  ,  )
											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 _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		MegatronBertForQuestionAnswering(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(
											    UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  start_positions=UpperCAmelCase_  ,  end_positions=UpperCAmelCase_  ,  )
											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 _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		self.num_labels
											a__				      =		MegatronBertForSequenceClassification(UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_		)
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.num_labels)		)


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		self.num_labels
											a__				      =		MegatronBertForTokenClassification(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		model(UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_		)
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.seq_length, self.num_labels)		)


							def _a      (							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											a__				      =		self.num_choices
											a__				      =		MegatronBertForMultipleChoice(config=UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.eval()
											a__				      =		input_ids.unsqueeze(1		).expand(-1  ,  self.num_choices  ,  -1		).contiguous()
											a__				      =		token_type_ids.unsqueeze(1		).expand(-1  ,  self.num_choices  ,  -1		).contiguous()
											a__				      =		input_mask.unsqueeze(1		).expand(-1  ,  self.num_choices  ,  -1		).contiguous()
											a__				      =		model(
											    UpperCAmelCase_  ,  attention_mask=UpperCAmelCase_  ,  token_type_ids=UpperCAmelCase_  ,  labels=UpperCAmelCase_  ,  )
											self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.num_choices)		)







							def _a      (							self		):
											a__				      =		self.prepare_config_and_inputs()
											(
											    a__	
											)				      =		config_and_inputs
											a__				      =		{'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):







							'''simple docstring'''






							UpperCamelCase__				:      Optional[int]         =					(
							    (
							        MegatronBertModel,
							        MegatronBertForMaskedLM,
							        MegatronBertForCausalLM,
							        MegatronBertForMultipleChoice,
							        MegatronBertForNextSentencePrediction,
							        MegatronBertForPreTraining,
							        MegatronBertForQuestionAnswering,
							        MegatronBertForSequenceClassification,
							        MegatronBertForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							UpperCamelCase__				:      Any         =					(
							    {
							        """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 {}
							)
							UpperCamelCase__				:      Tuple         =					True
							# test_resize_embeddings = False
							UpperCamelCase__				:      List[str]         =					False


							def _a      (							self  ,  a_  ,  a_  ,  a_=False		):
											a__				      =		super()._prepare_for_class(UpperCAmelCase_  ,  UpperCAmelCase_  ,  return_labels=UpperCAmelCase_		)

											if return_labels:
															if model_class in get_values(UpperCAmelCase_		):
																			a__				      =		torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.seq_length)  ,  dtype=torch.long  ,  device=UpperCAmelCase_		)
																			a__				      =		torch.zeros(
																			    self.model_tester.batch_size  ,  dtype=torch.long  ,  device=UpperCAmelCase_		)
											return inputs_dict


							def _a      (							self		):
											a__				      =		MegatronBertModelTester(self		)
											a__				      =		ConfigTester(self  ,  config_class=UpperCAmelCase_  ,  hidden_size=37		)


							def _a      (							self		):
											self.config_tester.run_common_tests()


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_model(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_masked_lm(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_pretraining(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_question_answering(*UpperCAmelCase_		)


							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*UpperCAmelCase_		)







							def _a      (							self		):
											a__				      =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_megatron_bert_for_token_classification(*UpperCAmelCase_		)




def 			A_      (	__a     :				Dict		):

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


UpperCAmelCase														=					1E-4




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







							'''simple docstring'''






							@slow
							@unittest.skip("""Model is not available."""		)
							def _a      (							self		):
											a__				      =		'nvidia/megatron-bert-uncased-345m'
											if "MYDIR" in os.environ:
															a__				      =		os.path.join(os.environ["""MYDIR"""]  ,  UpperCAmelCase_		)
											a__				      =		MegatronBertModel.from_pretrained(UpperCAmelCase_		)
											model.to(UpperCAmelCase_		)
											model.half()
											a__				      =		_long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]		)
											with torch.no_grad():
															a__				      =		model(UpperCAmelCase_		)[0]
											a__				      =		torch.Size((1, 9, 1_024)		)
											self.assertEqual(output.shape  ,  UpperCAmelCase_		)

											a__				      =		[-0.6_040, -0.2_517, -0.1_025, 0.3_420, -0.6_758, -0.0_017, -0.1_089, -0.1_990, 0.5_728]
											for ii in range(3		):
															for jj in range(3		):
																			a__				      =		output[0, ii, jj]
																			a__				      =		expected[3 * ii + jj]
																			a__				      =		'ii={} jj={} a={} b={}'.format(UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_  ,  UpperCAmelCase_		)
																			self.assertTrue(math.isclose(UpperCAmelCase_  ,  UpperCAmelCase_  ,  rel_tol=UpperCAmelCase_  ,  abs_tol=UpperCAmelCase_		)  ,  msg=UpperCAmelCase_		)






import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase							 =					logging.get_logger(__name__)

UpperCAmelCase							 =					{"""vocab_file""": """spiece.model"""}

UpperCAmelCase							 =					{
    """vocab_file""": {
        """bert_for_seq_generation""": (
            """https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model"""
        ),
    }
}

UpperCAmelCase							 =					{"""bert_for_seq_generation""": 512}

class  __snake_case      (   SCREAMING_SNAKE_CASE):







							'''simple docstring'''






							UpperCamelCase__				:      Optional[Any]         =					VOCAB_FILES_NAMES
							UpperCamelCase__				:      Any         =					PRETRAINED_VOCAB_FILES_MAP
							UpperCamelCase__				:      List[str]         =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							UpperCamelCase__				:      List[int]         =					[]
							UpperCamelCase__				:      Optional[int]         =					["""input_ids""", """attention_mask"""]


							def __init__(							self  ,  a_  ,  a_="<s>"  ,  a_="</s>"  ,  a_="<unk>"  ,  a_="<pad>"  ,  a_="<::::>"  ,  a_ = None  ,  **a_  ,  ):
											a__				      =		{} if sp_model_kwargs is None else sp_model_kwargs

											# Add extra_ids to the special token list
											super().__init__(
											    bos_token=a_  ,  eos_token=a_  ,  unk_token=a_  ,  pad_token=a_  ,  sep_token=a_  ,  sp_model_kwargs=self.sp_model_kwargs  ,  **a_  ,  )

											a__				      =		vocab_file

											a__				      =		spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.Load(a_		)


							@property
							def _a      (							self		):
											return self.sp_model.get_piece_size()


							def _a      (							self		):
											a__				      =		{self.convert_ids_to_tokens(a_		): i for i in range(self.vocab_size		)}
											vocab.update(self.added_tokens_encoder		)
											return vocab


							def __getstate__(							self		):
											a__				      =		self.__dict__.copy()
											a__				      =		None
											return state


							def __setstate__(							self  ,  a_		):
											a__				      =		d

											# for backward compatibility
											if not hasattr(self  ,  """sp_model_kwargs"""		):
															a__				      =		{}

											a__				      =		spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.Load(self.vocab_file		)


							def _a      (							self  ,  a_		):
											return self.sp_model.encode(a_  ,  out_type=a_		)


							def _a      (							self  ,  a_		):
											return self.sp_model.piece_to_id(a_		)


							def _a      (							self  ,  a_		):
											a__				      =		self.sp_model.IdToPiece(a_		)
											return token


							def _a      (							self  ,  a_		):
											a__				      =		[]
											a__				      =		""""""
											for token in tokens:
															# make sure that special tokens are not decoded using sentencepiece model
															if token in self.all_special_tokens:
																			out_string += self.sp_model.decode(a_		) + token
																			a__				      =		[]
															else:
																			current_sub_tokens.append(a_		)
											out_string += self.sp_model.decode(a_		)
											return out_string.strip()







							def _a      (							self  ,  a_  ,  a_ = None		):
											if not os.path.isdir(a_		):
															logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''		)
															return
											a__				      =		os.path.join(
											    a_  ,  (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]		)

											if os.path.abspath(self.vocab_file		) != os.path.abspath(a_		) and os.path.isfile(self.vocab_file		):
															copyfile(self.vocab_file  ,  a_		)
											elif not os.path.isfile(self.vocab_file		):
															with open(a_  ,  """wb"""		) as fi:
																			a__				      =		self.sp_model.serialized_model_proto()
																			fi.write(a_		)

											return (out_vocab_file,)

