




'''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


a  :				List[str]									=  logging.get_logger(__name__)

a  :				Dict									=  list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
a  :				List[str]									=  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class 						a				:
				snake_case_      =		field(
				    default=_lowerCamelCase   ,     metadata={"help": "Model type selected in the list: " + ", ".join(_lowerCamelCase     )}     )
				snake_case_      =		field(
				    default=_lowerCamelCase   ,     metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}     )
				snake_case_      =		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."
				        )
				    }   ,     )
				snake_case_      =		field(
				    default=128   ,     metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}   ,     )
				snake_case_      =		field(
				    default=64   ,     metadata={
				        "help": (
				            "The maximum number of tokens for the question. Questions longer than this will "
				            "be truncated to this length."
				        )
				    }   ,     )
				snake_case_      =		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."
				        )
				    }   ,     )
				snake_case_      =		field(
				    default=_lowerCamelCase   ,     metadata={"help": "Overwrite the cached training and evaluation sets"}     )
				snake_case_      =		field(
				    default=_lowerCamelCase   ,     metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}     )
				snake_case_      =		field(
				    default=0.0   ,     metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
				snake_case_      =		field(
				    default=20   ,     metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
				snake_case_      =		field(
				    default=0   ,     metadata={
				        "help": (
				            "language id of input for language-specific xlm models (see"
				            " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
				        )
				    }   ,     )
				snake_case_      =		field(default=1   ,     metadata={"help": "multiple threads for converting example to features"}     )







class 						a				(   _lowerCamelCase     ):
				snake_case_      =		"train"
				snake_case_      =		"dev"







class 						a				(   _lowerCamelCase     ):
				snake_case_      =		42
				snake_case_      =		42
				snake_case_      =		42
				snake_case_      =		42


				def __init__(		self    :					Any       ,				lowercase_    :					SquadDataTrainingArguments       ,				lowercase_    :					PreTrainedTokenizer       ,				lowercase_    :					Optional[int] = None       ,				lowercase_    :					Union[str, Split] = Split.train       ,				lowercase_    :					Optional[bool] = False       ,				lowercase_    :					Optional[str] = None       ,				lowercase_    :					Optional[str] = "pt"       ,				):
									snake_case_									=				args
									snake_case_									=				is_language_sensitive
									snake_case_									=				SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
									if isinstance(lowercase_       ,				lowercase_					):
														try:
																			snake_case_									=				Split[mode]
														except KeyError:
																			raise KeyError('''mode is not a valid split name'''					)
									snake_case_									=				mode
									# Load data features from cache or dataset file
									snake_case_									=				'''v2''' if args.version_2_with_negative else '''v1'''
									snake_case_									=				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.
									snake_case_									=				cached_features_file + '''.lock'''
									with FileLock(lowercase_					):
														if os.path.exists(lowercase_					) and not args.overwrite_cache:
																			snake_case_									=				time.time()
																			snake_case_									=				torch.load(lowercase_					)

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

																			snake_case_			,snake_case_									=				squad_convert_examples_to_features(
																			    examples=self.examples       ,				tokenizer=lowercase_       ,				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=lowercase_       ,				)

																			snake_case_									=				time.time()
																			torch.save(
																			    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}       ,				lowercase_       ,				)
																			# ^ 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]					):
									return len(self.features					)


				def __getitem__(		self    :					Union[str, Any]       ,				lowercase_    :					Optional[int]					):
									# Convert to Tensors and build dataset
									snake_case_									=				self.features[i]

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

									snake_case_									=				{
									    '''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:
														snake_case_									=				torch.tensor(feature.start_position       ,				dtype=torch.long					)
														snake_case_									=				torch.tensor(feature.end_position       ,				dtype=torch.long					)
														inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}					)

									return inputs







