


import unittest

from transformers import MPNetConfig, is_torch_available
from transformers.testing_utils import 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 (
           MPNetForMaskedLM,
           MPNetForMultipleChoice,
           MPNetForQuestionAnswering,
           MPNetForSequenceClassification,
           MPNetForTokenClassification,
           MPNetModel,
       )

class       __magic_name__	:


       def __init__(      self							:     Union[str, Any]							,	lowerCamelCase__							:     List[Any]							,	lowerCamelCase__							:     Tuple=13							,	lowerCamelCase__							:     List[Any]=7							,	lowerCamelCase__							:     Dict=True							,	lowerCamelCase__							:     int=True							,	lowerCamelCase__							:     Optional[Any]=False							,	lowerCamelCase__							:     Union[str, Any]=True							,	lowerCamelCase__							:     Optional[int]=99							,	lowerCamelCase__							:     Union[str, Any]=64							,	lowerCamelCase__							:     Optional[int]=5							,	lowerCamelCase__							:     Dict=4							,	lowerCamelCase__							:     Dict=64							,	lowerCamelCase__							:     str="gelu"							,	lowerCamelCase__							:     int=0.1							,	lowerCamelCase__							:     List[str]=0.1							,	lowerCamelCase__							:     Tuple=512							,	lowerCamelCase__							:     Optional[Any]=16							,	lowerCamelCase__							:     Tuple=2							,	lowerCamelCase__							:     List[Any]=0.02							,	lowerCamelCase__							:     List[Any]=3							,	lowerCamelCase__							:     List[Any]=4							,	lowerCamelCase__							:     Any=None							,	)  ->      List[str]:





        '''simple docstring'''






        UpperCamelCase__					:    Optional[Any]          =   parent
        UpperCamelCase__					:    List[Any]          =   batch_size
        UpperCamelCase__					:    Optional[int]          =   seq_length
        UpperCamelCase__					:    Optional[int]          =   is_training
        UpperCamelCase__					:    str          =   use_input_mask
        UpperCamelCase__					:    List[Any]          =   use_token_type_ids
        UpperCamelCase__					:    Any          =   use_labels
        UpperCamelCase__					:    Optional[Any]          =   vocab_size
        UpperCamelCase__					:    str          =   hidden_size
        UpperCamelCase__					:    Dict          =   num_hidden_layers
        UpperCamelCase__					:    Optional[Any]          =   num_attention_heads
        UpperCamelCase__					:    Union[str, Any]          =   intermediate_size
        UpperCamelCase__					:    Dict          =   hidden_act
        UpperCamelCase__					:    Union[str, Any]          =   hidden_dropout_prob
        UpperCamelCase__					:    List[str]          =   attention_probs_dropout_prob
        UpperCamelCase__					:    List[str]          =   max_position_embeddings
        UpperCamelCase__					:    List[str]          =   type_vocab_size
        UpperCamelCase__					:    Any          =   type_sequence_label_size
        UpperCamelCase__					:    List[str]          =   initializer_range
        UpperCamelCase__					:    str          =   num_labels
        UpperCamelCase__					:    Union[str, Any]          =   num_choices
        UpperCamelCase__					:    Optional[Any]          =   scope


       def      UpperCAmelCase__	(      self							:     Tuple			)  ->      List[str]:





        '''simple docstring'''






        return MPNetConfig.from_pretrained('''microsoft/mpnet-base'''			)


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





        '''simple docstring'''






        UpperCamelCase__					:    Dict          =   ids_tensor([self.batch_size, self.seq_length]							,	self.vocab_size			)

        UpperCamelCase__					:    Union[str, Any]          =   None
        if self.use_input_mask:
         UpperCamelCase__					:    Union[str, Any]          =   random_attention_mask([self.batch_size, self.seq_length]			)

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

        UpperCamelCase__					:    Any          =   self.get_config()
        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


       def      UpperCAmelCase__	(      self							:     List[str]			)  ->      List[Any]:





        '''simple docstring'''






        return MPNetConfig(
            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							,	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							,	initializer_range=self.initializer_range							,	)


       def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     int							,	lowerCamelCase__							:     Tuple							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Optional[Any]			)  ->      List[Any]:





        '''simple docstring'''






        UpperCamelCase__					:    Tuple          =   MPNetModel(config=lowerCamelCase__			)
        model.to(lowerCamelCase__			)
        model.eval()
        UpperCamelCase__					:    int          =   model(lowerCamelCase__							,	lowerCamelCase__			)
        UpperCamelCase__					:    List[str]          =   model(lowerCamelCase__			)
        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      UpperCAmelCase__	(      self							:     Any							,	lowerCamelCase__							:     Optional[int]							,	lowerCamelCase__							:     Dict							,	lowerCamelCase__							:     int							,	lowerCamelCase__							:     Dict							,	lowerCamelCase__							:     Optional[Any]							,	lowerCamelCase__							:     List[str]			)  ->      List[str]:





        '''simple docstring'''






        UpperCamelCase__					:    Optional[Any]          =   MPNetForQuestionAnswering(config=lowerCamelCase__			)
        model.to(lowerCamelCase__			)
        model.eval()
        UpperCamelCase__					:    int          =   model(
            lowerCamelCase__							,	attention_mask=lowerCamelCase__							,	start_positions=lowerCamelCase__							,	end_positions=lowerCamelCase__							,	)
        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      UpperCAmelCase__	(      self							:     Any							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     List[str]							,	lowerCamelCase__							:     List[str]							,	lowerCamelCase__							:     Tuple							,	lowerCamelCase__							:     Optional[int]			)  ->      Optional[Any]:





        '''simple docstring'''






        UpperCamelCase__					:    int          =   self.num_labels
        UpperCamelCase__					:    Union[str, Any]          =   MPNetForSequenceClassification(lowerCamelCase__			)
        model.to(lowerCamelCase__			)
        model.eval()
        UpperCamelCase__					:    str          =   model(lowerCamelCase__							,	attention_mask=lowerCamelCase__							,	labels=lowerCamelCase__			)
        self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_labels)			)


       def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     Tuple							,	lowerCamelCase__							:     int							,	lowerCamelCase__							:     List[Any]							,	lowerCamelCase__							:     Dict							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     Optional[Any]			)  ->      Union[str, Any]:





        '''simple docstring'''






        UpperCamelCase__					:    Optional[Any]          =   self.num_choices
        UpperCamelCase__					:    Dict          =   MPNetForMultipleChoice(config=lowerCamelCase__			)
        model.to(lowerCamelCase__			)
        model.eval()
        UpperCamelCase__					:    int          =   input_ids.unsqueeze(1			).expand(-1							,	self.num_choices							,	-1			).contiguous()
        UpperCamelCase__					:    List[Any]          =   input_mask.unsqueeze(1			).expand(-1							,	self.num_choices							,	-1			).contiguous()
        UpperCamelCase__					:    Dict          =   model(
            lowerCamelCase__							,	attention_mask=lowerCamelCase__							,	labels=lowerCamelCase__							,	)
        self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_choices)			)


       def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     Optional[int]							,	lowerCamelCase__							:     Optional[int]							,	lowerCamelCase__							:     Optional[int]							,	lowerCamelCase__							:     Any							,	lowerCamelCase__							:     int							,	lowerCamelCase__							:     List[Any]			)  ->      List[Any]:





        '''simple docstring'''






        UpperCamelCase__					:    Tuple          =   self.num_labels
        UpperCamelCase__					:    Optional[int]          =   MPNetForTokenClassification(config=lowerCamelCase__			)
        model.to(lowerCamelCase__			)
        model.eval()
        UpperCamelCase__					:    Any          =   model(lowerCamelCase__							,	attention_mask=lowerCamelCase__							,	labels=lowerCamelCase__			)
        self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.seq_length, self.num_labels)			)


       def      UpperCAmelCase__	(      self							:     List[Any]			)  ->      int:





        '''simple docstring'''






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



