




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


SCREAMING_SNAKE_CASE:     int									= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE:     List[Any]									= list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
SCREAMING_SNAKE_CASE:     List[Any]									= tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



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



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      ="train"
						lowerCAmelCase__			      ="dev"



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      =42
						lowerCAmelCase__			      =42
						lowerCAmelCase__			      =42
						lowerCAmelCase__			      =42



						def __init__(			self	:   Dict					,							snake_case__	:   SquadDataTrainingArguments					,							snake_case__	:   PreTrainedTokenizer					,							snake_case__	:   Optional[int] = None					,							snake_case__	:   Union[str, Split] = Split.train					,							snake_case__	:   Optional[bool] = False					,							snake_case__	:   Optional[str] = None					,							snake_case__	:   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(snake_case__					,							snake_case__  ):
										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(snake_case__  ):
										if os.path.exists(snake_case__  ) and not args.overwrite_cache:
												SCREAMING_SNAKE_CASE_					      =							time.time()
												SCREAMING_SNAKE_CASE_					      =							torch.load(snake_case__  )

												# 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'					,							snake_case__  )
												SCREAMING_SNAKE_CASE_					      =							self.old_features.get('examples'					,							snake_case__  )
												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=snake_case__					,							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=snake_case__					,							)

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

								"""simple docstring"""

								return len(self.features  )






						def __getitem__(			self	:   List[str]					,							snake_case__	:   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 collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
						from ...onnx.config import PatchingSpec
						from ...tokenization_utils_base import PreTrainedTokenizerBase


SCREAMING_SNAKE_CASE:     str									= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE:     Optional[int]									= {
    '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json''',
    '''allenai/longformer-large-4096''': '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json''',
    '''allenai/longformer-large-4096-finetuned-triviaqa''': (
        '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json'''
    ),
    '''allenai/longformer-base-4096-extra.pos.embd.only''': (
        '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json'''
    ),
    '''allenai/longformer-large-4096-extra.pos.embd.only''': (
        '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json'''
    ),
}



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      ="longformer"



						def __init__(			self	:   Optional[Any]					,							snake_case__	:   Union[List[int], int] = 5_12					,							snake_case__	:   int = 2					,							snake_case__	:   int = 1					,							snake_case__	:   int = 0					,							snake_case__	:   int = 2					,							snake_case__	:   int = 3_05_22					,							snake_case__	:   int = 7_68					,							snake_case__	:   int = 12					,							snake_case__	:   int = 12					,							snake_case__	:   int = 30_72					,							snake_case__	:   str = "gelu"					,							snake_case__	:   float = 0.1					,							snake_case__	:   float = 0.1					,							snake_case__	:   int = 5_12					,							snake_case__	:   int = 2					,							snake_case__	:   float = 0.02					,							snake_case__	:   float = 1e-12					,							snake_case__	:   bool = False					,							**snake_case__	:   Tuple					,							):

								"""simple docstring"""

								super().__init__(pad_token_id=snake_case__					,							**snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							attention_window
								SCREAMING_SNAKE_CASE_					      =							sep_token_id
								SCREAMING_SNAKE_CASE_					      =							bos_token_id
								SCREAMING_SNAKE_CASE_					      =							eos_token_id
								SCREAMING_SNAKE_CASE_					      =							vocab_size
								SCREAMING_SNAKE_CASE_					      =							hidden_size
								SCREAMING_SNAKE_CASE_					      =							num_hidden_layers
								SCREAMING_SNAKE_CASE_					      =							num_attention_heads
								SCREAMING_SNAKE_CASE_					      =							hidden_act
								SCREAMING_SNAKE_CASE_					      =							intermediate_size
								SCREAMING_SNAKE_CASE_					      =							hidden_dropout_prob
								SCREAMING_SNAKE_CASE_					      =							attention_probs_dropout_prob
								SCREAMING_SNAKE_CASE_					      =							max_position_embeddings
								SCREAMING_SNAKE_CASE_					      =							type_vocab_size
								SCREAMING_SNAKE_CASE_					      =							initializer_range
								SCREAMING_SNAKE_CASE_					      =							layer_norm_eps
								SCREAMING_SNAKE_CASE_					      =							onnx_export



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):



						def __init__(			self	:   Dict					,							snake_case__	:   "PretrainedConfig"					,							snake_case__	:   str = "default"					,							snake_case__	:   "List[PatchingSpec]" = None  ):

								"""simple docstring"""

								super().__init__(snake_case__					,							snake_case__					,							snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							True



						@property
						def 	__a					(			self	:   Union[str, Any]  ):

								"""simple docstring"""

								if self.task == "multiple-choice":
										SCREAMING_SNAKE_CASE_					      =							{0: 'batch', 1: 'choice', 2: 'sequence'}
								else:
										SCREAMING_SNAKE_CASE_					      =							{0: 'batch', 1: 'sequence'}
								return OrderedDict(
								    [
								        ('input_ids', dynamic_axis),
								        ('attention_mask', dynamic_axis),
								        ('global_attention_mask', dynamic_axis),
								    ]  )



						@property
						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							super().outputs
								if self.task == "default":
										SCREAMING_SNAKE_CASE_					      =							{0: 'batch'}
								return outputs



						@property
						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								return 1e-4



						@property
						def 	__a					(			self	:   List[str]  ):

								"""simple docstring"""

								return max(super().default_onnx_opset					,							14  )






						def 	__a					(			self	:   List[str]					,							snake_case__	:   "PreTrainedTokenizerBase"					,							snake_case__	:   int = -1					,							snake_case__	:   int = -1					,							snake_case__	:   bool = False					,							snake_case__	:   Optional[TensorType] = None					,							):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							super().generate_dummy_inputs(
								    preprocessor=snake_case__					,							batch_size=snake_case__					,							seq_length=snake_case__					,							is_pair=snake_case__					,							framework=snake_case__  )
								import torch

								# for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
								# makes the export fail randomly
								SCREAMING_SNAKE_CASE_					      =							torch.zeros_like(inputs['input_ids']  )
								# make every second token global
								SCREAMING_SNAKE_CASE_					      =							1

								return inputs