'''simple docstring'''

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


				def __init__(		self    :					List[Any]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any=13       ,				lowercase_    :					Optional[Any]=7       ,				lowercase_    :					Optional[Any]=True       ,				lowercase_    :					Dict=True       ,				lowercase_    :					Tuple=False       ,				lowercase_    :					Optional[Any]=True       ,				lowercase_    :					Any=99       ,				lowercase_    :					Union[str, Any]=64       ,				lowercase_    :					str=5       ,				lowercase_    :					int=4       ,				lowercase_    :					List[Any]=64       ,				lowercase_    :					Dict="gelu"       ,				lowercase_    :					Optional[int]=0.1       ,				lowercase_    :					Optional[Any]=0.1       ,				lowercase_    :					Tuple=512       ,				lowercase_    :					List[Any]=16       ,				lowercase_    :					str=2       ,				lowercase_    :					List[str]=0.02       ,				lowercase_    :					Optional[Any]=3       ,				lowercase_    :					Optional[Any]=4       ,				lowercase_    :					List[Any]=None       ,				):
									snake_case_									=				parent
									snake_case_									=				batch_size
									snake_case_									=				seq_length
									snake_case_									=				is_training
									snake_case_									=				use_input_mask
									snake_case_									=				use_token_type_ids
									snake_case_									=				use_labels
									snake_case_									=				vocab_size
									snake_case_									=				hidden_size
									snake_case_									=				num_hidden_layers
									snake_case_									=				num_attention_heads
									snake_case_									=				intermediate_size
									snake_case_									=				hidden_act
									snake_case_									=				hidden_dropout_prob
									snake_case_									=				attention_probs_dropout_prob
									snake_case_									=				max_position_embeddings
									snake_case_									=				type_vocab_size
									snake_case_									=				type_sequence_label_size
									snake_case_									=				initializer_range
									snake_case_									=				num_labels
									snake_case_									=				num_choices
									snake_case_									=				scope


				def   A_ (		self    :					List[str]					):
									return MPNetConfig.from_pretrained('''microsoft/mpnet-base'''					)


				def   A_ (		self    :					str					):
									snake_case_									=				ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size					)

									snake_case_									=				None
									if self.use_input_mask:
														snake_case_									=				random_attention_mask([self.batch_size, self.seq_length]					)

									snake_case_									=				None
									snake_case_									=				None
									snake_case_									=				None
									if self.use_labels:
														snake_case_									=				ids_tensor([self.batch_size]       ,				self.type_sequence_label_size					)
														snake_case_									=				ids_tensor([self.batch_size, self.seq_length]       ,				self.num_labels					)
														snake_case_									=				ids_tensor([self.batch_size]       ,				self.num_choices					)

									snake_case_									=				self.get_config()
									return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels


				def   A_ (		self    :					Tuple					):
									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   A_ (		self    :					Any       ,				lowercase_    :					Dict       ,				lowercase_    :					str       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Union[str, Any]       ,				lowercase_    :					Dict       ,				lowercase_    :					Optional[int]					):
									snake_case_									=				MPNetModel(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				lowercase_					)
									snake_case_									=				model(lowercase_					)
									self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)					)
									self.parent.assertEqual(result.pooler_output.shape       ,				(self.batch_size, self.hidden_size)					)


				def   A_ (		self    :					str       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any       ,				lowercase_    :					str       ,				lowercase_    :					Tuple       ,				lowercase_    :					Tuple       ,				lowercase_    :					Optional[int]					):
									snake_case_									=				MPNetForQuestionAnswering(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(
									    lowercase_       ,				attention_mask=lowercase_       ,				start_positions=lowercase_       ,				end_positions=lowercase_       ,				)
									self.parent.assertEqual(result.start_logits.shape       ,				(self.batch_size, self.seq_length)					)
									self.parent.assertEqual(result.end_logits.shape       ,				(self.batch_size, self.seq_length)					)


				def   A_ (		self    :					Tuple       ,				lowercase_    :					Tuple       ,				lowercase_    :					List[str]       ,				lowercase_    :					str       ,				lowercase_    :					Optional[int]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Any					):
									snake_case_									=				self.num_labels
									snake_case_									=				MPNetForSequenceClassification(lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_					)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_labels)					)


				def   A_ (		self    :					Any       ,				lowercase_    :					Any       ,				lowercase_    :					str       ,				lowercase_    :					Tuple       ,				lowercase_    :					List[str]       ,				lowercase_    :					Union[str, Any]       ,				lowercase_    :					Dict					):
									snake_case_									=				self.num_choices
									snake_case_									=				MPNetForMultipleChoice(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				input_ids.unsqueeze(1					).expand(-1       ,				self.num_choices       ,				-1					).contiguous()
									snake_case_									=				input_mask.unsqueeze(1					).expand(-1       ,				self.num_choices       ,				-1					).contiguous()
									snake_case_									=				model(
									    lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_       ,				)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_choices)					)


				def   A_ (		self    :					Union[str, Any]       ,				lowercase_    :					List[Any]       ,				lowercase_    :					Optional[Any]       ,				lowercase_    :					Optional[int]       ,				lowercase_    :					str       ,				lowercase_    :					int       ,				lowercase_    :					List[str]					):
									snake_case_									=				self.num_labels
									snake_case_									=				MPNetForTokenClassification(config=lowercase_					)
									model.to(lowercase_					)
									model.eval()
									snake_case_									=				model(lowercase_       ,				attention_mask=lowercase_       ,				labels=lowercase_					)
									self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.seq_length, self.num_labels)					)


				def   A_ (		self    :					Union[str, Any]					):
									snake_case_									=				self.prepare_config_and_inputs()
									((snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_)			,(snake_case_))									=				config_and_inputs
									snake_case_									=				{'''input_ids''': input_ids, '''attention_mask''': input_mask}
									return config, inputs_dict