@require_torch
class       __magic_name__	(     __lowerCAmelCase					,				__lowerCAmelCase					,				unittest.TestCase):
       A:		Dict			=      (
           (
               MPNetForMaskedLM,
               MPNetForMultipleChoice,
               MPNetForQuestionAnswering,
               MPNetForSequenceClassification,
               MPNetForTokenClassification,
               MPNetModel,
           )
           if is_torch_available()
           else ()
       )
       A:		List[str]			=      (
           {
               "feature-extraction": MPNetModel,
               "fill-mask": MPNetForMaskedLM,
               "question-answering": MPNetForQuestionAnswering,
               "text-classification": MPNetForSequenceClassification,
               "token-classification": MPNetForTokenClassification,
               "zero-shot": MPNetForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       A:		str			=      False
       A:		Any			=      True


       def      UpperCAmelCase__	(      self							:     int			)  ->      Any:





        '''simple docstring'''






        UpperCamelCase__					:    Union[str, Any]          =   MPNetModelTester(self			)
        UpperCamelCase__					:    Any          =   ConfigTester(self							,	config_class=lowerCamelCase__							,	hidden_size=37			)


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





        '''simple docstring'''






        self.config_tester.run_common_tests()


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





        '''simple docstring'''






        UpperCamelCase__					:    Optional[int]          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_model(*lowerCamelCase__			)


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





        '''simple docstring'''






        UpperCamelCase__					:    str          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowerCamelCase__			)


       def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      List[str]:





        '''simple docstring'''






        UpperCamelCase__					:    int          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowerCamelCase__			)


       def      UpperCAmelCase__	(      self							:     int			)  ->      Dict:





        '''simple docstring'''






        UpperCamelCase__					:    Optional[int]          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_token_classification(*lowerCamelCase__			)


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





        '''simple docstring'''






        UpperCamelCase__					:    int          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_question_answering(*lowerCamelCase__			)



