
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 		UpperCamelCase__  :
   def __init__(self			: Optional[Any] ,    snake_case_			: str ,    snake_case_			: List[str]=1_3 ,    snake_case_			: Union[str, Any]=7 ,    snake_case_			: str=True ,    snake_case_			: Union[str, Any]=True ,    snake_case_			: Dict=True ,    snake_case_			: Dict=True ,    snake_case_			: Optional[Any]=9_9 ,    snake_case_			: Optional[Any]=6_4 ,    snake_case_			: Union[str, Any]=3_2 ,    snake_case_			: Any=5 ,    snake_case_			: Dict=4 ,    snake_case_			: List[str]=3_7 ,    snake_case_			: str="gelu" ,    snake_case_			: Dict=0.1 ,    snake_case_			: Union[str, Any]=0.1 ,    snake_case_			: List[str]=5_1_2 ,    snake_case_			: Tuple=1_6 ,    snake_case_			: Union[str, Any]=2 ,    snake_case_			: Dict=0.02 ,    snake_case_			: Any=3 ,    snake_case_			: Optional[int]=4 ,    snake_case_			: Optional[Any]=None ,    ):
    __a			:  Tuple		    =  parent
    __a			:  Dict		    =  batch_size
    __a			:  Union[str, Any]		    =  seq_length
    __a			:  str		    =  is_training
    __a			:  Dict		    =  use_input_mask
    __a			:  Tuple		    =  use_token_type_ids
    __a			:  str		    =  use_labels
    __a			:  int		    =  vocab_size
    __a			:  List[str]		    =  hidden_size
    __a			:  Dict		    =  embedding_size
    __a			:  Dict		    =  num_hidden_layers
    __a			:  Optional[int]		    =  num_attention_heads
    __a			:  int		    =  intermediate_size
    __a			:  Union[str, Any]		    =  hidden_act
    __a			:  Optional[Any]		    =  hidden_dropout_prob
    __a			:  str		    =  attention_probs_dropout_prob
    __a			:  str		    =  max_position_embeddings
    __a			:  List[str]		    =  type_vocab_size
    __a			:  Tuple		    =  type_sequence_label_size
    __a			:  Tuple		    =  initializer_range
    __a			:  List[str]		    =  num_labels
    __a			:  Dict		    =  num_choices
    __a			:  List[str]		    =  scope
   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  Union[str, Any]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.vocab_size       )

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

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

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

    __a			:  Optional[int]		    =  self.get_config()

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

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







   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  Tuple		    =  self.prepare_config_and_inputs()
    (
        (
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	(
        __a
    )    ,	
    )			:  str		    =  config_and_inputs
    __a			:  Dict		    =  {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Any     	=				(
       (
           MegatronBertModel,
           MegatronBertForMaskedLM,
           MegatronBertForCausalLM,
           MegatronBertForMultipleChoice,
           MegatronBertForNextSentencePrediction,
           MegatronBertForPreTraining,
           MegatronBertForQuestionAnswering,
           MegatronBertForSequenceClassification,
           MegatronBertForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE				:							Tuple     	=				(
       {
           "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				:							Optional[Any]     	=				True
   # test_resize_embeddings = False
   _SCREAMING_SNAKE_CASE				:							List[Any]     	=				False
   def 				lowerCAmelCase      (self			: Any ,    snake_case_			: Optional[Any] ,    snake_case_			: int ,    snake_case_			: Dict=False       ):
    __a			:  List[str]		    =  super()._prepare_for_class(snake_case_ ,    snake_case_ ,    return_labels=snake_case_       )

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







   def 				lowerCAmelCase      (self			: Dict       ):
    __a			:  int		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_megatron_bert_for_token_classification(*snake_case_       )





def        __UpperCamelCase					(    lowerCAmelCase__							:    str  ):
 return torch.tensor(
     lowerCAmelCase__  ,       dtype=torch.long  ,       device=lowerCAmelCase__  ,       )


lowercase__          =1e-4



@require_torch
@require_sentencepiece
@require_tokenizers
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @slow
   @unittest.skip('''Model is not available.'''       )
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  List[str]		    =  '''nvidia/megatron-bert-uncased-345m'''
    if "MYDIR" in os.environ:
     __a			:  Tuple		    =  os.path.join(os.environ['''MYDIR'''] ,    snake_case_       )
    __a			:  Any		    =  MegatronBertModel.from_pretrained(snake_case_       )
    model.to(snake_case_       )
    model.half()
    __a			:  Union[str, Any]		    =  _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			:  List[str]		    =  model(snake_case_       )[0]
    __a			:  Optional[int]		    =  torch.Size((1, 9, 1_0_2_4)       )
    self.assertEqual(output.shape ,    snake_case_       )

    __a			:  Tuple		    =  [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728]
    for ii in range(3       ):
     for jj in range(3       ):
      __a			:  Optional[int]		    =  output[0, ii, jj]
      __a			:  Any		    =  expected[3 * ii + jj]
      __a			:  Union[str, Any]		    =  '''ii={} jj={} a={} b={}'''.format(snake_case_ ,    snake_case_ ,    snake_case_ ,    snake_case_       )
      self.assertTrue(math.isclose(snake_case_ ,    snake_case_ ,    rel_tol=snake_case_ ,    abs_tol=snake_case_       ) ,    msg=snake_case_       )


import os
import sys
import unittest


lowercase__          =os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))

import get_test_info  # noqa: E402
from get_test_info import (  # noqa: E402
    get_model_to_test_mapping,
    get_model_to_tester_mapping,
    get_test_to_tester_mapping,
)


lowercase__          =os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py')
lowercase__          =os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py')



class 		UpperCamelCase__  (	unittest.TestCase   ):
   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a			:  str		    =  get_test_to_tester_mapping(snake_case_       )
    __a			:  Tuple		    =  get_test_to_tester_mapping(snake_case_       )

    __a			:  Union[str, Any]		    =  {'''BertModelTest''': '''BertModelTester'''}

    __a			:  Tuple		    =  {
        '''BlipModelTest''': '''BlipModelTester''',
        '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''',
        '''BlipTextModelTest''': '''BlipTextModelTester''',
        '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''',
        '''BlipVQAModelTest''': '''BlipVQAModelTester''',
        '''BlipVisionModelTest''': '''BlipVisionModelTester''',
    }

    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )
    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  Optional[int]		    =  get_model_to_test_mapping(snake_case_       )
    __a			:  Any		    =  get_model_to_test_mapping(snake_case_       )

    __a			:  List[Any]		    =  {
        '''BertForMaskedLM''': ['''BertModelTest'''],
        '''BertForMultipleChoice''': ['''BertModelTest'''],
        '''BertForNextSentencePrediction''': ['''BertModelTest'''],
        '''BertForPreTraining''': ['''BertModelTest'''],
        '''BertForQuestionAnswering''': ['''BertModelTest'''],
        '''BertForSequenceClassification''': ['''BertModelTest'''],
        '''BertForTokenClassification''': ['''BertModelTest'''],
        '''BertLMHeadModel''': ['''BertModelTest'''],
        '''BertModel''': ['''BertModelTest'''],
    }

    __a			:  Dict		    =  {
        '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''],
        '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''],
        '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''],
        '''BlipModel''': ['''BlipModelTest'''],
        '''BlipTextModel''': ['''BlipTextModelTest'''],
        '''BlipVisionModel''': ['''BlipVisionModelTest'''],
    }

    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )
    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )







   def 				lowerCAmelCase      (self			: int       ):
    __a			:  Any		    =  get_model_to_tester_mapping(snake_case_       )
    __a			:  List[str]		    =  get_model_to_tester_mapping(snake_case_       )

    __a			:  Any		    =  {
        '''BertForMaskedLM''': ['''BertModelTester'''],
        '''BertForMultipleChoice''': ['''BertModelTester'''],
        '''BertForNextSentencePrediction''': ['''BertModelTester'''],
        '''BertForPreTraining''': ['''BertModelTester'''],
        '''BertForQuestionAnswering''': ['''BertModelTester'''],
        '''BertForSequenceClassification''': ['''BertModelTester'''],
        '''BertForTokenClassification''': ['''BertModelTester'''],
        '''BertLMHeadModel''': ['''BertModelTester'''],
        '''BertModel''': ['''BertModelTester'''],
    }

    __a			:  int		    =  {
        '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''],
        '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''],
        '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''],
        '''BlipModel''': ['''BlipModelTester'''],
        '''BlipTextModel''': ['''BlipTextModelTester'''],
        '''BlipVisionModel''': ['''BlipVisionModelTester'''],
    }

    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )
    self.assertEqual(get_test_info.to_json(snake_case_       ) ,    snake_case_       )
