



'''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


lowercase_									=    logging.get_logger(__name__)

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






@dataclass
class __A     :



 '''simple docstring'''







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






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			int		=			'train'
 __lowerCamelCase       :			Union[str, Any]		=			'dev'






class __A     (    A		):



 '''simple docstring'''







 __lowerCamelCase       :			SquadDataTrainingArguments
 __lowerCamelCase       :			List[SquadFeatures]
 __lowerCamelCase       :			Split
 __lowerCamelCase       :			bool



 def __init__(self					,  A					,  A					,  A = None					,  A = Split.train					,  A = False					,  A = None					,  A = "pt"					,  )       ->	int:


      """simple docstring"""



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

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

                _a    ,       _a           =    squad_convert_examples_to_features(
                    examples=self.examples					,  tokenizer=A					,  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=A					,  )

                _a           =    time.time()
                torch.save(
                    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}					,  A					,  )
                # ^ 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					,  A			)       ->	Dict[str, torch.Tensor]:


      """simple docstring"""



      _a           =    self.features[i]

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

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

      return inputs







'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from argparse import ArgumentParser

from accelerate.commands.config import get_config_parser
from accelerate.commands.env import env_command_parser
from accelerate.commands.launch import launch_command_parser
from accelerate.commands.test import test_command_parser
from accelerate.commands.tpu import tpu_command_parser


def       _lowercase							(					):
 __A	:		Dict	  =      ArgumentParser('Accelerate CLI tool',					usage='accelerate <command> [<args>]',					allow_abbrev=UpperCamelCase__      )
 __A	:		Any	  =      parser.add_subparsers(help='accelerate command helpers'      )

 # Register commands
 get_config_parser(subparsers=UpperCamelCase__      )
 env_command_parser(subparsers=UpperCamelCase__      )
 launch_command_parser(subparsers=UpperCamelCase__      )
 tpu_command_parser(subparsers=UpperCamelCase__      )
 test_command_parser(subparsers=UpperCamelCase__      )

 # Let's go
 __A	:		Optional[Any]	  =      parser.parse_args()

 if not hasattr(UpperCamelCase__,					'func'      ):
  parser.print_help()
  exit(1      )

 # Run
 args.func(UpperCamelCase__      )


if __name__ == "__main__":
 main()






