


# Copyright 2022 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.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available

def    lowercase_	(	_A    :					Dict=None		):

      """simple docstring"""




      if subparsers is not None:
            lowerCamelCase__	:       List[Any]					=						subparsers.add_parser("env"		)
      else:
            lowerCamelCase__	:       Optional[Any]					=						argparse.ArgumentParser("Accelerate env command"		)

      parser.add_argument(
          "--config_file"					,      default=_A					,      help="The config file to use for the default values in the launching script."		)

      if subparsers is not None:
            parser.set_defaults(func=_A		)
      return parser

def    lowercase_	(	_A    :					Tuple		):

      """simple docstring"""




      lowerCamelCase__	:       int					=						torch.__version__
      lowerCamelCase__	:       Optional[int]					=						torch.cuda.is_available()
      lowerCamelCase__	:       Any					=						is_xpu_available()
      lowerCamelCase__	:       Dict					=						is_npu_available()

      lowerCamelCase__	:       str					=						"Not found"
      # Get the default from the config file.
      if args.config_file is not None or os.path.isfile(_A		):
            lowerCamelCase__	:       Any					=						load_config_from_file(args.config_file		).to_dict()

      lowerCamelCase__	:       List[str]					=						{
          "`Accelerate` version": version,
          "Platform": platform.platform(),
          "Python version": platform.python_version(),
          "Numpy version": np.__version__,
          "PyTorch version (GPU?)": F"{pt_version} ({pt_cuda_available})",
          "PyTorch XPU available": str(_A		),
          "PyTorch NPU available": str(_A		),
          "System RAM": F"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB",
      }
      if pt_cuda_available:
            lowerCamelCase__	:       Dict					=						torch.cuda.get_device_name()

      print("\nCopy-and-paste the text below in your GitHub issue\n"		)
      print("\n".join([F"- {prop}: {val}" for prop, val in info.items()]		)		)

      print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:"		)
      lowerCamelCase__	:       Optional[int]					=						(
          "\n".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()]		)
          if isinstance(_A					,      _A		)
          else F"\t{accelerate_config}"
      )
      print(_A		)

      lowerCamelCase__	:       Tuple					=						accelerate_config

      return info

def    lowercase_	(	):

      """simple docstring"""




      lowerCamelCase__	:       Optional[int]					=						env_command_parser()
      lowerCamelCase__	:       List[Any]					=						parser.parse_args()
      env_command(_A		)
      return 0


if __name__ == "__main__":
    raise SystemExit(main())






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


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

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







@dataclass
class     _lowercase				:


       """simple docstring"""




       A__      		=    field(
           default=lowercase__							,						metadata={"help": "Model type selected in the list: " + ", ".join(lowercase__)})
       A__      		=    field(
           default=lowercase__							,						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=lowercase__							,						metadata={"help": "Overwrite the cached training and evaluation sets"})
       A__      		=    field(
           default=lowercase__							,						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     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    "train"
       A__      		=    "dev"







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    42
       A__      		=    42
       A__      		=    42
       A__      		=    42





       def __init__(     self							:    Optional[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"      ,   ):


             '''simple docstring'''



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

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

                         lowerCamelCase__					,     lowerCamelCase__	:       Tuple					=						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__	:       int					=						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] ):


             '''simple docstring'''



             return len(self.features )





       def __getitem__(     self							:    List[str]      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						self.features[i]

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

             lowerCamelCase__	:       List[str]					=						{
                 "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__	:       List[Any]					=						torch.tensor(feature.end_position      ,   dtype=torch.long )
                   inputs.update({"start_positions": start_positions, "end_positions": end_positions} )

             return inputs