@require_torch
class 						a				(   _lowerCamelCase   ,     _lowerCamelCase   ,     unittest.TestCase     ):
				snake_case_      =		(
				    (
				        MPNetForMaskedLM,
				        MPNetForMultipleChoice,
				        MPNetForQuestionAnswering,
				        MPNetForSequenceClassification,
				        MPNetForTokenClassification,
				        MPNetModel,
				    )
				    if is_torch_available()
				    else ()
				)
				snake_case_      =		(
				    {
				        "feature-extraction": MPNetModel,
				        "fill-mask": MPNetForMaskedLM,
				        "question-answering": MPNetForQuestionAnswering,
				        "text-classification": MPNetForSequenceClassification,
				        "token-classification": MPNetForTokenClassification,
				        "zero-shot": MPNetForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				snake_case_      =		False
				snake_case_      =		True


				def   A_ (		self    :					Tuple					):
									snake_case_									=				MPNetModelTester(self					)
									snake_case_									=				ConfigTester(self       ,				config_class=lowercase_       ,				hidden_size=37					)


				def   A_ (		self    :					Union[str, Any]					):
									self.config_tester.run_common_tests()


				def   A_ (		self    :					Tuple					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_model(*lowercase_					)


				def   A_ (		self    :					List[Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase_					)


				def   A_ (		self    :					List[Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase_					)


				def   A_ (		self    :					Union[str, Any]					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase_					)


				def   A_ (		self    :					Tuple					):
									snake_case_									=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase_					)







@require_torch
class 						a				(   unittest.TestCase     ):


				@slow
				def   A_ (		self    :					List[Any]					):
									snake_case_									=				MPNetModel.from_pretrained('''microsoft/mpnet-base'''					)
									snake_case_									=				torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]					)
									snake_case_									=				model(lowercase_					)[0]
									snake_case_									=				torch.Size((1, 11, 768)					)
									self.assertEqual(output.shape       ,				lowercase_					)
									snake_case_									=				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]       ,				lowercase_       ,				atol=1e-4					)					)

