
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


_lowerCamelCase					   =logging.get_logger(__name__)

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





@dataclass
class 							A__		:
      _UpperCAmelCase				:    str           =			field(
          default=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """Model type selected in the list: """ + """, """.join(__SCREAMING_SNAKE_CASE)})
      _UpperCAmelCase				:    str           =			field(
          default=__SCREAMING_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=__SCREAMING_SNAKE_CASE  ,   metadata={"""help""": """Overwrite the cached training and evaluation sets"""})
      _UpperCAmelCase				:    bool           =			field(
          default=__SCREAMING_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__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    Tuple           =			"""train"""
      _UpperCAmelCase				:    Any           =			"""dev"""





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

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

         lowerCamelCase			,    lowerCamelCase		:	List[str]							=      squad_convert_examples_to_features(
             examples=self.examples    ,  tokenizer=__magic_name__    ,  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=__magic_name__    ,  )

         lowerCamelCase		:	List[Any]							=      time.time()
         torch.save(
             {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}    ,  __magic_name__    ,  )
         # ^ 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      ):
       return len(self.features      )






      def __getitem__(      self    ,  __magic_name__      ):
       # Convert to Tensors and build dataset
       lowerCamelCase		:	Tuple							=      self.features[i]

       lowerCamelCase		:	Union[str, Any]							=      torch.tensor(feature.input_ids    ,  dtype=torch.long      )
       lowerCamelCase		:	Tuple							=      torch.tensor(feature.attention_mask    ,  dtype=torch.long      )
       lowerCamelCase		:	Dict							=      torch.tensor(feature.token_type_ids    ,  dtype=torch.long      )
       lowerCamelCase		:	Any							=      torch.tensor(feature.cls_index    ,  dtype=torch.long      )
       lowerCamelCase		:	int							=      torch.tensor(feature.p_mask    ,  dtype=torch.float      )
       lowerCamelCase		:	Any							=      torch.tensor(feature.is_impossible    ,  dtype=torch.float      )

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

       return inputs






from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


_lowerCamelCase					   =logging.get_logger(__name__)

_lowerCamelCase					   ={
    """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}





class 							A__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    List[Any]           =			"""gpt_neo"""
      _UpperCAmelCase				:    Union[str, Any]           =			["""past_key_values"""]
      _UpperCAmelCase				:    List[Any]           =			{"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}
      def __init__(      self    ,  __magic_name__=5_0_2_5_7    ,  __magic_name__=2_0_4_8    ,  __magic_name__=2_0_4_8    ,  __magic_name__=2_4    ,  __magic_name__=[[["global", "local"], 1_2]]    ,  __magic_name__=1_6    ,  __magic_name__=None    ,  __magic_name__=2_5_6    ,  __magic_name__="gelu_new"    ,  __magic_name__=0.0    ,  __magic_name__=0.0    ,  __magic_name__=0.0    ,  __magic_name__=0.1    ,  __magic_name__=1e-5    ,  __magic_name__=0.02    ,  __magic_name__=True    ,  __magic_name__=5_0_2_5_6    ,  __magic_name__=5_0_2_5_6    ,  **__magic_name__    ,  ):
       lowerCamelCase		:	List[Any]							=      vocab_size
       lowerCamelCase		:	str							=      max_position_embeddings
       lowerCamelCase		:	str							=      hidden_size
       lowerCamelCase		:	Optional[int]							=      num_layers
       lowerCamelCase		:	str							=      num_heads
       lowerCamelCase		:	Optional[Any]							=      intermediate_size
       lowerCamelCase		:	List[Any]							=      window_size
       lowerCamelCase		:	int							=      activation_function
       lowerCamelCase		:	Union[str, Any]							=      resid_dropout
       lowerCamelCase		:	List[Any]							=      embed_dropout
       lowerCamelCase		:	List[str]							=      attention_dropout
       lowerCamelCase		:	Dict							=      classifier_dropout
       lowerCamelCase		:	Any							=      layer_norm_epsilon
       lowerCamelCase		:	Dict							=      initializer_range
       lowerCamelCase		:	Dict							=      use_cache

       lowerCamelCase		:	Optional[Any]							=      bos_token_id
       lowerCamelCase		:	int							=      eos_token_id

       lowerCamelCase		:	List[Any]							=      attention_types
       lowerCamelCase		:	Optional[Any]							=      self.expand_attention_types_params(__magic_name__      )

       if len(self.attention_layers      ) != self.num_layers:
        raise ValueError(
            """Configuration for convolutional module is incorrect. """
            """It is required that `len(config.attention_layers)` == `config.num_layers` """
            F'''but is `len(config.attention_layers) = {len(self.attention_layers      )}`, '''
            F'''`config.num_layers = {self.num_layers}`. '''
            """`config.attention_layers` is prepared using `config.attention_types`. """
            """Please verify the value of `config.attention_types` argument."""      )

       super().__init__(bos_token_id=__magic_name__    ,  eos_token_id=__magic_name__    ,  **__magic_name__      )






      @staticmethod
      def 						UpperCamelCase__							(      __magic_name__      ):
       lowerCamelCase		:	Optional[int]							=      []
       for item in attention_types:
        for _ in range(item[1]      ):
         attentions.extend(item[0]      )
       return attentions





def     _a					(						lowerCamelCase,	lowerCamelCase,	lowerCamelCase,	lowerCamelCase							):
 import torch

 lowerCamelCase		:	Any							=      input.size()
 lowerCamelCase		:	List[Any]							=      len(lowerCamelCase							)
 lowerCamelCase		:	Optional[Any]							=      shape[dimension]

 lowerCamelCase		:	Optional[int]							=      torch.arange(0,	lowerCamelCase,	lowerCamelCase							)
 lowerCamelCase		:	Dict							=      torch.div(sizedim - size,	lowerCamelCase,	rounding_mode="""floor"""							) + 1
 lowerCamelCase		:	int							=      torch.arange(lowerCamelCase							) + low_indices[:min_length][:, None]

 lowerCamelCase		:	str							=      [slice(lowerCamelCase							)] * rank
 lowerCamelCase		:	List[str]							=      indices
 lowerCamelCase		:	Dict							=      input[s]

 lowerCamelCase		:	Any							=      list(range(0,	rank + 1							)							)
 perm.append(perm.pop(dimension + 1							)							)

 return sliced.permute(lowerCamelCase							)





def     _a					(						lowerCamelCase,	lowerCamelCase							):
 import torch

 lowerCamelCase		:	List[Any]							=      torch.arange(1,	lowerCamelCase							)
 lowerCamelCase		:	Optional[int]							=      torch.remainder(lowerCamelCase,	lowerCamelCase							)
 lowerCamelCase		:	List[Any]							=      remainders == 0
 lowerCamelCase		:	List[Any]							=      candidates[divisor_indices]
 lowerCamelCase		:	Optional[Any]							=      torch.max(lowerCamelCase							)
 return largest_divisor, torch.div(lowerCamelCase,	lowerCamelCase,	rounding_mode="""floor"""							)





class 							A__		(	__SCREAMING_SNAKE_CASE):
      @property
      def 						UpperCamelCase__							(      self      ):
       lowerCamelCase		:	str							=      OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}      )
       if self.use_past:
        self.fill_with_past_key_values_(__magic_name__    ,  direction="""inputs"""      )
        lowerCamelCase		:	int							=      {0: """batch""", 1: """past_sequence + sequence"""}
       else:
        lowerCamelCase		:	Tuple							=      {0: """batch""", 1: """sequence"""}

       return common_inputs
      @property
      def 						UpperCamelCase__							(      self      ):
       return self._config.num_heads
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__ = -1    ,  __magic_name__ = -1    ,  __magic_name__ = False    ,  __magic_name__ = None    ,  ):
       lowerCamelCase		:	Optional[int]							=      super(__magic_name__    ,  self      ).generate_dummy_inputs(
           __magic_name__    ,  batch_size=__magic_name__    ,  seq_length=__magic_name__    ,  is_pair=__magic_name__    ,  framework=__magic_name__      )

       # We need to order the input in the way they appears in the forward()
       lowerCamelCase		:	int							=      OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}      )

       # Need to add the past_keys
       if self.use_past:
        if not is_torch_available():
         raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""      )
        else:
         import torch

         lowerCamelCase			,    lowerCamelCase		:	Optional[Any]							=      common_inputs["""input_ids"""].shape
         # Not using the same length for past_key_values
         lowerCamelCase		:	Optional[int]							=      seqlen + 2
         lowerCamelCase		:	List[Any]							=      (
             batch,
             self.num_attention_heads,
             past_key_values_length,
             self._config.hidden_size // self.num_attention_heads,
         )
         lowerCamelCase		:	str							=      [
             (torch.zeros(__magic_name__      ), torch.zeros(__magic_name__      )) for _ in range(self.num_layers      )
         ]

       lowerCamelCase		:	Tuple							=      common_inputs["""attention_mask"""]
       if self.use_past:
        lowerCamelCase		:	str							=      ordered_inputs["""attention_mask"""].dtype
        lowerCamelCase		:	Any							=      torch.cat(
            [ordered_inputs["""attention_mask"""], torch.ones(__magic_name__    ,  __magic_name__    ,  dtype=__magic_name__      )]    ,  dim=1      )

       return ordered_inputs






      @property
      def 						UpperCamelCase__							(      self      ):
       return 1_3




