

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







    """simple docstring"""





    def __init__(      self :       str,lowercase_ :       List[str],lowercase_ :       Optional[int]=1_3,lowercase_ :       Union[str, Any]=7,lowercase_ :       str=True,lowercase_ :       Tuple=True,lowercase_ :       Any=True,lowercase_ :       Optional[Any]=True,lowercase_ :       Union[str, Any]=9_9,lowercase_ :       Any=6_4,lowercase_ :       Optional[int]=3_2,lowercase_ :       Union[str, Any]=5,lowercase_ :       str=4,lowercase_ :       str=3_7,lowercase_ :       Optional[Any]="gelu",lowercase_ :       str=0.1,lowercase_ :       Tuple=0.1,lowercase_ :       Optional[int]=5_1_2,lowercase_ :       int=1_6,lowercase_ :       Dict=2,lowercase_ :       Dict=0.02,lowercase_ :       List[str]=3,lowercase_ :       List[str]=4,lowercase_ :       List[str]=None,)->    Dict:





        '''simple docstring'''







        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 						snake_case__     (      self :       int		)->    Dict:





        '''simple docstring'''







        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 						snake_case__     (      self :       List[str]		)->    Dict:





        '''simple docstring'''







        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 						snake_case__     (      self :       Union[str, Any],lowercase_ :       int,lowercase_ :       List[str],lowercase_ :       Tuple,lowercase_ :       Any,lowercase_ :       Any,lowercase_ :       int,lowercase_ :       Dict		)->    Dict:





        '''simple docstring'''







        A__          =   MegatronBertModel(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   model(lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_		)
        A__          =   model(lowercase_,token_type_ids=lowercase_		)
        A__          =   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 						snake_case__     (      self :       List[Any],lowercase_ :       int,lowercase_ :       Tuple,lowercase_ :       Optional[Any],lowercase_ :       Union[str, Any],lowercase_ :       int,lowercase_ :       Tuple,lowercase_ :       Union[str, Any]		)->    Optional[int]:





        '''simple docstring'''







        A__          =   MegatronBertForMaskedLM(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   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 						snake_case__     (      self :       List[Any],lowercase_ :       Tuple,lowercase_ :       int,lowercase_ :       Union[str, Any],lowercase_ :       Tuple,lowercase_ :       Dict,lowercase_ :       List[str],lowercase_ :       Union[str, Any]		)->    Any:





        '''simple docstring'''







        A__          =   MegatronBertForCausalLM(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   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 						snake_case__     (      self :       Optional[Any],lowercase_ :       Optional[Any],lowercase_ :       Union[str, Any],lowercase_ :       Tuple,lowercase_ :       str,lowercase_ :       str,lowercase_ :       Union[str, Any],lowercase_ :       List[str]		)->    Any:





        '''simple docstring'''







        A__          =   MegatronBertForNextSentencePrediction(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   model(
            lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_,labels=lowercase_,)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, 2)		)


    def 						snake_case__     (      self :       Union[str, Any],lowercase_ :       Union[str, Any],lowercase_ :       List[str],lowercase_ :       Any,lowercase_ :       Any,lowercase_ :       Optional[Any],lowercase_ :       List[Any],lowercase_ :       Dict		)->    Union[str, Any]:





        '''simple docstring'''







        A__          =   MegatronBertForPreTraining(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   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 						snake_case__     (      self :       Tuple,lowercase_ :       str,lowercase_ :       Optional[int],lowercase_ :       List[Any],lowercase_ :       Optional[int],lowercase_ :       List[Any],lowercase_ :       str,lowercase_ :       Dict		)->    Dict:





        '''simple docstring'''







        A__          =   MegatronBertForQuestionAnswering(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   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 						snake_case__     (      self :       Union[str, Any],lowercase_ :       Union[str, Any],lowercase_ :       Dict,lowercase_ :       Optional[int],lowercase_ :       Any,lowercase_ :       Optional[int],lowercase_ :       Optional[Any],lowercase_ :       Any		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.num_labels
        A__          =   MegatronBertForSequenceClassification(lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   model(lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_,labels=lowercase_		)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)		)


    def 						snake_case__     (      self :       Any,lowercase_ :       Dict,lowercase_ :       Optional[int],lowercase_ :       Union[str, Any],lowercase_ :       Tuple,lowercase_ :       Optional[Any],lowercase_ :       str,lowercase_ :       Tuple		)->    int:





        '''simple docstring'''







        A__          =   self.num_labels
        A__          =   MegatronBertForTokenClassification(config=lowercase_		)
        model.to(lowercase_		)
        model.eval()
        A__          =   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 						snake_case__     (      self :       Any,lowercase_ :       Any,lowercase_ :       Union[str, Any],lowercase_ :       Tuple,lowercase_ :       int,lowercase_ :       Optional[Any],lowercase_ :       Dict,lowercase_ :       Any		)->    Any:





        '''simple docstring'''







        A__          =   self.num_choices
        A__          =   MegatronBertForMultipleChoice(config=lowercase_		)
        model.to(lowercase_		)
        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(
            lowercase_,attention_mask=lowercase_,token_type_ids=lowercase_,labels=lowercase_,)
        self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices)		)


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





        '''simple docstring'''







        A__          =   self.prepare_config_and_inputs()
        (
            (
            A__
        )      ,						(
            A__
        )      ,						(
            A__
        )      ,						(
            A__
        )      ,						(
            A__
        )      ,						(
            A__
        )      ,						(
            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  A						(							_UpperCAmelCase    ,							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							(
        (
            MegatronBertModel,
            MegatronBertForMaskedLM,
            MegatronBertForCausalLM,
            MegatronBertForMultipleChoice,
            MegatronBertForNextSentencePrediction,
            MegatronBertForPreTraining,
            MegatronBertForQuestionAnswering,
            MegatronBertForSequenceClassification,
            MegatronBertForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    lowerCamelCase			=							(
        {
            '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 {}
    )
    lowerCamelCase			=							True
    # test_resize_embeddings = False
    lowerCamelCase			=							False


    def 						snake_case__     (      self :       List[Any],lowercase_ :       Any,lowercase_ :       List[Any],lowercase_ :       List[str]=False		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   super()._prepare_for_class(lowercase_,lowercase_,return_labels=lowercase_		)

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


    def 						snake_case__     (      self :       Optional[Any]		)->    int:





        '''simple docstring'''







        A__          =   MegatronBertModelTester(self		)
        A__          =   ConfigTester(self,config_class=lowercase_,hidden_size=3_7		)


    def 						snake_case__     (      self :       int		)->    int:





        '''simple docstring'''







        self.config_tester.run_common_tests()


    def 						snake_case__     (      self :       Tuple		)->    Optional[int]:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_model(*lowercase_		)


    def 						snake_case__     (      self :       int		)->    str:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_masked_lm(*lowercase_		)


    def 						snake_case__     (      self :       List[Any]		)->    Tuple:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*lowercase_		)


    def 						snake_case__     (      self :       str		)->    Dict:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*lowercase_		)


    def 						snake_case__     (      self :       Dict		)->    Any:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_pretraining(*lowercase_		)


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





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_question_answering(*lowercase_		)


    def 						snake_case__     (      self :       Optional[Any]		)->    str:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*lowercase_		)


    def 						snake_case__     (      self :       List[Any]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_token_classification(*lowercase_		)




def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	int      )							->      Any:





    '''simple docstring'''






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


lowercase_       		=  1e-4


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







    """simple docstring"""





    @slow
    @unittest.skip('Model is not available.'		)
    def 						snake_case__     (      self :       Any		)->    Tuple:





        '''simple docstring'''







        A__          =   'nvidia/megatron-bert-uncased-345m'
        if "MYDIR" in os.environ:
            A__          =   os.path.join(os.environ['MYDIR'],lowercase_		)
        A__          =   MegatronBertModel.from_pretrained(lowercase_		)
        model.to(lowercase_		)
        model.half()
        A__          =   _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]]		)
        with torch.no_grad():
            A__          =   model(lowercase_		)[0]
        A__          =   torch.Size((1, 9, 1_0_2_4)		)
        self.assertEqual(output.shape,lowercase_		)

        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(lowercase_,lowercase_,lowercase_,lowercase_		)
                self.assertTrue(math.isclose(lowercase_,lowercase_,rel_tol=lowercase_,abs_tol=lowercase_		),msg=lowercase_		)








"""simple docstring"""




from transformers import BertTokenizerFast

from .custom_tokenization import CustomTokenizer

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : List[str]	    =   CustomTokenizer
      pass