





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


_snake_case    :       str		       =    logging.get_logger(__name__)

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



@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


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





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					"""train"""
  a_              =					"""dev"""





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42






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

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

           __lowerCAmelCase      ,      __lowerCAmelCase				      =      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_   ,    )

           __lowerCAmelCase				      =      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					:						Tuple	)				->		List[str]:
     return len(self.features	)






  def __getitem__(							self					:						Dict   ,    lowerCAmelCase_					:						Optional[int]	)				->		Dict[str, torch.Tensor]:
     # Convert to Tensors and build dataset
     __lowerCAmelCase				      =      self.features[i]

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

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

     return inputs






'''simple docstring'''

from dataclasses import asdict, dataclass
from typing import Optional

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


__lowerCAmelCase		     =  logging.get_logger(__name__)

# TODO Update this
__lowerCAmelCase		     =  {
    '''facebook/esm-1b''': '''https://huggingface.co/facebook/esm-1b/resolve/main/config.json''',
    # See all ESM models at https://huggingface.co/models?filter=esm
}

class       __magic_name__		(       _UpperCamelCase  ):
							lowerCAmelCase			:       Any  							=   'esm'







							def __init__(				self   :			Optional[int]      ,_UpperCAmelCase   :			Optional[Any]=None      ,_UpperCAmelCase   :			Dict=None      ,_UpperCAmelCase   :			Union[str, Any]=None      ,_UpperCAmelCase   :			List[Any]=768      ,_UpperCAmelCase   :			Union[str, Any]=12      ,_UpperCAmelCase   :			List[str]=12      ,_UpperCAmelCase   :			Tuple=3072      ,_UpperCAmelCase   :			Dict=0.1      ,_UpperCAmelCase   :			Tuple=0.1      ,_UpperCAmelCase   :			List[str]=1026      ,_UpperCAmelCase   :			List[str]=0.02      ,_UpperCAmelCase   :			Optional[int]=1E-12      ,_UpperCAmelCase   :			List[str]="absolute"      ,_UpperCAmelCase   :			Tuple=True      ,_UpperCAmelCase   :			Tuple=None      ,_UpperCAmelCase   :			List[Any]=False      ,_UpperCAmelCase   :			int=False      ,_UpperCAmelCase   :			int=None      ,_UpperCAmelCase   :			Union[str, Any]=None      ,**_UpperCAmelCase   :			List[Any]      ,):
									super().__init__(pad_token_id=_UpperCAmelCase      ,mask_token_id=_UpperCAmelCase      ,**_UpperCAmelCase						)

									_a	: Optional[Any]								=				vocab_size
									_a	: Union[str, Any]								=				hidden_size
									_a	: Dict								=				num_hidden_layers
									_a	: int								=				num_attention_heads
									_a	: Dict								=				intermediate_size
									_a	: List[Any]								=				hidden_dropout_prob
									_a	: List[Any]								=				attention_probs_dropout_prob
									_a	: Optional[Any]								=				max_position_embeddings
									_a	: Optional[int]								=				initializer_range
									_a	: List[Any]								=				layer_norm_eps
									_a	: int								=				position_embedding_type
									_a	: Optional[int]								=				use_cache
									_a	: Any								=				emb_layer_norm_before
									_a	: List[str]								=				token_dropout
									_a	: List[str]								=				is_folding_model
									if is_folding_model:
											if esmfold_config is None:
													logger.info('No esmfold_config supplied for folding model, using default values.'						)
													_a	: Dict								=				EsmFoldConfig()
											elif isinstance(_UpperCAmelCase      ,_UpperCAmelCase						):
													_a	: Dict								=				EsmFoldConfig(**_UpperCAmelCase						)
											_a	: Optional[int]								=				esmfold_config
											if vocab_list is None:
													logger.warning('No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!'						)
													_a	: Optional[int]								=				get_default_vocab_list()
											else:
													_a	: Optional[int]								=				vocab_list
									else:
											_a	: Optional[Any]								=				None
											_a	: Union[str, Any]								=				None
									if self.esmfold_config is not None and getattr(self.esmfold_config      ,'use_esm_attn_map'      ,_UpperCAmelCase						):
											raise ValueError('The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!'						)







							def 				__lowercase     (				self   :			Any						):
									_a	: str								=				super().to_dict()
									if isinstance(self.esmfold_config      ,_UpperCAmelCase						):
											_a	: List[str]								=				self.esmfold_config.to_dict()
									return output

