






"""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    lowercase_    :






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







        '''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 			lowerCamelCase__    (    self	)	->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 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''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=a_     ,     initializer_range=self.initializer_range     ,     )






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Dict:







        '''simple docstring'''


        _a							=	MegatronBertModel(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	model(a_     ,     attention_mask=a_     ,     token_type_ids=a_	)
        _a							=	model(a_     ,     token_type_ids=a_	)
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Any:







        '''simple docstring'''


        _a							=	MegatronBertForMaskedLM(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Dict:







        '''simple docstring'''


        _a							=	MegatronBertForCausalLM(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Optional[int]:







        '''simple docstring'''


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






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Tuple:







        '''simple docstring'''


        _a							=	MegatronBertForPreTraining(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->List[str]:







        '''simple docstring'''


        _a							=	MegatronBertForQuestionAnswering(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Optional[Any]:







        '''simple docstring'''


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






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->int:







        '''simple docstring'''


        _a							=	self.num_labels
        _a							=	MegatronBertForTokenClassification(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_     ,     a_	)	->Union[str, Any]:







        '''simple docstring'''


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






      def 			lowerCamelCase__    (    self	)	->List[str]:







        '''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    lowercase_    (_UpperCAmelCase,    _UpperCAmelCase,    unittest.TestCase     ):
      A__	:		Union[str, Any]       			=				(
          (
              MegatronBertModel,
              MegatronBertForMaskedLM,
              MegatronBertForCausalLM,
              MegatronBertForMultipleChoice,
              MegatronBertForNextSentencePrediction,
              MegatronBertForPreTraining,
              MegatronBertForQuestionAnswering,
              MegatronBertForSequenceClassification,
              MegatronBertForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      A__	:		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 {}
      )
      A__	:		Tuple       			=				True
      # test_resize_embeddings = False
      A__	:		str       			=				False






      def 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_=False	)	->Tuple:







        '''simple docstring'''


        _a							=	super()._prepare_for_class(a_     ,     a_     ,     return_labels=a_	)

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






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	MegatronBertModelTester(self	)
        _a							=	ConfigTester(self     ,     config_class=a_     ,     hidden_size=3_7	)






      def 			lowerCamelCase__    (    self	)	->Union[str, Any]:







        '''simple docstring'''


        self.config_tester.run_common_tests()






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_model(*a_	)






      def 			lowerCamelCase__    (    self	)	->List[str]:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_masked_lm(*a_	)






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







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*a_	)






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*a_	)






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_pretraining(*a_	)






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_question_answering(*a_	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*a_	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_megatron_bert_for_token_classification(*a_	)







def        lowerCAmelCase (      UpperCamelCase_:							List[str]					)       ->							List[Any]:







  '''simple docstring'''







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


UpperCamelCase							       =		1e-4




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






      @slow
      @unittest.skip("Model is not available."	)
      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        _a							=	"nvidia/megatron-bert-uncased-345m"
        if "MYDIR" in os.environ:
          _a							=	os.path.join(os.environ["MYDIR"]     ,     a_	)
        _a							=	MegatronBertModel.from_pretrained(a_	)
        model.to(a_	)
        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(a_	)[0]
        _a							=	torch.Size((1, 9, 1_0_2_4)	)
        self.assertEqual(output.shape     ,     a_	)

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










"""simple docstring"""




import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCamelCase							       =    logging.get_logger(__name__)

UpperCamelCase							       =    list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase							       =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class    lowercase_    :
      A__	:		str       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_UpperCAmelCase     )}     )
      A__	:		str       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}     )
      A__	:		int       			=				field(
          default=128,    metadata={
              '''help''': (
                  '''The maximum total input sequence length after tokenization. Sequences longer '''
                  '''than this will be truncated, sequences shorter will be padded.'''
              )
          },    )
      A__	:		int       			=				field(
          default=128,    metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''},    )
      A__	:		int       			=				field(
          default=64,    metadata={
              '''help''': (
                  '''The maximum number of tokens for the question. Questions longer than this will '''
                  '''be truncated to this length.'''
              )
          },    )
      A__	:		int       			=				field(
          default=30,    metadata={
              '''help''': (
                  '''The maximum length of an answer that can be generated. This is needed because the start '''
                  '''and end predictions are not conditioned on one another.'''
              )
          },    )
      A__	:		bool       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}     )
      A__	:		bool       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}     )
      A__	:		float       			=				field(
          default=0.0,    metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
      A__	:		int       			=				field(
          default=20,    metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
      A__	:		int       			=				field(
          default=0,    metadata={
              '''help''': (
                  '''language id of input for language-specific xlm models (see'''
                  ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
              )
          },    )
      A__	:		int       			=				field(default=1,    metadata={'''help''': '''multiple threads for converting example to features'''}     )







class    lowercase_    (_UpperCAmelCase     ):
      A__	:		Tuple       			=				'''train'''
      A__	:		List[Any]       			=				'''dev'''







class    lowercase_    (_UpperCAmelCase     ):
      A__	:		SquadDataTrainingArguments
      A__	:		List[SquadFeatures]
      A__	:		Split
      A__	:		bool






      def __init__(    self     ,     a_     ,     a_     ,     a_ = None     ,     a_ = Split.train     ,     a_ = False     ,     a_ = None     ,     a_ = "pt"     ,     )	->List[str]:







        '''simple docstring'''


        _a							=	args
        _a							=	is_language_sensitive
        _a							=	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
        if isinstance(a_     ,     a_	):
          try:
            _a							=	Split[mode]
          except KeyError:
            raise KeyError("mode is not a valid split name"	)
        _a							=	mode
        # Load data features from cache or dataset file
        _a							=	"v2" if args.version_2_with_negative else "v1"
        _a							=	os.path.join(
            cache_dir if cache_dir is not None else args.data_dir     ,     f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''     ,     )

        # Make sure only the first process in distributed training processes the dataset,
        # and the others will use the cache.
        _a							=	cached_features_file + ".lock"
        with FileLock(a_	):
          if os.path.exists(a_	) and not args.overwrite_cache:
            _a							=	time.time()
            _a							=	torch.load(a_	)

            # Legacy cache files have only features, while new cache files
            # will have dataset and examples also.
            _a							=	self.old_features["features"]
            _a							=	self.old_features.get("dataset"     ,     a_	)
            _a							=	self.old_features.get("examples"     ,     a_	)
            logger.info(
                f'''Loading features from cached file {cached_features_file} [took %.3f s]'''     ,     time.time() - start	)

            if self.dataset is None or self.examples is None:
              logger.warning(
                  f'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
                  " future run"	)
          else:
            if mode == Split.dev:
              _a							=	self.processor.get_dev_examples(args.data_dir	)
            else:
              _a							=	self.processor.get_train_examples(args.data_dir	)

            _a			,	_a							=	squad_convert_examples_to_features(
                examples=self.examples     ,     tokenizer=a_     ,     max_seq_length=args.max_seq_length     ,     doc_stride=args.doc_stride     ,     max_query_length=args.max_query_length     ,     is_training=mode == Split.train     ,     threads=args.threads     ,     return_dataset=a_     ,     )

            _a							=	time.time()
            torch.save(
                {"features": self.features, "dataset": self.dataset, "examples": self.examples}     ,     a_     ,     )
            # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
            logger.info(
                f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''	)






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







        '''simple docstring'''


        return len(self.features	)






      def __getitem__(    self     ,     a_	)	->Dict[str, torch.Tensor]:







        '''simple docstring'''


        _a							=	self.features[i]

        _a							=	torch.tensor(feature.input_ids     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.attention_mask     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.token_type_ids     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.cls_index     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.p_mask     ,     dtype=torch.float	)
        _a							=	torch.tensor(feature.is_impossible     ,     dtype=torch.float	)

        _a							=	{
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "token_type_ids": token_type_ids,
        }

        if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
          del inputs["token_type_ids"]

        if self.args.model_type in ["xlnet", "xlm"]:
          inputs.update({"cls_index": cls_index, "p_mask": p_mask}	)
          if self.args.version_2_with_negative:
            inputs.update({"is_impossible": is_impossible}	)
          if self.is_language_sensitive:
            inputs.update({"langs": (torch.ones(input_ids.shape     ,     dtype=torch.intaa	) * self.args.lang_id)}	)

        if self.mode == Split.train:
          _a							=	torch.tensor(feature.start_position     ,     dtype=torch.long	)
          _a							=	torch.tensor(feature.end_position     ,     dtype=torch.long	)
          inputs.update({"start_positions": start_positions, "end_positions": end_positions}	)

        return inputs