@require_torch
class       __magic_name__	(     unittest.TestCase):


       @slow
       def      UpperCAmelCase__	(      self							:     Tuple			)  ->      Dict:





        '''simple docstring'''






        UpperCamelCase__					:    str          =   MPNetModel.from_pretrained('''microsoft/mpnet-base'''			)
        UpperCamelCase__					:    Union[str, Any]          =   torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]			)
        UpperCamelCase__					:    Union[str, Any]          =   model(lowerCamelCase__			)[0]
        UpperCamelCase__					:    Tuple          =   torch.Size((1, 11, 768)			)
        self.assertEqual(output.shape							,	lowerCamelCase__			)
        UpperCamelCase__					:    str          =   torch.tensor(
            [[[-0.0550, 0.1943, -0.0740], [-0.0562, 0.2211, -0.0579], [-0.0437, 0.3337, -0.0641]]]			)
        # compare the actual values for a slice.
        self.assertTrue(torch.allclose(output[:, :3, :3]							,	lowerCamelCase__							,	atol=1E-4			)			)






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       :       List[str]						       =				logging.get_logger(__name__)

__UpperCamelCase       :       Union[str, Any]						       =				list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__UpperCamelCase       :       Dict						       =				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class       __magic_name__	:
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "Model type selected in the list: " + ", ".join(__lowerCAmelCase)})
     A:		str			=      field(
         default=__lowerCAmelCase					,				metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
     A:		int			=      field(
         default=1_2_8					,				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=1_2_8					,				metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}					,				)
     A:		int			=      field(
         default=6_4					,				metadata={
             "help": (
                 "The maximum number of tokens for the question. Questions longer than this will "
                 "be truncated to this length."
             )
         }					,				)
     A:		int			=      field(
         default=3_0					,				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=__lowerCAmelCase					,				metadata={"help": "Overwrite the cached training and evaluation sets"})
     A:		bool			=      field(
         default=__lowerCAmelCase					,				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=2_0					,				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       __magic_name__	(     __lowerCAmelCase):
     A:		Union[str, Any]			=      "train"
     A:		List[str]			=      "dev"



class       __magic_name__	(     __lowerCAmelCase):
     A:		SquadDataTrainingArguments
     A:		List[SquadFeatures]
     A:		Split
     A:		bool


     def __init__(      self							:     Tuple							,	lowerCamelCase__							:     SquadDataTrainingArguments							,	lowerCamelCase__							:     PreTrainedTokenizer							,	lowerCamelCase__							:     Optional[int] = None							,	lowerCamelCase__							:     Union[str, Split] = Split.train							,	lowerCamelCase__							:     Optional[bool] = False							,	lowerCamelCase__							:     Optional[str] = None							,	lowerCamelCase__							:     Optional[str] = "pt"							,	)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    Dict          =   args
      UpperCamelCase__					:    Union[str, Any]          =   is_language_sensitive
      UpperCamelCase__					:    List[Any]          =   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
      if isinstance(lowerCamelCase__							,	lowerCamelCase__			):
       try:
        UpperCamelCase__					:    Union[str, Any]          =   Split[mode]
       except KeyError:
        raise KeyError('''mode is not a valid split name'''			)
      UpperCamelCase__					:    List[str]          =   mode
      # Load data features from cache or dataset file
      UpperCamelCase__					:    List[str]          =   '''v2''' if args.version_2_with_negative else '''v1'''
      UpperCamelCase__					:    str          =   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.
      UpperCamelCase__					:    Tuple          =   cached_features_file + '''.lock'''
      with FileLock(lowerCamelCase__			):
       if os.path.exists(lowerCamelCase__			) and not args.overwrite_cache:
        UpperCamelCase__					:    int          =   time.time()
        UpperCamelCase__					:    List[str]          =   torch.load(lowerCamelCase__			)

        # Legacy cache files have only features, while new cache files
        # will have dataset and examples also.
        UpperCamelCase__					:    Any          =   self.old_features['''features''']
        UpperCamelCase__					:    Union[str, Any]          =   self.old_features.get('''dataset'''							,	lowerCamelCase__			)
        UpperCamelCase__					:    List[str]          =   self.old_features.get('''examples'''							,	lowerCamelCase__			)
        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:
         UpperCamelCase__					:    List[str]          =   self.processor.get_dev_examples(args.data_dir			)
        else:
         UpperCamelCase__					:    Any          =   self.processor.get_train_examples(args.data_dir			)

        UpperCamelCase__       ,				UpperCamelCase__					:    Union[str, Any]          =   squad_convert_examples_to_features(
            examples=self.examples							,	tokenizer=lowerCamelCase__							,	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=lowerCamelCase__							,	)

        UpperCamelCase__					:    Tuple          =   time.time()
        torch.save(
            {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}							,	lowerCamelCase__							,	)
        # ^ 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							:     Any			)  ->      List[str]:





      '''simple docstring'''






      return len(self.features			)


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





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   self.features[i]

      UpperCamelCase__					:    Optional[Any]          =   torch.tensor(feature.input_ids							,	dtype=torch.long			)
      UpperCamelCase__					:    Tuple          =   torch.tensor(feature.attention_mask							,	dtype=torch.long			)
      UpperCamelCase__					:    Optional[int]          =   torch.tensor(feature.token_type_ids							,	dtype=torch.long			)
      UpperCamelCase__					:    int          =   torch.tensor(feature.cls_index							,	dtype=torch.long			)
      UpperCamelCase__					:    List[Any]          =   torch.tensor(feature.p_mask							,	dtype=torch.float			)
      UpperCamelCase__					:    Any          =   torch.tensor(feature.is_impossible							,	dtype=torch.float			)

      UpperCamelCase__					:    Dict          =   {
          '''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:
       UpperCamelCase__					:    Optional[Any]          =   torch.tensor(feature.start_position							,	dtype=torch.long			)
       UpperCamelCase__					:    Optional[int]          =   torch.tensor(feature.end_position							,	dtype=torch.long			)
       inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}			)

      return inputs