@dataclass
class       __magic_name__		:
							lowerCAmelCase			:       str  							=   None
							lowerCAmelCase			:       bool  							=   True
							lowerCAmelCase			:       bool  							=   False
							lowerCAmelCase			:       bool  							=   False
							lowerCAmelCase			:       bool  							=   False
							lowerCAmelCase			:       float  							=   0

							lowerCAmelCase			:       bool  							=   True
							lowerCAmelCase			:       bool  							=   False

							lowerCAmelCase			:       int  							=   1_2_8
							lowerCAmelCase			:       "TrunkConfig"  							=   None







							def 				__lowercase     (				self   :			List[str]						):
									if self.trunk is None:
											_a	: Dict								=				TrunkConfig()
									elif isinstance(self.trunk      ,_UpperCAmelCase						):
											_a	: str								=				TrunkConfig(**self.trunk						)







							def 				__lowercase     (				self   :			List[Any]						):
									_a	: List[str]								=				asdict(self						)
									_a	: List[str]								=				self.trunk.to_dict()
									return output

@dataclass
class       __magic_name__		:
							lowerCAmelCase			:       int  							=   4_8
							lowerCAmelCase			:       int  							=   1_0_2_4
							lowerCAmelCase			:       int  							=   1_2_8
							lowerCAmelCase			:       int  							=   3_2
							lowerCAmelCase			:       int  							=   3_2
							lowerCAmelCase			:       int  							=   3_2
							lowerCAmelCase			:       float  							=   0
							lowerCAmelCase			:       float  							=   0
							lowerCAmelCase			:       bool  							=   False
							lowerCAmelCase			:       int  							=   4
							lowerCAmelCase			:       Optional[int]  							=   1_2_8
							lowerCAmelCase			:       "StructureModuleConfig"  							=   None







							def 				__lowercase     (				self   :			str						):
									if self.structure_module is None:
											_a	: Tuple								=				StructureModuleConfig()
									elif isinstance(self.structure_module      ,_UpperCAmelCase						):
											_a	: List[str]								=				StructureModuleConfig(**self.structure_module						)

									if self.max_recycles <= 0:
											raise ValueError(F"""`max_recycles` should be positive, got {self.max_recycles}."""						)
									if self.sequence_state_dim % self.sequence_state_dim != 0:
											raise ValueError(
											    '`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got'
											    F""" {self.sequence_state_dim} and {self.sequence_state_dim}."""						)
									if self.pairwise_state_dim % self.pairwise_state_dim != 0:
											raise ValueError(
											    '`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got'
											    F""" {self.pairwise_state_dim} and {self.pairwise_state_dim}."""						)

									_a	: Optional[int]								=				self.sequence_state_dim // self.sequence_head_width
									_a	: int								=				self.pairwise_state_dim // self.pairwise_head_width

									if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width:
											raise ValueError(
											    '`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got'
											    F""" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}."""						)
									if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width:
											raise ValueError(
											    '`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got'
											    F""" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}."""						)
									if self.pairwise_state_dim % 2 != 0:
											raise ValueError(F"""`pairwise_state_dim` should be even, got {self.pairwise_state_dim}."""						)

									if self.dropout >= 0.4:
											raise ValueError(F"""`dropout` should not be greater than 0.4, got {self.dropout}."""						)







							def 				__lowercase     (				self   :			Optional[int]						):
									_a	: Optional[Any]								=				asdict(self						)
									_a	: Optional[Any]								=				self.structure_module.to_dict()
									return output

@dataclass
class       __magic_name__		:
							lowerCAmelCase			:       int  							=   3_8_4
							lowerCAmelCase			:       int  							=   1_2_8
							lowerCAmelCase			:       int  							=   1_6
							lowerCAmelCase			:       int  							=   1_2_8
							lowerCAmelCase			:       int  							=   1_2
							lowerCAmelCase			:       int  							=   4
							lowerCAmelCase			:       int  							=   8
							lowerCAmelCase			:       float  							=   0.1
							lowerCAmelCase			:       int  							=   8
							lowerCAmelCase			:       int  							=   1
							lowerCAmelCase			:       int  							=   2
							lowerCAmelCase			:       int  							=   7
							lowerCAmelCase			:       int  							=   1_0
							lowerCAmelCase			:       float  							=   1e-8
							lowerCAmelCase			:       float  							=   1e5







							def 				__lowercase     (				self   :			str						):
									return asdict(self						)



def 	__lowerCamelCase	( )     -> Optional[int]:
		return (
		    "<cls>",
		    "<pad>",
		    "<eos>",
		    "<unk>",
		    "L",
		    "A",
		    "G",
		    "V",
		    "S",
		    "E",
		    "R",
		    "T",
		    "I",
		    "D",
		    "P",
		    "K",
		    "Q",
		    "N",
		    "F",
		    "Y",
		    "M",
		    "H",
		    "W",
		    "C",
		    "X",
		    "B",
		    "U",
		    "Z",
		    "O",
		    ".",
		    "-",
		    "<null_1>",
		    "<mask>",
		)




