




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__ :   Optional[int]					=							logging.get_logger(__name__)

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





@dataclass
class        lowerCamelCase_							:


 '''simple docstring'''







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





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    "train"
 lowercase_				    =    "dev"





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    42
 lowercase_				    =    42
 lowercase_				    =    42
 lowercase_				    =    42



 def __init__(							self  :		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"				,				):
       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  :		List[Any]						):
       return len(self.features						)




 def __getitem__(							self  :		Optional[int]				,				_lowerCAmelCase  :		Optional[Any]						):
       # Convert to Tensors and build dataset
       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





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer


lowerCamelCase__ :   Union[str, Any]					=							logging.get_logger(__name__)

lowerCamelCase__ :   Dict					=							{'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCamelCase__ :   Tuple					=							{
    'vocab_file': {
        'squeezebert/squeezebert-uncased': (
            'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt'
        ),
        'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt',
        'squeezebert/squeezebert-mnli-headless': (
            'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt'
        ),
    },
    'tokenizer_file': {
        'squeezebert/squeezebert-uncased': (
            'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json'
        ),
        'squeezebert/squeezebert-mnli': (
            'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json'
        ),
        'squeezebert/squeezebert-mnli-headless': (
            'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json'
        ),
    },
}

lowerCamelCase__ :   int					=							{
    'squeezebert/squeezebert-uncased': 512,
    'squeezebert/squeezebert-mnli': 512,
    'squeezebert/squeezebert-mnli-headless': 512,
}


lowerCamelCase__ :   str					=							{
    'squeezebert/squeezebert-uncased': {'do_lower_case': True},
    'squeezebert/squeezebert-mnli': {'do_lower_case': True},
    'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True},
}





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    VOCAB_FILES_NAMES
 lowercase_				    =    PRETRAINED_VOCAB_FILES_MAP
 lowercase_				    =    PRETRAINED_INIT_CONFIGURATION
 lowercase_				    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowercase_				    =    SqueezeBertTokenizer



 def __init__(							self  :		Tuple				,				_lowerCAmelCase  :		Dict=None				,				_lowerCAmelCase  :		int=None				,				_lowerCAmelCase  :		List[str]=True				,				_lowerCAmelCase  :		str="[UNK]"				,				_lowerCAmelCase  :		Union[str, Any]="[SEP]"				,				_lowerCAmelCase  :		List[Any]="[PAD]"				,				_lowerCAmelCase  :		str="[CLS]"				,				_lowerCAmelCase  :		Dict="[MASK]"				,				_lowerCAmelCase  :		Optional[int]=True				,				_lowerCAmelCase  :		Dict=None				,				**_lowerCAmelCase  :		str				,				):
       super().__init__(
           _lowerCAmelCase				,				tokenizer_file=_lowerCAmelCase				,				do_lower_case=_lowerCAmelCase				,				unk_token=_lowerCAmelCase				,				sep_token=_lowerCAmelCase				,				pad_token=_lowerCAmelCase				,				cls_token=_lowerCAmelCase				,				mask_token=_lowerCAmelCase				,				tokenize_chinese_chars=_lowerCAmelCase				,				strip_accents=_lowerCAmelCase				,				**_lowerCAmelCase				,				)

       SCREAMING_SNAKE_CASE_							=			json.loads(self.backend_tokenizer.normalizer.__getstate__()						)
       if (
           normalizer_state.get('lowercase'				,				_lowerCAmelCase						) != do_lower_case
           or normalizer_state.get('strip_accents'				,				_lowerCAmelCase						) != strip_accents
           or normalizer_state.get('handle_chinese_chars'				,				_lowerCAmelCase						) != tokenize_chinese_chars
       ):
             SCREAMING_SNAKE_CASE_							=			getattr(_lowerCAmelCase				,				normalizer_state.pop('type'						)						)
             SCREAMING_SNAKE_CASE_							=			do_lower_case
             SCREAMING_SNAKE_CASE_							=			strip_accents
             SCREAMING_SNAKE_CASE_							=			tokenize_chinese_chars
             SCREAMING_SNAKE_CASE_							=			normalizer_class(**_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			do_lower_case



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		Optional[int]=None						):
       SCREAMING_SNAKE_CASE_							=			[self.cls_token_id] + token_ids_a + [self.sep_token_id]

       if token_ids_a:
             output += token_ids_a + [self.sep_token_id]

       return output



 def       lowerCAmelCase_  (							self  :		Optional[int]				,				_lowerCAmelCase  :		List[int]				,				_lowerCAmelCase  :		Optional[List[int]] = None						):
       SCREAMING_SNAKE_CASE_							=			[self.sep_token_id]
       SCREAMING_SNAKE_CASE_							=			[self.cls_token_id]
       if token_ids_a is None:
             return len(cls + token_ids_a + sep						) * [0]
       return len(cls + token_ids_a + sep						) * [0] + len(token_ids_a + sep						) * [1]




 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		Optional[str] = None						):
       SCREAMING_SNAKE_CASE_							=			self._tokenizer.model.save(_lowerCAmelCase				,				name=_lowerCAmelCase						)
       return tuple(_lowerCAmelCase						)