





'''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   	=    logging.get_logger(__name__)

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







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







class __a			( _snake_case      ):
   __UpperCamelCase :			Optional[Any]						   =						'train'
   __UpperCamelCase :			List[Any]						   =						'dev'







class __a			( _snake_case      ):
   __UpperCamelCase :			SquadDataTrainingArguments
   __UpperCamelCase :			List[SquadFeatures]
   __UpperCamelCase :			Split
   __UpperCamelCase :			bool





   def __init__(       self					:      List[str]					,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"					,):

      '''simple docstring'''

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

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

            __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							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					,)

            __SCREAMING_SNAKE_CASE   				=							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					:      Optional[Any]     ):

      '''simple docstring'''

      return len(self.features     )





   def __getitem__(       self					:      Optional[Any]					,lowerCamelCase					:      Optional[int]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.features[i]

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

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

      return inputs










from typing import Callable, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase    :		int		      =    logging.get_logger(__name__)

_lowerCamelCase    :		Union[str, Any]		      =    {
    """microsoft/xprophetnet-large-wiki100-cased""": (
        """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json"""
    ),
}


class 						lowercase    (							SCREAMING_SNAKE_CASE_):
						'''simple docstring'''


						UpperCAmelCase			:		Tuple		=		'xlm-prophetnet'
						UpperCAmelCase			:		int		=		['past_key_values']
						UpperCAmelCase			:		List[Any]		=		{
						    'num_attention_heads': 'num_encoder_attention_heads',
						}







						def __init__(  self    :				List[Any]       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[Union[str, Callable]] = "gelu"       ,	snake_case    :				Optional[int] = 30522       ,	snake_case    :				Optional[int] = 1024       ,	snake_case    :				Optional[int] = 4096       ,	snake_case    :				Optional[int] = 12       ,	snake_case    :				Optional[int] = 16       ,	snake_case    :				Optional[int] = 4096       ,	snake_case    :				Optional[int] = 12       ,	snake_case    :				Optional[int] = 16       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[int] = 512       ,	snake_case    :				Optional[float] = 0.02       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[int] = 0       ,	snake_case    :				Optional[int] = 2       ,	snake_case    :				Optional[int] = 32       ,	snake_case    :				Optional[int] = 128       ,	snake_case    :				Optional[bool] = False       ,	snake_case    :				Optional[float] = 0.0       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[int] = 0       ,	snake_case    :				Optional[int] = 1       ,	snake_case    :				Optional[int] = 2       ,	**snake_case    :				Optional[int]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				vocab_size
											SCREAMING_SNAKE_CASE							:     int						=				hidden_size
											SCREAMING_SNAKE_CASE							:     Dict						=				encoder_ffn_dim
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				num_encoder_layers
											SCREAMING_SNAKE_CASE							:     str						=				num_encoder_attention_heads
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				decoder_ffn_dim
											SCREAMING_SNAKE_CASE							:     Any						=				num_decoder_layers
											SCREAMING_SNAKE_CASE							:     List[str]						=				num_decoder_attention_heads
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				max_position_embeddings
											SCREAMING_SNAKE_CASE							:     Any						=				init_std  # Normal(0, this parameter)
											SCREAMING_SNAKE_CASE							:     List[str]						=				activation_function

											# parameters for xlmprophetnet
											SCREAMING_SNAKE_CASE							:     Tuple						=				ngram
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				num_buckets
											SCREAMING_SNAKE_CASE							:     Any						=				relative_max_distance
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				disable_ngram_loss
											SCREAMING_SNAKE_CASE							:     List[str]						=				eps

											# 3 Types of Dropout
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				attention_dropout
											SCREAMING_SNAKE_CASE							:     Any						=				activation_dropout
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				dropout

											SCREAMING_SNAKE_CASE							:     Tuple						=				use_cache

											super().__init__(
											    pad_token_id=snake_case       ,	bos_token_id=snake_case       ,	eos_token_id=snake_case       ,	is_encoder_decoder=snake_case       ,	add_cross_attention=snake_case       ,	decoder_start_token_id=snake_case       ,	**snake_case       ,	)







						@property
						def       lowerCamelCase_				(  self    :				Optional[Any]	):



											'''simple docstring'''


											return self.num_encoder_layers + self.num_decoder_layers







						@num_hidden_layers.setter
						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				Optional[int]	):



											'''simple docstring'''


											raise NotImplementedError(
											    'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'
											    ' `num_decoder_layers`.'	)