




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

     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		,     )						->							Optional[int]:
           _A							:     Optional[int]			=						parent
           _A							:     Optional[Any]			=						batch_size
           _A							:     Tuple			=						seq_length
           _A							:     Optional[Any]			=						is_training
           _A							:     List[Any]			=						use_input_mask
           _A							:     Any			=						use_token_type_ids
           _A							:     List[Any]			=						use_labels
           _A							:     Optional[int]			=						vocab_size
           _A							:     str			=						hidden_size
           _A							:     List[str]			=						embedding_size
           _A							:     List[str]			=						num_hidden_layers
           _A							:     List[str]			=						num_attention_heads
           _A							:     Dict			=						intermediate_size
           _A							:     Dict			=						hidden_act
           _A							:     Any			=						hidden_dropout_prob
           _A							:     List[Any]			=						attention_probs_dropout_prob
           _A							:     str			=						max_position_embeddings
           _A							:     List[str]			=						type_vocab_size
           _A							:     int			=						type_sequence_label_size
           _A							:     Optional[Any]			=						initializer_range
           _A							:     Union[str, Any]			=						num_labels
           _A							:     Any			=						num_choices
           _A							:     List[str]			=						scope

     def 					a__	(  self				)						->							Union[str, Any]:
           _A							:     str			=						ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size				)

           _A							:     List[str]			=						None
           if self.use_input_mask:
                 _A							:     Tuple			=						random_attention_mask([self.batch_size, self.seq_length]				)

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

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

           _A							:     List[Any]			=						self.get_config()

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

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

     def 					a__	(  self		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a				)						->							Any:
           _A							:     Tuple			=						MegatronBertModel(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     str			=						model(_a		,     attention_mask=_a		,     token_type_ids=_a				)
           _A							:     Any			=						model(_a		,     token_type_ids=_a				)
           _A							:     int			=						model(_a				)

           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				)						->							List[str]:
           _A							:     List[Any]			=						MegatronBertForMaskedLM(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     List[Any]			=						model(_a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a				)
           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				)						->							Union[str, Any]:
           _A							:     Optional[int]			=						MegatronBertForCausalLM(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     List[Any]			=						model(_a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a				)
           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				)						->							Union[str, Any]:
           _A							:     List[str]			=						MegatronBertForNextSentencePrediction(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     List[str]			=						model(
               _a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a		,     )
           self.parent.assertEqual(result.logits.shape		,     (self.batch_size, 2)				)

     def 					a__	(  self		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a				)						->							List[str]:
           _A							:     Dict			=						MegatronBertForPreTraining(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     str			=						model(
               _a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a		,     next_sentence_label=_a		,     )
           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				)						->							List[str]:
           _A							:     Dict			=						MegatronBertForQuestionAnswering(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     Dict			=						model(
               _a		,     attention_mask=_a		,     token_type_ids=_a		,     start_positions=_a		,     end_positions=_a		,     )
           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				)						->							Tuple:
           _A							:     Tuple			=						self.num_labels
           _A							:     Any			=						MegatronBertForSequenceClassification(_a				)
           model.to(_a				)
           model.eval()
           _A							:     str			=						model(_a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a				)
           self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)				)

     def 					a__	(  self		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a		,     _a				)						->							int:
           _A							:     Union[str, Any]			=						self.num_labels
           _A							:     Optional[int]			=						MegatronBertForTokenClassification(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     Dict			=						model(_a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a				)
           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				)						->							Union[str, Any]:
           _A							:     str			=						self.num_choices
           _A							:     Optional[Any]			=						MegatronBertForMultipleChoice(config=_a				)
           model.to(_a				)
           model.eval()
           _A							:     List[str]			=						input_ids.unsqueeze(1				).expand(-1		,     self.num_choices		,     -1				).contiguous()
           _A							:     int			=						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							:     Optional[int]			=						model(
               _a		,     attention_mask=_a		,     token_type_ids=_a		,     labels=_a		,     )
           self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_choices)				)



     def 					a__	(  self				)						->							int:
           _A							:     Optional[int]			=						self.prepare_config_and_inputs()
           (
               (
               _A
           )			,   (
               _A
           )			,   (
               _A
           )			,   (
               _A
           )			,   (
               _A
           )			,   (
               _A
           )			,   (
               _A
           )			,   
           )							:     int			=						config_and_inputs
           _A							:     Optional[int]			=						{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
           return config, inputs_dict







@require_torch
class 						lowercase							(   UpperCamelCase__,UpperCamelCase__,unittest.TestCase		):
     _a							 =						(
         (
             MegatronBertModel,
             MegatronBertForMaskedLM,
             MegatronBertForCausalLM,
             MegatronBertForMultipleChoice,
             MegatronBertForNextSentencePrediction,
             MegatronBertForPreTraining,
             MegatronBertForQuestionAnswering,
             MegatronBertForSequenceClassification,
             MegatronBertForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     _a							 =						(
         {
             "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 {}
     )
     _a							 =						True
     # test_resize_embeddings = False
     _a							 =						False

     def 					a__	(  self		,     _a		,     _a		,     _a=False				)						->							Optional[int]:
           _A							:     List[str]			=						super()._prepare_for_class(_a		,     _a		,     return_labels=_a				)

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

     def 					a__	(  self				)						->							Dict:
           _A							:     Dict			=						MegatronBertModelTester(self				)
           _A							:     str			=						ConfigTester(self		,     config_class=_a		,     hidden_size=37				)

     def 					a__	(  self				)						->							str:
           self.config_tester.run_common_tests()

     def 					a__	(  self				)						->							Optional[int]:
           _A							:     List[str]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_model(*_a				)

     def 					a__	(  self				)						->							List[Any]:
           _A							:     Optional[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_masked_lm(*_a				)

     def 					a__	(  self				)						->							Dict:
           _A							:     List[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*_a				)

     def 					a__	(  self				)						->							int:
           _A							:     Optional[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*_a				)

     def 					a__	(  self				)						->							List[str]:
           _A							:     int			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_pretraining(*_a				)

     def 					a__	(  self				)						->							int:
           _A							:     Tuple			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_question_answering(*_a				)

     def 					a__	(  self				)						->							Dict:
           _A							:     List[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*_a				)



     def 					a__	(  self				)						->							int:
           _A							:     List[Any]			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_megatron_bert_for_token_classification(*_a				)







def 				lowerCAmelCase_	(     snake_case_     ):
      return torch.tensor(
          snake_case_,dtype=torch.long,device=snake_case_,)


_snake_case										=       1e-4







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

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

           _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							:     Any			=						output[0, ii, jj]
                       _A							:     Optional[int]			=						expected[3 * ii + jj]
                       _A							:     Tuple			=						"""ii={} jj={} a={} b={}""".format(_a		,     _a		,     _a		,     _a				)
                       self.assertTrue(math.isclose(_a		,     _a		,     rel_tol=_a		,     abs_tol=_a				)		,     msg=_a				)








import argparse
from collections import defaultdict

import yaml


lowercase      :       int									=  """docs/source/en/_toctree.yml"""



def A_	(		A__				)  ->		Tuple:
       a__						:	int =				defaultdict(A__				)
       a__						:	List[str] =				[]
       a__						:	Any =				[]
       for doc in doc_list:
              if "local" in doc:
                     counts[doc["local"]] += 1

              if doc["title"].lower() == "overview":
                     overview_doc.append({'local': doc['local'], 'title': doc['title']}				)
              else:
                     new_doc_list.append(A__				)

       a__						:	int =				new_doc_list
       a__						:	List[str] =				[key for key, value in counts.items() if value > 1]

       a__						:	Tuple =				[]
       for duplicate_key in duplicates:
              a__						:	int =				list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key}				)
              if len(A__				) > 1:
                     raise ValueError(
                         F'{duplicate_key} is present several times in the documentation table of content at '
                         '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
                         'others.'				)
              # Only add this once
              new_doc.append({'local': duplicate_key, 'title': titles[0]}				)

       # Add none duplicate-keys
       new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1]				)
       a__						:	Any =				sorted(A__		,      key=lambda A__				: s["title"].lower()				)

       # "overview" gets special treatment and is always first
       if len(A__				) > 1:
              raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.'				)

       overview_doc.extend(A__				)

       # Sort
       return overview_doc



def A_	(		A__=False				)  ->		str:
       with open(A__		,      encoding='utf-8'				) as f:
              a__						:	int =				yaml.safe_load(f.read()				)

       # Get to the API doc
       a__						:	Tuple =				0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       a__						:	Any =				content[api_idx]['sections']

       # Then to the model doc
       a__						:	List[str] =				0
       while api_doc[scheduler_idx]["title"] != "Schedulers":
              scheduler_idx += 1

       a__						:	Tuple =				api_doc[scheduler_idx]['sections']
       a__						:	Optional[int] =				clean_doc_toc(A__				)

       a__						:	int =				False
       if new_scheduler_doc != scheduler_doc:
              a__						:	int =				True
              if overwrite:
                     a__						:	int =				new_scheduler_doc

       if diff:
              if overwrite:
                     a__						:	Optional[Any] =				api_doc
                     with open(A__		,      'w'		,      encoding='utf-8'				) as f:
                            f.write(yaml.dump(A__		,      allow_unicode=A__				)				)
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'				)



def A_	(		A__=False				)  ->		Tuple:
       with open(A__		,      encoding='utf-8'				) as f:
              a__						:	Optional[Any] =				yaml.safe_load(f.read()				)

       # Get to the API doc
       a__						:	Optional[int] =				0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       a__						:	int =				content[api_idx]['sections']

       # Then to the model doc
       a__						:	List[Any] =				0
       while api_doc[pipeline_idx]["title"] != "Pipelines":
              pipeline_idx += 1

       a__						:	Optional[int] =				False
       a__						:	Union[str, Any] =				api_doc[pipeline_idx]['sections']
       a__						:	List[str] =				[]

       # sort sub pipeline docs
       for pipeline_doc in pipeline_docs:
              if "section" in pipeline_doc:
                     a__						:	Any =				pipeline_doc['section']
                     a__						:	Dict =				clean_doc_toc(A__				)
                     if overwrite:
                            a__						:	Optional[Any] =				new_sub_pipeline_doc
              new_pipeline_docs.append(A__				)

       # sort overall pipeline doc
       a__						:	Optional[Any] =				clean_doc_toc(A__				)

       if new_pipeline_docs != pipeline_docs:
              a__						:	List[Any] =				True
              if overwrite:
                     a__						:	Union[str, Any] =				new_pipeline_docs

       if diff:
              if overwrite:
                     a__						:	Dict =				api_doc
                     with open(A__		,      'w'		,      encoding='utf-8'				) as f:
                            f.write(yaml.dump(A__		,      allow_unicode=A__				)				)
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'				)


if __name__ == "__main__":
    lowercase      :       List[Any]									=  argparse.ArgumentParser()
    parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
    lowercase      :       str									=  parser.parse_args()

    check_scheduler_doc(args.fix_and_overwrite)
    check_pipeline_doc(args.fix_and_overwrite)


